Файловый менеджер - Редактировать - /home/beautybuzzbeyond/public_html/private/vendor.tar
Назад
wp-polyfill.min.js 0000604 00000112053 14720015030 0010130 0 ustar 00 !function(r){"use strict";var t,e,n;t=[function(r,t,e){e(1),e(73),e(76),e(78),e(80),e(92),e(93),e(95),e(98),e(100),e(101),e(110),e(111),e(114),e(120),e(135),e(137),e(138),r.exports=e(139)},function(r,t,e){var n=e(2),o=e(67),a=e(11),i=e(68),c=Array;n({target:"Array",proto:!0},{toReversed:function(){return o(a(this),c)}}),i("toReversed")},function(t,e,n){var o=n(3),a=n(4).f,i=n(42),c=n(46),u=n(36),f=n(54),s=n(66);t.exports=function(t,e){var n,p,l,y,v,h=t.target,g=t.global,d=t.stat;if(n=g?o:d?o[h]||u(h,{}):o[h]&&o[h].prototype)for(p in e){if(y=e[p],l=t.dontCallGetSet?(v=a(n,p))&&v.value:n[p],!s(g?p:h+(d?".":"#")+p,t.forced)&&l!==r){if(typeof y==typeof l)continue;f(y,l)}(t.sham||l&&l.sham)&&i(y,"sham",!0),c(n,p,y,t)}}},function(r,t,e){var n=function(r){return r&&r.Math===Math&&r};r.exports=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof global&&global)||n("object"==typeof this&&this)||function(){return this}()||Function("return this")()},function(r,t,e){var n=e(5),o=e(7),a=e(9),i=e(10),c=e(11),u=e(17),f=e(37),s=e(40),p=Object.getOwnPropertyDescriptor;t.f=n?p:function(r,t){if(r=c(r),t=u(t),s)try{return p(r,t)}catch(r){}if(f(r,t))return i(!o(a.f,r,t),r[t])}},function(r,t,e){var n=e(6);r.exports=!n((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]}))},function(r,t,e){r.exports=function(r){try{return!!r()}catch(r){return!0}}},function(r,t,e){var n=e(8),o=Function.prototype.call;r.exports=n?o.bind(o):function(){return o.apply(o,arguments)}},function(r,t,e){var n=e(6);r.exports=!n((function(){var r=function(){}.bind();return"function"!=typeof r||r.hasOwnProperty("prototype")}))},function(r,t,e){var n={}.propertyIsEnumerable,o=Object.getOwnPropertyDescriptor,a=o&&!n.call({1:2},1);t.f=a?function(r){var t=o(this,r);return!!t&&t.enumerable}:n},function(r,t,e){r.exports=function(r,t){return{enumerable:!(1&r),configurable:!(2&r),writable:!(4&r),value:t}}},function(r,t,e){var n=e(12),o=e(15);r.exports=function(r){return n(o(r))}},function(r,t,e){var n=e(13),o=e(6),a=e(14),i=Object,c=n("".split);r.exports=o((function(){return!i("z").propertyIsEnumerable(0)}))?function(r){return"String"===a(r)?c(r,""):i(r)}:i},function(r,t,e){var n=e(8),o=Function.prototype,a=o.call,i=n&&o.bind.bind(a,a);r.exports=n?i:function(r){return function(){return a.apply(r,arguments)}}},function(r,t,e){var n=e(13),o=n({}.toString),a=n("".slice);r.exports=function(r){return a(o(r),8,-1)}},function(r,t,e){var n=e(16),o=TypeError;r.exports=function(r){if(n(r))throw new o("Can't call method on "+r);return r}},function(t,e,n){t.exports=function(t){return null===t||t===r}},function(r,t,e){var n=e(18),o=e(21);r.exports=function(r){var t=n(r,"string");return o(t)?t:t+""}},function(t,e,n){var o=n(7),a=n(19),i=n(21),c=n(28),u=n(31),f=n(32),s=TypeError,p=f("toPrimitive");t.exports=function(t,e){if(!a(t)||i(t))return t;var n,f=c(t,p);if(f){if(e===r&&(e="default"),n=o(f,t,e),!a(n)||i(n))return n;throw new s("Can't convert object to primitive value")}return e===r&&(e="number"),u(t,e)}},function(r,t,e){var n=e(20);r.exports=function(r){return"object"==typeof r?null!==r:n(r)}},function(t,e,n){var o="object"==typeof document&&document.all;t.exports=void 0===o&&o!==r?function(r){return"function"==typeof r||r===o}:function(r){return"function"==typeof r}},function(r,t,e){var n=e(22),o=e(20),a=e(23),i=e(24),c=Object;r.exports=i?function(r){return"symbol"==typeof r}:function(r){var t=n("Symbol");return o(t)&&a(t.prototype,c(r))}},function(t,e,n){var o=n(3),a=n(20);t.exports=function(t,e){return arguments.length<2?(n=o[t],a(n)?n:r):o[t]&&o[t][e];var n}},function(r,t,e){var n=e(13);r.exports=n({}.isPrototypeOf)},function(r,t,e){var n=e(25);r.exports=n&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},function(r,t,e){var n=e(26),o=e(6),a=e(3).String;r.exports=!!Object.getOwnPropertySymbols&&!o((function(){var r=Symbol("symbol detection");return!a(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&n&&n<41}))},function(r,t,e){var n,o,a=e(3),i=e(27),c=a.process,u=a.Deno,f=c&&c.versions||u&&u.version,s=f&&f.v8;s&&(o=(n=s.split("."))[0]>0&&n[0]<4?1:+(n[0]+n[1])),!o&&i&&(!(n=i.match(/Edge\/(\d+)/))||n[1]>=74)&&(n=i.match(/Chrome\/(\d+)/))&&(o=+n[1]),r.exports=o},function(r,t,e){r.exports="undefined"!=typeof navigator&&String(navigator.userAgent)||""},function(t,e,n){var o=n(29),a=n(16);t.exports=function(t,e){var n=t[e];return a(n)?r:o(n)}},function(r,t,e){var n=e(20),o=e(30),a=TypeError;r.exports=function(r){if(n(r))return r;throw new a(o(r)+" is not a function")}},function(r,t,e){var n=String;r.exports=function(r){try{return n(r)}catch(r){return"Object"}}},function(r,t,e){var n=e(7),o=e(20),a=e(19),i=TypeError;r.exports=function(r,t){var e,c;if("string"===t&&o(e=r.toString)&&!a(c=n(e,r)))return c;if(o(e=r.valueOf)&&!a(c=n(e,r)))return c;if("string"!==t&&o(e=r.toString)&&!a(c=n(e,r)))return c;throw new i("Can't convert object to primitive value")}},function(r,t,e){var n=e(3),o=e(33),a=e(37),i=e(39),c=e(25),u=e(24),f=n.Symbol,s=o("wks"),p=u?f.for||f:f&&f.withoutSetter||i;r.exports=function(r){return a(s,r)||(s[r]=c&&a(f,r)?f[r]:p("Symbol."+r)),s[r]}},function(t,e,n){var o=n(34),a=n(35);(t.exports=function(t,e){return a[t]||(a[t]=e!==r?e:{})})("versions",[]).push({version:"3.35.1",mode:o?"pure":"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.35.1/LICENSE",source:"https://github.com/zloirock/core-js"})},function(r,t,e){r.exports=!1},function(r,t,e){var n=e(3),o=e(36),a="__core-js_shared__",i=n[a]||o(a,{});r.exports=i},function(r,t,e){var n=e(3),o=Object.defineProperty;r.exports=function(r,t){try{o(n,r,{value:t,configurable:!0,writable:!0})}catch(e){n[r]=t}return t}},function(r,t,e){var n=e(13),o=e(38),a=n({}.hasOwnProperty);r.exports=Object.hasOwn||function(r,t){return a(o(r),t)}},function(r,t,e){var n=e(15),o=Object;r.exports=function(r){return o(n(r))}},function(t,e,n){var o=n(13),a=0,i=Math.random(),c=o(1..toString);t.exports=function(t){return"Symbol("+(t===r?"":t)+")_"+c(++a+i,36)}},function(r,t,e){var n=e(5),o=e(6),a=e(41);r.exports=!n&&!o((function(){return 7!==Object.defineProperty(a("div"),"a",{get:function(){return 7}}).a}))},function(r,t,e){var n=e(3),o=e(19),a=n.document,i=o(a)&&o(a.createElement);r.exports=function(r){return i?a.createElement(r):{}}},function(r,t,e){var n=e(5),o=e(43),a=e(10);r.exports=n?function(r,t,e){return o.f(r,t,a(1,e))}:function(r,t,e){return r[t]=e,r}},function(r,t,e){var n=e(5),o=e(40),a=e(44),i=e(45),c=e(17),u=TypeError,f=Object.defineProperty,s=Object.getOwnPropertyDescriptor,p="enumerable",l="configurable",y="writable";t.f=n?a?function(r,t,e){if(i(r),t=c(t),i(e),"function"==typeof r&&"prototype"===t&&"value"in e&&y in e&&!e[y]){var n=s(r,t);n&&n[y]&&(r[t]=e.value,e={configurable:l in e?e[l]:n[l],enumerable:p in e?e[p]:n[p],writable:!1})}return f(r,t,e)}:f:function(r,t,e){if(i(r),t=c(t),i(e),o)try{return f(r,t,e)}catch(r){}if("get"in e||"set"in e)throw new u("Accessors not supported");return"value"in e&&(r[t]=e.value),r}},function(r,t,e){var n=e(5),o=e(6);r.exports=n&&o((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype}))},function(r,t,e){var n=e(19),o=String,a=TypeError;r.exports=function(r){if(n(r))return r;throw new a(o(r)+" is not an object")}},function(t,e,n){var o=n(20),a=n(43),i=n(47),c=n(36);t.exports=function(t,e,n,u){u||(u={});var f=u.enumerable,s=u.name!==r?u.name:e;if(o(n)&&i(n,s,u),u.global)f?t[e]=n:c(e,n);else{try{u.unsafe?t[e]&&(f=!0):delete t[e]}catch(r){}f?t[e]=n:a.f(t,e,{value:n,enumerable:!1,configurable:!u.nonConfigurable,writable:!u.nonWritable})}return t}},function(t,e,n){var o=n(13),a=n(6),i=n(20),c=n(37),u=n(5),f=n(48).CONFIGURABLE,s=n(49),p=n(50),l=p.enforce,y=p.get,v=String,h=Object.defineProperty,g=o("".slice),d=o("".replace),b=o([].join),m=u&&!a((function(){return 8!==h((function(){}),"length",{value:8}).length})),w=String(String).split("String"),x=t.exports=function(t,e,n){"Symbol("===g(v(e),0,7)&&(e="["+d(v(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),n&&n.getter&&(e="get "+e),n&&n.setter&&(e="set "+e),(!c(t,"name")||f&&t.name!==e)&&(u?h(t,"name",{value:e,configurable:!0}):t.name=e),m&&n&&c(n,"arity")&&t.length!==n.arity&&h(t,"length",{value:n.arity});try{n&&c(n,"constructor")&&n.constructor?u&&h(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=r)}catch(r){}var o=l(t);return c(o,"source")||(o.source=b(w,"string"==typeof e?e:"")),t};Function.prototype.toString=x((function(){return i(this)&&y(this).source||s(this)}),"toString")},function(r,t,e){var n=e(5),o=e(37),a=Function.prototype,i=n&&Object.getOwnPropertyDescriptor,c=o(a,"name"),u=c&&"something"===function(){}.name,f=c&&(!n||n&&i(a,"name").configurable);r.exports={EXISTS:c,PROPER:u,CONFIGURABLE:f}},function(r,t,e){var n=e(13),o=e(20),a=e(35),i=n(Function.toString);o(a.inspectSource)||(a.inspectSource=function(r){return i(r)}),r.exports=a.inspectSource},function(r,t,e){var n,o,a,i=e(51),c=e(3),u=e(19),f=e(42),s=e(37),p=e(35),l=e(52),y=e(53),v="Object already initialized",h=c.TypeError,g=c.WeakMap;if(i||p.state){var d=p.state||(p.state=new g);d.get=d.get,d.has=d.has,d.set=d.set,n=function(r,t){if(d.has(r))throw new h(v);return t.facade=r,d.set(r,t),t},o=function(r){return d.get(r)||{}},a=function(r){return d.has(r)}}else{var b=l("state");y[b]=!0,n=function(r,t){if(s(r,b))throw new h(v);return t.facade=r,f(r,b,t),t},o=function(r){return s(r,b)?r[b]:{}},a=function(r){return s(r,b)}}r.exports={set:n,get:o,has:a,enforce:function(r){return a(r)?o(r):n(r,{})},getterFor:function(r){return function(t){var e;if(!u(t)||(e=o(t)).type!==r)throw new h("Incompatible receiver, "+r+" required");return e}}}},function(r,t,e){var n=e(3),o=e(20),a=n.WeakMap;r.exports=o(a)&&/native code/.test(String(a))},function(r,t,e){var n=e(33),o=e(39),a=n("keys");r.exports=function(r){return a[r]||(a[r]=o(r))}},function(r,t,e){r.exports={}},function(r,t,e){var n=e(37),o=e(55),a=e(4),i=e(43);r.exports=function(r,t,e){for(var c=o(t),u=i.f,f=a.f,s=0;s<c.length;s++){var p=c[s];n(r,p)||e&&n(e,p)||u(r,p,f(t,p))}}},function(r,t,e){var n=e(22),o=e(13),a=e(56),i=e(65),c=e(45),u=o([].concat);r.exports=n("Reflect","ownKeys")||function(r){var t=a.f(c(r)),e=i.f;return e?u(t,e(r)):t}},function(r,t,e){var n=e(57),o=e(64).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(r){return n(r,o)}},function(r,t,e){var n=e(13),o=e(37),a=e(11),i=e(58).indexOf,c=e(53),u=n([].push);r.exports=function(r,t){var e,n=a(r),f=0,s=[];for(e in n)!o(c,e)&&o(n,e)&&u(s,e);for(;t.length>f;)o(n,e=t[f++])&&(~i(s,e)||u(s,e));return s}},function(r,t,e){var n=e(11),o=e(59),a=e(62),i=function(r){return function(t,e,i){var c,u=n(t),f=a(u),s=o(i,f);if(r&&e!=e){for(;f>s;)if((c=u[s++])!=c)return!0}else for(;f>s;s++)if((r||s in u)&&u[s]===e)return r||s||0;return!r&&-1}};r.exports={includes:i(!0),indexOf:i(!1)}},function(r,t,e){var n=e(60),o=Math.max,a=Math.min;r.exports=function(r,t){var e=n(r);return e<0?o(e+t,0):a(e,t)}},function(r,t,e){var n=e(61);r.exports=function(r){var t=+r;return t!=t||0===t?0:n(t)}},function(r,t,e){var n=Math.ceil,o=Math.floor;r.exports=Math.trunc||function(r){var t=+r;return(t>0?o:n)(t)}},function(r,t,e){var n=e(63);r.exports=function(r){return n(r.length)}},function(r,t,e){var n=e(60),o=Math.min;r.exports=function(r){var t=n(r);return t>0?o(t,9007199254740991):0}},function(r,t,e){r.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},function(r,t,e){t.f=Object.getOwnPropertySymbols},function(r,t,e){var n=e(6),o=e(20),a=/#|\.prototype\./,i=function(r,t){var e=u[c(r)];return e===s||e!==f&&(o(t)?n(t):!!t)},c=i.normalize=function(r){return String(r).replace(a,".").toLowerCase()},u=i.data={},f=i.NATIVE="N",s=i.POLYFILL="P";r.exports=i},function(r,t,e){var n=e(62);r.exports=function(r,t){for(var e=n(r),o=new t(e),a=0;a<e;a++)o[a]=r[e-a-1];return o}},function(t,e,n){var o=n(32),a=n(69),i=n(43).f,c=o("unscopables"),u=Array.prototype;u[c]===r&&i(u,c,{configurable:!0,value:a(null)}),t.exports=function(r){u[c][r]=!0}},function(t,e,n){var o,a=n(45),i=n(70),c=n(64),u=n(53),f=n(72),s=n(41),p=n(52),l="prototype",y="script",v=p("IE_PROTO"),h=function(){},g=function(r){return"<"+y+">"+r+"</"+y+">"},d=function(r){r.write(g("")),r.close();var t=r.parentWindow.Object;return r=null,t},b=function(){try{o=new ActiveXObject("htmlfile")}catch(r){}var r,t,e;b="undefined"!=typeof document?document.domain&&o?d(o):(t=s("iframe"),e="java"+y+":",t.style.display="none",f.appendChild(t),t.src=String(e),(r=t.contentWindow.document).open(),r.write(g("document.F=Object")),r.close(),r.F):d(o);for(var n=c.length;n--;)delete b[l][c[n]];return b()};u[v]=!0,t.exports=Object.create||function(t,e){var n;return null!==t?(h[l]=a(t),n=new h,h[l]=null,n[v]=t):n=b(),e===r?n:i.f(n,e)}},function(r,t,e){var n=e(5),o=e(44),a=e(43),i=e(45),c=e(11),u=e(71);t.f=n&&!o?Object.defineProperties:function(r,t){i(r);for(var e,n=c(t),o=u(t),f=o.length,s=0;f>s;)a.f(r,e=o[s++],n[e]);return r}},function(r,t,e){var n=e(57),o=e(64);r.exports=Object.keys||function(r){return n(r,o)}},function(r,t,e){var n=e(22);r.exports=n("document","documentElement")},function(t,e,n){var o=n(2),a=n(13),i=n(29),c=n(11),u=n(74),f=n(75),s=n(68),p=Array,l=a(f("Array","sort"));o({target:"Array",proto:!0},{toSorted:function(t){t!==r&&i(t);var e=c(this),n=u(p,e);return l(n,t)}}),s("toSorted")},function(r,t,e){var n=e(62);r.exports=function(r,t,e){for(var o=0,a=arguments.length>2?e:n(t),i=new r(a);a>o;)i[o]=t[o++];return i}},function(r,t,e){var n=e(3);r.exports=function(r,t){var e=n[r],o=e&&e.prototype;return o&&o[t]}},function(r,t,e){var n=e(2),o=e(68),a=e(77),i=e(62),c=e(59),u=e(11),f=e(60),s=Array,p=Math.max,l=Math.min;n({target:"Array",proto:!0},{toSpliced:function(r,t){var e,n,o,y,v=u(this),h=i(v),g=c(r,h),d=arguments.length,b=0;for(0===d?e=n=0:1===d?(e=0,n=h-g):(e=d-2,n=l(p(f(t),0),h-g)),o=a(h+e-n),y=s(o);b<g;b++)y[b]=v[b];for(;b<g+e;b++)y[b]=arguments[b-g+2];for(;b<o;b++)y[b]=v[b+n-e];return y}}),o("toSpliced")},function(r,t,e){var n=TypeError;r.exports=function(r){if(r>9007199254740991)throw n("Maximum allowed index exceeded");return r}},function(r,t,e){var n=e(2),o=e(79),a=e(11),i=Array;n({target:"Array",proto:!0},{with:function(r,t){return o(a(this),i,r,t)}})},function(r,t,e){var n=e(62),o=e(60),a=RangeError;r.exports=function(r,t,e,i){var c=n(r),u=o(e),f=u<0?c+u:u;if(f>=c||f<0)throw new a("Incorrect index");for(var s=new t(c),p=0;p<c;p++)s[p]=p===f?i:r[p];return s}},function(r,t,e){var n=e(2),o=e(13),a=e(29),i=e(15),c=e(81),u=e(91),f=e(34),s=u.Map,p=u.has,l=u.get,y=u.set,v=o([].push);n({target:"Map",stat:!0,forced:f},{groupBy:function(r,t){i(r),a(t);var e=new s,n=0;return c(r,(function(r){var o=t(r,n++);p(e,o)?v(l(e,o),r):y(e,o,[r])})),e}})},function(r,t,e){var n=e(82),o=e(7),a=e(45),i=e(30),c=e(84),u=e(62),f=e(23),s=e(86),p=e(87),l=e(90),y=TypeError,v=function(r,t){this.stopped=r,this.result=t},h=v.prototype;r.exports=function(r,t,e){var g,d,b,m,w,x,E,A=e&&e.that,O=!(!e||!e.AS_ENTRIES),S=!(!e||!e.IS_RECORD),R=!(!e||!e.IS_ITERATOR),T=!(!e||!e.INTERRUPTED),_=n(t,A),I=function(r){return g&&l(g,"normal",r),new v(!0,r)},j=function(r){return O?(a(r),T?_(r[0],r[1],I):_(r[0],r[1])):T?_(r,I):_(r)};if(S)g=r.iterator;else if(R)g=r;else{if(!(d=p(r)))throw new y(i(r)+" is not iterable");if(c(d)){for(b=0,m=u(r);m>b;b++)if((w=j(r[b]))&&f(h,w))return w;return new v(!1)}g=s(r,d)}for(x=S?r.next:g.next;!(E=o(x,g)).done;){try{w=j(E.value)}catch(r){l(g,"throw",r)}if("object"==typeof w&&w&&f(h,w))return w}return new v(!1)}},function(t,e,n){var o=n(83),a=n(29),i=n(8),c=o(o.bind);t.exports=function(t,e){return a(t),e===r?t:i?c(t,e):function(){return t.apply(e,arguments)}}},function(r,t,e){var n=e(14),o=e(13);r.exports=function(r){if("Function"===n(r))return o(r)}},function(t,e,n){var o=n(32),a=n(85),i=o("iterator"),c=Array.prototype;t.exports=function(t){return t!==r&&(a.Array===t||c[i]===t)}},function(r,t,e){r.exports={}},function(r,t,e){var n=e(7),o=e(29),a=e(45),i=e(30),c=e(87),u=TypeError;r.exports=function(r,t){var e=arguments.length<2?c(r):t;if(o(e))return a(n(e,r));throw new u(i(r)+" is not iterable")}},function(r,t,e){var n=e(88),o=e(28),a=e(16),i=e(85),c=e(32)("iterator");r.exports=function(r){if(!a(r))return o(r,c)||o(r,"@@iterator")||i[n(r)]}},function(t,e,n){var o=n(89),a=n(20),i=n(14),c=n(32)("toStringTag"),u=Object,f="Arguments"===i(function(){return arguments}());t.exports=o?i:function(t){var e,n,o;return t===r?"Undefined":null===t?"Null":"string"==typeof(n=function(r,t){try{return r[t]}catch(r){}}(e=u(t),c))?n:f?i(e):"Object"===(o=i(e))&&a(e.callee)?"Arguments":o}},function(r,t,e){var n={};n[e(32)("toStringTag")]="z",r.exports="[object z]"===String(n)},function(r,t,e){var n=e(7),o=e(45),a=e(28);r.exports=function(r,t,e){var i,c;o(r);try{if(!(i=a(r,"return"))){if("throw"===t)throw e;return e}i=n(i,r)}catch(r){c=!0,i=r}if("throw"===t)throw e;if(c)throw i;return o(i),e}},function(r,t,e){var n=e(13),o=Map.prototype;r.exports={Map,set:n(o.set),get:n(o.get),has:n(o.has),remove:n(o.delete),proto:o}},function(r,t,e){var n=e(2),o=e(22),a=e(13),i=e(29),c=e(15),u=e(17),f=e(81),s=o("Object","create"),p=a([].push);n({target:"Object",stat:!0},{groupBy:function(r,t){c(r),i(t);var e=s(null),n=0;return f(r,(function(r){var o=u(t(r,n++));o in e?p(e[o],r):e[o]=[r]})),e}})},function(r,t,e){var n=e(2),o=e(94);n({target:"Promise",stat:!0},{withResolvers:function(){var r=o.f(this);return{promise:r.promise,resolve:r.resolve,reject:r.reject}}})},function(t,e,n){var o=n(29),a=TypeError,i=function(t){var e,n;this.promise=new t((function(t,o){if(e!==r||n!==r)throw new a("Bad Promise constructor");e=t,n=o})),this.resolve=o(e),this.reject=o(n)};t.exports.f=function(r){return new i(r)}},function(r,t,e){var n=e(3),o=e(5),a=e(96),i=e(97),c=e(6),u=n.RegExp,f=u.prototype;o&&c((function(){var r=!0;try{u(".","d")}catch(t){r=!1}var t={},e="",n=r?"dgimsy":"gimsy",o=function(r,n){Object.defineProperty(t,r,{get:function(){return e+=n,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var i in r&&(a.hasIndices="d"),a)o(i,a[i]);return Object.getOwnPropertyDescriptor(f,"flags").get.call(t)!==n||e!==n}))&&a(f,"flags",{configurable:!0,get:i})},function(r,t,e){var n=e(47),o=e(43);r.exports=function(r,t,e){return e.get&&n(e.get,t,{getter:!0}),e.set&&n(e.set,t,{setter:!0}),o.f(r,t,e)}},function(r,t,e){var n=e(45);r.exports=function(){var r=n(this),t="";return r.hasIndices&&(t+="d"),r.global&&(t+="g"),r.ignoreCase&&(t+="i"),r.multiline&&(t+="m"),r.dotAll&&(t+="s"),r.unicode&&(t+="u"),r.unicodeSets&&(t+="v"),r.sticky&&(t+="y"),t}},function(r,t,e){var n=e(2),o=e(13),a=e(15),i=e(99),c=o("".charCodeAt);n({target:"String",proto:!0},{isWellFormed:function(){for(var r=i(a(this)),t=r.length,e=0;e<t;e++){var n=c(r,e);if(55296==(63488&n)&&(n>=56320||++e>=t||56320!=(64512&c(r,e))))return!1}return!0}})},function(r,t,e){var n=e(88),o=String;r.exports=function(r){if("Symbol"===n(r))throw new TypeError("Cannot convert a Symbol value to a string");return o(r)}},function(r,t,e){var n=e(2),o=e(7),a=e(13),i=e(15),c=e(99),u=e(6),f=Array,s=a("".charAt),p=a("".charCodeAt),l=a([].join),y="".toWellFormed,v=y&&u((function(){return"1"!==o(y,1)}));n({target:"String",proto:!0,forced:v},{toWellFormed:function(){var r=c(i(this));if(v)return o(y,r);for(var t=r.length,e=f(t),n=0;n<t;n++){var a=p(r,n);55296!=(63488&a)?e[n]=s(r,n):a>=56320||n+1>=t||56320!=(64512&p(r,n+1))?e[n]="�":(e[n]=s(r,n),e[++n]=s(r,n))}return l(e,"")}})},function(r,t,e){var n=e(67),o=e(102),a=o.aTypedArray,i=o.exportTypedArrayMethod,c=o.getTypedArrayConstructor;i("toReversed",(function(){return n(a(this),c(this))}))},function(t,e,n){var o,a,i,c=n(103),u=n(5),f=n(3),s=n(20),p=n(19),l=n(37),y=n(88),v=n(30),h=n(42),g=n(46),d=n(96),b=n(23),m=n(104),w=n(106),x=n(32),E=n(39),A=n(50),O=A.enforce,S=A.get,R=f.Int8Array,T=R&&R.prototype,_=f.Uint8ClampedArray,I=_&&_.prototype,j=R&&m(R),M=T&&m(T),D=Object.prototype,P=f.TypeError,k=x("toStringTag"),C=E("TYPED_ARRAY_TAG"),U="TypedArrayConstructor",L=c&&!!w&&"Opera"!==y(f.opera),N=!1,F={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},B={BigInt64Array:8,BigUint64Array:8},V=function(r){var t=m(r);if(p(t)){var e=S(t);return e&&l(e,U)?e[U]:V(t)}},z=function(r){if(!p(r))return!1;var t=y(r);return l(F,t)||l(B,t)};for(o in F)(i=(a=f[o])&&a.prototype)?O(i)[U]=a:L=!1;for(o in B)(i=(a=f[o])&&a.prototype)&&(O(i)[U]=a);if((!L||!s(j)||j===Function.prototype)&&(j=function(){throw new P("Incorrect invocation")},L))for(o in F)f[o]&&w(f[o],j);if((!L||!M||M===D)&&(M=j.prototype,L))for(o in F)f[o]&&w(f[o].prototype,M);if(L&&m(I)!==M&&w(I,M),u&&!l(M,k))for(o in N=!0,d(M,k,{configurable:!0,get:function(){return p(this)?this[C]:r}}),F)f[o]&&h(f[o],C,o);t.exports={NATIVE_ARRAY_BUFFER_VIEWS:L,TYPED_ARRAY_TAG:N&&C,aTypedArray:function(r){if(z(r))return r;throw new P("Target is not a typed array")},aTypedArrayConstructor:function(r){if(s(r)&&(!w||b(j,r)))return r;throw new P(v(r)+" is not a typed array constructor")},exportTypedArrayMethod:function(r,t,e,n){if(u){if(e)for(var o in F){var a=f[o];if(a&&l(a.prototype,r))try{delete a.prototype[r]}catch(e){try{a.prototype[r]=t}catch(r){}}}M[r]&&!e||g(M,r,e?t:L&&T[r]||t,n)}},exportTypedArrayStaticMethod:function(r,t,e){var n,o;if(u){if(w){if(e)for(n in F)if((o=f[n])&&l(o,r))try{delete o[r]}catch(r){}if(j[r]&&!e)return;try{return g(j,r,e?t:L&&j[r]||t)}catch(r){}}for(n in F)!(o=f[n])||o[r]&&!e||g(o,r,t)}},getTypedArrayConstructor:V,isView:function(r){if(!p(r))return!1;var t=y(r);return"DataView"===t||l(F,t)||l(B,t)},isTypedArray:z,TypedArray:j,TypedArrayPrototype:M}},function(r,t,e){r.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},function(r,t,e){var n=e(37),o=e(20),a=e(38),i=e(52),c=e(105),u=i("IE_PROTO"),f=Object,s=f.prototype;r.exports=c?f.getPrototypeOf:function(r){var t=a(r);if(n(t,u))return t[u];var e=t.constructor;return o(e)&&t instanceof e?e.prototype:t instanceof f?s:null}},function(r,t,e){var n=e(6);r.exports=!n((function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype}))},function(t,e,n){var o=n(107),a=n(45),i=n(108);t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r,t=!1,e={};try{(r=o(Object.prototype,"__proto__","set"))(e,[]),t=e instanceof Array}catch(r){}return function(e,n){return a(e),i(n),t?r(e,n):e.__proto__=n,e}}():r)},function(r,t,e){var n=e(13),o=e(29);r.exports=function(r,t,e){try{return n(o(Object.getOwnPropertyDescriptor(r,t)[e]))}catch(r){}}},function(r,t,e){var n=e(109),o=String,a=TypeError;r.exports=function(r){if(n(r))return r;throw new a("Can't set "+o(r)+" as a prototype")}},function(r,t,e){var n=e(19);r.exports=function(r){return n(r)||null===r}},function(t,e,n){var o=n(102),a=n(13),i=n(29),c=n(74),u=o.aTypedArray,f=o.getTypedArrayConstructor,s=o.exportTypedArrayMethod,p=a(o.TypedArrayPrototype.sort);s("toSorted",(function(t){t!==r&&i(t);var e=u(this),n=c(f(e),e);return p(n,t)}))},function(r,t,e){var n=e(79),o=e(102),a=e(112),i=e(60),c=e(113),u=o.aTypedArray,f=o.getTypedArrayConstructor,s=o.exportTypedArrayMethod,p=!!function(){try{new Int8Array(1).with(2,{valueOf:function(){throw 8}})}catch(r){return 8===r}}();s("with",{with:function(r,t){var e=u(this),o=i(r),s=a(e)?c(t):+t;return n(e,f(e),o,s)}}.with,!p)},function(r,t,e){var n=e(88);r.exports=function(r){var t=n(r);return"BigInt64Array"===t||"BigUint64Array"===t}},function(r,t,e){var n=e(18),o=TypeError;r.exports=function(r){var t=n(r,"number");if("number"==typeof t)throw new o("Can't convert number to bigint");return BigInt(t)}},function(t,e,n){var o=n(2),a=n(3),i=n(22),c=n(10),u=n(43).f,f=n(37),s=n(115),p=n(116),l=n(117),y=n(118),v=n(119),h=n(5),g=n(34),d="DOMException",b=i("Error"),m=i(d),w=function(){s(this,x);var t=arguments.length,e=l(t<1?r:arguments[0]),n=l(t<2?r:arguments[1],"Error"),o=new m(e,n),a=new b(e);return a.name=d,u(o,"stack",c(1,v(a.stack,1))),p(o,this,w),o},x=w.prototype=m.prototype,E="stack"in new b(d),A="stack"in new m(1,2),O=m&&h&&Object.getOwnPropertyDescriptor(a,d),S=!(!O||O.writable&&O.configurable),R=E&&!S&&!A;o({global:!0,constructor:!0,forced:g||R},{DOMException:R?w:m});var T=i(d),_=T.prototype;if(_.constructor!==T)for(var I in g||u(_,"constructor",c(1,T)),y)if(f(y,I)){var j=y[I],M=j.s;f(T,M)||u(T,M,c(6,j.c))}},function(r,t,e){var n=e(23),o=TypeError;r.exports=function(r,t){if(n(t,r))return r;throw new o("Incorrect invocation")}},function(r,t,e){var n=e(20),o=e(19),a=e(106);r.exports=function(r,t,e){var i,c;return a&&n(i=t.constructor)&&i!==e&&o(c=i.prototype)&&c!==e.prototype&&a(r,c),r}},function(t,e,n){var o=n(99);t.exports=function(t,e){return t===r?arguments.length<2?"":e:o(t)}},function(r,t,e){r.exports={IndexSizeError:{s:"INDEX_SIZE_ERR",c:1,m:1},DOMStringSizeError:{s:"DOMSTRING_SIZE_ERR",c:2,m:0},HierarchyRequestError:{s:"HIERARCHY_REQUEST_ERR",c:3,m:1},WrongDocumentError:{s:"WRONG_DOCUMENT_ERR",c:4,m:1},InvalidCharacterError:{s:"INVALID_CHARACTER_ERR",c:5,m:1},NoDataAllowedError:{s:"NO_DATA_ALLOWED_ERR",c:6,m:0},NoModificationAllowedError:{s:"NO_MODIFICATION_ALLOWED_ERR",c:7,m:1},NotFoundError:{s:"NOT_FOUND_ERR",c:8,m:1},NotSupportedError:{s:"NOT_SUPPORTED_ERR",c:9,m:1},InUseAttributeError:{s:"INUSE_ATTRIBUTE_ERR",c:10,m:1},InvalidStateError:{s:"INVALID_STATE_ERR",c:11,m:1},SyntaxError:{s:"SYNTAX_ERR",c:12,m:1},InvalidModificationError:{s:"INVALID_MODIFICATION_ERR",c:13,m:1},NamespaceError:{s:"NAMESPACE_ERR",c:14,m:1},InvalidAccessError:{s:"INVALID_ACCESS_ERR",c:15,m:1},ValidationError:{s:"VALIDATION_ERR",c:16,m:0},TypeMismatchError:{s:"TYPE_MISMATCH_ERR",c:17,m:1},SecurityError:{s:"SECURITY_ERR",c:18,m:1},NetworkError:{s:"NETWORK_ERR",c:19,m:1},AbortError:{s:"ABORT_ERR",c:20,m:1},URLMismatchError:{s:"URL_MISMATCH_ERR",c:21,m:1},QuotaExceededError:{s:"QUOTA_EXCEEDED_ERR",c:22,m:1},TimeoutError:{s:"TIMEOUT_ERR",c:23,m:1},InvalidNodeTypeError:{s:"INVALID_NODE_TYPE_ERR",c:24,m:1},DataCloneError:{s:"DATA_CLONE_ERR",c:25,m:1}}},function(r,t,e){var n=e(13),o=Error,a=n("".replace),i=String(new o("zxcasd").stack),c=/\n\s*at [^:]*:[^\n]*/,u=c.test(i);r.exports=function(r,t){if(u&&"string"==typeof r&&!o.prepareStackTrace)for(;t--;)r=a(r,c,"");return r}},function(t,e,n){var o,a=n(34),i=n(2),c=n(3),u=n(22),f=n(13),s=n(6),p=n(39),l=n(20),y=n(121),v=n(16),h=n(19),g=n(21),d=n(81),b=n(45),m=n(88),w=n(37),x=n(122),E=n(42),A=n(62),O=n(123),S=n(124),R=n(91),T=n(125),_=n(126),I=n(128),j=n(134),M=n(131),D=c.Object,P=c.Array,k=c.Date,C=c.Error,U=c.TypeError,L=c.PerformanceMark,N=u("DOMException"),F=R.Map,B=R.has,V=R.get,z=R.set,W=T.Set,G=T.add,Y=T.has,H=u("Object","keys"),Q=f([].push),X=f((!0).valueOf),q=f(1..valueOf),K=f("".valueOf),Z=f(k.prototype.getTime),$=p("structuredClone"),J="DataCloneError",rr="Transferring",tr=function(r){return!s((function(){var t=new c.Set([7]),e=r(t),n=r(D(7));return e===t||!e.has(7)||!h(n)||7!=+n}))&&r},er=function(r,t){return!s((function(){var e=new t,n=r({a:e,b:e});return!(n&&n.a===n.b&&n.a instanceof t&&n.a.stack===e.stack)}))},nr=c.structuredClone,or=a||!er(nr,C)||!er(nr,N)||(o=nr,!!s((function(){var r=o(new c.AggregateError([1],$,{cause:3}));return"AggregateError"!==r.name||1!==r.errors[0]||r.message!==$||3!==r.cause}))),ar=!nr&&tr((function(r){return new L($,{detail:r}).detail})),ir=tr(nr)||ar,cr=function(r){throw new N("Uncloneable type: "+r,J)},ur=function(r,t){throw new N((t||"Cloning")+" of "+r+" cannot be properly polyfilled in this engine",J)},fr=function(r,t){return ir||ur(t),ir(r)},sr=function(t,e,n){if(B(e,t))return V(e,t);var o,a,i,u,f,s;if("SharedArrayBuffer"===(n||m(t)))o=ir?ir(t):t;else{var p=c.DataView;p||l(t.slice)||ur("ArrayBuffer");try{if(l(t.slice)&&!t.resizable)o=t.slice(0);else{a=t.byteLength,i="maxByteLength"in t?{maxByteLength:t.maxByteLength}:r,o=new ArrayBuffer(a,i),u=new p(t),f=new p(o);for(s=0;s<a;s++)f.setUint8(s,u.getUint8(s))}}catch(r){throw new N("ArrayBuffer is detached",J)}}return z(e,t,o),o},pr=function(t,e){if(g(t)&&cr("Symbol"),!h(t))return t;if(e){if(B(e,t))return V(e,t)}else e=new F;var n,o,a,i,f,s,p,y,v=m(t);switch(v){case"Array":a=P(A(t));break;case"Object":a={};break;case"Map":a=new F;break;case"Set":a=new W;break;case"RegExp":a=new RegExp(t.source,S(t));break;case"Error":switch(o=t.name){case"AggregateError":a=new(u(o))([]);break;case"EvalError":case"RangeError":case"ReferenceError":case"SuppressedError":case"SyntaxError":case"TypeError":case"URIError":a=new(u(o));break;case"CompileError":case"LinkError":case"RuntimeError":a=new(u("WebAssembly",o));break;default:a=new C}break;case"DOMException":a=new N(t.message,t.name);break;case"ArrayBuffer":case"SharedArrayBuffer":a=sr(t,e,v);break;case"DataView":case"Int8Array":case"Uint8Array":case"Uint8ClampedArray":case"Int16Array":case"Uint16Array":case"Int32Array":case"Uint32Array":case"Float16Array":case"Float32Array":case"Float64Array":case"BigInt64Array":case"BigUint64Array":s="DataView"===v?t.byteLength:t.length,a=function(r,t,e,n,o){var a=c[t];return h(a)||ur(t),new a(sr(r.buffer,o),e,n)}(t,v,t.byteOffset,s,e);break;case"DOMQuad":try{a=new DOMQuad(pr(t.p1,e),pr(t.p2,e),pr(t.p3,e),pr(t.p4,e))}catch(r){a=fr(t,v)}break;case"File":if(ir)try{a=ir(t),m(a)!==v&&(a=r)}catch(r){}if(!a)try{a=new File([t],t.name,t)}catch(r){}a||ur(v);break;case"FileList":if(i=function(){var r;try{r=new c.DataTransfer}catch(t){try{r=new c.ClipboardEvent("").clipboardData}catch(r){}}return r&&r.items&&r.files?r:null}()){for(f=0,s=A(t);f<s;f++)i.items.add(pr(t[f],e));a=i.files}else a=fr(t,v);break;case"ImageData":try{a=new ImageData(pr(t.data,e),t.width,t.height,{colorSpace:t.colorSpace})}catch(r){a=fr(t,v)}break;default:if(ir)a=ir(t);else switch(v){case"BigInt":a=D(t.valueOf());break;case"Boolean":a=D(X(t));break;case"Number":a=D(q(t));break;case"String":a=D(K(t));break;case"Date":a=new k(Z(t));break;case"Blob":try{a=t.slice(0,t.size,t.type)}catch(r){ur(v)}break;case"DOMPoint":case"DOMPointReadOnly":n=c[v];try{a=n.fromPoint?n.fromPoint(t):new n(t.x,t.y,t.z,t.w)}catch(r){ur(v)}break;case"DOMRect":case"DOMRectReadOnly":n=c[v];try{a=n.fromRect?n.fromRect(t):new n(t.x,t.y,t.width,t.height)}catch(r){ur(v)}break;case"DOMMatrix":case"DOMMatrixReadOnly":n=c[v];try{a=n.fromMatrix?n.fromMatrix(t):new n(t)}catch(r){ur(v)}break;case"AudioData":case"VideoFrame":l(t.clone)||ur(v);try{a=t.clone()}catch(r){cr(v)}break;case"CropTarget":case"CryptoKey":case"FileSystemDirectoryHandle":case"FileSystemFileHandle":case"FileSystemHandle":case"GPUCompilationInfo":case"GPUCompilationMessage":case"ImageBitmap":case"RTCCertificate":case"WebAssembly.Module":ur(v);default:cr(v)}}switch(z(e,t,a),v){case"Array":case"Object":for(p=H(t),f=0,s=A(p);f<s;f++)y=p[f],x(a,y,pr(t[y],e));break;case"Map":t.forEach((function(r,t){z(a,pr(t,e),pr(r,e))}));break;case"Set":t.forEach((function(r){G(a,pr(r,e))}));break;case"Error":E(a,"message",pr(t.message,e)),w(t,"cause")&&E(a,"cause",pr(t.cause,e)),"AggregateError"===o?a.errors=pr(t.errors,e):"SuppressedError"===o&&(a.error=pr(t.error,e),a.suppressed=pr(t.suppressed,e));case"DOMException":j&&E(a,"stack",pr(t.stack,e))}return a};i({global:!0,enumerable:!0,sham:!M,forced:or},{structuredClone:function(t){var e,n,o=O(arguments.length,1)>1&&!v(arguments[1])?b(arguments[1]):r,a=o?o.transfer:r;a!==r&&(n=function(t,e){if(!h(t))throw new U("Transfer option cannot be converted to a sequence");var n=[];d(t,(function(r){Q(n,b(r))}));for(var o,a,i,u,f,s=0,p=A(n),v=new W;s<p;){if(o=n[s++],"ArrayBuffer"===(a=m(o))?Y(v,o):B(e,o))throw new N("Duplicate transferable",J);if("ArrayBuffer"!==a){if(M)u=nr(o,{transfer:[o]});else switch(a){case"ImageBitmap":i=c.OffscreenCanvas,y(i)||ur(a,rr);try{(f=new i(o.width,o.height)).getContext("bitmaprenderer").transferFromImageBitmap(o),u=f.transferToImageBitmap()}catch(r){}break;case"AudioData":case"VideoFrame":l(o.clone)&&l(o.close)||ur(a,rr);try{u=o.clone(),o.close()}catch(r){}break;case"MediaSourceHandle":case"MessagePort":case"OffscreenCanvas":case"ReadableStream":case"TransformStream":case"WritableStream":ur(a,rr)}if(u===r)throw new N("This object cannot be transferred: "+a,J);z(e,o,u)}else G(v,o)}return v}(a,e=new F));var i=pr(t,e);return n&&function(r){_(r,(function(r){M?ir(r,{transfer:[r]}):l(r.transfer)?r.transfer():I?I(r):ur("ArrayBuffer",rr)}))}(n),i}})},function(r,t,e){var n=e(13),o=e(6),a=e(20),i=e(88),c=e(22),u=e(49),f=function(){},s=c("Reflect","construct"),p=/^\s*(?:class|function)\b/,l=n(p.exec),y=!p.test(f),v=function(r){if(!a(r))return!1;try{return s(f,[],r),!0}catch(r){return!1}},h=function(r){if(!a(r))return!1;switch(i(r)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return y||!!l(p,u(r))}catch(r){return!0}};h.sham=!0,r.exports=!s||o((function(){var r;return v(v.call)||!v(Object)||!v((function(){r=!0}))||r}))?h:v},function(r,t,e){var n=e(17),o=e(43),a=e(10);r.exports=function(r,t,e){var i=n(t);i in r?o.f(r,i,a(0,e)):r[i]=e}},function(r,t,e){var n=TypeError;r.exports=function(r,t){if(r<t)throw new n("Not enough arguments");return r}},function(t,e,n){var o=n(7),a=n(37),i=n(23),c=n(97),u=RegExp.prototype;t.exports=function(t){var e=t.flags;return e!==r||"flags"in u||a(t,"flags")||!i(u,t)?e:o(c,t)}},function(r,t,e){var n=e(13),o=Set.prototype;r.exports={Set,add:n(o.add),has:n(o.has),remove:n(o.delete),proto:o}},function(r,t,e){var n=e(13),o=e(127),a=e(125),i=a.Set,c=a.proto,u=n(c.forEach),f=n(c.keys),s=f(new i).next;r.exports=function(r,t,e){return e?o({iterator:f(r),next:s},t):u(r,t)}},function(t,e,n){var o=n(7);t.exports=function(t,e,n){for(var a,i,c=n?t:t.iterator,u=t.next;!(a=o(u,c)).done;)if((i=e(a.value))!==r)return i}},function(r,t,e){var n,o,a,i,c=e(3),u=e(129),f=e(131),s=c.structuredClone,p=c.ArrayBuffer,l=c.MessageChannel,y=!1;if(f)y=function(r){s(r,{transfer:[r]})};else if(p)try{l||(n=u("worker_threads"))&&(l=n.MessageChannel),l&&(o=new l,a=new p(2),i=function(r){o.port1.postMessage(null,[r])},2===a.byteLength&&(i(a),0===a.byteLength&&(y=i)))}catch(r){}r.exports=y},function(r,t,e){var n=e(130);r.exports=function(r){try{if(n)return Function('return require("'+r+'")')()}catch(r){}}},function(r,t,e){var n=e(3),o=e(14);r.exports="process"===o(n.process)},function(r,t,e){var n=e(3),o=e(6),a=e(26),i=e(132),c=e(133),u=e(130),f=n.structuredClone;r.exports=!!f&&!o((function(){if(c&&a>92||u&&a>94||i&&a>97)return!1;var r=new ArrayBuffer(8),t=f(r,{transfer:[r]});return 0!==r.byteLength||8!==t.byteLength}))},function(r,t,e){var n=e(133),o=e(130);r.exports=!n&&!o&&"object"==typeof window&&"object"==typeof document},function(r,t,e){r.exports="object"==typeof Deno&&Deno&&"object"==typeof Deno.version},function(r,t,e){var n=e(6),o=e(10);r.exports=!n((function(){var r=new Error("a");return!("stack"in r)||(Object.defineProperty(r,"stack",o(1,7)),7!==r.stack)}))},function(t,e,n){var o=n(2),a=n(22),i=n(6),c=n(123),u=n(99),f=n(136),s=a("URL");o({target:"URL",stat:!0,forced:!(f&&i((function(){s.canParse()})))},{canParse:function(t){var e=c(arguments.length,1),n=u(t),o=e<2||arguments[1]===r?r:u(arguments[1]);try{return!!new s(n,o)}catch(r){return!1}}})},function(t,e,n){var o=n(6),a=n(32),i=n(5),c=n(34),u=a("iterator");t.exports=!o((function(){var t=new URL("b?a=1&b=2&c=3","http://a"),e=t.searchParams,n=new URLSearchParams("a=1&a=2&b=3"),o="";return t.pathname="c%20d",e.forEach((function(r,t){e.delete("b"),o+=t+r})),n.delete("a",2),n.delete("b",r),c&&(!t.toJSON||!n.has("a",1)||n.has("a",2)||!n.has("a",r)||n.has("b"))||!e.size&&(c||!i)||!e.sort||"http://a/c%20d?a=1&c=3"!==t.href||"3"!==e.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!e[u]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==o||"x"!==new URL("http://x",r).host}))},function(t,e,n){var o=n(46),a=n(13),i=n(99),c=n(123),u=URLSearchParams,f=u.prototype,s=a(f.append),p=a(f.delete),l=a(f.forEach),y=a([].push),v=new u("a=1&a=2&b=3");v.delete("a",1),v.delete("b",r),v+""!="a=2"&&o(f,"delete",(function(t){var e=arguments.length,n=e<2?r:arguments[1];if(e&&n===r)return p(this,t);var o=[];l(this,(function(r,t){y(o,{key:t,value:r})})),c(e,1);for(var a,u=i(t),f=i(n),v=0,h=0,g=!1,d=o.length;v<d;)a=o[v++],g||a.key===u?(g=!0,p(this,a.key)):h++;for(;h<d;)(a=o[h++]).key===u&&a.value===f||s(this,a.key,a.value)}),{enumerable:!0,unsafe:!0})},function(t,e,n){var o=n(46),a=n(13),i=n(99),c=n(123),u=URLSearchParams,f=u.prototype,s=a(f.getAll),p=a(f.has),l=new u("a=1");!l.has("a",2)&&l.has("a",r)||o(f,"has",(function(t){var e=arguments.length,n=e<2?r:arguments[1];if(e&&n===r)return p(this,t);var o=s(this,t);c(e,1);for(var a=i(n),u=0;u<o.length;)if(o[u++]===a)return!0;return!1}),{enumerable:!0,unsafe:!0})},function(r,t,e){var n=e(5),o=e(13),a=e(96),i=URLSearchParams.prototype,c=o(i.forEach);n&&!("size"in i)&&a(i,"size",{get:function(){var r=0;return c(this,(function(){r++})),r},configurable:!0,enumerable:!0})}],e={},(n=function(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}).m=t,n.c=e,n.d=function(r,t,e){n.o(r,t)||Object.defineProperty(r,t,{enumerable:!0,get:e})},n.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},n.t=function(r,t){if(1&t&&(r=n(r)),8&t)return r;if(4&t&&"object"==typeof r&&r&&r.__esModule)return r;var e=Object.create(null);if(n.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:r}),2&t&&"string"!=typeof r)for(var o in r)n.d(e,o,function(t){return r[t]}.bind(null,o));return e},n.n=function(r){var t=r&&r.__esModule?function(){return r.default}:function(){return r};return n.d(t,"a",t),t},n.o=function(r,t){return Object.prototype.hasOwnProperty.call(r,t)},n.p="",n(n.s=0)}(); wp-polyfill-formdata.js 0000644 00000027142 14720015030 0011151 0 ustar 00 /* formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */ /* global FormData self Blob File */ /* eslint-disable no-inner-declarations */ if (typeof Blob !== 'undefined' && (typeof FormData === 'undefined' || !FormData.prototype.keys)) { const global = typeof globalThis === 'object' ? globalThis : typeof window === 'object' ? window : typeof self === 'object' ? self : this // keep a reference to native implementation const _FormData = global.FormData // To be monkey patched const _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send const _fetch = global.Request && global.fetch const _sendBeacon = global.navigator && global.navigator.sendBeacon // Might be a worker thread... const _match = global.Element && global.Element.prototype // Unable to patch Request/Response constructor correctly #109 // only way is to use ES6 class extend // https://github.com/babel/babel/issues/1966 const stringTag = global.Symbol && Symbol.toStringTag // Add missing stringTags to blob and files if (stringTag) { if (!Blob.prototype[stringTag]) { Blob.prototype[stringTag] = 'Blob' } if ('File' in global && !File.prototype[stringTag]) { File.prototype[stringTag] = 'File' } } // Fix so you can construct your own File try { new File([], '') // eslint-disable-line } catch (a) { global.File = function File (b, d, c) { const blob = new Blob(b, c || {}) const t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date() Object.defineProperties(blob, { name: { value: d }, lastModified: { value: +t }, toString: { value () { return '[object File]' } } }) if (stringTag) { Object.defineProperty(blob, stringTag, { value: 'File' }) } return blob } } function ensureArgs (args, expected) { if (args.length < expected) { throw new TypeError(`${expected} argument required, but only ${args.length} present.`) } } /** * @param {string} name * @param {string | undefined} filename * @returns {[string, File|string]} */ function normalizeArgs (name, value, filename) { if (value instanceof Blob) { filename = filename !== undefined ? String(filename + '') : typeof value.name === 'string' ? value.name : 'blob' if (value.name !== filename || Object.prototype.toString.call(value) === '[object Blob]') { value = new File([value], filename) } return [String(name), value] } return [String(name), String(value)] } // normalize line feeds for textarea // https://html.spec.whatwg.org/multipage/form-elements.html#textarea-line-break-normalisation-transformation function normalizeLinefeeds (value) { return value.replace(/\r?\n|\r/g, '\r\n') } /** * @template T * @param {ArrayLike<T>} arr * @param {{ (elm: T): void; }} cb */ function each (arr, cb) { for (let i = 0; i < arr.length; i++) { cb(arr[i]) } } const escape = str => str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') /** * @implements {Iterable} */ class FormDataPolyfill { /** * FormData class * * @param {HTMLFormElement=} form */ constructor (form) { /** @type {[string, string|File][]} */ this._data = [] const self = this form && each(form.elements, (/** @type {HTMLInputElement} */ elm) => { if ( !elm.name || elm.disabled || elm.type === 'submit' || elm.type === 'button' || elm.matches('form fieldset[disabled] *') ) return if (elm.type === 'file') { const files = elm.files && elm.files.length ? elm.files : [new File([], '', { type: 'application/octet-stream' })] // #78 each(files, file => { self.append(elm.name, file) }) } else if (elm.type === 'select-multiple' || elm.type === 'select-one') { each(elm.options, opt => { !opt.disabled && opt.selected && self.append(elm.name, opt.value) }) } else if (elm.type === 'checkbox' || elm.type === 'radio') { if (elm.checked) self.append(elm.name, elm.value) } else { const value = elm.type === 'textarea' ? normalizeLinefeeds(elm.value) : elm.value self.append(elm.name, value) } }) } /** * Append a field * * @param {string} name field name * @param {string|Blob|File} value string / blob / file * @param {string=} filename filename to use with blob * @return {undefined} */ append (name, value, filename) { ensureArgs(arguments, 2) this._data.push(normalizeArgs(name, value, filename)) } /** * Delete all fields values given name * * @param {string} name Field name * @return {undefined} */ delete (name) { ensureArgs(arguments, 1) const result = [] name = String(name) each(this._data, entry => { entry[0] !== name && result.push(entry) }) this._data = result } /** * Iterate over all fields as [name, value] * * @return {Iterator} */ * entries () { for (var i = 0; i < this._data.length; i++) { yield this._data[i] } } /** * Iterate over all fields * * @param {Function} callback Executed for each item with parameters (value, name, thisArg) * @param {Object=} thisArg `this` context for callback function */ forEach (callback, thisArg) { ensureArgs(arguments, 1) for (const [name, value] of this) { callback.call(thisArg, value, name, this) } } /** * Return first field value given name * or null if non existent * * @param {string} name Field name * @return {string|File|null} value Fields value */ get (name) { ensureArgs(arguments, 1) const entries = this._data name = String(name) for (let i = 0; i < entries.length; i++) { if (entries[i][0] === name) { return entries[i][1] } } return null } /** * Return all fields values given name * * @param {string} name Fields name * @return {Array} [{String|File}] */ getAll (name) { ensureArgs(arguments, 1) const result = [] name = String(name) each(this._data, data => { data[0] === name && result.push(data[1]) }) return result } /** * Check for field name existence * * @param {string} name Field name * @return {boolean} */ has (name) { ensureArgs(arguments, 1) name = String(name) for (let i = 0; i < this._data.length; i++) { if (this._data[i][0] === name) { return true } } return false } /** * Iterate over all fields name * * @return {Iterator} */ * keys () { for (const [name] of this) { yield name } } /** * Overwrite all values given name * * @param {string} name Filed name * @param {string} value Field value * @param {string=} filename Filename (optional) */ set (name, value, filename) { ensureArgs(arguments, 2) name = String(name) /** @type {[string, string|File][]} */ const result = [] const args = normalizeArgs(name, value, filename) let replace = true // - replace the first occurrence with same name // - discards the remaining with same name // - while keeping the same order items where added each(this._data, data => { data[0] === name ? replace && (replace = !result.push(args)) : result.push(data) }) replace && result.push(args) this._data = result } /** * Iterate over all fields * * @return {Iterator} */ * values () { for (const [, value] of this) { yield value } } /** * Return a native (perhaps degraded) FormData with only a `append` method * Can throw if it's not supported * * @return {FormData} */ ['_asNative'] () { const fd = new _FormData() for (const [name, value] of this) { fd.append(name, value) } return fd } /** * [_blob description] * * @return {Blob} [description] */ ['_blob'] () { const boundary = '----formdata-polyfill-' + Math.random(), chunks = [], p = `--${boundary}\r\nContent-Disposition: form-data; name="` this.forEach((value, name) => typeof value == 'string' ? chunks.push(p + escape(normalizeLinefeeds(name)) + `"\r\n\r\n${normalizeLinefeeds(value)}\r\n`) : chunks.push(p + escape(normalizeLinefeeds(name)) + `"; filename="${escape(value.name)}"\r\nContent-Type: ${value.type||"application/octet-stream"}\r\n\r\n`, value, `\r\n`)) chunks.push(`--${boundary}--`) return new Blob(chunks, { type: "multipart/form-data; boundary=" + boundary }) } /** * The class itself is iterable * alias for formdata.entries() * * @return {Iterator} */ [Symbol.iterator] () { return this.entries() } /** * Create the default string description. * * @return {string} [object FormData] */ toString () { return '[object FormData]' } } if (_match && !_match.matches) { _match.matches = _match.matchesSelector || _match.mozMatchesSelector || _match.msMatchesSelector || _match.oMatchesSelector || _match.webkitMatchesSelector || function (s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s) var i = matches.length while (--i >= 0 && matches.item(i) !== this) {} return i > -1 } } if (stringTag) { /** * Create the default string description. * It is accessed internally by the Object.prototype.toString(). */ FormDataPolyfill.prototype[stringTag] = 'FormData' } // Patch xhr's send method to call _blob transparently if (_send) { const setRequestHeader = global.XMLHttpRequest.prototype.setRequestHeader global.XMLHttpRequest.prototype.setRequestHeader = function (name, value) { setRequestHeader.call(this, name, value) if (name.toLowerCase() === 'content-type') this._hasContentType = true } global.XMLHttpRequest.prototype.send = function (data) { // need to patch send b/c old IE don't send blob's type (#44) if (data instanceof FormDataPolyfill) { const blob = data['_blob']() if (!this._hasContentType) this.setRequestHeader('Content-Type', blob.type) _send.call(this, blob) } else { _send.call(this, data) } } } // Patch fetch's function to call _blob transparently if (_fetch) { global.fetch = function (input, init) { if (init && init.body && init.body instanceof FormDataPolyfill) { init.body = init.body['_blob']() } return _fetch.call(this, input, init) } } // Patch navigator.sendBeacon to use native FormData if (_sendBeacon) { global.navigator.sendBeacon = function (url, data) { if (data instanceof FormDataPolyfill) { data = data['_asNative']() } return _sendBeacon.call(this, url, data) } } global['FormData'] = FormDataPolyfill } wp-polyfill-url.min.js 0000644 00000133743 14720015030 0010745 0 ustar 00 !function e(t,n,r){function i(o,s){if(!n[o]){if(!t[o]){var l="function"==typeof require&&require;if(!s&&l)return l(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[o]={exports:{}};t[o][0].call(u.exports,(function(e){return i(t[o][1][e]||e)}),u,u.exports,e,t,n,r)}return n[o].exports}for(var a="function"==typeof require&&require,o=0;o<r.length;o++)i(r[o]);return i}({1:[function(e,t,n){t.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},{}],2:[function(e,t,n){var r=e("../internals/is-object");t.exports=function(e){if(!r(e)&&null!==e)throw TypeError("Can't set "+String(e)+" as a prototype");return e}},{"../internals/is-object":37}],3:[function(e,t,n){var r=e("../internals/well-known-symbol"),i=e("../internals/object-create"),a=e("../internals/object-define-property"),o=r("unscopables"),s=Array.prototype;null==s[o]&&a.f(s,o,{configurable:!0,value:i(null)}),t.exports=function(e){s[o][e]=!0}},{"../internals/object-create":45,"../internals/object-define-property":47,"../internals/well-known-symbol":77}],4:[function(e,t,n){t.exports=function(e,t,n){if(!(e instanceof t))throw TypeError("Incorrect "+(n?n+" ":"")+"invocation");return e}},{}],5:[function(e,t,n){var r=e("../internals/is-object");t.exports=function(e){if(!r(e))throw TypeError(String(e)+" is not an object");return e}},{"../internals/is-object":37}],6:[function(e,t,n){"use strict";var r=e("../internals/function-bind-context"),i=e("../internals/to-object"),a=e("../internals/call-with-safe-iteration-closing"),o=e("../internals/is-array-iterator-method"),s=e("../internals/to-length"),l=e("../internals/create-property"),c=e("../internals/get-iterator-method");t.exports=function(e){var t,n,u,f,p,h,b=i(e),d="function"==typeof this?this:Array,y=arguments.length,g=y>1?arguments[1]:void 0,v=void 0!==g,m=c(b),w=0;if(v&&(g=r(g,y>2?arguments[2]:void 0,2)),null==m||d==Array&&o(m))for(n=new d(t=s(b.length));t>w;w++)h=v?g(b[w],w):b[w],l(n,w,h);else for(p=(f=m.call(b)).next,n=new d;!(u=p.call(f)).done;w++)h=v?a(f,g,[u.value,w],!0):u.value,l(n,w,h);return n.length=w,n}},{"../internals/call-with-safe-iteration-closing":8,"../internals/create-property":16,"../internals/function-bind-context":23,"../internals/get-iterator-method":25,"../internals/is-array-iterator-method":35,"../internals/to-length":71,"../internals/to-object":72}],7:[function(e,t,n){var r=e("../internals/to-indexed-object"),i=e("../internals/to-length"),a=e("../internals/to-absolute-index"),o=function(e){return function(t,n,o){var s,l=r(t),c=i(l.length),u=a(o,c);if(e&&n!=n){for(;c>u;)if((s=l[u++])!=s)return!0}else for(;c>u;u++)if((e||u in l)&&l[u]===n)return e||u||0;return!e&&-1}};t.exports={includes:o(!0),indexOf:o(!1)}},{"../internals/to-absolute-index":68,"../internals/to-indexed-object":69,"../internals/to-length":71}],8:[function(e,t,n){var r=e("../internals/an-object");t.exports=function(e,t,n,i){try{return i?t(r(n)[0],n[1]):t(n)}catch(t){var a=e.return;throw void 0!==a&&r(a.call(e)),t}}},{"../internals/an-object":5}],9:[function(e,t,n){var r={}.toString;t.exports=function(e){return r.call(e).slice(8,-1)}},{}],10:[function(e,t,n){var r=e("../internals/to-string-tag-support"),i=e("../internals/classof-raw"),a=e("../internals/well-known-symbol")("toStringTag"),o="Arguments"==i(function(){return arguments}());t.exports=r?i:function(e){var t,n,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),a))?n:o?i(t):"Object"==(r=i(t))&&"function"==typeof t.callee?"Arguments":r}},{"../internals/classof-raw":9,"../internals/to-string-tag-support":74,"../internals/well-known-symbol":77}],11:[function(e,t,n){var r=e("../internals/has"),i=e("../internals/own-keys"),a=e("../internals/object-get-own-property-descriptor"),o=e("../internals/object-define-property");t.exports=function(e,t){for(var n=i(t),s=o.f,l=a.f,c=0;c<n.length;c++){var u=n[c];r(e,u)||s(e,u,l(t,u))}}},{"../internals/has":28,"../internals/object-define-property":47,"../internals/object-get-own-property-descriptor":48,"../internals/own-keys":56}],12:[function(e,t,n){var r=e("../internals/fails");t.exports=!r((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}))},{"../internals/fails":22}],13:[function(e,t,n){"use strict";var r=e("../internals/iterators-core").IteratorPrototype,i=e("../internals/object-create"),a=e("../internals/create-property-descriptor"),o=e("../internals/set-to-string-tag"),s=e("../internals/iterators"),l=function(){return this};t.exports=function(e,t,n){var c=t+" Iterator";return e.prototype=i(r,{next:a(1,n)}),o(e,c,!1,!0),s[c]=l,e}},{"../internals/create-property-descriptor":15,"../internals/iterators":40,"../internals/iterators-core":39,"../internals/object-create":45,"../internals/set-to-string-tag":62}],14:[function(e,t,n){var r=e("../internals/descriptors"),i=e("../internals/object-define-property"),a=e("../internals/create-property-descriptor");t.exports=r?function(e,t,n){return i.f(e,t,a(1,n))}:function(e,t,n){return e[t]=n,e}},{"../internals/create-property-descriptor":15,"../internals/descriptors":18,"../internals/object-define-property":47}],15:[function(e,t,n){t.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},{}],16:[function(e,t,n){"use strict";var r=e("../internals/to-primitive"),i=e("../internals/object-define-property"),a=e("../internals/create-property-descriptor");t.exports=function(e,t,n){var o=r(t);o in e?i.f(e,o,a(0,n)):e[o]=n}},{"../internals/create-property-descriptor":15,"../internals/object-define-property":47,"../internals/to-primitive":73}],17:[function(e,t,n){"use strict";var r=e("../internals/export"),i=e("../internals/create-iterator-constructor"),a=e("../internals/object-get-prototype-of"),o=e("../internals/object-set-prototype-of"),s=e("../internals/set-to-string-tag"),l=e("../internals/create-non-enumerable-property"),c=e("../internals/redefine"),u=e("../internals/well-known-symbol"),f=e("../internals/is-pure"),p=e("../internals/iterators"),h=e("../internals/iterators-core"),b=h.IteratorPrototype,d=h.BUGGY_SAFARI_ITERATORS,y=u("iterator"),g=function(){return this};t.exports=function(e,t,n,u,h,v,m){i(n,t,u);var w,j,x,k=function(e){if(e===h&&L)return L;if(!d&&e in O)return O[e];switch(e){case"keys":case"values":case"entries":return function(){return new n(this,e)}}return function(){return new n(this)}},S=t+" Iterator",A=!1,O=e.prototype,R=O[y]||O["@@iterator"]||h&&O[h],L=!d&&R||k(h),U="Array"==t&&O.entries||R;if(U&&(w=a(U.call(new e)),b!==Object.prototype&&w.next&&(f||a(w)===b||(o?o(w,b):"function"!=typeof w[y]&&l(w,y,g)),s(w,S,!0,!0),f&&(p[S]=g))),"values"==h&&R&&"values"!==R.name&&(A=!0,L=function(){return R.call(this)}),f&&!m||O[y]===L||l(O,y,L),p[t]=L,h)if(j={values:k("values"),keys:v?L:k("keys"),entries:k("entries")},m)for(x in j)!d&&!A&&x in O||c(O,x,j[x]);else r({target:t,proto:!0,forced:d||A},j);return j}},{"../internals/create-iterator-constructor":13,"../internals/create-non-enumerable-property":14,"../internals/export":21,"../internals/is-pure":38,"../internals/iterators":40,"../internals/iterators-core":39,"../internals/object-get-prototype-of":51,"../internals/object-set-prototype-of":55,"../internals/redefine":59,"../internals/set-to-string-tag":62,"../internals/well-known-symbol":77}],18:[function(e,t,n){var r=e("../internals/fails");t.exports=!r((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},{"../internals/fails":22}],19:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/is-object"),a=r.document,o=i(a)&&i(a.createElement);t.exports=function(e){return o?a.createElement(e):{}}},{"../internals/global":27,"../internals/is-object":37}],20:[function(e,t,n){t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},{}],21:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/object-get-own-property-descriptor").f,a=e("../internals/create-non-enumerable-property"),o=e("../internals/redefine"),s=e("../internals/set-global"),l=e("../internals/copy-constructor-properties"),c=e("../internals/is-forced");t.exports=function(e,t){var n,u,f,p,h,b=e.target,d=e.global,y=e.stat;if(n=d?r:y?r[b]||s(b,{}):(r[b]||{}).prototype)for(u in t){if(p=t[u],f=e.noTargetGet?(h=i(n,u))&&h.value:n[u],!c(d?u:b+(y?".":"#")+u,e.forced)&&void 0!==f){if(typeof p==typeof f)continue;l(p,f)}(e.sham||f&&f.sham)&&a(p,"sham",!0),o(n,u,p,e)}}},{"../internals/copy-constructor-properties":11,"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/is-forced":36,"../internals/object-get-own-property-descriptor":48,"../internals/redefine":59,"../internals/set-global":61}],22:[function(e,t,n){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],23:[function(e,t,n){var r=e("../internals/a-function");t.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 0:return function(){return e.call(t)};case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)}}return function(){return e.apply(t,arguments)}}},{"../internals/a-function":1}],24:[function(e,t,n){var r=e("../internals/path"),i=e("../internals/global"),a=function(e){return"function"==typeof e?e:void 0};t.exports=function(e,t){return arguments.length<2?a(r[e])||a(i[e]):r[e]&&r[e][t]||i[e]&&i[e][t]}},{"../internals/global":27,"../internals/path":57}],25:[function(e,t,n){var r=e("../internals/classof"),i=e("../internals/iterators"),a=e("../internals/well-known-symbol")("iterator");t.exports=function(e){if(null!=e)return e[a]||e["@@iterator"]||i[r(e)]}},{"../internals/classof":10,"../internals/iterators":40,"../internals/well-known-symbol":77}],26:[function(e,t,n){var r=e("../internals/an-object"),i=e("../internals/get-iterator-method");t.exports=function(e){var t=i(e);if("function"!=typeof t)throw TypeError(String(e)+" is not iterable");return r(t.call(e))}},{"../internals/an-object":5,"../internals/get-iterator-method":25}],27:[function(e,t,n){(function(e){var n=function(e){return e&&e.Math==Math&&e};t.exports=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof e&&e)||Function("return this")()}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],28:[function(e,t,n){var r={}.hasOwnProperty;t.exports=function(e,t){return r.call(e,t)}},{}],29:[function(e,t,n){t.exports={}},{}],30:[function(e,t,n){var r=e("../internals/get-built-in");t.exports=r("document","documentElement")},{"../internals/get-built-in":24}],31:[function(e,t,n){var r=e("../internals/descriptors"),i=e("../internals/fails"),a=e("../internals/document-create-element");t.exports=!r&&!i((function(){return 7!=Object.defineProperty(a("div"),"a",{get:function(){return 7}}).a}))},{"../internals/descriptors":18,"../internals/document-create-element":19,"../internals/fails":22}],32:[function(e,t,n){var r=e("../internals/fails"),i=e("../internals/classof-raw"),a="".split;t.exports=r((function(){return!Object("z").propertyIsEnumerable(0)}))?function(e){return"String"==i(e)?a.call(e,""):Object(e)}:Object},{"../internals/classof-raw":9,"../internals/fails":22}],33:[function(e,t,n){var r=e("../internals/shared-store"),i=Function.toString;"function"!=typeof r.inspectSource&&(r.inspectSource=function(e){return i.call(e)}),t.exports=r.inspectSource},{"../internals/shared-store":64}],34:[function(e,t,n){var r,i,a,o=e("../internals/native-weak-map"),s=e("../internals/global"),l=e("../internals/is-object"),c=e("../internals/create-non-enumerable-property"),u=e("../internals/has"),f=e("../internals/shared-key"),p=e("../internals/hidden-keys"),h=s.WeakMap;if(o){var b=new h,d=b.get,y=b.has,g=b.set;r=function(e,t){return g.call(b,e,t),t},i=function(e){return d.call(b,e)||{}},a=function(e){return y.call(b,e)}}else{var v=f("state");p[v]=!0,r=function(e,t){return c(e,v,t),t},i=function(e){return u(e,v)?e[v]:{}},a=function(e){return u(e,v)}}t.exports={set:r,get:i,has:a,enforce:function(e){return a(e)?i(e):r(e,{})},getterFor:function(e){return function(t){var n;if(!l(t)||(n=i(t)).type!==e)throw TypeError("Incompatible receiver, "+e+" required");return n}}}},{"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/has":28,"../internals/hidden-keys":29,"../internals/is-object":37,"../internals/native-weak-map":43,"../internals/shared-key":63}],35:[function(e,t,n){var r=e("../internals/well-known-symbol"),i=e("../internals/iterators"),a=r("iterator"),o=Array.prototype;t.exports=function(e){return void 0!==e&&(i.Array===e||o[a]===e)}},{"../internals/iterators":40,"../internals/well-known-symbol":77}],36:[function(e,t,n){var r=e("../internals/fails"),i=/#|\.prototype\./,a=function(e,t){var n=s[o(e)];return n==c||n!=l&&("function"==typeof t?r(t):!!t)},o=a.normalize=function(e){return String(e).replace(i,".").toLowerCase()},s=a.data={},l=a.NATIVE="N",c=a.POLYFILL="P";t.exports=a},{"../internals/fails":22}],37:[function(e,t,n){t.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},{}],38:[function(e,t,n){t.exports=!1},{}],39:[function(e,t,n){"use strict";var r,i,a,o=e("../internals/object-get-prototype-of"),s=e("../internals/create-non-enumerable-property"),l=e("../internals/has"),c=e("../internals/well-known-symbol"),u=e("../internals/is-pure"),f=c("iterator"),p=!1;[].keys&&("next"in(a=[].keys())?(i=o(o(a)))!==Object.prototype&&(r=i):p=!0),null==r&&(r={}),u||l(r,f)||s(r,f,(function(){return this})),t.exports={IteratorPrototype:r,BUGGY_SAFARI_ITERATORS:p}},{"../internals/create-non-enumerable-property":14,"../internals/has":28,"../internals/is-pure":38,"../internals/object-get-prototype-of":51,"../internals/well-known-symbol":77}],40:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29}],41:[function(e,t,n){var r=e("../internals/fails");t.exports=!!Object.getOwnPropertySymbols&&!r((function(){return!String(Symbol())}))},{"../internals/fails":22}],42:[function(e,t,n){var r=e("../internals/fails"),i=e("../internals/well-known-symbol"),a=e("../internals/is-pure"),o=i("iterator");t.exports=!r((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,n="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),n+=r+e})),a&&!e.toJSON||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[o]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==n||"x"!==new URL("http://x",void 0).host}))},{"../internals/fails":22,"../internals/is-pure":38,"../internals/well-known-symbol":77}],43:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/inspect-source"),a=r.WeakMap;t.exports="function"==typeof a&&/native code/.test(i(a))},{"../internals/global":27,"../internals/inspect-source":33}],44:[function(e,t,n){"use strict";var r=e("../internals/descriptors"),i=e("../internals/fails"),a=e("../internals/object-keys"),o=e("../internals/object-get-own-property-symbols"),s=e("../internals/object-property-is-enumerable"),l=e("../internals/to-object"),c=e("../internals/indexed-object"),u=Object.assign,f=Object.defineProperty;t.exports=!u||i((function(){if(r&&1!==u({b:1},u(f({},"a",{enumerable:!0,get:function(){f(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol();return e[n]=7,"abcdefghijklmnopqrst".split("").forEach((function(e){t[e]=e})),7!=u({},e)[n]||"abcdefghijklmnopqrst"!=a(u({},t)).join("")}))?function(e,t){for(var n=l(e),i=arguments.length,u=1,f=o.f,p=s.f;i>u;)for(var h,b=c(arguments[u++]),d=f?a(b).concat(f(b)):a(b),y=d.length,g=0;y>g;)h=d[g++],r&&!p.call(b,h)||(n[h]=b[h]);return n}:u},{"../internals/descriptors":18,"../internals/fails":22,"../internals/indexed-object":32,"../internals/object-get-own-property-symbols":50,"../internals/object-keys":53,"../internals/object-property-is-enumerable":54,"../internals/to-object":72}],45:[function(e,t,n){var r,i=e("../internals/an-object"),a=e("../internals/object-define-properties"),o=e("../internals/enum-bug-keys"),s=e("../internals/hidden-keys"),l=e("../internals/html"),c=e("../internals/document-create-element"),u=e("../internals/shared-key")("IE_PROTO"),f=function(){},p=function(e){return"<script>"+e+"<\/script>"},h=function(){try{r=document.domain&&new ActiveXObject("htmlfile")}catch(e){}var e,t;h=r?function(e){e.write(p("")),e.close();var t=e.parentWindow.Object;return e=null,t}(r):((t=c("iframe")).style.display="none",l.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(p("document.F=Object")),e.close(),e.F);for(var n=o.length;n--;)delete h.prototype[o[n]];return h()};s[u]=!0,t.exports=Object.create||function(e,t){var n;return null!==e?(f.prototype=i(e),n=new f,f.prototype=null,n[u]=e):n=h(),void 0===t?n:a(n,t)}},{"../internals/an-object":5,"../internals/document-create-element":19,"../internals/enum-bug-keys":20,"../internals/hidden-keys":29,"../internals/html":30,"../internals/object-define-properties":46,"../internals/shared-key":63}],46:[function(e,t,n){var r=e("../internals/descriptors"),i=e("../internals/object-define-property"),a=e("../internals/an-object"),o=e("../internals/object-keys");t.exports=r?Object.defineProperties:function(e,t){a(e);for(var n,r=o(t),s=r.length,l=0;s>l;)i.f(e,n=r[l++],t[n]);return e}},{"../internals/an-object":5,"../internals/descriptors":18,"../internals/object-define-property":47,"../internals/object-keys":53}],47:[function(e,t,n){var r=e("../internals/descriptors"),i=e("../internals/ie8-dom-define"),a=e("../internals/an-object"),o=e("../internals/to-primitive"),s=Object.defineProperty;n.f=r?s:function(e,t,n){if(a(e),t=o(t,!0),a(n),i)try{return s(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(e[t]=n.value),e}},{"../internals/an-object":5,"../internals/descriptors":18,"../internals/ie8-dom-define":31,"../internals/to-primitive":73}],48:[function(e,t,n){var r=e("../internals/descriptors"),i=e("../internals/object-property-is-enumerable"),a=e("../internals/create-property-descriptor"),o=e("../internals/to-indexed-object"),s=e("../internals/to-primitive"),l=e("../internals/has"),c=e("../internals/ie8-dom-define"),u=Object.getOwnPropertyDescriptor;n.f=r?u:function(e,t){if(e=o(e),t=s(t,!0),c)try{return u(e,t)}catch(e){}if(l(e,t))return a(!i.f.call(e,t),e[t])}},{"../internals/create-property-descriptor":15,"../internals/descriptors":18,"../internals/has":28,"../internals/ie8-dom-define":31,"../internals/object-property-is-enumerable":54,"../internals/to-indexed-object":69,"../internals/to-primitive":73}],49:[function(e,t,n){var r=e("../internals/object-keys-internal"),i=e("../internals/enum-bug-keys").concat("length","prototype");n.f=Object.getOwnPropertyNames||function(e){return r(e,i)}},{"../internals/enum-bug-keys":20,"../internals/object-keys-internal":52}],50:[function(e,t,n){n.f=Object.getOwnPropertySymbols},{}],51:[function(e,t,n){var r=e("../internals/has"),i=e("../internals/to-object"),a=e("../internals/shared-key"),o=e("../internals/correct-prototype-getter"),s=a("IE_PROTO"),l=Object.prototype;t.exports=o?Object.getPrototypeOf:function(e){return e=i(e),r(e,s)?e[s]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?l:null}},{"../internals/correct-prototype-getter":12,"../internals/has":28,"../internals/shared-key":63,"../internals/to-object":72}],52:[function(e,t,n){var r=e("../internals/has"),i=e("../internals/to-indexed-object"),a=e("../internals/array-includes").indexOf,o=e("../internals/hidden-keys");t.exports=function(e,t){var n,s=i(e),l=0,c=[];for(n in s)!r(o,n)&&r(s,n)&&c.push(n);for(;t.length>l;)r(s,n=t[l++])&&(~a(c,n)||c.push(n));return c}},{"../internals/array-includes":7,"../internals/has":28,"../internals/hidden-keys":29,"../internals/to-indexed-object":69}],53:[function(e,t,n){var r=e("../internals/object-keys-internal"),i=e("../internals/enum-bug-keys");t.exports=Object.keys||function(e){return r(e,i)}},{"../internals/enum-bug-keys":20,"../internals/object-keys-internal":52}],54:[function(e,t,n){"use strict";var r={}.propertyIsEnumerable,i=Object.getOwnPropertyDescriptor,a=i&&!r.call({1:2},1);n.f=a?function(e){var t=i(this,e);return!!t&&t.enumerable}:r},{}],55:[function(e,t,n){var r=e("../internals/an-object"),i=e("../internals/a-possible-prototype");t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,n={};try{(e=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(n,[]),t=n instanceof Array}catch(e){}return function(n,a){return r(n),i(a),t?e.call(n,a):n.__proto__=a,n}}():void 0)},{"../internals/a-possible-prototype":2,"../internals/an-object":5}],56:[function(e,t,n){var r=e("../internals/get-built-in"),i=e("../internals/object-get-own-property-names"),a=e("../internals/object-get-own-property-symbols"),o=e("../internals/an-object");t.exports=r("Reflect","ownKeys")||function(e){var t=i.f(o(e)),n=a.f;return n?t.concat(n(e)):t}},{"../internals/an-object":5,"../internals/get-built-in":24,"../internals/object-get-own-property-names":49,"../internals/object-get-own-property-symbols":50}],57:[function(e,t,n){var r=e("../internals/global");t.exports=r},{"../internals/global":27}],58:[function(e,t,n){var r=e("../internals/redefine");t.exports=function(e,t,n){for(var i in t)r(e,i,t[i],n);return e}},{"../internals/redefine":59}],59:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/create-non-enumerable-property"),a=e("../internals/has"),o=e("../internals/set-global"),s=e("../internals/inspect-source"),l=e("../internals/internal-state"),c=l.get,u=l.enforce,f=String(String).split("String");(t.exports=function(e,t,n,s){var l=!!s&&!!s.unsafe,c=!!s&&!!s.enumerable,p=!!s&&!!s.noTargetGet;"function"==typeof n&&("string"!=typeof t||a(n,"name")||i(n,"name",t),u(n).source=f.join("string"==typeof t?t:"")),e!==r?(l?!p&&e[t]&&(c=!0):delete e[t],c?e[t]=n:i(e,t,n)):c?e[t]=n:o(t,n)})(Function.prototype,"toString",(function(){return"function"==typeof this&&c(this).source||s(this)}))},{"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/has":28,"../internals/inspect-source":33,"../internals/internal-state":34,"../internals/set-global":61}],60:[function(e,t,n){t.exports=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}},{}],61:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/create-non-enumerable-property");t.exports=function(e,t){try{i(r,e,t)}catch(n){r[e]=t}return t}},{"../internals/create-non-enumerable-property":14,"../internals/global":27}],62:[function(e,t,n){var r=e("../internals/object-define-property").f,i=e("../internals/has"),a=e("../internals/well-known-symbol")("toStringTag");t.exports=function(e,t,n){e&&!i(e=n?e:e.prototype,a)&&r(e,a,{configurable:!0,value:t})}},{"../internals/has":28,"../internals/object-define-property":47,"../internals/well-known-symbol":77}],63:[function(e,t,n){var r=e("../internals/shared"),i=e("../internals/uid"),a=r("keys");t.exports=function(e){return a[e]||(a[e]=i(e))}},{"../internals/shared":65,"../internals/uid":75}],64:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/set-global"),a=r["__core-js_shared__"]||i("__core-js_shared__",{});t.exports=a},{"../internals/global":27,"../internals/set-global":61}],65:[function(e,t,n){var r=e("../internals/is-pure"),i=e("../internals/shared-store");(t.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.6.4",mode:r?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})},{"../internals/is-pure":38,"../internals/shared-store":64}],66:[function(e,t,n){var r=e("../internals/to-integer"),i=e("../internals/require-object-coercible"),a=function(e){return function(t,n){var a,o,s=String(i(t)),l=r(n),c=s.length;return l<0||l>=c?e?"":void 0:(a=s.charCodeAt(l))<55296||a>56319||l+1===c||(o=s.charCodeAt(l+1))<56320||o>57343?e?s.charAt(l):a:e?s.slice(l,l+2):o-56320+(a-55296<<10)+65536}};t.exports={codeAt:a(!1),charAt:a(!0)}},{"../internals/require-object-coercible":60,"../internals/to-integer":70}],67:[function(e,t,n){"use strict";var r=/[^\0-\u007E]/,i=/[.\u3002\uFF0E\uFF61]/g,a="Overflow: input needs wider integers to process",o=Math.floor,s=String.fromCharCode,l=function(e){return e+22+75*(e<26)},c=function(e,t,n){var r=0;for(e=n?o(e/700):e>>1,e+=o(e/t);e>455;r+=36)e=o(e/35);return o(r+36*e/(e+38))},u=function(e){var t,n,r=[],i=(e=function(e){for(var t=[],n=0,r=e.length;n<r;){var i=e.charCodeAt(n++);if(i>=55296&&i<=56319&&n<r){var a=e.charCodeAt(n++);56320==(64512&a)?t.push(((1023&i)<<10)+(1023&a)+65536):(t.push(i),n--)}else t.push(i)}return t}(e)).length,u=128,f=0,p=72;for(t=0;t<e.length;t++)(n=e[t])<128&&r.push(s(n));var h=r.length,b=h;for(h&&r.push("-");b<i;){var d=2147483647;for(t=0;t<e.length;t++)(n=e[t])>=u&&n<d&&(d=n);var y=b+1;if(d-u>o((2147483647-f)/y))throw RangeError(a);for(f+=(d-u)*y,u=d,t=0;t<e.length;t++){if((n=e[t])<u&&++f>2147483647)throw RangeError(a);if(n==u){for(var g=f,v=36;;v+=36){var m=v<=p?1:v>=p+26?26:v-p;if(g<m)break;var w=g-m,j=36-m;r.push(s(l(m+w%j))),g=o(w/j)}r.push(s(l(g))),p=c(f,y,b==h),f=0,++b}}++f,++u}return r.join("")};t.exports=function(e){var t,n,a=[],o=e.toLowerCase().replace(i,".").split(".");for(t=0;t<o.length;t++)n=o[t],a.push(r.test(n)?"xn--"+u(n):n);return a.join(".")}},{}],68:[function(e,t,n){var r=e("../internals/to-integer"),i=Math.max,a=Math.min;t.exports=function(e,t){var n=r(e);return n<0?i(n+t,0):a(n,t)}},{"../internals/to-integer":70}],69:[function(e,t,n){var r=e("../internals/indexed-object"),i=e("../internals/require-object-coercible");t.exports=function(e){return r(i(e))}},{"../internals/indexed-object":32,"../internals/require-object-coercible":60}],70:[function(e,t,n){var r=Math.ceil,i=Math.floor;t.exports=function(e){return isNaN(e=+e)?0:(e>0?i:r)(e)}},{}],71:[function(e,t,n){var r=e("../internals/to-integer"),i=Math.min;t.exports=function(e){return e>0?i(r(e),9007199254740991):0}},{"../internals/to-integer":70}],72:[function(e,t,n){var r=e("../internals/require-object-coercible");t.exports=function(e){return Object(r(e))}},{"../internals/require-object-coercible":60}],73:[function(e,t,n){var r=e("../internals/is-object");t.exports=function(e,t){if(!r(e))return e;var n,i;if(t&&"function"==typeof(n=e.toString)&&!r(i=n.call(e)))return i;if("function"==typeof(n=e.valueOf)&&!r(i=n.call(e)))return i;if(!t&&"function"==typeof(n=e.toString)&&!r(i=n.call(e)))return i;throw TypeError("Can't convert object to primitive value")}},{"../internals/is-object":37}],74:[function(e,t,n){var r={};r[e("../internals/well-known-symbol")("toStringTag")]="z",t.exports="[object z]"===String(r)},{"../internals/well-known-symbol":77}],75:[function(e,t,n){var r=0,i=Math.random();t.exports=function(e){return"Symbol("+String(void 0===e?"":e)+")_"+(++r+i).toString(36)}},{}],76:[function(e,t,n){var r=e("../internals/native-symbol");t.exports=r&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},{"../internals/native-symbol":41}],77:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/shared"),a=e("../internals/has"),o=e("../internals/uid"),s=e("../internals/native-symbol"),l=e("../internals/use-symbol-as-uid"),c=i("wks"),u=r.Symbol,f=l?u:u&&u.withoutSetter||o;t.exports=function(e){return a(c,e)||(s&&a(u,e)?c[e]=u[e]:c[e]=f("Symbol."+e)),c[e]}},{"../internals/global":27,"../internals/has":28,"../internals/native-symbol":41,"../internals/shared":65,"../internals/uid":75,"../internals/use-symbol-as-uid":76}],78:[function(e,t,n){"use strict";var r=e("../internals/to-indexed-object"),i=e("../internals/add-to-unscopables"),a=e("../internals/iterators"),o=e("../internals/internal-state"),s=e("../internals/define-iterator"),l=o.set,c=o.getterFor("Array Iterator");t.exports=s(Array,"Array",(function(e,t){l(this,{type:"Array Iterator",target:r(e),index:0,kind:t})}),(function(){var e=c(this),t=e.target,n=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==n?{value:r,done:!1}:"values"==n?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}}),"values"),a.Arguments=a.Array,i("keys"),i("values"),i("entries")},{"../internals/add-to-unscopables":3,"../internals/define-iterator":17,"../internals/internal-state":34,"../internals/iterators":40,"../internals/to-indexed-object":69}],79:[function(e,t,n){"use strict";var r=e("../internals/string-multibyte").charAt,i=e("../internals/internal-state"),a=e("../internals/define-iterator"),o=i.set,s=i.getterFor("String Iterator");a(String,"String",(function(e){o(this,{type:"String Iterator",string:String(e),index:0})}),(function(){var e,t=s(this),n=t.string,i=t.index;return i>=n.length?{value:void 0,done:!0}:(e=r(n,i),t.index+=e.length,{value:e,done:!1})}))},{"../internals/define-iterator":17,"../internals/internal-state":34,"../internals/string-multibyte":66}],80:[function(e,t,n){"use strict";e("../modules/es.array.iterator");var r=e("../internals/export"),i=e("../internals/get-built-in"),a=e("../internals/native-url"),o=e("../internals/redefine"),s=e("../internals/redefine-all"),l=e("../internals/set-to-string-tag"),c=e("../internals/create-iterator-constructor"),u=e("../internals/internal-state"),f=e("../internals/an-instance"),p=e("../internals/has"),h=e("../internals/function-bind-context"),b=e("../internals/classof"),d=e("../internals/an-object"),y=e("../internals/is-object"),g=e("../internals/object-create"),v=e("../internals/create-property-descriptor"),m=e("../internals/get-iterator"),w=e("../internals/get-iterator-method"),j=e("../internals/well-known-symbol"),x=i("fetch"),k=i("Headers"),S=j("iterator"),A=u.set,O=u.getterFor("URLSearchParams"),R=u.getterFor("URLSearchParamsIterator"),L=/\+/g,U=Array(4),P=function(e){return U[e-1]||(U[e-1]=RegExp("((?:%[\\da-f]{2}){"+e+"})","gi"))},I=function(e){try{return decodeURIComponent(e)}catch(t){return e}},q=function(e){var t=e.replace(L," "),n=4;try{return decodeURIComponent(t)}catch(e){for(;n;)t=t.replace(P(n--),I);return t}},E=/[!'()~]|%20/g,_={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},T=function(e){return _[e]},B=function(e){return encodeURIComponent(e).replace(E,T)},F=function(e,t){if(t)for(var n,r,i=t.split("&"),a=0;a<i.length;)(n=i[a++]).length&&(r=n.split("="),e.push({key:q(r.shift()),value:q(r.join("="))}))},C=function(e){this.entries.length=0,F(this.entries,e)},M=function(e,t){if(e<t)throw TypeError("Not enough arguments")},N=c((function(e,t){A(this,{type:"URLSearchParamsIterator",iterator:m(O(e).entries),kind:t})}),"Iterator",(function(){var e=R(this),t=e.kind,n=e.iterator.next(),r=n.value;return n.done||(n.value="keys"===t?r.key:"values"===t?r.value:[r.key,r.value]),n})),D=function(){f(this,D,"URLSearchParams");var e,t,n,r,i,a,o,s,l,c=arguments.length>0?arguments[0]:void 0,u=[];if(A(this,{type:"URLSearchParams",entries:u,updateURL:function(){},updateSearchParams:C}),void 0!==c)if(y(c))if("function"==typeof(e=w(c)))for(n=(t=e.call(c)).next;!(r=n.call(t)).done;){if((o=(a=(i=m(d(r.value))).next).call(i)).done||(s=a.call(i)).done||!a.call(i).done)throw TypeError("Expected sequence with length 2");u.push({key:o.value+"",value:s.value+""})}else for(l in c)p(c,l)&&u.push({key:l,value:c[l]+""});else F(u,"string"==typeof c?"?"===c.charAt(0)?c.slice(1):c:c+"")},z=D.prototype;s(z,{append:function(e,t){M(arguments.length,2);var n=O(this);n.entries.push({key:e+"",value:t+""}),n.updateURL()},delete:function(e){M(arguments.length,1);for(var t=O(this),n=t.entries,r=e+"",i=0;i<n.length;)n[i].key===r?n.splice(i,1):i++;t.updateURL()},get:function(e){M(arguments.length,1);for(var t=O(this).entries,n=e+"",r=0;r<t.length;r++)if(t[r].key===n)return t[r].value;return null},getAll:function(e){M(arguments.length,1);for(var t=O(this).entries,n=e+"",r=[],i=0;i<t.length;i++)t[i].key===n&&r.push(t[i].value);return r},has:function(e){M(arguments.length,1);for(var t=O(this).entries,n=e+"",r=0;r<t.length;)if(t[r++].key===n)return!0;return!1},set:function(e,t){M(arguments.length,1);for(var n,r=O(this),i=r.entries,a=!1,o=e+"",s=t+"",l=0;l<i.length;l++)(n=i[l]).key===o&&(a?i.splice(l--,1):(a=!0,n.value=s));a||i.push({key:o,value:s}),r.updateURL()},sort:function(){var e,t,n,r=O(this),i=r.entries,a=i.slice();for(i.length=0,n=0;n<a.length;n++){for(e=a[n],t=0;t<n;t++)if(i[t].key>e.key){i.splice(t,0,e);break}t===n&&i.push(e)}r.updateURL()},forEach:function(e){for(var t,n=O(this).entries,r=h(e,arguments.length>1?arguments[1]:void 0,3),i=0;i<n.length;)r((t=n[i++]).value,t.key,this)},keys:function(){return new N(this,"keys")},values:function(){return new N(this,"values")},entries:function(){return new N(this,"entries")}},{enumerable:!0}),o(z,S,z.entries),o(z,"toString",(function(){for(var e,t=O(this).entries,n=[],r=0;r<t.length;)e=t[r++],n.push(B(e.key)+"="+B(e.value));return n.join("&")}),{enumerable:!0}),l(D,"URLSearchParams"),r({global:!0,forced:!a},{URLSearchParams:D}),a||"function"!=typeof x||"function"!=typeof k||r({global:!0,enumerable:!0,forced:!0},{fetch:function(e){var t,n,r,i=[e];return arguments.length>1&&(y(t=arguments[1])&&(n=t.body,"URLSearchParams"===b(n)&&((r=t.headers?new k(t.headers):new k).has("content-type")||r.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),t=g(t,{body:v(0,String(n)),headers:v(0,r)}))),i.push(t)),x.apply(this,i)}}),t.exports={URLSearchParams:D,getState:O}},{"../internals/an-instance":4,"../internals/an-object":5,"../internals/classof":10,"../internals/create-iterator-constructor":13,"../internals/create-property-descriptor":15,"../internals/export":21,"../internals/function-bind-context":23,"../internals/get-built-in":24,"../internals/get-iterator":26,"../internals/get-iterator-method":25,"../internals/has":28,"../internals/internal-state":34,"../internals/is-object":37,"../internals/native-url":42,"../internals/object-create":45,"../internals/redefine":59,"../internals/redefine-all":58,"../internals/set-to-string-tag":62,"../internals/well-known-symbol":77,"../modules/es.array.iterator":78}],81:[function(e,t,n){"use strict";e("../modules/es.string.iterator");var r,i=e("../internals/export"),a=e("../internals/descriptors"),o=e("../internals/native-url"),s=e("../internals/global"),l=e("../internals/object-define-properties"),c=e("../internals/redefine"),u=e("../internals/an-instance"),f=e("../internals/has"),p=e("../internals/object-assign"),h=e("../internals/array-from"),b=e("../internals/string-multibyte").codeAt,d=e("../internals/string-punycode-to-ascii"),y=e("../internals/set-to-string-tag"),g=e("../modules/web.url-search-params"),v=e("../internals/internal-state"),m=s.URL,w=g.URLSearchParams,j=g.getState,x=v.set,k=v.getterFor("URL"),S=Math.floor,A=Math.pow,O=/[A-Za-z]/,R=/[\d+\-.A-Za-z]/,L=/\d/,U=/^(0x|0X)/,P=/^[0-7]+$/,I=/^\d+$/,q=/^[\dA-Fa-f]+$/,E=/[\u0000\u0009\u000A\u000D #%/:?@[\\]]/,_=/[\u0000\u0009\u000A\u000D #/:?@[\\]]/,T=/^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g,B=/[\u0009\u000A\u000D]/g,F=function(e,t){var n,r,i;if("["==t.charAt(0)){if("]"!=t.charAt(t.length-1))return"Invalid host";if(!(n=M(t.slice(1,-1))))return"Invalid host";e.host=n}else if(Y(e)){if(t=d(t),E.test(t))return"Invalid host";if(null===(n=C(t)))return"Invalid host";e.host=n}else{if(_.test(t))return"Invalid host";for(n="",r=h(t),i=0;i<r.length;i++)n+=$(r[i],D);e.host=n}},C=function(e){var t,n,r,i,a,o,s,l=e.split(".");if(l.length&&""==l[l.length-1]&&l.pop(),(t=l.length)>4)return e;for(n=[],r=0;r<t;r++){if(""==(i=l[r]))return e;if(a=10,i.length>1&&"0"==i.charAt(0)&&(a=U.test(i)?16:8,i=i.slice(8==a?1:2)),""===i)o=0;else{if(!(10==a?I:8==a?P:q).test(i))return e;o=parseInt(i,a)}n.push(o)}for(r=0;r<t;r++)if(o=n[r],r==t-1){if(o>=A(256,5-t))return null}else if(o>255)return null;for(s=n.pop(),r=0;r<n.length;r++)s+=n[r]*A(256,3-r);return s},M=function(e){var t,n,r,i,a,o,s,l=[0,0,0,0,0,0,0,0],c=0,u=null,f=0,p=function(){return e.charAt(f)};if(":"==p()){if(":"!=e.charAt(1))return;f+=2,u=++c}for(;p();){if(8==c)return;if(":"!=p()){for(t=n=0;n<4&&q.test(p());)t=16*t+parseInt(p(),16),f++,n++;if("."==p()){if(0==n)return;if(f-=n,c>6)return;for(r=0;p();){if(i=null,r>0){if(!("."==p()&&r<4))return;f++}if(!L.test(p()))return;for(;L.test(p());){if(a=parseInt(p(),10),null===i)i=a;else{if(0==i)return;i=10*i+a}if(i>255)return;f++}l[c]=256*l[c]+i,2!=++r&&4!=r||c++}if(4!=r)return;break}if(":"==p()){if(f++,!p())return}else if(p())return;l[c++]=t}else{if(null!==u)return;f++,u=++c}}if(null!==u)for(o=c-u,c=7;0!=c&&o>0;)s=l[c],l[c--]=l[u+o-1],l[u+--o]=s;else if(8!=c)return;return l},N=function(e){var t,n,r,i;if("number"==typeof e){for(t=[],n=0;n<4;n++)t.unshift(e%256),e=S(e/256);return t.join(".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,n=1,r=null,i=0,a=0;a<8;a++)0!==e[a]?(i>n&&(t=r,n=i),r=null,i=0):(null===r&&(r=a),++i);return i>n&&(t=r,n=i),t}(e),n=0;n<8;n++)i&&0===e[n]||(i&&(i=!1),r===n?(t+=n?":":"::",i=!0):(t+=e[n].toString(16),n<7&&(t+=":")));return"["+t+"]"}return e},D={},z=p({},D,{" ":1,'"':1,"<":1,">":1,"`":1}),G=p({},z,{"#":1,"?":1,"{":1,"}":1}),W=p({},G,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),$=function(e,t){var n=b(e,0);return n>32&&n<127&&!f(t,e)?e:encodeURIComponent(e)},J={ftp:21,file:null,http:80,https:443,ws:80,wss:443},Y=function(e){return f(J,e.scheme)},X=function(e){return""!=e.username||""!=e.password},Z=function(e){return!e.host||e.cannotBeABaseURL||"file"==e.scheme},H=function(e,t){var n;return 2==e.length&&O.test(e.charAt(0))&&(":"==(n=e.charAt(1))||!t&&"|"==n)},K=function(e){var t;return e.length>1&&H(e.slice(0,2))&&(2==e.length||"/"===(t=e.charAt(2))||"\\"===t||"?"===t||"#"===t)},V=function(e){var t=e.path,n=t.length;!n||"file"==e.scheme&&1==n&&H(t[0],!0)||t.pop()},Q=function(e){return"."===e||"%2e"===e.toLowerCase()},ee={},te={},ne={},re={},ie={},ae={},oe={},se={},le={},ce={},ue={},fe={},pe={},he={},be={},de={},ye={},ge={},ve={},me={},we={},je=function(e,t,n,i){var a,o,s,l,c,u=n||ee,p=0,b="",d=!1,y=!1,g=!1;for(n||(e.scheme="",e.username="",e.password="",e.host=null,e.port=null,e.path=[],e.query=null,e.fragment=null,e.cannotBeABaseURL=!1,t=t.replace(T,"")),t=t.replace(B,""),a=h(t);p<=a.length;){switch(o=a[p],u){case ee:if(!o||!O.test(o)){if(n)return"Invalid scheme";u=ne;continue}b+=o.toLowerCase(),u=te;break;case te:if(o&&(R.test(o)||"+"==o||"-"==o||"."==o))b+=o.toLowerCase();else{if(":"!=o){if(n)return"Invalid scheme";b="",u=ne,p=0;continue}if(n&&(Y(e)!=f(J,b)||"file"==b&&(X(e)||null!==e.port)||"file"==e.scheme&&!e.host))return;if(e.scheme=b,n)return void(Y(e)&&J[e.scheme]==e.port&&(e.port=null));b="","file"==e.scheme?u=he:Y(e)&&i&&i.scheme==e.scheme?u=re:Y(e)?u=se:"/"==a[p+1]?(u=ie,p++):(e.cannotBeABaseURL=!0,e.path.push(""),u=ve)}break;case ne:if(!i||i.cannotBeABaseURL&&"#"!=o)return"Invalid scheme";if(i.cannotBeABaseURL&&"#"==o){e.scheme=i.scheme,e.path=i.path.slice(),e.query=i.query,e.fragment="",e.cannotBeABaseURL=!0,u=we;break}u="file"==i.scheme?he:ae;continue;case re:if("/"!=o||"/"!=a[p+1]){u=ae;continue}u=le,p++;break;case ie:if("/"==o){u=ce;break}u=ge;continue;case ae:if(e.scheme=i.scheme,o==r)e.username=i.username,e.password=i.password,e.host=i.host,e.port=i.port,e.path=i.path.slice(),e.query=i.query;else if("/"==o||"\\"==o&&Y(e))u=oe;else if("?"==o)e.username=i.username,e.password=i.password,e.host=i.host,e.port=i.port,e.path=i.path.slice(),e.query="",u=me;else{if("#"!=o){e.username=i.username,e.password=i.password,e.host=i.host,e.port=i.port,e.path=i.path.slice(),e.path.pop(),u=ge;continue}e.username=i.username,e.password=i.password,e.host=i.host,e.port=i.port,e.path=i.path.slice(),e.query=i.query,e.fragment="",u=we}break;case oe:if(!Y(e)||"/"!=o&&"\\"!=o){if("/"!=o){e.username=i.username,e.password=i.password,e.host=i.host,e.port=i.port,u=ge;continue}u=ce}else u=le;break;case se:if(u=le,"/"!=o||"/"!=b.charAt(p+1))continue;p++;break;case le:if("/"!=o&&"\\"!=o){u=ce;continue}break;case ce:if("@"==o){d&&(b="%40"+b),d=!0,s=h(b);for(var v=0;v<s.length;v++){var m=s[v];if(":"!=m||g){var w=$(m,W);g?e.password+=w:e.username+=w}else g=!0}b=""}else if(o==r||"/"==o||"?"==o||"#"==o||"\\"==o&&Y(e)){if(d&&""==b)return"Invalid authority";p-=h(b).length+1,b="",u=ue}else b+=o;break;case ue:case fe:if(n&&"file"==e.scheme){u=de;continue}if(":"!=o||y){if(o==r||"/"==o||"?"==o||"#"==o||"\\"==o&&Y(e)){if(Y(e)&&""==b)return"Invalid host";if(n&&""==b&&(X(e)||null!==e.port))return;if(l=F(e,b))return l;if(b="",u=ye,n)return;continue}"["==o?y=!0:"]"==o&&(y=!1),b+=o}else{if(""==b)return"Invalid host";if(l=F(e,b))return l;if(b="",u=pe,n==fe)return}break;case pe:if(!L.test(o)){if(o==r||"/"==o||"?"==o||"#"==o||"\\"==o&&Y(e)||n){if(""!=b){var j=parseInt(b,10);if(j>65535)return"Invalid port";e.port=Y(e)&&j===J[e.scheme]?null:j,b=""}if(n)return;u=ye;continue}return"Invalid port"}b+=o;break;case he:if(e.scheme="file","/"==o||"\\"==o)u=be;else{if(!i||"file"!=i.scheme){u=ge;continue}if(o==r)e.host=i.host,e.path=i.path.slice(),e.query=i.query;else if("?"==o)e.host=i.host,e.path=i.path.slice(),e.query="",u=me;else{if("#"!=o){K(a.slice(p).join(""))||(e.host=i.host,e.path=i.path.slice(),V(e)),u=ge;continue}e.host=i.host,e.path=i.path.slice(),e.query=i.query,e.fragment="",u=we}}break;case be:if("/"==o||"\\"==o){u=de;break}i&&"file"==i.scheme&&!K(a.slice(p).join(""))&&(H(i.path[0],!0)?e.path.push(i.path[0]):e.host=i.host),u=ge;continue;case de:if(o==r||"/"==o||"\\"==o||"?"==o||"#"==o){if(!n&&H(b))u=ge;else if(""==b){if(e.host="",n)return;u=ye}else{if(l=F(e,b))return l;if("localhost"==e.host&&(e.host=""),n)return;b="",u=ye}continue}b+=o;break;case ye:if(Y(e)){if(u=ge,"/"!=o&&"\\"!=o)continue}else if(n||"?"!=o)if(n||"#"!=o){if(o!=r&&(u=ge,"/"!=o))continue}else e.fragment="",u=we;else e.query="",u=me;break;case ge:if(o==r||"/"==o||"\\"==o&&Y(e)||!n&&("?"==o||"#"==o)){if(".."===(c=(c=b).toLowerCase())||"%2e."===c||".%2e"===c||"%2e%2e"===c?(V(e),"/"==o||"\\"==o&&Y(e)||e.path.push("")):Q(b)?"/"==o||"\\"==o&&Y(e)||e.path.push(""):("file"==e.scheme&&!e.path.length&&H(b)&&(e.host&&(e.host=""),b=b.charAt(0)+":"),e.path.push(b)),b="","file"==e.scheme&&(o==r||"?"==o||"#"==o))for(;e.path.length>1&&""===e.path[0];)e.path.shift();"?"==o?(e.query="",u=me):"#"==o&&(e.fragment="",u=we)}else b+=$(o,G);break;case ve:"?"==o?(e.query="",u=me):"#"==o?(e.fragment="",u=we):o!=r&&(e.path[0]+=$(o,D));break;case me:n||"#"!=o?o!=r&&("'"==o&&Y(e)?e.query+="%27":e.query+="#"==o?"%23":$(o,D)):(e.fragment="",u=we);break;case we:o!=r&&(e.fragment+=$(o,z))}p++}},xe=function(e){var t,n,r=u(this,xe,"URL"),i=arguments.length>1?arguments[1]:void 0,o=String(e),s=x(r,{type:"URL"});if(void 0!==i)if(i instanceof xe)t=k(i);else if(n=je(t={},String(i)))throw TypeError(n);if(n=je(s,o,null,t))throw TypeError(n);var l=s.searchParams=new w,c=j(l);c.updateSearchParams(s.query),c.updateURL=function(){s.query=String(l)||null},a||(r.href=Se.call(r),r.origin=Ae.call(r),r.protocol=Oe.call(r),r.username=Re.call(r),r.password=Le.call(r),r.host=Ue.call(r),r.hostname=Pe.call(r),r.port=Ie.call(r),r.pathname=qe.call(r),r.search=Ee.call(r),r.searchParams=_e.call(r),r.hash=Te.call(r))},ke=xe.prototype,Se=function(){var e=k(this),t=e.scheme,n=e.username,r=e.password,i=e.host,a=e.port,o=e.path,s=e.query,l=e.fragment,c=t+":";return null!==i?(c+="//",X(e)&&(c+=n+(r?":"+r:"")+"@"),c+=N(i),null!==a&&(c+=":"+a)):"file"==t&&(c+="//"),c+=e.cannotBeABaseURL?o[0]:o.length?"/"+o.join("/"):"",null!==s&&(c+="?"+s),null!==l&&(c+="#"+l),c},Ae=function(){var e=k(this),t=e.scheme,n=e.port;if("blob"==t)try{return new URL(t.path[0]).origin}catch(e){return"null"}return"file"!=t&&Y(e)?t+"://"+N(e.host)+(null!==n?":"+n:""):"null"},Oe=function(){return k(this).scheme+":"},Re=function(){return k(this).username},Le=function(){return k(this).password},Ue=function(){var e=k(this),t=e.host,n=e.port;return null===t?"":null===n?N(t):N(t)+":"+n},Pe=function(){var e=k(this).host;return null===e?"":N(e)},Ie=function(){var e=k(this).port;return null===e?"":String(e)},qe=function(){var e=k(this),t=e.path;return e.cannotBeABaseURL?t[0]:t.length?"/"+t.join("/"):""},Ee=function(){var e=k(this).query;return e?"?"+e:""},_e=function(){return k(this).searchParams},Te=function(){var e=k(this).fragment;return e?"#"+e:""},Be=function(e,t){return{get:e,set:t,configurable:!0,enumerable:!0}};if(a&&l(ke,{href:Be(Se,(function(e){var t=k(this),n=String(e),r=je(t,n);if(r)throw TypeError(r);j(t.searchParams).updateSearchParams(t.query)})),origin:Be(Ae),protocol:Be(Oe,(function(e){var t=k(this);je(t,String(e)+":",ee)})),username:Be(Re,(function(e){var t=k(this),n=h(String(e));if(!Z(t)){t.username="";for(var r=0;r<n.length;r++)t.username+=$(n[r],W)}})),password:Be(Le,(function(e){var t=k(this),n=h(String(e));if(!Z(t)){t.password="";for(var r=0;r<n.length;r++)t.password+=$(n[r],W)}})),host:Be(Ue,(function(e){var t=k(this);t.cannotBeABaseURL||je(t,String(e),ue)})),hostname:Be(Pe,(function(e){var t=k(this);t.cannotBeABaseURL||je(t,String(e),fe)})),port:Be(Ie,(function(e){var t=k(this);Z(t)||(""==(e=String(e))?t.port=null:je(t,e,pe))})),pathname:Be(qe,(function(e){var t=k(this);t.cannotBeABaseURL||(t.path=[],je(t,e+"",ye))})),search:Be(Ee,(function(e){var t=k(this);""==(e=String(e))?t.query=null:("?"==e.charAt(0)&&(e=e.slice(1)),t.query="",je(t,e,me)),j(t.searchParams).updateSearchParams(t.query)})),searchParams:Be(_e),hash:Be(Te,(function(e){var t=k(this);""!=(e=String(e))?("#"==e.charAt(0)&&(e=e.slice(1)),t.fragment="",je(t,e,we)):t.fragment=null}))}),c(ke,"toJSON",(function(){return Se.call(this)}),{enumerable:!0}),c(ke,"toString",(function(){return Se.call(this)}),{enumerable:!0}),m){var Fe=m.createObjectURL,Ce=m.revokeObjectURL;Fe&&c(xe,"createObjectURL",(function(e){return Fe.apply(m,arguments)})),Ce&&c(xe,"revokeObjectURL",(function(e){return Ce.apply(m,arguments)}))}y(xe,"URL"),i({global:!0,forced:!o,sham:!a},{URL:xe})},{"../internals/an-instance":4,"../internals/array-from":6,"../internals/descriptors":18,"../internals/export":21,"../internals/global":27,"../internals/has":28,"../internals/internal-state":34,"../internals/native-url":42,"../internals/object-assign":44,"../internals/object-define-properties":46,"../internals/redefine":59,"../internals/set-to-string-tag":62,"../internals/string-multibyte":66,"../internals/string-punycode-to-ascii":67,"../modules/es.string.iterator":79,"../modules/web.url-search-params":80}],82:[function(e,t,n){"use strict";e("../internals/export")({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return URL.prototype.toString.call(this)}})},{"../internals/export":21}],83:[function(e,t,n){e("../modules/web.url"),e("../modules/web.url.to-json"),e("../modules/web.url-search-params");var r=e("../internals/path");t.exports=r.URL},{"../internals/path":57,"../modules/web.url":81,"../modules/web.url-search-params":80,"../modules/web.url.to-json":82}]},{},[83]); wp-polyfill-object-fit.min.js 0000644 00000005637 14720015030 0012171 0 ustar 00 !function(){"use strict";if("undefined"!=typeof window){var t=window.navigator.userAgent.match(/Edge\/(\d{2})\./),e=t?parseInt(t[1],10):null,i=!!e&&16<=e&&e<=18;if("objectFit"in document.documentElement.style==0||i){var n=function(t,e,i){var n,o,l,a,d;if((i=i.split(" ")).length<2&&(i[1]=i[0]),"x"===t)n=i[0],o=i[1],l="left",a="right",d=e.clientWidth;else{if("y"!==t)return;n=i[1],o=i[0],l="top",a="bottom",d=e.clientHeight}if(n!==l&&o!==l){if(n!==a&&o!==a)return"center"===n||"50%"===n?(e.style[l]="50%",void(e.style["margin-"+l]=d/-2+"px")):void(0<=n.indexOf("%")?(n=parseInt(n,10))<50?(e.style[l]=n+"%",e.style["margin-"+l]=d*(n/-100)+"px"):(n=100-n,e.style[a]=n+"%",e.style["margin-"+a]=d*(n/-100)+"px"):e.style[l]=n);e.style[a]="0"}else e.style[l]="0"},o=function(t){var e=t.dataset?t.dataset.objectFit:t.getAttribute("data-object-fit"),i=t.dataset?t.dataset.objectPosition:t.getAttribute("data-object-position");e=e||"cover",i=i||"50% 50%";var o=t.parentNode;return function(t){var e=window.getComputedStyle(t,null),i=e.getPropertyValue("position"),n=e.getPropertyValue("overflow"),o=e.getPropertyValue("display");i&&"static"!==i||(t.style.position="relative"),"hidden"!==n&&(t.style.overflow="hidden"),o&&"inline"!==o||(t.style.display="block"),0===t.clientHeight&&(t.style.height="100%"),-1===t.className.indexOf("object-fit-polyfill")&&(t.className=t.className+" object-fit-polyfill")}(o),function(t){var e=window.getComputedStyle(t,null),i={"max-width":"none","max-height":"none","min-width":"0px","min-height":"0px",top:"auto",right:"auto",bottom:"auto",left:"auto","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px"};for(var n in i)e.getPropertyValue(n)!==i[n]&&(t.style[n]=i[n])}(t),t.style.position="absolute",t.style.width="auto",t.style.height="auto","scale-down"===e&&(e=t.clientWidth<o.clientWidth&&t.clientHeight<o.clientHeight?"none":"contain"),"none"===e?(n("x",t,i),void n("y",t,i)):"fill"===e?(t.style.width="100%",t.style.height="100%",n("x",t,i),void n("y",t,i)):(t.style.height="100%",void("cover"===e&&t.clientWidth>o.clientWidth||"contain"===e&&t.clientWidth<o.clientWidth?(t.style.top="0",t.style.marginTop="0",n("x",t,i)):(t.style.width="100%",t.style.height="auto",t.style.left="0",t.style.marginLeft="0",n("y",t,i))))},l=function(t){if(void 0===t||t instanceof Event)t=document.querySelectorAll("[data-object-fit]");else if(t&&t.nodeName)t=[t];else if("object"!=typeof t||!t.length||!t[0].nodeName)return!1;for(var e=0;e<t.length;e++)if(t[e].nodeName){var n=t[e].nodeName.toLowerCase();if("img"===n){if(i)continue;t[e].complete?o(t[e]):t[e].addEventListener("load",(function(){o(this)}))}else"video"===n?0<t[e].readyState?o(t[e]):t[e].addEventListener("loadedmetadata",(function(){o(this)})):o(t[e])}return!0};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",l):l(),window.addEventListener("resize",l),window.objectFitPolyfill=l}else window.objectFitPolyfill=function(){return!1}}}(); react.min.js 0000604 00000024604 14720015030 0006754 0 ustar 00 /** * @license React * react.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. */ !function(){"use strict";var e,t;e=this,t=function(e){function t(e,t,n){this.props=e,this.context=t,this.refs=F,this.updater=n||O}function n(){}function r(e,t,n){this.props=e,this.context=t,this.refs=F,this.updater=n||O}function o(e,t,n){var r,o={},u=null,a=null;if(null!=t)for(r in void 0!==t.ref&&(a=t.ref),void 0!==t.key&&(u=""+t.key),t)U.call(t,r)&&!q.hasOwnProperty(r)&&(o[r]=t[r]);var i=arguments.length-2;if(1===i)o.children=n;else if(1<i){for(var l=Array(i),c=0;c<i;c++)l[c]=arguments[c+2];o.children=l}if(e&&e.defaultProps)for(r in i=e.defaultProps)void 0===o[r]&&(o[r]=i[r]);return{$$typeof:k,type:e,key:u,ref:a,props:o,_owner:V.current}}function u(e){return"object"==typeof e&&null!==e&&e.$$typeof===k}function a(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,(function(e){return t[e]}))}(""+e.key):t.toString(36)}function i(e,t,n,r,o){var l=typeof e;"undefined"!==l&&"boolean"!==l||(e=null);var c=!1;if(null===e)c=!0;else switch(l){case"string":case"number":c=!0;break;case"object":switch(e.$$typeof){case k:case w:c=!0}}if(c)return o=o(c=e),e=""===r?"."+a(c,0):r,D(o)?(n="",null!=e&&(n=e.replace(A,"$&/")+"/"),i(o,t,n,"",(function(e){return e}))):null!=o&&(u(o)&&(o=function(e,t){return{$$typeof:k,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(o,n+(!o.key||c&&c.key===o.key?"":(""+o.key).replace(A,"$&/")+"/")+e)),t.push(o)),1;if(c=0,r=""===r?".":r+":",D(e))for(var f=0;f<e.length;f++){var s=r+a(l=e[f],f);c+=i(l,t,n,s,o)}else if(s=function(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=T&&e[T]||e["@@iterator"])?e:null}(e),"function"==typeof s)for(e=s.call(e),f=0;!(l=e.next()).done;)c+=i(l=l.value,t,n,s=r+a(l,f++),o);else if("object"===l)throw t=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return c}function l(e,t,n){if(null==e)return e;var r=[],o=0;return i(e,r,"","",(function(e){return t.call(n,e,o++)})),r}function c(e){if(-1===e._status){var t=e._result;(t=t()).then((function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)}),(function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)})),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}function f(e,t){var n=e.length;e.push(t);e:for(;0<n;){var r=n-1>>>1,o=e[r];if(!(0<y(o,t)))break e;e[r]=t,e[n]=o,n=r}}function s(e){return 0===e.length?null:e[0]}function p(e){if(0===e.length)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;e:for(var r=0,o=e.length,u=o>>>1;r<u;){var a=2*(r+1)-1,i=e[a],l=a+1,c=e[l];if(0>y(i,n))l<o&&0>y(c,i)?(e[r]=c,e[l]=n,r=l):(e[r]=i,e[a]=n,r=a);else{if(!(l<o&&0>y(c,n)))break e;e[r]=c,e[l]=n,r=l}}}return t}function y(e,t){var n=e.sortIndex-t.sortIndex;return 0!==n?n:e.id-t.id}function d(e){for(var t=s(J);null!==t;){if(null===t.callback)p(J);else{if(!(t.startTime<=e))break;p(J),t.sortIndex=t.expirationTime,f(G,t)}t=s(J)}}function b(e){if(te=!1,d(e),!ee)if(null!==s(G))ee=!0,_(v);else{var t=s(J);null!==t&&h(b,t.startTime-e)}}function v(e,t){ee=!1,te&&(te=!1,re(ie),ie=-1),Z=!0;var n=X;try{for(d(t),Q=s(G);null!==Q&&(!(Q.expirationTime>t)||e&&!m());){var r=Q.callback;if("function"==typeof r){Q.callback=null,X=Q.priorityLevel;var o=r(Q.expirationTime<=t);t=H(),"function"==typeof o?Q.callback=o:Q===s(G)&&p(G),d(t)}else p(G);Q=s(G)}if(null!==Q)var u=!0;else{var a=s(J);null!==a&&h(b,a.startTime-t),u=!1}return u}finally{Q=null,X=n,Z=!1}}function m(){return!(H()-ce<le)}function _(e){ae=e,ue||(ue=!0,se())}function h(e,t){ie=ne((function(){e(H())}),t)}function g(e){throw Error("act(...) is not supported in production builds of React.")}var k=Symbol.for("react.element"),w=Symbol.for("react.portal"),S=Symbol.for("react.fragment"),x=Symbol.for("react.strict_mode"),C=Symbol.for("react.profiler"),E=Symbol.for("react.provider"),R=Symbol.for("react.context"),P=Symbol.for("react.forward_ref"),$=Symbol.for("react.suspense"),I=Symbol.for("react.memo"),j=Symbol.for("react.lazy"),T=Symbol.iterator,O={isMounted:function(e){return!1},enqueueForceUpdate:function(e,t,n){},enqueueReplaceState:function(e,t,n,r){},enqueueSetState:function(e,t,n,r){}},L=Object.assign,F={};t.prototype.isReactComponent={},t.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},t.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},n.prototype=t.prototype;var M=r.prototype=new n;M.constructor=r,L(M,t.prototype),M.isPureReactComponent=!0;var D=Array.isArray,U=Object.prototype.hasOwnProperty,V={current:null},q={key:!0,ref:!0,__self:!0,__source:!0},A=/\/+/g,N={current:null},B={transition:null};if("object"==typeof performance&&"function"==typeof performance.now)var z=performance,H=function(){return z.now()};else{var W=Date,Y=W.now();H=function(){return W.now()-Y}}var G=[],J=[],K=1,Q=null,X=3,Z=!1,ee=!1,te=!1,ne="function"==typeof setTimeout?setTimeout:null,re="function"==typeof clearTimeout?clearTimeout:null,oe="undefined"!=typeof setImmediate?setImmediate:null;"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var ue=!1,ae=null,ie=-1,le=5,ce=-1,fe=function(){if(null!==ae){var e=H();ce=e;var t=!0;try{t=ae(!0,e)}finally{t?se():(ue=!1,ae=null)}}else ue=!1};if("function"==typeof oe)var se=function(){oe(fe)};else if("undefined"!=typeof MessageChannel){var pe=(M=new MessageChannel).port2;M.port1.onmessage=fe,se=function(){pe.postMessage(null)}}else se=function(){ne(fe,0)};M={ReactCurrentDispatcher:N,ReactCurrentOwner:V,ReactCurrentBatchConfig:B,Scheduler:{__proto__:null,unstable_ImmediatePriority:1,unstable_UserBlockingPriority:2,unstable_NormalPriority:3,unstable_IdlePriority:5,unstable_LowPriority:4,unstable_runWithPriority:function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=X;X=e;try{return t()}finally{X=n}},unstable_next:function(e){switch(X){case 1:case 2:case 3:var t=3;break;default:t=X}var n=X;X=t;try{return e()}finally{X=n}},unstable_scheduleCallback:function(e,t,n){var r=H();switch(n="object"==typeof n&&null!==n&&"number"==typeof(n=n.delay)&&0<n?r+n:r,e){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return e={id:K++,callback:t,priorityLevel:e,startTime:n,expirationTime:o=n+o,sortIndex:-1},n>r?(e.sortIndex=n,f(J,e),null===s(G)&&e===s(J)&&(te?(re(ie),ie=-1):te=!0,h(b,n-r))):(e.sortIndex=o,f(G,e),ee||Z||(ee=!0,_(v))),e},unstable_cancelCallback:function(e){e.callback=null},unstable_wrapCallback:function(e){var t=X;return function(){var n=X;X=t;try{return e.apply(this,arguments)}finally{X=n}}},unstable_getCurrentPriorityLevel:function(){return X},unstable_shouldYield:m,unstable_requestPaint:function(){},unstable_continueExecution:function(){ee||Z||(ee=!0,_(v))},unstable_pauseExecution:function(){},unstable_getFirstCallbackNode:function(){return s(G)},get unstable_now(){return H},unstable_forceFrameRate:function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):le=0<e?Math.floor(1e3/e):5},unstable_Profiling:null}},e.Children={map:l,forEach:function(e,t,n){l(e,(function(){t.apply(this,arguments)}),n)},count:function(e){var t=0;return l(e,(function(){t++})),t},toArray:function(e){return l(e,(function(e){return e}))||[]},only:function(e){if(!u(e))throw Error("React.Children.only expected to receive a single React element child.");return e}},e.Component=t,e.Fragment=S,e.Profiler=C,e.PureComponent=r,e.StrictMode=x,e.Suspense=$,e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=M,e.act=g,e.cloneElement=function(e,t,n){if(null==e)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=L({},e.props),o=e.key,u=e.ref,a=e._owner;if(null!=t){if(void 0!==t.ref&&(u=t.ref,a=V.current),void 0!==t.key&&(o=""+t.key),e.type&&e.type.defaultProps)var i=e.type.defaultProps;for(l in t)U.call(t,l)&&!q.hasOwnProperty(l)&&(r[l]=void 0===t[l]&&void 0!==i?i[l]:t[l])}var l=arguments.length-2;if(1===l)r.children=n;else if(1<l){i=Array(l);for(var c=0;c<l;c++)i[c]=arguments[c+2];r.children=i}return{$$typeof:k,type:e.type,key:o,ref:u,props:r,_owner:a}},e.createContext=function(e){return(e={$$typeof:R,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:E,_context:e},e.Consumer=e},e.createElement=o,e.createFactory=function(e){var t=o.bind(null,e);return t.type=e,t},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:P,render:e}},e.isValidElement=u,e.lazy=function(e){return{$$typeof:j,_payload:{_status:-1,_result:e},_init:c}},e.memo=function(e,t){return{$$typeof:I,type:e,compare:void 0===t?null:t}},e.startTransition=function(e,t){t=B.transition,B.transition={};try{e()}finally{B.transition=t}},e.unstable_act=g,e.useCallback=function(e,t){return N.current.useCallback(e,t)},e.useContext=function(e){return N.current.useContext(e)},e.useDebugValue=function(e,t){},e.useDeferredValue=function(e){return N.current.useDeferredValue(e)},e.useEffect=function(e,t){return N.current.useEffect(e,t)},e.useId=function(){return N.current.useId()},e.useImperativeHandle=function(e,t,n){return N.current.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return N.current.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return N.current.useLayoutEffect(e,t)},e.useMemo=function(e,t){return N.current.useMemo(e,t)},e.useReducer=function(e,t,n){return N.current.useReducer(e,t,n)},e.useRef=function(e){return N.current.useRef(e)},e.useState=function(e){return N.current.useState(e)},e.useSyncExternalStore=function(e,t,n){return N.current.useSyncExternalStore(e,t,n)},e.useTransition=function(){return N.current.useTransition()},e.version="18.3.1"},"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).React={})}(); wp-polyfill.js 0000604 00000365731 14720015030 0007363 0 ustar 00 /** * core-js 3.35.1 * © 2014-2024 Denis Pushkarev (zloirock.ru) * license: https://github.com/zloirock/core-js/blob/v3.35.1/LICENSE * source: https://github.com/zloirock/core-js */ !function (undefined) { 'use strict'; /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ var __webpack_require__ = function (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 = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(1); __webpack_require__(73); __webpack_require__(76); __webpack_require__(78); __webpack_require__(80); __webpack_require__(92); __webpack_require__(93); __webpack_require__(95); __webpack_require__(98); __webpack_require__(100); __webpack_require__(101); __webpack_require__(110); __webpack_require__(111); __webpack_require__(114); __webpack_require__(120); __webpack_require__(135); __webpack_require__(137); __webpack_require__(138); module.exports = __webpack_require__(139); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var arrayToReversed = __webpack_require__(67); var toIndexedObject = __webpack_require__(11); var addToUnscopables = __webpack_require__(68); var $Array = Array; // `Array.prototype.toReversed` method // https://tc39.es/ecma262/#sec-array.prototype.toreversed $({ target: 'Array', proto: true }, { toReversed: function toReversed() { return arrayToReversed(toIndexedObject(this), $Array); } }); addToUnscopables('toReversed'); /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var getOwnPropertyDescriptor = __webpack_require__(4).f; var createNonEnumerableProperty = __webpack_require__(42); var defineBuiltIn = __webpack_require__(46); var defineGlobalProperty = __webpack_require__(36); var copyConstructorProperties = __webpack_require__(54); var isForced = __webpack_require__(66); /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.dontCallGetSet - prevent calling a getter on target options.name - the .name of the function if it does not match the key */ module.exports = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global; } else if (STATIC) { target = global[TARGET] || defineGlobalProperty(TARGET, {}); } else { target = global[TARGET] && global[TARGET].prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.dontCallGetSet) { descriptor = getOwnPropertyDescriptor(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty == typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { createNonEnumerableProperty(sourceProperty, 'sham', true); } defineBuiltIn(target, key, sourceProperty, options); } }; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var check = function (it) { return it && it.Math === Math && it; }; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 module.exports = // eslint-disable-next-line es/no-global-this -- safe check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || // eslint-disable-next-line no-restricted-globals -- safe check(typeof self == 'object' && self) || check(typeof global == 'object' && global) || check(typeof this == 'object' && this) || // eslint-disable-next-line no-new-func -- fallback (function () { return this; })() || Function('return this')(); /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var DESCRIPTORS = __webpack_require__(5); var call = __webpack_require__(7); var propertyIsEnumerableModule = __webpack_require__(9); var createPropertyDescriptor = __webpack_require__(10); var toIndexedObject = __webpack_require__(11); var toPropertyKey = __webpack_require__(17); var hasOwn = __webpack_require__(37); var IE8_DOM_DEFINE = __webpack_require__(40); // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPropertyKey(P); if (IE8_DOM_DEFINE) try { return $getOwnPropertyDescriptor(O, P); } catch (error) { /* empty */ } if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]); }; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var fails = __webpack_require__(6); // Detect IE8's incomplete defineProperty implementation module.exports = !fails(function () { // eslint-disable-next-line es/no-object-defineproperty -- required for testing return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7; }); /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function (exec) { try { return !!exec(); } catch (error) { return true; } }; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var NATIVE_BIND = __webpack_require__(8); var call = Function.prototype.call; module.exports = NATIVE_BIND ? call.bind(call) : function () { return call.apply(call, arguments); }; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var fails = __webpack_require__(6); module.exports = !fails(function () { // eslint-disable-next-line es/no-function-prototype-bind -- safe var test = (function () { /* empty */ }).bind(); // eslint-disable-next-line no-prototype-builtins -- safe return typeof test != 'function' || test.hasOwnProperty('prototype'); }); /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $propertyIsEnumerable = {}.propertyIsEnumerable; // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1); // `Object.prototype.propertyIsEnumerable` method implementation // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) { var descriptor = getOwnPropertyDescriptor(this, V); return !!descriptor && descriptor.enumerable; } : $propertyIsEnumerable; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // toObject with fallback for non-array-like ES3 strings var IndexedObject = __webpack_require__(12); var requireObjectCoercible = __webpack_require__(15); module.exports = function (it) { return IndexedObject(requireObjectCoercible(it)); }; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var fails = __webpack_require__(6); var classof = __webpack_require__(14); var $Object = Object; var split = uncurryThis(''.split); // fallback for non-array-like ES3 and non-enumerable old V8 strings module.exports = fails(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins -- safe return !$Object('z').propertyIsEnumerable(0); }) ? function (it) { return classof(it) === 'String' ? split(it, '') : $Object(it); } : $Object; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var NATIVE_BIND = __webpack_require__(8); var FunctionPrototype = Function.prototype; var call = FunctionPrototype.call; var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call); module.exports = NATIVE_BIND ? uncurryThisWithBind : function (fn) { return function () { return call.apply(fn, arguments); }; }; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var toString = uncurryThis({}.toString); var stringSlice = uncurryThis(''.slice); module.exports = function (it) { return stringSlice(toString(it), 8, -1); }; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isNullOrUndefined = __webpack_require__(16); var $TypeError = TypeError; // `RequireObjectCoercible` abstract operation // https://tc39.es/ecma262/#sec-requireobjectcoercible module.exports = function (it) { if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it); return it; }; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // we can't use just `it == null` since of `document.all` special case // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec module.exports = function (it) { return it === null || it === undefined; }; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toPrimitive = __webpack_require__(18); var isSymbol = __webpack_require__(21); // `ToPropertyKey` abstract operation // https://tc39.es/ecma262/#sec-topropertykey module.exports = function (argument) { var key = toPrimitive(argument, 'string'); return isSymbol(key) ? key : key + ''; }; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var call = __webpack_require__(7); var isObject = __webpack_require__(19); var isSymbol = __webpack_require__(21); var getMethod = __webpack_require__(28); var ordinaryToPrimitive = __webpack_require__(31); var wellKnownSymbol = __webpack_require__(32); var $TypeError = TypeError; var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); // `ToPrimitive` abstract operation // https://tc39.es/ecma262/#sec-toprimitive module.exports = function (input, pref) { if (!isObject(input) || isSymbol(input)) return input; var exoticToPrim = getMethod(input, TO_PRIMITIVE); var result; if (exoticToPrim) { if (pref === undefined) pref = 'default'; result = call(exoticToPrim, input, pref); if (!isObject(result) || isSymbol(result)) return result; throw new $TypeError("Can't convert object to primitive value"); } if (pref === undefined) pref = 'number'; return ordinaryToPrimitive(input, pref); }; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isCallable = __webpack_require__(20); module.exports = function (it) { return typeof it == 'object' ? it !== null : isCallable(it); }; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot var documentAll = typeof document == 'object' && document.all; // `IsCallable` abstract operation // https://tc39.es/ecma262/#sec-iscallable // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing module.exports = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) { return typeof argument == 'function' || argument === documentAll; } : function (argument) { return typeof argument == 'function'; }; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var getBuiltIn = __webpack_require__(22); var isCallable = __webpack_require__(20); var isPrototypeOf = __webpack_require__(23); var USE_SYMBOL_AS_UID = __webpack_require__(24); var $Object = Object; module.exports = USE_SYMBOL_AS_UID ? function (it) { return typeof it == 'symbol'; } : function (it) { var $Symbol = getBuiltIn('Symbol'); return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it)); }; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var isCallable = __webpack_require__(20); var aFunction = function (argument) { return isCallable(argument) ? argument : undefined; }; module.exports = function (namespace, method) { return arguments.length < 2 ? aFunction(global[namespace]) : global[namespace] && global[namespace][method]; }; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); module.exports = uncurryThis({}.isPrototypeOf); /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint-disable es/no-symbol -- required for testing */ var NATIVE_SYMBOL = __webpack_require__(25); module.exports = NATIVE_SYMBOL && !Symbol.sham && typeof Symbol.iterator == 'symbol'; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint-disable es/no-symbol -- required for testing */ var V8_VERSION = __webpack_require__(26); var fails = __webpack_require__(6); var global = __webpack_require__(3); var $String = global.String; // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing module.exports = !!Object.getOwnPropertySymbols && !fails(function () { var symbol = Symbol('symbol detection'); // Chrome 38 Symbol has incorrect toString conversion // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will, // of course, fail. return !$String(symbol) || !(Object(symbol) instanceof Symbol) || // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances !Symbol.sham && V8_VERSION && V8_VERSION < 41; }); /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var userAgent = __webpack_require__(27); var process = global.process; var Deno = global.Deno; var versions = process && process.versions || Deno && Deno.version; var v8 = versions && versions.v8; var match, version; if (v8) { match = v8.split('.'); // in old Chrome, versions of V8 isn't V8 = Chrome / 10 // but their correct versions are not interesting for us version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]); } // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0` // so check `userAgent` even if `.v8` exists, but 0 if (!version && userAgent) { match = userAgent.match(/Edge\/(\d+)/); if (!match || match[1] >= 74) { match = userAgent.match(/Chrome\/(\d+)/); if (match) version = +match[1]; } } module.exports = version; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = typeof navigator != 'undefined' && String(navigator.userAgent) || ''; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var aCallable = __webpack_require__(29); var isNullOrUndefined = __webpack_require__(16); // `GetMethod` abstract operation // https://tc39.es/ecma262/#sec-getmethod module.exports = function (V, P) { var func = V[P]; return isNullOrUndefined(func) ? undefined : aCallable(func); }; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isCallable = __webpack_require__(20); var tryToString = __webpack_require__(30); var $TypeError = TypeError; // `Assert: IsCallable(argument) is true` module.exports = function (argument) { if (isCallable(argument)) return argument; throw new $TypeError(tryToString(argument) + ' is not a function'); }; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $String = String; module.exports = function (argument) { try { return $String(argument); } catch (error) { return 'Object'; } }; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var call = __webpack_require__(7); var isCallable = __webpack_require__(20); var isObject = __webpack_require__(19); var $TypeError = TypeError; // `OrdinaryToPrimitive` abstract operation // https://tc39.es/ecma262/#sec-ordinarytoprimitive module.exports = function (input, pref) { var fn, val; if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val; if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val; if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val; throw new $TypeError("Can't convert object to primitive value"); }; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var shared = __webpack_require__(33); var hasOwn = __webpack_require__(37); var uid = __webpack_require__(39); var NATIVE_SYMBOL = __webpack_require__(25); var USE_SYMBOL_AS_UID = __webpack_require__(24); var Symbol = global.Symbol; var WellKnownSymbolsStore = shared('wks'); var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid; module.exports = function (name) { if (!hasOwn(WellKnownSymbolsStore, name)) { WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name) ? Symbol[name] : createWellKnownSymbol('Symbol.' + name); } return WellKnownSymbolsStore[name]; }; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var IS_PURE = __webpack_require__(34); var store = __webpack_require__(35); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: '3.35.1', mode: IS_PURE ? 'pure' : 'global', copyright: '© 2014-2024 Denis Pushkarev (zloirock.ru)', license: 'https://github.com/zloirock/core-js/blob/v3.35.1/LICENSE', source: 'https://github.com/zloirock/core-js' }); /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = false; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var defineGlobalProperty = __webpack_require__(36); var SHARED = '__core-js_shared__'; var store = global[SHARED] || defineGlobalProperty(SHARED, {}); module.exports = store; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); // eslint-disable-next-line es/no-object-defineproperty -- safe var defineProperty = Object.defineProperty; module.exports = function (key, value) { try { defineProperty(global, key, { value: value, configurable: true, writable: true }); } catch (error) { global[key] = value; } return value; }; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var toObject = __webpack_require__(38); var hasOwnProperty = uncurryThis({}.hasOwnProperty); // `HasOwnProperty` abstract operation // https://tc39.es/ecma262/#sec-hasownproperty // eslint-disable-next-line es/no-object-hasown -- safe module.exports = Object.hasOwn || function hasOwn(it, key) { return hasOwnProperty(toObject(it), key); }; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var requireObjectCoercible = __webpack_require__(15); var $Object = Object; // `ToObject` abstract operation // https://tc39.es/ecma262/#sec-toobject module.exports = function (argument) { return $Object(requireObjectCoercible(argument)); }; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var id = 0; var postfix = Math.random(); var toString = uncurryThis(1.0.toString); module.exports = function (key) { return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36); }; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var DESCRIPTORS = __webpack_require__(5); var fails = __webpack_require__(6); var createElement = __webpack_require__(41); // Thanks to IE8 for its funny defineProperty module.exports = !DESCRIPTORS && !fails(function () { // eslint-disable-next-line es/no-object-defineproperty -- required for testing return Object.defineProperty(createElement('div'), 'a', { get: function () { return 7; } }).a !== 7; }); /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var isObject = __webpack_require__(19); var document = global.document; // typeof document.createElement is 'object' in old IE var EXISTS = isObject(document) && isObject(document.createElement); module.exports = function (it) { return EXISTS ? document.createElement(it) : {}; }; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var DESCRIPTORS = __webpack_require__(5); var definePropertyModule = __webpack_require__(43); var createPropertyDescriptor = __webpack_require__(10); module.exports = DESCRIPTORS ? function (object, key, value) { return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var DESCRIPTORS = __webpack_require__(5); var IE8_DOM_DEFINE = __webpack_require__(40); var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(44); var anObject = __webpack_require__(45); var toPropertyKey = __webpack_require__(17); var $TypeError = TypeError; // eslint-disable-next-line es/no-object-defineproperty -- safe var $defineProperty = Object.defineProperty; // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var ENUMERABLE = 'enumerable'; var CONFIGURABLE = 'configurable'; var WRITABLE = 'writable'; // `Object.defineProperty` method // https://tc39.es/ecma262/#sec-object.defineproperty exports.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) { anObject(O); P = toPropertyKey(P); anObject(Attributes); if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) { var current = $getOwnPropertyDescriptor(O, P); if (current && current[WRITABLE]) { O[P] = Attributes.value; Attributes = { configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE], enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE], writable: false }; } } return $defineProperty(O, P, Attributes); } : $defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPropertyKey(P); anObject(Attributes); if (IE8_DOM_DEFINE) try { return $defineProperty(O, P, Attributes); } catch (error) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var DESCRIPTORS = __webpack_require__(5); var fails = __webpack_require__(6); // V8 ~ Chrome 36- // https://bugs.chromium.org/p/v8/issues/detail?id=3334 module.exports = DESCRIPTORS && fails(function () { // eslint-disable-next-line es/no-object-defineproperty -- required for testing return Object.defineProperty(function () { /* empty */ }, 'prototype', { value: 42, writable: false }).prototype !== 42; }); /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isObject = __webpack_require__(19); var $String = String; var $TypeError = TypeError; // `Assert: Type(argument) is Object` module.exports = function (argument) { if (isObject(argument)) return argument; throw new $TypeError($String(argument) + ' is not an object'); }; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isCallable = __webpack_require__(20); var definePropertyModule = __webpack_require__(43); var makeBuiltIn = __webpack_require__(47); var defineGlobalProperty = __webpack_require__(36); module.exports = function (O, key, value, options) { if (!options) options = {}; var simple = options.enumerable; var name = options.name !== undefined ? options.name : key; if (isCallable(value)) makeBuiltIn(value, name, options); if (options.global) { if (simple) O[key] = value; else defineGlobalProperty(key, value); } else { try { if (!options.unsafe) delete O[key]; else if (O[key]) simple = true; } catch (error) { /* empty */ } if (simple) O[key] = value; else definePropertyModule.f(O, key, { value: value, enumerable: false, configurable: !options.nonConfigurable, writable: !options.nonWritable }); } return O; }; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var fails = __webpack_require__(6); var isCallable = __webpack_require__(20); var hasOwn = __webpack_require__(37); var DESCRIPTORS = __webpack_require__(5); var CONFIGURABLE_FUNCTION_NAME = __webpack_require__(48).CONFIGURABLE; var inspectSource = __webpack_require__(49); var InternalStateModule = __webpack_require__(50); var enforceInternalState = InternalStateModule.enforce; var getInternalState = InternalStateModule.get; var $String = String; // eslint-disable-next-line es/no-object-defineproperty -- safe var defineProperty = Object.defineProperty; var stringSlice = uncurryThis(''.slice); var replace = uncurryThis(''.replace); var join = uncurryThis([].join); var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () { return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8; }); var TEMPLATE = String(String).split('String'); var makeBuiltIn = module.exports = function (value, name, options) { if (stringSlice($String(name), 0, 7) === 'Symbol(') { name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']'; } if (options && options.getter) name = 'get ' + name; if (options && options.setter) name = 'set ' + name; if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) { if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true }); else value.name = name; } if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) { defineProperty(value, 'length', { value: options.arity }); } try { if (options && hasOwn(options, 'constructor') && options.constructor) { if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false }); // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable } else if (value.prototype) value.prototype = undefined; } catch (error) { /* empty */ } var state = enforceInternalState(value); if (!hasOwn(state, 'source')) { state.source = join(TEMPLATE, typeof name == 'string' ? name : ''); } return value; }; // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative // eslint-disable-next-line no-extend-native -- required Function.prototype.toString = makeBuiltIn(function toString() { return isCallable(this) && getInternalState(this).source || inspectSource(this); }, 'toString'); /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var DESCRIPTORS = __webpack_require__(5); var hasOwn = __webpack_require__(37); var FunctionPrototype = Function.prototype; // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor; var EXISTS = hasOwn(FunctionPrototype, 'name'); // additional protection from minified / mangled / dropped function names var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something'; var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable)); module.exports = { EXISTS: EXISTS, PROPER: PROPER, CONFIGURABLE: CONFIGURABLE }; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var isCallable = __webpack_require__(20); var store = __webpack_require__(35); var functionToString = uncurryThis(Function.toString); // this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper if (!isCallable(store.inspectSource)) { store.inspectSource = function (it) { return functionToString(it); }; } module.exports = store.inspectSource; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var NATIVE_WEAK_MAP = __webpack_require__(51); var global = __webpack_require__(3); var isObject = __webpack_require__(19); var createNonEnumerableProperty = __webpack_require__(42); var hasOwn = __webpack_require__(37); var shared = __webpack_require__(35); var sharedKey = __webpack_require__(52); var hiddenKeys = __webpack_require__(53); var OBJECT_ALREADY_INITIALIZED = 'Object already initialized'; var TypeError = global.TypeError; var WeakMap = global.WeakMap; var set, get, has; var enforce = function (it) { return has(it) ? get(it) : set(it, {}); }; var getterFor = function (TYPE) { return function (it) { var state; if (!isObject(it) || (state = get(it)).type !== TYPE) { throw new TypeError('Incompatible receiver, ' + TYPE + ' required'); } return state; }; }; if (NATIVE_WEAK_MAP || shared.state) { var store = shared.state || (shared.state = new WeakMap()); /* eslint-disable no-self-assign -- prototype methods protection */ store.get = store.get; store.has = store.has; store.set = store.set; /* eslint-enable no-self-assign -- prototype methods protection */ set = function (it, metadata) { if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); metadata.facade = it; store.set(it, metadata); return metadata; }; get = function (it) { return store.get(it) || {}; }; has = function (it) { return store.has(it); }; } else { var STATE = sharedKey('state'); hiddenKeys[STATE] = true; set = function (it, metadata) { if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED); metadata.facade = it; createNonEnumerableProperty(it, STATE, metadata); return metadata; }; get = function (it) { return hasOwn(it, STATE) ? it[STATE] : {}; }; has = function (it) { return hasOwn(it, STATE); }; } module.exports = { set: set, get: get, has: has, enforce: enforce, getterFor: getterFor }; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var isCallable = __webpack_require__(20); var WeakMap = global.WeakMap; module.exports = isCallable(WeakMap) && /native code/.test(String(WeakMap)); /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var shared = __webpack_require__(33); var uid = __webpack_require__(39); var keys = shared('keys'); module.exports = function (key) { return keys[key] || (keys[key] = uid(key)); }; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = {}; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var hasOwn = __webpack_require__(37); var ownKeys = __webpack_require__(55); var getOwnPropertyDescriptorModule = __webpack_require__(4); var definePropertyModule = __webpack_require__(43); module.exports = function (target, source, exceptions) { var keys = ownKeys(source); var defineProperty = definePropertyModule.f; var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) { defineProperty(target, key, getOwnPropertyDescriptor(source, key)); } } }; /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var getBuiltIn = __webpack_require__(22); var uncurryThis = __webpack_require__(13); var getOwnPropertyNamesModule = __webpack_require__(56); var getOwnPropertySymbolsModule = __webpack_require__(65); var anObject = __webpack_require__(45); var concat = uncurryThis([].concat); // all object keys, includes non-enumerable and symbols module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { var keys = getOwnPropertyNamesModule.f(anObject(it)); var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys; }; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var internalObjectKeys = __webpack_require__(57); var enumBugKeys = __webpack_require__(64); var hiddenKeys = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method // https://tc39.es/ecma262/#sec-object.getownpropertynames // eslint-disable-next-line es/no-object-getownpropertynames -- safe exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return internalObjectKeys(O, hiddenKeys); }; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var hasOwn = __webpack_require__(37); var toIndexedObject = __webpack_require__(11); var indexOf = __webpack_require__(58).indexOf; var hiddenKeys = __webpack_require__(53); var push = uncurryThis([].push); module.exports = function (object, names) { var O = toIndexedObject(object); var i = 0; var result = []; var key; for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key); // Don't enum bug & hidden keys while (names.length > i) if (hasOwn(O, key = names[i++])) { ~indexOf(result, key) || push(result, key); } return result; }; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toIndexedObject = __webpack_require__(11); var toAbsoluteIndex = __webpack_require__(59); var lengthOfArrayLike = __webpack_require__(62); // `Array.prototype.{ indexOf, includes }` methods implementation var createMethod = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject($this); var length = lengthOfArrayLike(O); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare -- NaN check if (IS_INCLUDES && el !== el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare -- NaN check if (value !== value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) { if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; module.exports = { // `Array.prototype.includes` method // https://tc39.es/ecma262/#sec-array.prototype.includes includes: createMethod(true), // `Array.prototype.indexOf` method // https://tc39.es/ecma262/#sec-array.prototype.indexof indexOf: createMethod(false) }; /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toIntegerOrInfinity = __webpack_require__(60); var max = Math.max; var min = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). module.exports = function (index, length) { var integer = toIntegerOrInfinity(index); return integer < 0 ? max(integer + length, 0) : min(integer, length); }; /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var trunc = __webpack_require__(61); // `ToIntegerOrInfinity` abstract operation // https://tc39.es/ecma262/#sec-tointegerorinfinity module.exports = function (argument) { var number = +argument; // eslint-disable-next-line no-self-compare -- NaN check return number !== number || number === 0 ? 0 : trunc(number); }; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var ceil = Math.ceil; var floor = Math.floor; // `Math.trunc` method // https://tc39.es/ecma262/#sec-math.trunc // eslint-disable-next-line es/no-math-trunc -- safe module.exports = Math.trunc || function trunc(x) { var n = +x; return (n > 0 ? floor : ceil)(n); }; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toLength = __webpack_require__(63); // `LengthOfArrayLike` abstract operation // https://tc39.es/ecma262/#sec-lengthofarraylike module.exports = function (obj) { return toLength(obj.length); }; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toIntegerOrInfinity = __webpack_require__(60); var min = Math.min; // `ToLength` abstract operation // https://tc39.es/ecma262/#sec-tolength module.exports = function (argument) { var len = toIntegerOrInfinity(argument); return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 }; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // IE8- don't enum bug keys module.exports = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe exports.f = Object.getOwnPropertySymbols; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var fails = __webpack_require__(6); var isCallable = __webpack_require__(20); var replacement = /#|\.prototype\./; var isForced = function (feature, detection) { var value = data[normalize(feature)]; return value === POLYFILL ? true : value === NATIVE ? false : isCallable(detection) ? fails(detection) : !!detection; }; var normalize = isForced.normalize = function (string) { return String(string).replace(replacement, '.').toLowerCase(); }; var data = isForced.data = {}; var NATIVE = isForced.NATIVE = 'N'; var POLYFILL = isForced.POLYFILL = 'P'; module.exports = isForced; /***/ }), /* 67 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var lengthOfArrayLike = __webpack_require__(62); // https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.toReversed // https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.toReversed module.exports = function (O, C) { var len = lengthOfArrayLike(O); var A = new C(len); var k = 0; for (; k < len; k++) A[k] = O[len - k - 1]; return A; }; /***/ }), /* 68 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var wellKnownSymbol = __webpack_require__(32); var create = __webpack_require__(69); var defineProperty = __webpack_require__(43).f; var UNSCOPABLES = wellKnownSymbol('unscopables'); var ArrayPrototype = Array.prototype; // Array.prototype[@@unscopables] // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables if (ArrayPrototype[UNSCOPABLES] === undefined) { defineProperty(ArrayPrototype, UNSCOPABLES, { configurable: true, value: create(null) }); } // add a key to Array.prototype[@@unscopables] module.exports = function (key) { ArrayPrototype[UNSCOPABLES][key] = true; }; /***/ }), /* 69 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* global ActiveXObject -- old IE, WSH */ var anObject = __webpack_require__(45); var definePropertiesModule = __webpack_require__(70); var enumBugKeys = __webpack_require__(64); var hiddenKeys = __webpack_require__(53); var html = __webpack_require__(72); var documentCreateElement = __webpack_require__(41); var sharedKey = __webpack_require__(52); var GT = '>'; var LT = '<'; var PROTOTYPE = 'prototype'; var SCRIPT = 'script'; var IE_PROTO = sharedKey('IE_PROTO'); var EmptyConstructor = function () { /* empty */ }; var scriptTag = function (content) { return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; }; // Create object with fake `null` prototype: use ActiveX Object with cleared prototype var NullProtoObjectViaActiveX = function (activeXDocument) { activeXDocument.write(scriptTag('')); activeXDocument.close(); var temp = activeXDocument.parentWindow.Object; activeXDocument = null; // avoid memory leak return temp; }; // Create object with fake `null` prototype: use iframe Object with cleared prototype var NullProtoObjectViaIFrame = function () { // Thrash, waste and sodomy: IE GC bug var iframe = documentCreateElement('iframe'); var JS = 'java' + SCRIPT + ':'; var iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); // https://github.com/zloirock/core-js/issues/475 iframe.src = String(JS); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(scriptTag('document.F=Object')); iframeDocument.close(); return iframeDocument.F; }; // Check for document.domain and active x support // No need to use active x approach when document.domain is not set // see https://github.com/es-shims/es5-shim/issues/150 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 // avoid IE GC bug var activeXDocument; var NullProtoObject = function () { try { activeXDocument = new ActiveXObject('htmlfile'); } catch (error) { /* ignore */ } NullProtoObject = typeof document != 'undefined' ? document.domain && activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) // old IE : NullProtoObjectViaIFrame() : NullProtoObjectViaActiveX(activeXDocument); // WSH var length = enumBugKeys.length; while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; return NullProtoObject(); }; hiddenKeys[IE_PROTO] = true; // `Object.create` method // https://tc39.es/ecma262/#sec-object.create // eslint-disable-next-line es/no-object-create -- safe module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { EmptyConstructor[PROTOTYPE] = anObject(O); result = new EmptyConstructor(); EmptyConstructor[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = NullProtoObject(); return Properties === undefined ? result : definePropertiesModule.f(result, Properties); }; /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var DESCRIPTORS = __webpack_require__(5); var V8_PROTOTYPE_DEFINE_BUG = __webpack_require__(44); var definePropertyModule = __webpack_require__(43); var anObject = __webpack_require__(45); var toIndexedObject = __webpack_require__(11); var objectKeys = __webpack_require__(71); // `Object.defineProperties` method // https://tc39.es/ecma262/#sec-object.defineproperties // eslint-disable-next-line es/no-object-defineproperties -- safe exports.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var props = toIndexedObject(Properties); var keys = objectKeys(Properties); var length = keys.length; var index = 0; var key; while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]); return O; }; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var internalObjectKeys = __webpack_require__(57); var enumBugKeys = __webpack_require__(64); // `Object.keys` method // https://tc39.es/ecma262/#sec-object.keys // eslint-disable-next-line es/no-object-keys -- safe module.exports = Object.keys || function keys(O) { return internalObjectKeys(O, enumBugKeys); }; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var getBuiltIn = __webpack_require__(22); module.exports = getBuiltIn('document', 'documentElement'); /***/ }), /* 73 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var uncurryThis = __webpack_require__(13); var aCallable = __webpack_require__(29); var toIndexedObject = __webpack_require__(11); var arrayFromConstructorAndList = __webpack_require__(74); var getBuiltInPrototypeMethod = __webpack_require__(75); var addToUnscopables = __webpack_require__(68); var $Array = Array; var sort = uncurryThis(getBuiltInPrototypeMethod('Array', 'sort')); // `Array.prototype.toSorted` method // https://tc39.es/ecma262/#sec-array.prototype.tosorted $({ target: 'Array', proto: true }, { toSorted: function toSorted(compareFn) { if (compareFn !== undefined) aCallable(compareFn); var O = toIndexedObject(this); var A = arrayFromConstructorAndList($Array, O); return sort(A, compareFn); } }); addToUnscopables('toSorted'); /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var lengthOfArrayLike = __webpack_require__(62); module.exports = function (Constructor, list, $length) { var index = 0; var length = arguments.length > 2 ? $length : lengthOfArrayLike(list); var result = new Constructor(length); while (length > index) result[index] = list[index++]; return result; }; /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); module.exports = function (CONSTRUCTOR, METHOD) { var Constructor = global[CONSTRUCTOR]; var Prototype = Constructor && Constructor.prototype; return Prototype && Prototype[METHOD]; }; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var addToUnscopables = __webpack_require__(68); var doesNotExceedSafeInteger = __webpack_require__(77); var lengthOfArrayLike = __webpack_require__(62); var toAbsoluteIndex = __webpack_require__(59); var toIndexedObject = __webpack_require__(11); var toIntegerOrInfinity = __webpack_require__(60); var $Array = Array; var max = Math.max; var min = Math.min; // `Array.prototype.toSpliced` method // https://tc39.es/ecma262/#sec-array.prototype.tospliced $({ target: 'Array', proto: true }, { toSpliced: function toSpliced(start, deleteCount /* , ...items */) { var O = toIndexedObject(this); var len = lengthOfArrayLike(O); var actualStart = toAbsoluteIndex(start, len); var argumentsLength = arguments.length; var k = 0; var insertCount, actualDeleteCount, newLen, A; if (argumentsLength === 0) { insertCount = actualDeleteCount = 0; } else if (argumentsLength === 1) { insertCount = 0; actualDeleteCount = len - actualStart; } else { insertCount = argumentsLength - 2; actualDeleteCount = min(max(toIntegerOrInfinity(deleteCount), 0), len - actualStart); } newLen = doesNotExceedSafeInteger(len + insertCount - actualDeleteCount); A = $Array(newLen); for (; k < actualStart; k++) A[k] = O[k]; for (; k < actualStart + insertCount; k++) A[k] = arguments[k - actualStart + 2]; for (; k < newLen; k++) A[k] = O[k + actualDeleteCount - insertCount]; return A; } }); addToUnscopables('toSpliced'); /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $TypeError = TypeError; var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991 module.exports = function (it) { if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded'); return it; }; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var arrayWith = __webpack_require__(79); var toIndexedObject = __webpack_require__(11); var $Array = Array; // `Array.prototype.with` method // https://tc39.es/ecma262/#sec-array.prototype.with $({ target: 'Array', proto: true }, { 'with': function (index, value) { return arrayWith(toIndexedObject(this), $Array, index, value); } }); /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var lengthOfArrayLike = __webpack_require__(62); var toIntegerOrInfinity = __webpack_require__(60); var $RangeError = RangeError; // https://tc39.es/proposal-change-array-by-copy/#sec-array.prototype.with // https://tc39.es/proposal-change-array-by-copy/#sec-%typedarray%.prototype.with module.exports = function (O, C, index, value) { var len = lengthOfArrayLike(O); var relativeIndex = toIntegerOrInfinity(index); var actualIndex = relativeIndex < 0 ? len + relativeIndex : relativeIndex; if (actualIndex >= len || actualIndex < 0) throw new $RangeError('Incorrect index'); var A = new C(len); var k = 0; for (; k < len; k++) A[k] = k === actualIndex ? value : O[k]; return A; }; /***/ }), /* 80 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var uncurryThis = __webpack_require__(13); var aCallable = __webpack_require__(29); var requireObjectCoercible = __webpack_require__(15); var iterate = __webpack_require__(81); var MapHelpers = __webpack_require__(91); var IS_PURE = __webpack_require__(34); var Map = MapHelpers.Map; var has = MapHelpers.has; var get = MapHelpers.get; var set = MapHelpers.set; var push = uncurryThis([].push); // `Map.groupBy` method // https://github.com/tc39/proposal-array-grouping $({ target: 'Map', stat: true, forced: IS_PURE }, { groupBy: function groupBy(items, callbackfn) { requireObjectCoercible(items); aCallable(callbackfn); var map = new Map(); var k = 0; iterate(items, function (value) { var key = callbackfn(value, k++); if (!has(map, key)) set(map, key, [value]); else push(get(map, key), value); }); return map; } }); /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var bind = __webpack_require__(82); var call = __webpack_require__(7); var anObject = __webpack_require__(45); var tryToString = __webpack_require__(30); var isArrayIteratorMethod = __webpack_require__(84); var lengthOfArrayLike = __webpack_require__(62); var isPrototypeOf = __webpack_require__(23); var getIterator = __webpack_require__(86); var getIteratorMethod = __webpack_require__(87); var iteratorClose = __webpack_require__(90); var $TypeError = TypeError; var Result = function (stopped, result) { this.stopped = stopped; this.result = result; }; var ResultPrototype = Result.prototype; module.exports = function (iterable, unboundFunction, options) { var that = options && options.that; var AS_ENTRIES = !!(options && options.AS_ENTRIES); var IS_RECORD = !!(options && options.IS_RECORD); var IS_ITERATOR = !!(options && options.IS_ITERATOR); var INTERRUPTED = !!(options && options.INTERRUPTED); var fn = bind(unboundFunction, that); var iterator, iterFn, index, length, result, next, step; var stop = function (condition) { if (iterator) iteratorClose(iterator, 'normal', condition); return new Result(true, condition); }; var callFn = function (value) { if (AS_ENTRIES) { anObject(value); return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]); } return INTERRUPTED ? fn(value, stop) : fn(value); }; if (IS_RECORD) { iterator = iterable.iterator; } else if (IS_ITERATOR) { iterator = iterable; } else { iterFn = getIteratorMethod(iterable); if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable'); // optimisation for array iterators if (isArrayIteratorMethod(iterFn)) { for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) { result = callFn(iterable[index]); if (result && isPrototypeOf(ResultPrototype, result)) return result; } return new Result(false); } iterator = getIterator(iterable, iterFn); } next = IS_RECORD ? iterable.next : iterator.next; while (!(step = call(next, iterator)).done) { try { result = callFn(step.value); } catch (error) { iteratorClose(iterator, 'throw', error); } if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result; } return new Result(false); }; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(83); var aCallable = __webpack_require__(29); var NATIVE_BIND = __webpack_require__(8); var bind = uncurryThis(uncurryThis.bind); // optional / simple context binding module.exports = function (fn, that) { aCallable(fn); return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var classofRaw = __webpack_require__(14); var uncurryThis = __webpack_require__(13); module.exports = function (fn) { // Nashorn bug: // https://github.com/zloirock/core-js/issues/1128 // https://github.com/zloirock/core-js/issues/1130 if (classofRaw(fn) === 'Function') return uncurryThis(fn); }; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var wellKnownSymbol = __webpack_require__(32); var Iterators = __webpack_require__(85); var ITERATOR = wellKnownSymbol('iterator'); var ArrayPrototype = Array.prototype; // check on default Array iterator module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it); }; /***/ }), /* 85 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = {}; /***/ }), /* 86 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var call = __webpack_require__(7); var aCallable = __webpack_require__(29); var anObject = __webpack_require__(45); var tryToString = __webpack_require__(30); var getIteratorMethod = __webpack_require__(87); var $TypeError = TypeError; module.exports = function (argument, usingIterator) { var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator; if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument)); throw new $TypeError(tryToString(argument) + ' is not iterable'); }; /***/ }), /* 87 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var classof = __webpack_require__(88); var getMethod = __webpack_require__(28); var isNullOrUndefined = __webpack_require__(16); var Iterators = __webpack_require__(85); var wellKnownSymbol = __webpack_require__(32); var ITERATOR = wellKnownSymbol('iterator'); module.exports = function (it) { if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR) || getMethod(it, '@@iterator') || Iterators[classof(it)]; }; /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var TO_STRING_TAG_SUPPORT = __webpack_require__(89); var isCallable = __webpack_require__(20); var classofRaw = __webpack_require__(14); var wellKnownSymbol = __webpack_require__(32); var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var $Object = Object; // ES3 wrong here var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (error) { /* empty */ } }; // getting tag from ES6+ `Object.prototype.toString` module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) { var O, tag, result; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag // builtinTag case : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result; }; /***/ }), /* 89 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var wellKnownSymbol = __webpack_require__(32); var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var test = {}; test[TO_STRING_TAG] = 'z'; module.exports = String(test) === '[object z]'; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var call = __webpack_require__(7); var anObject = __webpack_require__(45); var getMethod = __webpack_require__(28); module.exports = function (iterator, kind, value) { var innerResult, innerError; anObject(iterator); try { innerResult = getMethod(iterator, 'return'); if (!innerResult) { if (kind === 'throw') throw value; return value; } innerResult = call(innerResult, iterator); } catch (error) { innerError = true; innerResult = error; } if (kind === 'throw') throw value; if (innerError) throw innerResult; anObject(innerResult); return value; }; /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); // eslint-disable-next-line es/no-map -- safe var MapPrototype = Map.prototype; module.exports = { // eslint-disable-next-line es/no-map -- safe Map: Map, set: uncurryThis(MapPrototype.set), get: uncurryThis(MapPrototype.get), has: uncurryThis(MapPrototype.has), remove: uncurryThis(MapPrototype['delete']), proto: MapPrototype }; /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var getBuiltIn = __webpack_require__(22); var uncurryThis = __webpack_require__(13); var aCallable = __webpack_require__(29); var requireObjectCoercible = __webpack_require__(15); var toPropertyKey = __webpack_require__(17); var iterate = __webpack_require__(81); var create = getBuiltIn('Object', 'create'); var push = uncurryThis([].push); // `Object.groupBy` method // https://github.com/tc39/proposal-array-grouping $({ target: 'Object', stat: true }, { groupBy: function groupBy(items, callbackfn) { requireObjectCoercible(items); aCallable(callbackfn); var obj = create(null); var k = 0; iterate(items, function (value) { var key = toPropertyKey(callbackfn(value, k++)); // in some IE versions, `hasOwnProperty` returns incorrect result on integer keys // but since it's a `null` prototype object, we can safely use `in` if (key in obj) push(obj[key], value); else obj[key] = [value]; }); return obj; } }); /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var newPromiseCapabilityModule = __webpack_require__(94); // `Promise.withResolvers` method // https://github.com/tc39/proposal-promise-with-resolvers $({ target: 'Promise', stat: true }, { withResolvers: function withResolvers() { var promiseCapability = newPromiseCapabilityModule.f(this); return { promise: promiseCapability.promise, resolve: promiseCapability.resolve, reject: promiseCapability.reject }; } }); /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var aCallable = __webpack_require__(29); var $TypeError = TypeError; var PromiseCapability = function (C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw new $TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aCallable(resolve); this.reject = aCallable(reject); }; // `NewPromiseCapability` abstract operation // https://tc39.es/ecma262/#sec-newpromisecapability module.exports.f = function (C) { return new PromiseCapability(C); }; /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var DESCRIPTORS = __webpack_require__(5); var defineBuiltInAccessor = __webpack_require__(96); var regExpFlags = __webpack_require__(97); var fails = __webpack_require__(6); // babel-minify and Closure Compiler transpiles RegExp('.', 'd') -> /./d and it causes SyntaxError var RegExp = global.RegExp; var RegExpPrototype = RegExp.prototype; var FORCED = DESCRIPTORS && fails(function () { var INDICES_SUPPORT = true; try { RegExp('.', 'd'); } catch (error) { INDICES_SUPPORT = false; } var O = {}; // modern V8 bug var calls = ''; var expected = INDICES_SUPPORT ? 'dgimsy' : 'gimsy'; var addGetter = function (key, chr) { // eslint-disable-next-line es/no-object-defineproperty -- safe Object.defineProperty(O, key, { get: function () { calls += chr; return true; } }); }; var pairs = { dotAll: 's', global: 'g', ignoreCase: 'i', multiline: 'm', sticky: 'y' }; if (INDICES_SUPPORT) pairs.hasIndices = 'd'; for (var key in pairs) addGetter(key, pairs[key]); // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var result = Object.getOwnPropertyDescriptor(RegExpPrototype, 'flags').get.call(O); return result !== expected || calls !== expected; }); // `RegExp.prototype.flags` getter // https://tc39.es/ecma262/#sec-get-regexp.prototype.flags if (FORCED) defineBuiltInAccessor(RegExpPrototype, 'flags', { configurable: true, get: regExpFlags }); /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var makeBuiltIn = __webpack_require__(47); var defineProperty = __webpack_require__(43); module.exports = function (target, name, descriptor) { if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true }); if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true }); return defineProperty.f(target, name, descriptor); }; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var anObject = __webpack_require__(45); // `RegExp.prototype.flags` getter implementation // https://tc39.es/ecma262/#sec-get-regexp.prototype.flags module.exports = function () { var that = anObject(this); var result = ''; if (that.hasIndices) result += 'd'; if (that.global) result += 'g'; if (that.ignoreCase) result += 'i'; if (that.multiline) result += 'm'; if (that.dotAll) result += 's'; if (that.unicode) result += 'u'; if (that.unicodeSets) result += 'v'; if (that.sticky) result += 'y'; return result; }; /***/ }), /* 98 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var uncurryThis = __webpack_require__(13); var requireObjectCoercible = __webpack_require__(15); var toString = __webpack_require__(99); var charCodeAt = uncurryThis(''.charCodeAt); // `String.prototype.isWellFormed` method // https://github.com/tc39/proposal-is-usv-string $({ target: 'String', proto: true }, { isWellFormed: function isWellFormed() { var S = toString(requireObjectCoercible(this)); var length = S.length; for (var i = 0; i < length; i++) { var charCode = charCodeAt(S, i); // single UTF-16 code unit if ((charCode & 0xF800) !== 0xD800) continue; // unpaired surrogate if (charCode >= 0xDC00 || ++i >= length || (charCodeAt(S, i) & 0xFC00) !== 0xDC00) return false; } return true; } }); /***/ }), /* 99 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var classof = __webpack_require__(88); var $String = String; module.exports = function (argument) { if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string'); return $String(argument); }; /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var call = __webpack_require__(7); var uncurryThis = __webpack_require__(13); var requireObjectCoercible = __webpack_require__(15); var toString = __webpack_require__(99); var fails = __webpack_require__(6); var $Array = Array; var charAt = uncurryThis(''.charAt); var charCodeAt = uncurryThis(''.charCodeAt); var join = uncurryThis([].join); // eslint-disable-next-line es/no-string-prototype-iswellformed-towellformed -- safe var $toWellFormed = ''.toWellFormed; var REPLACEMENT_CHARACTER = '\uFFFD'; // Safari bug var TO_STRING_CONVERSION_BUG = $toWellFormed && fails(function () { return call($toWellFormed, 1) !== '1'; }); // `String.prototype.toWellFormed` method // https://github.com/tc39/proposal-is-usv-string $({ target: 'String', proto: true, forced: TO_STRING_CONVERSION_BUG }, { toWellFormed: function toWellFormed() { var S = toString(requireObjectCoercible(this)); if (TO_STRING_CONVERSION_BUG) return call($toWellFormed, S); var length = S.length; var result = $Array(length); for (var i = 0; i < length; i++) { var charCode = charCodeAt(S, i); // single UTF-16 code unit if ((charCode & 0xF800) !== 0xD800) result[i] = charAt(S, i); // unpaired surrogate else if (charCode >= 0xDC00 || i + 1 >= length || (charCodeAt(S, i + 1) & 0xFC00) !== 0xDC00) result[i] = REPLACEMENT_CHARACTER; // surrogate pair else { result[i] = charAt(S, i); result[++i] = charAt(S, i); } } return join(result, ''); } }); /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var arrayToReversed = __webpack_require__(67); var ArrayBufferViewCore = __webpack_require__(102); var aTypedArray = ArrayBufferViewCore.aTypedArray; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor; // `%TypedArray%.prototype.toReversed` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.toreversed exportTypedArrayMethod('toReversed', function toReversed() { return arrayToReversed(aTypedArray(this), getTypedArrayConstructor(this)); }); /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var NATIVE_ARRAY_BUFFER = __webpack_require__(103); var DESCRIPTORS = __webpack_require__(5); var global = __webpack_require__(3); var isCallable = __webpack_require__(20); var isObject = __webpack_require__(19); var hasOwn = __webpack_require__(37); var classof = __webpack_require__(88); var tryToString = __webpack_require__(30); var createNonEnumerableProperty = __webpack_require__(42); var defineBuiltIn = __webpack_require__(46); var defineBuiltInAccessor = __webpack_require__(96); var isPrototypeOf = __webpack_require__(23); var getPrototypeOf = __webpack_require__(104); var setPrototypeOf = __webpack_require__(106); var wellKnownSymbol = __webpack_require__(32); var uid = __webpack_require__(39); var InternalStateModule = __webpack_require__(50); var enforceInternalState = InternalStateModule.enforce; var getInternalState = InternalStateModule.get; var Int8Array = global.Int8Array; var Int8ArrayPrototype = Int8Array && Int8Array.prototype; var Uint8ClampedArray = global.Uint8ClampedArray; var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype; var TypedArray = Int8Array && getPrototypeOf(Int8Array); var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype); var ObjectPrototype = Object.prototype; var TypeError = global.TypeError; var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); var TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor'; // Fixing native typed arrays in Opera Presto crashes the browser, see #595 var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera'; var TYPED_ARRAY_TAG_REQUIRED = false; var NAME, Constructor, Prototype; var TypedArrayConstructorsList = { Int8Array: 1, Uint8Array: 1, Uint8ClampedArray: 1, Int16Array: 2, Uint16Array: 2, Int32Array: 4, Uint32Array: 4, Float32Array: 4, Float64Array: 8 }; var BigIntArrayConstructorsList = { BigInt64Array: 8, BigUint64Array: 8 }; var isView = function isView(it) { if (!isObject(it)) return false; var klass = classof(it); return klass === 'DataView' || hasOwn(TypedArrayConstructorsList, klass) || hasOwn(BigIntArrayConstructorsList, klass); }; var getTypedArrayConstructor = function (it) { var proto = getPrototypeOf(it); if (!isObject(proto)) return; var state = getInternalState(proto); return (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor(proto); }; var isTypedArray = function (it) { if (!isObject(it)) return false; var klass = classof(it); return hasOwn(TypedArrayConstructorsList, klass) || hasOwn(BigIntArrayConstructorsList, klass); }; var aTypedArray = function (it) { if (isTypedArray(it)) return it; throw new TypeError('Target is not a typed array'); }; var aTypedArrayConstructor = function (C) { if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C; throw new TypeError(tryToString(C) + ' is not a typed array constructor'); }; var exportTypedArrayMethod = function (KEY, property, forced, options) { if (!DESCRIPTORS) return; if (forced) for (var ARRAY in TypedArrayConstructorsList) { var TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try { delete TypedArrayConstructor.prototype[KEY]; } catch (error) { // old WebKit bug - some methods are non-configurable try { TypedArrayConstructor.prototype[KEY] = property; } catch (error2) { /* empty */ } } } if (!TypedArrayPrototype[KEY] || forced) { defineBuiltIn(TypedArrayPrototype, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options); } }; var exportTypedArrayStaticMethod = function (KEY, property, forced) { var ARRAY, TypedArrayConstructor; if (!DESCRIPTORS) return; if (setPrototypeOf) { if (forced) for (ARRAY in TypedArrayConstructorsList) { TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try { delete TypedArrayConstructor[KEY]; } catch (error) { /* empty */ } } if (!TypedArray[KEY] || forced) { // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable try { return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property); } catch (error) { /* empty */ } } else return; } for (ARRAY in TypedArrayConstructorsList) { TypedArrayConstructor = global[ARRAY]; if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { defineBuiltIn(TypedArrayConstructor, KEY, property); } } }; for (NAME in TypedArrayConstructorsList) { Constructor = global[NAME]; Prototype = Constructor && Constructor.prototype; if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor; else NATIVE_ARRAY_BUFFER_VIEWS = false; } for (NAME in BigIntArrayConstructorsList) { Constructor = global[NAME]; Prototype = Constructor && Constructor.prototype; if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor; } // WebKit bug - typed arrays constructors prototype is Object.prototype if (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) { // eslint-disable-next-line no-shadow -- safe TypedArray = function TypedArray() { throw new TypeError('Incorrect invocation'); }; if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { if (global[NAME]) setPrototypeOf(global[NAME], TypedArray); } } if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) { TypedArrayPrototype = TypedArray.prototype; if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) { if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype); } } // WebKit bug - one more object in Uint8ClampedArray prototype chain if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); } if (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) { TYPED_ARRAY_TAG_REQUIRED = true; defineBuiltInAccessor(TypedArrayPrototype, TO_STRING_TAG, { configurable: true, get: function () { return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined; } }); for (NAME in TypedArrayConstructorsList) if (global[NAME]) { createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME); } } module.exports = { NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS, TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG, aTypedArray: aTypedArray, aTypedArrayConstructor: aTypedArrayConstructor, exportTypedArrayMethod: exportTypedArrayMethod, exportTypedArrayStaticMethod: exportTypedArrayStaticMethod, getTypedArrayConstructor: getTypedArrayConstructor, isView: isView, isTypedArray: isTypedArray, TypedArray: TypedArray, TypedArrayPrototype: TypedArrayPrototype }; /***/ }), /* 103 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // eslint-disable-next-line es/no-typed-arrays -- safe module.exports = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined'; /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var hasOwn = __webpack_require__(37); var isCallable = __webpack_require__(20); var toObject = __webpack_require__(38); var sharedKey = __webpack_require__(52); var CORRECT_PROTOTYPE_GETTER = __webpack_require__(105); var IE_PROTO = sharedKey('IE_PROTO'); var $Object = Object; var ObjectPrototype = $Object.prototype; // `Object.getPrototypeOf` method // https://tc39.es/ecma262/#sec-object.getprototypeof // eslint-disable-next-line es/no-object-getprototypeof -- safe module.exports = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) { var object = toObject(O); if (hasOwn(object, IE_PROTO)) return object[IE_PROTO]; var constructor = object.constructor; if (isCallable(constructor) && object instanceof constructor) { return constructor.prototype; } return object instanceof $Object ? ObjectPrototype : null; }; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var fails = __webpack_require__(6); module.exports = !fails(function () { function F() { /* empty */ } F.prototype.constructor = null; // eslint-disable-next-line es/no-object-getprototypeof -- required for testing return Object.getPrototypeOf(new F()) !== F.prototype; }); /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint-disable no-proto -- safe */ var uncurryThisAccessor = __webpack_require__(107); var anObject = __webpack_require__(45); var aPossiblePrototype = __webpack_require__(108); // `Object.setPrototypeOf` method // https://tc39.es/ecma262/#sec-object.setprototypeof // Works with __proto__ only. Old v8 can't work with null proto objects. // eslint-disable-next-line es/no-object-setprototypeof -- safe module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () { var CORRECT_SETTER = false; var test = {}; var setter; try { setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set'); setter(test, []); CORRECT_SETTER = test instanceof Array; } catch (error) { /* empty */ } return function setPrototypeOf(O, proto) { anObject(O); aPossiblePrototype(proto); if (CORRECT_SETTER) setter(O, proto); else O.__proto__ = proto; return O; }; }() : undefined); /***/ }), /* 107 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var aCallable = __webpack_require__(29); module.exports = function (object, key, method) { try { // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method])); } catch (error) { /* empty */ } }; /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isPossiblePrototype = __webpack_require__(109); var $String = String; var $TypeError = TypeError; module.exports = function (argument) { if (isPossiblePrototype(argument)) return argument; throw new $TypeError("Can't set " + $String(argument) + ' as a prototype'); }; /***/ }), /* 109 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isObject = __webpack_require__(19); module.exports = function (argument) { return isObject(argument) || argument === null; }; /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var ArrayBufferViewCore = __webpack_require__(102); var uncurryThis = __webpack_require__(13); var aCallable = __webpack_require__(29); var arrayFromConstructorAndList = __webpack_require__(74); var aTypedArray = ArrayBufferViewCore.aTypedArray; var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; var sort = uncurryThis(ArrayBufferViewCore.TypedArrayPrototype.sort); // `%TypedArray%.prototype.toSorted` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tosorted exportTypedArrayMethod('toSorted', function toSorted(compareFn) { if (compareFn !== undefined) aCallable(compareFn); var O = aTypedArray(this); var A = arrayFromConstructorAndList(getTypedArrayConstructor(O), O); return sort(A, compareFn); }); /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var arrayWith = __webpack_require__(79); var ArrayBufferViewCore = __webpack_require__(102); var isBigIntArray = __webpack_require__(112); var toIntegerOrInfinity = __webpack_require__(60); var toBigInt = __webpack_require__(113); var aTypedArray = ArrayBufferViewCore.aTypedArray; var getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor; var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod; var PROPER_ORDER = !!function () { try { // eslint-disable-next-line no-throw-literal, es/no-typed-arrays, es/no-array-prototype-with -- required for testing new Int8Array(1)['with'](2, { valueOf: function () { throw 8; } }); } catch (error) { // some early implementations, like WebKit, does not follow the final semantic // https://github.com/tc39/proposal-change-array-by-copy/pull/86 return error === 8; } }(); // `%TypedArray%.prototype.with` method // https://tc39.es/ecma262/#sec-%typedarray%.prototype.with exportTypedArrayMethod('with', { 'with': function (index, value) { var O = aTypedArray(this); var relativeIndex = toIntegerOrInfinity(index); var actualValue = isBigIntArray(O) ? toBigInt(value) : +value; return arrayWith(O, getTypedArrayConstructor(O), relativeIndex, actualValue); } }['with'], !PROPER_ORDER); /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var classof = __webpack_require__(88); module.exports = function (it) { var klass = classof(it); return klass === 'BigInt64Array' || klass === 'BigUint64Array'; }; /***/ }), /* 113 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toPrimitive = __webpack_require__(18); var $TypeError = TypeError; // `ToBigInt` abstract operation // https://tc39.es/ecma262/#sec-tobigint module.exports = function (argument) { var prim = toPrimitive(argument, 'number'); if (typeof prim == 'number') throw new $TypeError("Can't convert number to bigint"); // eslint-disable-next-line es/no-bigint -- safe return BigInt(prim); }; /***/ }), /* 114 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var global = __webpack_require__(3); var getBuiltIn = __webpack_require__(22); var createPropertyDescriptor = __webpack_require__(10); var defineProperty = __webpack_require__(43).f; var hasOwn = __webpack_require__(37); var anInstance = __webpack_require__(115); var inheritIfRequired = __webpack_require__(116); var normalizeStringArgument = __webpack_require__(117); var DOMExceptionConstants = __webpack_require__(118); var clearErrorStack = __webpack_require__(119); var DESCRIPTORS = __webpack_require__(5); var IS_PURE = __webpack_require__(34); var DOM_EXCEPTION = 'DOMException'; var Error = getBuiltIn('Error'); var NativeDOMException = getBuiltIn(DOM_EXCEPTION); var $DOMException = function DOMException() { anInstance(this, DOMExceptionPrototype); var argumentsLength = arguments.length; var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]); var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error'); var that = new NativeDOMException(message, name); var error = new Error(message); error.name = DOM_EXCEPTION; defineProperty(that, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1))); inheritIfRequired(that, this, $DOMException); return that; }; var DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype; var ERROR_HAS_STACK = 'stack' in new Error(DOM_EXCEPTION); var DOM_EXCEPTION_HAS_STACK = 'stack' in new NativeDOMException(1, 2); // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe var descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(global, DOM_EXCEPTION); // Bun ~ 0.1.1 DOMException have incorrect descriptor and we can't redefine it // https://github.com/Jarred-Sumner/bun/issues/399 var BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable); var FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK; // `DOMException` constructor patch for `.stack` where it's required // https://webidl.spec.whatwg.org/#es-DOMException-specialness $({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }, { // TODO: fix export logic DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException }); var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION); var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype; if (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) { if (!IS_PURE) { defineProperty(PolyfilledDOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, PolyfilledDOMException)); } for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) { var constant = DOMExceptionConstants[key]; var constantName = constant.s; if (!hasOwn(PolyfilledDOMException, constantName)) { defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c)); } } } /***/ }), /* 115 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isPrototypeOf = __webpack_require__(23); var $TypeError = TypeError; module.exports = function (it, Prototype) { if (isPrototypeOf(Prototype, it)) return it; throw new $TypeError('Incorrect invocation'); }; /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isCallable = __webpack_require__(20); var isObject = __webpack_require__(19); var setPrototypeOf = __webpack_require__(106); // makes subclassing work correct for wrapped built-ins module.exports = function ($this, dummy, Wrapper) { var NewTarget, NewTargetPrototype; if ( // it can work only with native `setPrototypeOf` setPrototypeOf && // we haven't completely correct pre-ES6 way for getting `new.target`, so use this isCallable(NewTarget = dummy.constructor) && NewTarget !== Wrapper && isObject(NewTargetPrototype = NewTarget.prototype) && NewTargetPrototype !== Wrapper.prototype ) setPrototypeOf($this, NewTargetPrototype); return $this; }; /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toString = __webpack_require__(99); module.exports = function (argument, $default) { return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument); }; /***/ }), /* 118 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = { IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 }, DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 }, HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 }, WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 }, InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 }, NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 }, NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 }, NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 }, NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 }, InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 }, InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 }, SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 }, InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 }, NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 }, InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 }, ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 }, TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 }, SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 }, NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 }, AbortError: { s: 'ABORT_ERR', c: 20, m: 1 }, URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 }, QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 }, TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 }, InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 }, DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 } }; /***/ }), /* 119 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var $Error = Error; var replace = uncurryThis(''.replace); var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd'); // eslint-disable-next-line redos/no-vulnerable -- safe var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/; var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST); module.exports = function (stack, dropEntries) { if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) { while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, ''); } return stack; }; /***/ }), /* 120 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var IS_PURE = __webpack_require__(34); var $ = __webpack_require__(2); var global = __webpack_require__(3); var getBuiltIn = __webpack_require__(22); var uncurryThis = __webpack_require__(13); var fails = __webpack_require__(6); var uid = __webpack_require__(39); var isCallable = __webpack_require__(20); var isConstructor = __webpack_require__(121); var isNullOrUndefined = __webpack_require__(16); var isObject = __webpack_require__(19); var isSymbol = __webpack_require__(21); var iterate = __webpack_require__(81); var anObject = __webpack_require__(45); var classof = __webpack_require__(88); var hasOwn = __webpack_require__(37); var createProperty = __webpack_require__(122); var createNonEnumerableProperty = __webpack_require__(42); var lengthOfArrayLike = __webpack_require__(62); var validateArgumentsLength = __webpack_require__(123); var getRegExpFlags = __webpack_require__(124); var MapHelpers = __webpack_require__(91); var SetHelpers = __webpack_require__(125); var setIterate = __webpack_require__(126); var detachTransferable = __webpack_require__(128); var ERROR_STACK_INSTALLABLE = __webpack_require__(134); var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(131); var Object = global.Object; var Array = global.Array; var Date = global.Date; var Error = global.Error; var TypeError = global.TypeError; var PerformanceMark = global.PerformanceMark; var DOMException = getBuiltIn('DOMException'); var Map = MapHelpers.Map; var mapHas = MapHelpers.has; var mapGet = MapHelpers.get; var mapSet = MapHelpers.set; var Set = SetHelpers.Set; var setAdd = SetHelpers.add; var setHas = SetHelpers.has; var objectKeys = getBuiltIn('Object', 'keys'); var push = uncurryThis([].push); var thisBooleanValue = uncurryThis(true.valueOf); var thisNumberValue = uncurryThis(1.0.valueOf); var thisStringValue = uncurryThis(''.valueOf); var thisTimeValue = uncurryThis(Date.prototype.getTime); var PERFORMANCE_MARK = uid('structuredClone'); var DATA_CLONE_ERROR = 'DataCloneError'; var TRANSFERRING = 'Transferring'; var checkBasicSemantic = function (structuredCloneImplementation) { return !fails(function () { var set1 = new global.Set([7]); var set2 = structuredCloneImplementation(set1); var number = structuredCloneImplementation(Object(7)); return set2 === set1 || !set2.has(7) || !isObject(number) || +number !== 7; }) && structuredCloneImplementation; }; var checkErrorsCloning = function (structuredCloneImplementation, $Error) { return !fails(function () { var error = new $Error(); var test = structuredCloneImplementation({ a: error, b: error }); return !(test && test.a === test.b && test.a instanceof $Error && test.a.stack === error.stack); }); }; // https://github.com/whatwg/html/pull/5749 var checkNewErrorsCloningSemantic = function (structuredCloneImplementation) { return !fails(function () { var test = structuredCloneImplementation(new global.AggregateError([1], PERFORMANCE_MARK, { cause: 3 })); return test.name !== 'AggregateError' || test.errors[0] !== 1 || test.message !== PERFORMANCE_MARK || test.cause !== 3; }); }; // FF94+, Safari 15.4+, Chrome 98+, NodeJS 17.0+, Deno 1.13+ // FF<103 and Safari implementations can't clone errors // https://bugzilla.mozilla.org/show_bug.cgi?id=1556604 // FF103 can clone errors, but `.stack` of clone is an empty string // https://bugzilla.mozilla.org/show_bug.cgi?id=1778762 // FF104+ fixed it on usual errors, but not on DOMExceptions // https://bugzilla.mozilla.org/show_bug.cgi?id=1777321 // Chrome <102 returns `null` if cloned object contains multiple references to one error // https://bugs.chromium.org/p/v8/issues/detail?id=12542 // NodeJS implementation can't clone DOMExceptions // https://github.com/nodejs/node/issues/41038 // only FF103+ supports new (html/5749) error cloning semantic var nativeStructuredClone = global.structuredClone; var FORCED_REPLACEMENT = IS_PURE || !checkErrorsCloning(nativeStructuredClone, Error) || !checkErrorsCloning(nativeStructuredClone, DOMException) || !checkNewErrorsCloningSemantic(nativeStructuredClone); // Chrome 82+, Safari 14.1+, Deno 1.11+ // Chrome 78-81 implementation swaps `.name` and `.message` of cloned `DOMException` // Chrome returns `null` if cloned object contains multiple references to one error // Safari 14.1 implementation doesn't clone some `RegExp` flags, so requires a workaround // Safari implementation can't clone errors // Deno 1.2-1.10 implementations too naive // NodeJS 16.0+ does not have `PerformanceMark` constructor // NodeJS <17.2 structured cloning implementation from `performance.mark` is too naive // and can't clone, for example, `RegExp` or some boxed primitives // https://github.com/nodejs/node/issues/40840 // no one of those implementations supports new (html/5749) error cloning semantic var structuredCloneFromMark = !nativeStructuredClone && checkBasicSemantic(function (value) { return new PerformanceMark(PERFORMANCE_MARK, { detail: value }).detail; }); var nativeRestrictedStructuredClone = checkBasicSemantic(nativeStructuredClone) || structuredCloneFromMark; var throwUncloneable = function (type) { throw new DOMException('Uncloneable type: ' + type, DATA_CLONE_ERROR); }; var throwUnpolyfillable = function (type, action) { throw new DOMException((action || 'Cloning') + ' of ' + type + ' cannot be properly polyfilled in this engine', DATA_CLONE_ERROR); }; var tryNativeRestrictedStructuredClone = function (value, type) { if (!nativeRestrictedStructuredClone) throwUnpolyfillable(type); return nativeRestrictedStructuredClone(value); }; var createDataTransfer = function () { var dataTransfer; try { dataTransfer = new global.DataTransfer(); } catch (error) { try { dataTransfer = new global.ClipboardEvent('').clipboardData; } catch (error2) { /* empty */ } } return dataTransfer && dataTransfer.items && dataTransfer.files ? dataTransfer : null; }; var cloneBuffer = function (value, map, $type) { if (mapHas(map, value)) return mapGet(map, value); var type = $type || classof(value); var clone, length, options, source, target, i; if (type === 'SharedArrayBuffer') { if (nativeRestrictedStructuredClone) clone = nativeRestrictedStructuredClone(value); // SharedArrayBuffer should use shared memory, we can't polyfill it, so return the original else clone = value; } else { var DataView = global.DataView; // `ArrayBuffer#slice` is not available in IE10 // `ArrayBuffer#slice` and `DataView` are not available in old FF if (!DataView && !isCallable(value.slice)) throwUnpolyfillable('ArrayBuffer'); // detached buffers throws in `DataView` and `.slice` try { if (isCallable(value.slice) && !value.resizable) { clone = value.slice(0); } else { length = value.byteLength; options = 'maxByteLength' in value ? { maxByteLength: value.maxByteLength } : undefined; // eslint-disable-next-line es/no-resizable-and-growable-arraybuffers -- safe clone = new ArrayBuffer(length, options); source = new DataView(value); target = new DataView(clone); for (i = 0; i < length; i++) { target.setUint8(i, source.getUint8(i)); } } } catch (error) { throw new DOMException('ArrayBuffer is detached', DATA_CLONE_ERROR); } } mapSet(map, value, clone); return clone; }; var cloneView = function (value, type, offset, length, map) { var C = global[type]; // in some old engines like Safari 9, typeof C is 'object' // on Uint8ClampedArray or some other constructors if (!isObject(C)) throwUnpolyfillable(type); return new C(cloneBuffer(value.buffer, map), offset, length); }; var structuredCloneInternal = function (value, map) { if (isSymbol(value)) throwUncloneable('Symbol'); if (!isObject(value)) return value; // effectively preserves circular references if (map) { if (mapHas(map, value)) return mapGet(map, value); } else map = new Map(); var type = classof(value); var C, name, cloned, dataTransfer, i, length, keys, key; switch (type) { case 'Array': cloned = Array(lengthOfArrayLike(value)); break; case 'Object': cloned = {}; break; case 'Map': cloned = new Map(); break; case 'Set': cloned = new Set(); break; case 'RegExp': // in this block because of a Safari 14.1 bug // old FF does not clone regexes passed to the constructor, so get the source and flags directly cloned = new RegExp(value.source, getRegExpFlags(value)); break; case 'Error': name = value.name; switch (name) { case 'AggregateError': cloned = new (getBuiltIn(name))([]); break; case 'EvalError': case 'RangeError': case 'ReferenceError': case 'SuppressedError': case 'SyntaxError': case 'TypeError': case 'URIError': cloned = new (getBuiltIn(name))(); break; case 'CompileError': case 'LinkError': case 'RuntimeError': cloned = new (getBuiltIn('WebAssembly', name))(); break; default: cloned = new Error(); } break; case 'DOMException': cloned = new DOMException(value.message, value.name); break; case 'ArrayBuffer': case 'SharedArrayBuffer': cloned = cloneBuffer(value, map, type); break; case 'DataView': case 'Int8Array': case 'Uint8Array': case 'Uint8ClampedArray': case 'Int16Array': case 'Uint16Array': case 'Int32Array': case 'Uint32Array': case 'Float16Array': case 'Float32Array': case 'Float64Array': case 'BigInt64Array': case 'BigUint64Array': length = type === 'DataView' ? value.byteLength : value.length; cloned = cloneView(value, type, value.byteOffset, length, map); break; case 'DOMQuad': try { cloned = new DOMQuad( structuredCloneInternal(value.p1, map), structuredCloneInternal(value.p2, map), structuredCloneInternal(value.p3, map), structuredCloneInternal(value.p4, map) ); } catch (error) { cloned = tryNativeRestrictedStructuredClone(value, type); } break; case 'File': if (nativeRestrictedStructuredClone) try { cloned = nativeRestrictedStructuredClone(value); // NodeJS 20.0.0 bug, https://github.com/nodejs/node/issues/47612 if (classof(cloned) !== type) cloned = undefined; } catch (error) { /* empty */ } if (!cloned) try { cloned = new File([value], value.name, value); } catch (error) { /* empty */ } if (!cloned) throwUnpolyfillable(type); break; case 'FileList': dataTransfer = createDataTransfer(); if (dataTransfer) { for (i = 0, length = lengthOfArrayLike(value); i < length; i++) { dataTransfer.items.add(structuredCloneInternal(value[i], map)); } cloned = dataTransfer.files; } else cloned = tryNativeRestrictedStructuredClone(value, type); break; case 'ImageData': // Safari 9 ImageData is a constructor, but typeof ImageData is 'object' try { cloned = new ImageData( structuredCloneInternal(value.data, map), value.width, value.height, { colorSpace: value.colorSpace } ); } catch (error) { cloned = tryNativeRestrictedStructuredClone(value, type); } break; default: if (nativeRestrictedStructuredClone) { cloned = nativeRestrictedStructuredClone(value); } else switch (type) { case 'BigInt': // can be a 3rd party polyfill cloned = Object(value.valueOf()); break; case 'Boolean': cloned = Object(thisBooleanValue(value)); break; case 'Number': cloned = Object(thisNumberValue(value)); break; case 'String': cloned = Object(thisStringValue(value)); break; case 'Date': cloned = new Date(thisTimeValue(value)); break; case 'Blob': try { cloned = value.slice(0, value.size, value.type); } catch (error) { throwUnpolyfillable(type); } break; case 'DOMPoint': case 'DOMPointReadOnly': C = global[type]; try { cloned = C.fromPoint ? C.fromPoint(value) : new C(value.x, value.y, value.z, value.w); } catch (error) { throwUnpolyfillable(type); } break; case 'DOMRect': case 'DOMRectReadOnly': C = global[type]; try { cloned = C.fromRect ? C.fromRect(value) : new C(value.x, value.y, value.width, value.height); } catch (error) { throwUnpolyfillable(type); } break; case 'DOMMatrix': case 'DOMMatrixReadOnly': C = global[type]; try { cloned = C.fromMatrix ? C.fromMatrix(value) : new C(value); } catch (error) { throwUnpolyfillable(type); } break; case 'AudioData': case 'VideoFrame': if (!isCallable(value.clone)) throwUnpolyfillable(type); try { cloned = value.clone(); } catch (error) { throwUncloneable(type); } break; case 'CropTarget': case 'CryptoKey': case 'FileSystemDirectoryHandle': case 'FileSystemFileHandle': case 'FileSystemHandle': case 'GPUCompilationInfo': case 'GPUCompilationMessage': case 'ImageBitmap': case 'RTCCertificate': case 'WebAssembly.Module': throwUnpolyfillable(type); // break omitted default: throwUncloneable(type); } } mapSet(map, value, cloned); switch (type) { case 'Array': case 'Object': keys = objectKeys(value); for (i = 0, length = lengthOfArrayLike(keys); i < length; i++) { key = keys[i]; createProperty(cloned, key, structuredCloneInternal(value[key], map)); } break; case 'Map': value.forEach(function (v, k) { mapSet(cloned, structuredCloneInternal(k, map), structuredCloneInternal(v, map)); }); break; case 'Set': value.forEach(function (v) { setAdd(cloned, structuredCloneInternal(v, map)); }); break; case 'Error': createNonEnumerableProperty(cloned, 'message', structuredCloneInternal(value.message, map)); if (hasOwn(value, 'cause')) { createNonEnumerableProperty(cloned, 'cause', structuredCloneInternal(value.cause, map)); } if (name === 'AggregateError') { cloned.errors = structuredCloneInternal(value.errors, map); } else if (name === 'SuppressedError') { cloned.error = structuredCloneInternal(value.error, map); cloned.suppressed = structuredCloneInternal(value.suppressed, map); } // break omitted case 'DOMException': if (ERROR_STACK_INSTALLABLE) { createNonEnumerableProperty(cloned, 'stack', structuredCloneInternal(value.stack, map)); } } return cloned; }; var tryToTransfer = function (rawTransfer, map) { if (!isObject(rawTransfer)) throw new TypeError('Transfer option cannot be converted to a sequence'); var transfer = []; iterate(rawTransfer, function (value) { push(transfer, anObject(value)); }); var i = 0; var length = lengthOfArrayLike(transfer); var buffers = new Set(); var value, type, C, transferred, canvas, context; while (i < length) { value = transfer[i++]; type = classof(value); if (type === 'ArrayBuffer' ? setHas(buffers, value) : mapHas(map, value)) { throw new DOMException('Duplicate transferable', DATA_CLONE_ERROR); } if (type === 'ArrayBuffer') { setAdd(buffers, value); continue; } if (PROPER_STRUCTURED_CLONE_TRANSFER) { transferred = nativeStructuredClone(value, { transfer: [value] }); } else switch (type) { case 'ImageBitmap': C = global.OffscreenCanvas; if (!isConstructor(C)) throwUnpolyfillable(type, TRANSFERRING); try { canvas = new C(value.width, value.height); context = canvas.getContext('bitmaprenderer'); context.transferFromImageBitmap(value); transferred = canvas.transferToImageBitmap(); } catch (error) { /* empty */ } break; case 'AudioData': case 'VideoFrame': if (!isCallable(value.clone) || !isCallable(value.close)) throwUnpolyfillable(type, TRANSFERRING); try { transferred = value.clone(); value.close(); } catch (error) { /* empty */ } break; case 'MediaSourceHandle': case 'MessagePort': case 'OffscreenCanvas': case 'ReadableStream': case 'TransformStream': case 'WritableStream': throwUnpolyfillable(type, TRANSFERRING); } if (transferred === undefined) throw new DOMException('This object cannot be transferred: ' + type, DATA_CLONE_ERROR); mapSet(map, value, transferred); } return buffers; }; var detachBuffers = function (buffers) { setIterate(buffers, function (buffer) { if (PROPER_STRUCTURED_CLONE_TRANSFER) { nativeRestrictedStructuredClone(buffer, { transfer: [buffer] }); } else if (isCallable(buffer.transfer)) { buffer.transfer(); } else if (detachTransferable) { detachTransferable(buffer); } else { throwUnpolyfillable('ArrayBuffer', TRANSFERRING); } }); }; // `structuredClone` method // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone $({ global: true, enumerable: true, sham: !PROPER_STRUCTURED_CLONE_TRANSFER, forced: FORCED_REPLACEMENT }, { structuredClone: function structuredClone(value /* , { transfer } */) { var options = validateArgumentsLength(arguments.length, 1) > 1 && !isNullOrUndefined(arguments[1]) ? anObject(arguments[1]) : undefined; var transfer = options ? options.transfer : undefined; var map, buffers; if (transfer !== undefined) { map = new Map(); buffers = tryToTransfer(transfer, map); } var clone = structuredCloneInternal(value, map); // since of an issue with cloning views of transferred buffers, we a forced to detach them later // https://github.com/zloirock/core-js/issues/1265 if (buffers) detachBuffers(buffers); return clone; } }); /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var fails = __webpack_require__(6); var isCallable = __webpack_require__(20); var classof = __webpack_require__(88); var getBuiltIn = __webpack_require__(22); var inspectSource = __webpack_require__(49); var noop = function () { /* empty */ }; var construct = getBuiltIn('Reflect', 'construct'); var constructorRegExp = /^\s*(?:class|function)\b/; var exec = uncurryThis(constructorRegExp.exec); var INCORRECT_TO_STRING = !constructorRegExp.test(noop); var isConstructorModern = function isConstructor(argument) { if (!isCallable(argument)) return false; try { construct(noop, [], argument); return true; } catch (error) { return false; } }; var isConstructorLegacy = function isConstructor(argument) { if (!isCallable(argument)) return false; switch (classof(argument)) { case 'AsyncFunction': case 'GeneratorFunction': case 'AsyncGeneratorFunction': return false; } try { // we can't check .prototype since constructors produced by .bind haven't it // `Function#toString` throws on some built-it function in some legacy engines // (for example, `DOMQuad` and similar in FF41-) return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument)); } catch (error) { return true; } }; isConstructorLegacy.sham = true; // `IsConstructor` abstract operation // https://tc39.es/ecma262/#sec-isconstructor module.exports = !construct || fails(function () { var called; return isConstructorModern(isConstructorModern.call) || !isConstructorModern(Object) || !isConstructorModern(function () { called = true; }) || called; }) ? isConstructorLegacy : isConstructorModern; /***/ }), /* 122 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toPropertyKey = __webpack_require__(17); var definePropertyModule = __webpack_require__(43); var createPropertyDescriptor = __webpack_require__(10); module.exports = function (object, key, value) { var propertyKey = toPropertyKey(key); if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value)); else object[propertyKey] = value; }; /***/ }), /* 123 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $TypeError = TypeError; module.exports = function (passed, required) { if (passed < required) throw new $TypeError('Not enough arguments'); return passed; }; /***/ }), /* 124 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var call = __webpack_require__(7); var hasOwn = __webpack_require__(37); var isPrototypeOf = __webpack_require__(23); var regExpFlags = __webpack_require__(97); var RegExpPrototype = RegExp.prototype; module.exports = function (R) { var flags = R.flags; return flags === undefined && !('flags' in RegExpPrototype) && !hasOwn(R, 'flags') && isPrototypeOf(RegExpPrototype, R) ? call(regExpFlags, R) : flags; }; /***/ }), /* 125 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); // eslint-disable-next-line es/no-set -- safe var SetPrototype = Set.prototype; module.exports = { // eslint-disable-next-line es/no-set -- safe Set: Set, add: uncurryThis(SetPrototype.add), has: uncurryThis(SetPrototype.has), remove: uncurryThis(SetPrototype['delete']), proto: SetPrototype }; /***/ }), /* 126 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var uncurryThis = __webpack_require__(13); var iterateSimple = __webpack_require__(127); var SetHelpers = __webpack_require__(125); var Set = SetHelpers.Set; var SetPrototype = SetHelpers.proto; var forEach = uncurryThis(SetPrototype.forEach); var keys = uncurryThis(SetPrototype.keys); var next = keys(new Set()).next; module.exports = function (set, fn, interruptible) { return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn); }; /***/ }), /* 127 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var call = __webpack_require__(7); module.exports = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) { var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator; var next = record.next; var step, result; while (!(step = call(next, iterator)).done) { result = fn(step.value); if (result !== undefined) return result; } }; /***/ }), /* 128 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var tryNodeRequire = __webpack_require__(129); var PROPER_STRUCTURED_CLONE_TRANSFER = __webpack_require__(131); var structuredClone = global.structuredClone; var $ArrayBuffer = global.ArrayBuffer; var $MessageChannel = global.MessageChannel; var detach = false; var WorkerThreads, channel, buffer, $detach; if (PROPER_STRUCTURED_CLONE_TRANSFER) { detach = function (transferable) { structuredClone(transferable, { transfer: [transferable] }); }; } else if ($ArrayBuffer) try { if (!$MessageChannel) { WorkerThreads = tryNodeRequire('worker_threads'); if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel; } if ($MessageChannel) { channel = new $MessageChannel(); buffer = new $ArrayBuffer(2); $detach = function (transferable) { channel.port1.postMessage(null, [transferable]); }; if (buffer.byteLength === 2) { $detach(buffer); if (buffer.byteLength === 0) detach = $detach; } } } catch (error) { /* empty */ } module.exports = detach; /***/ }), /* 129 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var IS_NODE = __webpack_require__(130); module.exports = function (name) { try { // eslint-disable-next-line no-new-func -- safe if (IS_NODE) return Function('return require("' + name + '")')(); } catch (error) { /* empty */ } }; /***/ }), /* 130 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var classof = __webpack_require__(14); module.exports = classof(global.process) === 'process'; /***/ }), /* 131 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(3); var fails = __webpack_require__(6); var V8 = __webpack_require__(26); var IS_BROWSER = __webpack_require__(132); var IS_DENO = __webpack_require__(133); var IS_NODE = __webpack_require__(130); var structuredClone = global.structuredClone; module.exports = !!structuredClone && !fails(function () { // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation // https://github.com/zloirock/core-js/issues/679 if ((IS_DENO && V8 > 92) || (IS_NODE && V8 > 94) || (IS_BROWSER && V8 > 97)) return false; var buffer = new ArrayBuffer(8); var clone = structuredClone(buffer, { transfer: [buffer] }); return buffer.byteLength !== 0 || clone.byteLength !== 8; }); /***/ }), /* 132 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var IS_DENO = __webpack_require__(133); var IS_NODE = __webpack_require__(130); module.exports = !IS_DENO && !IS_NODE && typeof window == 'object' && typeof document == 'object'; /***/ }), /* 133 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* global Deno -- Deno case */ module.exports = typeof Deno == 'object' && Deno && typeof Deno.version == 'object'; /***/ }), /* 134 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var fails = __webpack_require__(6); var createPropertyDescriptor = __webpack_require__(10); module.exports = !fails(function () { var error = new Error('a'); if (!('stack' in error)) return true; // eslint-disable-next-line es/no-object-defineproperty -- safe Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7)); return error.stack !== 7; }); /***/ }), /* 135 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $ = __webpack_require__(2); var getBuiltIn = __webpack_require__(22); var fails = __webpack_require__(6); var validateArgumentsLength = __webpack_require__(123); var toString = __webpack_require__(99); var USE_NATIVE_URL = __webpack_require__(136); var URL = getBuiltIn('URL'); // https://github.com/nodejs/node/issues/47505 // https://github.com/denoland/deno/issues/18893 var THROWS_WITHOUT_ARGUMENTS = USE_NATIVE_URL && fails(function () { URL.canParse(); }); // `URL.canParse` method // https://url.spec.whatwg.org/#dom-url-canparse $({ target: 'URL', stat: true, forced: !THROWS_WITHOUT_ARGUMENTS }, { canParse: function canParse(url) { var length = validateArgumentsLength(arguments.length, 1); var urlString = toString(url); var base = length < 2 || arguments[1] === undefined ? undefined : toString(arguments[1]); try { return !!new URL(urlString, base); } catch (error) { return false; } } }); /***/ }), /* 136 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var fails = __webpack_require__(6); var wellKnownSymbol = __webpack_require__(32); var DESCRIPTORS = __webpack_require__(5); var IS_PURE = __webpack_require__(34); var ITERATOR = wellKnownSymbol('iterator'); module.exports = !fails(function () { // eslint-disable-next-line unicorn/relative-url-style -- required for testing var url = new URL('b?a=1&b=2&c=3', 'http://a'); var params = url.searchParams; var params2 = new URLSearchParams('a=1&a=2&b=3'); var result = ''; url.pathname = 'c%20d'; params.forEach(function (value, key) { params['delete']('b'); result += key + value; }); params2['delete']('a', 2); // `undefined` case is a Chromium 117 bug // https://bugs.chromium.org/p/v8/issues/detail?id=14222 params2['delete']('b', undefined); return (IS_PURE && (!url.toJSON || !params2.has('a', 1) || params2.has('a', 2) || !params2.has('a', undefined) || params2.has('b'))) || (!params.size && (IS_PURE || !DESCRIPTORS)) || !params.sort || url.href !== 'http://a/c%20d?a=1&c=3' || params.get('c') !== '3' || String(new URLSearchParams('?a=1')) !== 'a=1' || !params[ITERATOR] // throws in Edge || new URL('https://a@b').username !== 'a' || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' // not punycoded in Edge || new URL('http://тест').host !== 'xn--e1aybc' // not escaped in Chrome 62- || new URL('http://a#б').hash !== '#%D0%B1' // fails in Chrome 66- || result !== 'a1c3' // throws in Safari || new URL('http://x', undefined).host !== 'x'; }); /***/ }), /* 137 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var defineBuiltIn = __webpack_require__(46); var uncurryThis = __webpack_require__(13); var toString = __webpack_require__(99); var validateArgumentsLength = __webpack_require__(123); var $URLSearchParams = URLSearchParams; var URLSearchParamsPrototype = $URLSearchParams.prototype; var append = uncurryThis(URLSearchParamsPrototype.append); var $delete = uncurryThis(URLSearchParamsPrototype['delete']); var forEach = uncurryThis(URLSearchParamsPrototype.forEach); var push = uncurryThis([].push); var params = new $URLSearchParams('a=1&a=2&b=3'); params['delete']('a', 1); // `undefined` case is a Chromium 117 bug // https://bugs.chromium.org/p/v8/issues/detail?id=14222 params['delete']('b', undefined); if (params + '' !== 'a=2') { defineBuiltIn(URLSearchParamsPrototype, 'delete', function (name /* , value */) { var length = arguments.length; var $value = length < 2 ? undefined : arguments[1]; if (length && $value === undefined) return $delete(this, name); var entries = []; forEach(this, function (v, k) { // also validates `this` push(entries, { key: k, value: v }); }); validateArgumentsLength(length, 1); var key = toString(name); var value = toString($value); var index = 0; var dindex = 0; var found = false; var entriesLength = entries.length; var entry; while (index < entriesLength) { entry = entries[index++]; if (found || entry.key === key) { found = true; $delete(this, entry.key); } else dindex++; } while (dindex < entriesLength) { entry = entries[dindex++]; if (!(entry.key === key && entry.value === value)) append(this, entry.key, entry.value); } }, { enumerable: true, unsafe: true }); } /***/ }), /* 138 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var defineBuiltIn = __webpack_require__(46); var uncurryThis = __webpack_require__(13); var toString = __webpack_require__(99); var validateArgumentsLength = __webpack_require__(123); var $URLSearchParams = URLSearchParams; var URLSearchParamsPrototype = $URLSearchParams.prototype; var getAll = uncurryThis(URLSearchParamsPrototype.getAll); var $has = uncurryThis(URLSearchParamsPrototype.has); var params = new $URLSearchParams('a=1'); // `undefined` case is a Chromium 117 bug // https://bugs.chromium.org/p/v8/issues/detail?id=14222 if (params.has('a', 2) || !params.has('a', undefined)) { defineBuiltIn(URLSearchParamsPrototype, 'has', function has(name /* , value */) { var length = arguments.length; var $value = length < 2 ? undefined : arguments[1]; if (length && $value === undefined) return $has(this, name); var values = getAll(this, name); // also validates `this` validateArgumentsLength(length, 1); var value = toString($value); var index = 0; while (index < values.length) { if (values[index++] === value) return true; } return false; }, { enumerable: true, unsafe: true }); } /***/ }), /* 139 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var DESCRIPTORS = __webpack_require__(5); var uncurryThis = __webpack_require__(13); var defineBuiltInAccessor = __webpack_require__(96); var URLSearchParamsPrototype = URLSearchParams.prototype; var forEach = uncurryThis(URLSearchParamsPrototype.forEach); // `URLSearchParams.prototype.size` getter // https://github.com/whatwg/url/pull/734 if (DESCRIPTORS && !('size' in URLSearchParamsPrototype)) { defineBuiltInAccessor(URLSearchParamsPrototype, 'size', { get: function size() { var count = 0; forEach(this, function () { count++; }); return count; }, configurable: true, enumerable: true }); } /***/ }) /******/ ]); }(); wp-polyfill-element-closest.js 0000644 00000000654 14720015030 0012456 0 ustar 00 !function(e){var t=e.Element.prototype;"function"!=typeof t.matches&&(t.matches=t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||function(e){for(var t=(this.document||this.ownerDocument).querySelectorAll(e),o=0;t[o]&&t[o]!==this;)++o;return Boolean(t[o])}),"function"!=typeof t.closest&&(t.closest=function(e){for(var t=this;t&&1===t.nodeType;){if(t.matches(e))return t;t=t.parentNode}return null})}(window); wp-polyfill-inert.min.js 0000604 00000020020 14720015030 0011237 0 ustar 00 !function(e){"object"==typeof exports&&"undefined"!=typeof module||"function"!=typeof define||!define.amd?e():define("inert",e)}((function(){"use strict";var e,t,n,i,o,r,s=function(e,t,n){return t&&a(e.prototype,t),n&&a(e,n),e};function a(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function d(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){d(this,u),this._inertManager=t,this._rootElement=e,this._managedNodes=new Set,this._rootElement.hasAttribute("aria-hidden")?this._savedAriaHidden=this._rootElement.getAttribute("aria-hidden"):this._savedAriaHidden=null,this._rootElement.setAttribute("aria-hidden","true"),this._makeSubtreeUnfocusable(this._rootElement),this._observer=new MutationObserver(this._onMutation.bind(this)),this._observer.observe(this._rootElement,{attributes:!0,childList:!0,subtree:!0})}function h(e,t){d(this,h),this._node=e,this._overrodeFocusMethod=!1,this._inertRoots=new Set([t]),this._savedTabIndex=null,this._destroyed=!1,this.ensureUntabbable()}function l(e){if(d(this,l),!e)throw new Error("Missing required argument; InertManager needs to wrap a document.");this._document=e,this._managedNodes=new Map,this._inertRoots=new Map,this._observer=new MutationObserver(this._watchForInert.bind(this)),_(e.head||e.body||e.documentElement),"loading"===e.readyState?e.addEventListener("DOMContentLoaded",this._onDocumentLoaded.bind(this)):this._onDocumentLoaded()}function c(e,t,n){if(e.nodeType==Node.ELEMENT_NODE){var i=e;if(s=(t&&t(i),i.shadowRoot))return void c(s,t,s);if("content"==i.localName){for(var o=(s=i).getDistributedNodes?s.getDistributedNodes():[],r=0;r<o.length;r++)c(o[r],t,n);return}if("slot"==i.localName){for(var s,a=(s=i).assignedNodes?s.assignedNodes({flatten:!0}):[],d=0;d<a.length;d++)c(a[d],t,n);return}}for(var u=e.firstChild;null!=u;)c(u,t,n),u=u.nextSibling}function _(e){var t;e.querySelector("style#inert-style, link#inert-style")||((t=document.createElement("style")).setAttribute("id","inert-style"),t.textContent="\n[inert] {\n pointer-events: none;\n cursor: default;\n}\n\n[inert], [inert] * {\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n",e.appendChild(t))}"undefined"!=typeof window&&"undefined"!=typeof Element&&(e=Array.prototype.slice,t=Element.prototype.matches||Element.prototype.msMatchesSelector,n=["a[href]","area[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","details","summary","iframe","object","embed","video","[contenteditable]"].join(","),s(u,[{key:"destructor",value:function(){this._observer.disconnect(),this._rootElement&&(null!==this._savedAriaHidden?this._rootElement.setAttribute("aria-hidden",this._savedAriaHidden):this._rootElement.removeAttribute("aria-hidden")),this._managedNodes.forEach((function(e){this._unmanageNode(e.node)}),this),this._observer=null,this._rootElement=null,this._managedNodes=null,this._inertManager=null}},{key:"_makeSubtreeUnfocusable",value:function(e){var t=this,n=(c(e,(function(e){return t._visitNode(e)})),document.activeElement);if(!document.body.contains(e)){for(var i=e,o=void 0;i;){if(i.nodeType===Node.DOCUMENT_FRAGMENT_NODE){o=i;break}i=i.parentNode}o&&(n=o.activeElement)}e.contains(n)&&(n.blur(),n===document.activeElement&&document.body.focus())}},{key:"_visitNode",value:function(e){e.nodeType===Node.ELEMENT_NODE&&(e!==this._rootElement&&e.hasAttribute("inert")&&this._adoptInertRoot(e),(t.call(e,n)||e.hasAttribute("tabindex"))&&this._manageNode(e))}},{key:"_manageNode",value:function(e){e=this._inertManager.register(e,this),this._managedNodes.add(e)}},{key:"_unmanageNode",value:function(e){(e=this._inertManager.deregister(e,this))&&this._managedNodes.delete(e)}},{key:"_unmanageSubtree",value:function(e){var t=this;c(e,(function(e){return t._unmanageNode(e)}))}},{key:"_adoptInertRoot",value:function(e){var t=this._inertManager.getInertRoot(e);t||(this._inertManager.setInert(e,!0),t=this._inertManager.getInertRoot(e)),t.managedNodes.forEach((function(e){this._manageNode(e.node)}),this)}},{key:"_onMutation",value:function(t,n){t.forEach((function(t){var n,i=t.target;"childList"===t.type?(e.call(t.addedNodes).forEach((function(e){this._makeSubtreeUnfocusable(e)}),this),e.call(t.removedNodes).forEach((function(e){this._unmanageSubtree(e)}),this)):"attributes"===t.type&&("tabindex"===t.attributeName?this._manageNode(i):i!==this._rootElement&&"inert"===t.attributeName&&i.hasAttribute("inert")&&(this._adoptInertRoot(i),n=this._inertManager.getInertRoot(i),this._managedNodes.forEach((function(e){i.contains(e.node)&&n._manageNode(e.node)}))))}),this)}},{key:"managedNodes",get:function(){return new Set(this._managedNodes)}},{key:"hasSavedAriaHidden",get:function(){return null!==this._savedAriaHidden}},{key:"savedAriaHidden",set:function(e){this._savedAriaHidden=e},get:function(){return this._savedAriaHidden}}]),i=u,s(h,[{key:"destructor",value:function(){var e;this._throwIfDestroyed(),this._node&&this._node.nodeType===Node.ELEMENT_NODE&&(e=this._node,null!==this._savedTabIndex?e.setAttribute("tabindex",this._savedTabIndex):e.removeAttribute("tabindex"),this._overrodeFocusMethod&&delete e.focus),this._node=null,this._inertRoots=null,this._destroyed=!0}},{key:"_throwIfDestroyed",value:function(){if(this.destroyed)throw new Error("Trying to access destroyed InertNode")}},{key:"ensureUntabbable",value:function(){var e;this.node.nodeType===Node.ELEMENT_NODE&&(e=this.node,t.call(e,n)?-1===e.tabIndex&&this.hasSavedTabIndex||(e.hasAttribute("tabindex")&&(this._savedTabIndex=e.tabIndex),e.setAttribute("tabindex","-1"),e.nodeType===Node.ELEMENT_NODE&&(e.focus=function(){},this._overrodeFocusMethod=!0)):e.hasAttribute("tabindex")&&(this._savedTabIndex=e.tabIndex,e.removeAttribute("tabindex")))}},{key:"addInertRoot",value:function(e){this._throwIfDestroyed(),this._inertRoots.add(e)}},{key:"removeInertRoot",value:function(e){this._throwIfDestroyed(),this._inertRoots.delete(e),0===this._inertRoots.size&&this.destructor()}},{key:"destroyed",get:function(){return this._destroyed}},{key:"hasSavedTabIndex",get:function(){return null!==this._savedTabIndex}},{key:"node",get:function(){return this._throwIfDestroyed(),this._node}},{key:"savedTabIndex",set:function(e){this._throwIfDestroyed(),this._savedTabIndex=e},get:function(){return this._throwIfDestroyed(),this._savedTabIndex}}]),o=h,s(l,[{key:"setInert",value:function(e,t){if(t){if(!this._inertRoots.has(e)&&(t=new i(e,this),e.setAttribute("inert",""),this._inertRoots.set(e,t),!this._document.body.contains(e)))for(var n=e.parentNode;n;)11===n.nodeType&&_(n),n=n.parentNode}else this._inertRoots.has(e)&&(this._inertRoots.get(e).destructor(),this._inertRoots.delete(e),e.removeAttribute("inert"))}},{key:"getInertRoot",value:function(e){return this._inertRoots.get(e)}},{key:"register",value:function(e,t){var n=this._managedNodes.get(e);return void 0!==n?n.addInertRoot(t):n=new o(e,t),this._managedNodes.set(e,n),n}},{key:"deregister",value:function(e,t){var n=this._managedNodes.get(e);return n?(n.removeInertRoot(t),n.destroyed&&this._managedNodes.delete(e),n):null}},{key:"_onDocumentLoaded",value:function(){e.call(this._document.querySelectorAll("[inert]")).forEach((function(e){this.setInert(e,!0)}),this),this._observer.observe(this._document.body||this._document.documentElement,{attributes:!0,subtree:!0,childList:!0})}},{key:"_watchForInert",value:function(n,i){var o=this;n.forEach((function(n){switch(n.type){case"childList":e.call(n.addedNodes).forEach((function(n){var i;n.nodeType===Node.ELEMENT_NODE&&(i=e.call(n.querySelectorAll("[inert]")),t.call(n,"[inert]")&&i.unshift(n),i.forEach((function(e){this.setInert(e,!0)}),o))}),o);break;case"attributes":if("inert"!==n.attributeName)return;var i=n.target,r=i.hasAttribute("inert");o.setInert(i,r)}}),this)}}]),s=l,HTMLElement.prototype.hasOwnProperty("inert")||(r=new s(document),Object.defineProperty(HTMLElement.prototype,"inert",{enumerable:!0,get:function(){return this.hasAttribute("inert")},set:function(e){r.setInert(this,e)}})))})); wp-polyfill-node-contains.min.js 0000644 00000000541 14720015030 0012671 0 ustar 00 !function(){function e(e){if(!(0 in arguments))throw new TypeError("1 argument is required");do{if(this===e)return!0}while(e=e&&e.parentNode);return!1}if("HTMLElement"in self&&"contains"in HTMLElement.prototype)try{delete HTMLElement.prototype.contains}catch(e){}"Node"in self?Node.prototype.contains=e:document.contains=Element.prototype.contains=e}(); wp-polyfill-url.js 0000644 00000327374 14720015030 0010170 0 ustar 00 (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ module.exports = function (it) { if (typeof it != 'function') { throw TypeError(String(it) + ' is not a function'); } return it; }; },{}],2:[function(require,module,exports){ var isObject = require('../internals/is-object'); module.exports = function (it) { if (!isObject(it) && it !== null) { throw TypeError("Can't set " + String(it) + ' as a prototype'); } return it; }; },{"../internals/is-object":37}],3:[function(require,module,exports){ var wellKnownSymbol = require('../internals/well-known-symbol'); var create = require('../internals/object-create'); var definePropertyModule = require('../internals/object-define-property'); var UNSCOPABLES = wellKnownSymbol('unscopables'); var ArrayPrototype = Array.prototype; // Array.prototype[@@unscopables] // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables if (ArrayPrototype[UNSCOPABLES] == undefined) { definePropertyModule.f(ArrayPrototype, UNSCOPABLES, { configurable: true, value: create(null) }); } // add a key to Array.prototype[@@unscopables] module.exports = function (key) { ArrayPrototype[UNSCOPABLES][key] = true; }; },{"../internals/object-create":45,"../internals/object-define-property":47,"../internals/well-known-symbol":77}],4:[function(require,module,exports){ module.exports = function (it, Constructor, name) { if (!(it instanceof Constructor)) { throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation'); } return it; }; },{}],5:[function(require,module,exports){ var isObject = require('../internals/is-object'); module.exports = function (it) { if (!isObject(it)) { throw TypeError(String(it) + ' is not an object'); } return it; }; },{"../internals/is-object":37}],6:[function(require,module,exports){ 'use strict'; var bind = require('../internals/function-bind-context'); var toObject = require('../internals/to-object'); var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing'); var isArrayIteratorMethod = require('../internals/is-array-iterator-method'); var toLength = require('../internals/to-length'); var createProperty = require('../internals/create-property'); var getIteratorMethod = require('../internals/get-iterator-method'); // `Array.from` method implementation // https://tc39.github.io/ecma262/#sec-array.from module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { var O = toObject(arrayLike); var C = typeof this == 'function' ? this : Array; var argumentsLength = arguments.length; var mapfn = argumentsLength > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var iteratorMethod = getIteratorMethod(O); var index = 0; var length, result, step, iterator, next, value; if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); // if the target is not iterable or it's an array with the default iterator - use a simple case if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) { iterator = iteratorMethod.call(O); next = iterator.next; result = new C(); for (;!(step = next.call(iterator)).done; index++) { value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value; createProperty(result, index, value); } } else { length = toLength(O.length); result = new C(length); for (;length > index; index++) { value = mapping ? mapfn(O[index], index) : O[index]; createProperty(result, index, value); } } result.length = index; return result; }; },{"../internals/call-with-safe-iteration-closing":8,"../internals/create-property":16,"../internals/function-bind-context":23,"../internals/get-iterator-method":25,"../internals/is-array-iterator-method":35,"../internals/to-length":71,"../internals/to-object":72}],7:[function(require,module,exports){ var toIndexedObject = require('../internals/to-indexed-object'); var toLength = require('../internals/to-length'); var toAbsoluteIndex = require('../internals/to-absolute-index'); // `Array.prototype.{ indexOf, includes }` methods implementation var createMethod = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) { if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; module.exports = { // `Array.prototype.includes` method // https://tc39.github.io/ecma262/#sec-array.prototype.includes includes: createMethod(true), // `Array.prototype.indexOf` method // https://tc39.github.io/ecma262/#sec-array.prototype.indexof indexOf: createMethod(false) }; },{"../internals/to-absolute-index":68,"../internals/to-indexed-object":69,"../internals/to-length":71}],8:[function(require,module,exports){ var anObject = require('../internals/an-object'); // call something on iterator step with safe closing on error module.exports = function (iterator, fn, value, ENTRIES) { try { return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch (error) { var returnMethod = iterator['return']; if (returnMethod !== undefined) anObject(returnMethod.call(iterator)); throw error; } }; },{"../internals/an-object":5}],9:[function(require,module,exports){ var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; },{}],10:[function(require,module,exports){ var TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support'); var classofRaw = require('../internals/classof-raw'); var wellKnownSymbol = require('../internals/well-known-symbol'); var TO_STRING_TAG = wellKnownSymbol('toStringTag'); // ES3 wrong here var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (error) { /* empty */ } }; // getting tag from ES6+ `Object.prototype.toString` module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) { var O, tag, result; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag // builtinTag case : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result; }; },{"../internals/classof-raw":9,"../internals/to-string-tag-support":74,"../internals/well-known-symbol":77}],11:[function(require,module,exports){ var has = require('../internals/has'); var ownKeys = require('../internals/own-keys'); var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor'); var definePropertyModule = require('../internals/object-define-property'); module.exports = function (target, source) { var keys = ownKeys(source); var defineProperty = definePropertyModule.f; var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key)); } }; },{"../internals/has":28,"../internals/object-define-property":47,"../internals/object-get-own-property-descriptor":48,"../internals/own-keys":56}],12:[function(require,module,exports){ var fails = require('../internals/fails'); module.exports = !fails(function () { function F() { /* empty */ } F.prototype.constructor = null; return Object.getPrototypeOf(new F()) !== F.prototype; }); },{"../internals/fails":22}],13:[function(require,module,exports){ 'use strict'; var IteratorPrototype = require('../internals/iterators-core').IteratorPrototype; var create = require('../internals/object-create'); var createPropertyDescriptor = require('../internals/create-property-descriptor'); var setToStringTag = require('../internals/set-to-string-tag'); var Iterators = require('../internals/iterators'); var returnThis = function () { return this; }; module.exports = function (IteratorConstructor, NAME, next) { var TO_STRING_TAG = NAME + ' Iterator'; IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(1, next) }); setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true); Iterators[TO_STRING_TAG] = returnThis; return IteratorConstructor; }; },{"../internals/create-property-descriptor":15,"../internals/iterators":40,"../internals/iterators-core":39,"../internals/object-create":45,"../internals/set-to-string-tag":62}],14:[function(require,module,exports){ var DESCRIPTORS = require('../internals/descriptors'); var definePropertyModule = require('../internals/object-define-property'); var createPropertyDescriptor = require('../internals/create-property-descriptor'); module.exports = DESCRIPTORS ? function (object, key, value) { return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); } : function (object, key, value) { object[key] = value; return object; }; },{"../internals/create-property-descriptor":15,"../internals/descriptors":18,"../internals/object-define-property":47}],15:[function(require,module,exports){ module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; },{}],16:[function(require,module,exports){ 'use strict'; var toPrimitive = require('../internals/to-primitive'); var definePropertyModule = require('../internals/object-define-property'); var createPropertyDescriptor = require('../internals/create-property-descriptor'); module.exports = function (object, key, value) { var propertyKey = toPrimitive(key); if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value)); else object[propertyKey] = value; }; },{"../internals/create-property-descriptor":15,"../internals/object-define-property":47,"../internals/to-primitive":73}],17:[function(require,module,exports){ 'use strict'; var $ = require('../internals/export'); var createIteratorConstructor = require('../internals/create-iterator-constructor'); var getPrototypeOf = require('../internals/object-get-prototype-of'); var setPrototypeOf = require('../internals/object-set-prototype-of'); var setToStringTag = require('../internals/set-to-string-tag'); var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); var redefine = require('../internals/redefine'); var wellKnownSymbol = require('../internals/well-known-symbol'); var IS_PURE = require('../internals/is-pure'); var Iterators = require('../internals/iterators'); var IteratorsCore = require('../internals/iterators-core'); var IteratorPrototype = IteratorsCore.IteratorPrototype; var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS; var ITERATOR = wellKnownSymbol('iterator'); var KEYS = 'keys'; var VALUES = 'values'; var ENTRIES = 'entries'; var returnThis = function () { return this; }; module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { createIteratorConstructor(IteratorConstructor, NAME, next); var getIterationMethod = function (KIND) { if (KIND === DEFAULT && defaultIterator) return defaultIterator; if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND]; switch (KIND) { case KEYS: return function keys() { return new IteratorConstructor(this, KIND); }; case VALUES: return function values() { return new IteratorConstructor(this, KIND); }; case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); }; } return function () { return new IteratorConstructor(this); }; }; var TO_STRING_TAG = NAME + ' Iterator'; var INCORRECT_VALUES_NAME = false; var IterablePrototype = Iterable.prototype; var nativeIterator = IterablePrototype[ITERATOR] || IterablePrototype['@@iterator'] || DEFAULT && IterablePrototype[DEFAULT]; var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT); var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; var CurrentIteratorPrototype, methods, KEY; // fix native if (anyNativeIterator) { CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable())); if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) { if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) { if (setPrototypeOf) { setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype); } else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') { createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis); } } // Set @@toStringTag to native iterators setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true); if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis; } } // fix Array#{values, @@iterator}.name in V8 / FF if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) { INCORRECT_VALUES_NAME = true; defaultIterator = function values() { return nativeIterator.call(this); }; } // define iterator if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) { createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator); } Iterators[NAME] = defaultIterator; // export additional methods if (DEFAULT) { methods = { values: getIterationMethod(VALUES), keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), entries: getIterationMethod(ENTRIES) }; if (FORCED) for (KEY in methods) { if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { redefine(IterablePrototype, KEY, methods[KEY]); } } else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods); } return methods; }; },{"../internals/create-iterator-constructor":13,"../internals/create-non-enumerable-property":14,"../internals/export":21,"../internals/is-pure":38,"../internals/iterators":40,"../internals/iterators-core":39,"../internals/object-get-prototype-of":51,"../internals/object-set-prototype-of":55,"../internals/redefine":59,"../internals/set-to-string-tag":62,"../internals/well-known-symbol":77}],18:[function(require,module,exports){ var fails = require('../internals/fails'); // Thank's IE8 for his funny defineProperty module.exports = !fails(function () { return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7; }); },{"../internals/fails":22}],19:[function(require,module,exports){ var global = require('../internals/global'); var isObject = require('../internals/is-object'); var document = global.document; // typeof document.createElement is 'object' in old IE var EXISTS = isObject(document) && isObject(document.createElement); module.exports = function (it) { return EXISTS ? document.createElement(it) : {}; }; },{"../internals/global":27,"../internals/is-object":37}],20:[function(require,module,exports){ // IE8- don't enum bug keys module.exports = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; },{}],21:[function(require,module,exports){ var global = require('../internals/global'); var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f; var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); var redefine = require('../internals/redefine'); var setGlobal = require('../internals/set-global'); var copyConstructorProperties = require('../internals/copy-constructor-properties'); var isForced = require('../internals/is-forced'); /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.noTargetGet - prevent calling a getter on target */ module.exports = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global; } else if (STATIC) { target = global[TARGET] || setGlobal(TARGET, {}); } else { target = (global[TARGET] || {}).prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.noTargetGet) { descriptor = getOwnPropertyDescriptor(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty === typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { createNonEnumerableProperty(sourceProperty, 'sham', true); } // extend global redefine(target, key, sourceProperty, options); } }; },{"../internals/copy-constructor-properties":11,"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/is-forced":36,"../internals/object-get-own-property-descriptor":48,"../internals/redefine":59,"../internals/set-global":61}],22:[function(require,module,exports){ module.exports = function (exec) { try { return !!exec(); } catch (error) { return true; } }; },{}],23:[function(require,module,exports){ var aFunction = require('../internals/a-function'); // optional / simple context binding module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 0: return function () { return fn.call(that); }; case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; },{"../internals/a-function":1}],24:[function(require,module,exports){ var path = require('../internals/path'); var global = require('../internals/global'); var aFunction = function (variable) { return typeof variable == 'function' ? variable : undefined; }; module.exports = function (namespace, method) { return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace]) : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method]; }; },{"../internals/global":27,"../internals/path":57}],25:[function(require,module,exports){ var classof = require('../internals/classof'); var Iterators = require('../internals/iterators'); var wellKnownSymbol = require('../internals/well-known-symbol'); var ITERATOR = wellKnownSymbol('iterator'); module.exports = function (it) { if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; },{"../internals/classof":10,"../internals/iterators":40,"../internals/well-known-symbol":77}],26:[function(require,module,exports){ var anObject = require('../internals/an-object'); var getIteratorMethod = require('../internals/get-iterator-method'); module.exports = function (it) { var iteratorMethod = getIteratorMethod(it); if (typeof iteratorMethod != 'function') { throw TypeError(String(it) + ' is not iterable'); } return anObject(iteratorMethod.call(it)); }; },{"../internals/an-object":5,"../internals/get-iterator-method":25}],27:[function(require,module,exports){ (function (global){ var check = function (it) { return it && it.Math == Math && it; }; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 module.exports = // eslint-disable-next-line no-undef check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || check(typeof self == 'object' && self) || check(typeof global == 'object' && global) || // eslint-disable-next-line no-new-func Function('return this')(); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],28:[function(require,module,exports){ var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; },{}],29:[function(require,module,exports){ module.exports = {}; },{}],30:[function(require,module,exports){ var getBuiltIn = require('../internals/get-built-in'); module.exports = getBuiltIn('document', 'documentElement'); },{"../internals/get-built-in":24}],31:[function(require,module,exports){ var DESCRIPTORS = require('../internals/descriptors'); var fails = require('../internals/fails'); var createElement = require('../internals/document-create-element'); // Thank's IE8 for his funny defineProperty module.exports = !DESCRIPTORS && !fails(function () { return Object.defineProperty(createElement('div'), 'a', { get: function () { return 7; } }).a != 7; }); },{"../internals/descriptors":18,"../internals/document-create-element":19,"../internals/fails":22}],32:[function(require,module,exports){ var fails = require('../internals/fails'); var classof = require('../internals/classof-raw'); var split = ''.split; // fallback for non-array-like ES3 and non-enumerable old V8 strings module.exports = fails(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins return !Object('z').propertyIsEnumerable(0); }) ? function (it) { return classof(it) == 'String' ? split.call(it, '') : Object(it); } : Object; },{"../internals/classof-raw":9,"../internals/fails":22}],33:[function(require,module,exports){ var store = require('../internals/shared-store'); var functionToString = Function.toString; // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper if (typeof store.inspectSource != 'function') { store.inspectSource = function (it) { return functionToString.call(it); }; } module.exports = store.inspectSource; },{"../internals/shared-store":64}],34:[function(require,module,exports){ var NATIVE_WEAK_MAP = require('../internals/native-weak-map'); var global = require('../internals/global'); var isObject = require('../internals/is-object'); var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); var objectHas = require('../internals/has'); var sharedKey = require('../internals/shared-key'); var hiddenKeys = require('../internals/hidden-keys'); var WeakMap = global.WeakMap; var set, get, has; var enforce = function (it) { return has(it) ? get(it) : set(it, {}); }; var getterFor = function (TYPE) { return function (it) { var state; if (!isObject(it) || (state = get(it)).type !== TYPE) { throw TypeError('Incompatible receiver, ' + TYPE + ' required'); } return state; }; }; if (NATIVE_WEAK_MAP) { var store = new WeakMap(); var wmget = store.get; var wmhas = store.has; var wmset = store.set; set = function (it, metadata) { wmset.call(store, it, metadata); return metadata; }; get = function (it) { return wmget.call(store, it) || {}; }; has = function (it) { return wmhas.call(store, it); }; } else { var STATE = sharedKey('state'); hiddenKeys[STATE] = true; set = function (it, metadata) { createNonEnumerableProperty(it, STATE, metadata); return metadata; }; get = function (it) { return objectHas(it, STATE) ? it[STATE] : {}; }; has = function (it) { return objectHas(it, STATE); }; } module.exports = { set: set, get: get, has: has, enforce: enforce, getterFor: getterFor }; },{"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/has":28,"../internals/hidden-keys":29,"../internals/is-object":37,"../internals/native-weak-map":43,"../internals/shared-key":63}],35:[function(require,module,exports){ var wellKnownSymbol = require('../internals/well-known-symbol'); var Iterators = require('../internals/iterators'); var ITERATOR = wellKnownSymbol('iterator'); var ArrayPrototype = Array.prototype; // check on default Array iterator module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it); }; },{"../internals/iterators":40,"../internals/well-known-symbol":77}],36:[function(require,module,exports){ var fails = require('../internals/fails'); var replacement = /#|\.prototype\./; var isForced = function (feature, detection) { var value = data[normalize(feature)]; return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == 'function' ? fails(detection) : !!detection; }; var normalize = isForced.normalize = function (string) { return String(string).replace(replacement, '.').toLowerCase(); }; var data = isForced.data = {}; var NATIVE = isForced.NATIVE = 'N'; var POLYFILL = isForced.POLYFILL = 'P'; module.exports = isForced; },{"../internals/fails":22}],37:[function(require,module,exports){ module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; },{}],38:[function(require,module,exports){ module.exports = false; },{}],39:[function(require,module,exports){ 'use strict'; var getPrototypeOf = require('../internals/object-get-prototype-of'); var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); var has = require('../internals/has'); var wellKnownSymbol = require('../internals/well-known-symbol'); var IS_PURE = require('../internals/is-pure'); var ITERATOR = wellKnownSymbol('iterator'); var BUGGY_SAFARI_ITERATORS = false; var returnThis = function () { return this; }; // `%IteratorPrototype%` object // https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator; if ([].keys) { arrayIterator = [].keys(); // Safari 8 has buggy iterators w/o `next` if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true; else { PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator)); if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype; } } if (IteratorPrototype == undefined) IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() if (!IS_PURE && !has(IteratorPrototype, ITERATOR)) { createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis); } module.exports = { IteratorPrototype: IteratorPrototype, BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS }; },{"../internals/create-non-enumerable-property":14,"../internals/has":28,"../internals/is-pure":38,"../internals/object-get-prototype-of":51,"../internals/well-known-symbol":77}],40:[function(require,module,exports){ arguments[4][29][0].apply(exports,arguments) },{"dup":29}],41:[function(require,module,exports){ var fails = require('../internals/fails'); module.exports = !!Object.getOwnPropertySymbols && !fails(function () { // Chrome 38 Symbol has incorrect toString conversion // eslint-disable-next-line no-undef return !String(Symbol()); }); },{"../internals/fails":22}],42:[function(require,module,exports){ var fails = require('../internals/fails'); var wellKnownSymbol = require('../internals/well-known-symbol'); var IS_PURE = require('../internals/is-pure'); var ITERATOR = wellKnownSymbol('iterator'); module.exports = !fails(function () { var url = new URL('b?a=1&b=2&c=3', 'http://a'); var searchParams = url.searchParams; var result = ''; url.pathname = 'c%20d'; searchParams.forEach(function (value, key) { searchParams['delete']('b'); result += key + value; }); return (IS_PURE && !url.toJSON) || !searchParams.sort || url.href !== 'http://a/c%20d?a=1&c=3' || searchParams.get('c') !== '3' || String(new URLSearchParams('?a=1')) !== 'a=1' || !searchParams[ITERATOR] // throws in Edge || new URL('https://a@b').username !== 'a' || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' // not punycoded in Edge || new URL('http://тест').host !== 'xn--e1aybc' // not escaped in Chrome 62- || new URL('http://a#б').hash !== '#%D0%B1' // fails in Chrome 66- || result !== 'a1c3' // throws in Safari || new URL('http://x', undefined).host !== 'x'; }); },{"../internals/fails":22,"../internals/is-pure":38,"../internals/well-known-symbol":77}],43:[function(require,module,exports){ var global = require('../internals/global'); var inspectSource = require('../internals/inspect-source'); var WeakMap = global.WeakMap; module.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap)); },{"../internals/global":27,"../internals/inspect-source":33}],44:[function(require,module,exports){ 'use strict'; var DESCRIPTORS = require('../internals/descriptors'); var fails = require('../internals/fails'); var objectKeys = require('../internals/object-keys'); var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols'); var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable'); var toObject = require('../internals/to-object'); var IndexedObject = require('../internals/indexed-object'); var nativeAssign = Object.assign; var defineProperty = Object.defineProperty; // `Object.assign` method // https://tc39.github.io/ecma262/#sec-object.assign module.exports = !nativeAssign || fails(function () { // should have correct order of operations (Edge bug) if (DESCRIPTORS && nativeAssign({ b: 1 }, nativeAssign(defineProperty({}, 'a', { enumerable: true, get: function () { defineProperty(this, 'b', { value: 3, enumerable: false }); } }), { b: 2 })).b !== 1) return true; // should work with symbols and should have deterministic property order (V8 bug) var A = {}; var B = {}; // eslint-disable-next-line no-undef var symbol = Symbol(); var alphabet = 'abcdefghijklmnopqrst'; A[symbol] = 7; alphabet.split('').forEach(function (chr) { B[chr] = chr; }); return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet; }) ? function assign(target, source) { // eslint-disable-line no-unused-vars var T = toObject(target); var argumentsLength = arguments.length; var index = 1; var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; var propertyIsEnumerable = propertyIsEnumerableModule.f; while (argumentsLength > index) { var S = IndexedObject(arguments[index++]); var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S); var length = keys.length; var j = 0; var key; while (length > j) { key = keys[j++]; if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key]; } } return T; } : nativeAssign; },{"../internals/descriptors":18,"../internals/fails":22,"../internals/indexed-object":32,"../internals/object-get-own-property-symbols":50,"../internals/object-keys":53,"../internals/object-property-is-enumerable":54,"../internals/to-object":72}],45:[function(require,module,exports){ var anObject = require('../internals/an-object'); var defineProperties = require('../internals/object-define-properties'); var enumBugKeys = require('../internals/enum-bug-keys'); var hiddenKeys = require('../internals/hidden-keys'); var html = require('../internals/html'); var documentCreateElement = require('../internals/document-create-element'); var sharedKey = require('../internals/shared-key'); var GT = '>'; var LT = '<'; var PROTOTYPE = 'prototype'; var SCRIPT = 'script'; var IE_PROTO = sharedKey('IE_PROTO'); var EmptyConstructor = function () { /* empty */ }; var scriptTag = function (content) { return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; }; // Create object with fake `null` prototype: use ActiveX Object with cleared prototype var NullProtoObjectViaActiveX = function (activeXDocument) { activeXDocument.write(scriptTag('')); activeXDocument.close(); var temp = activeXDocument.parentWindow.Object; activeXDocument = null; // avoid memory leak return temp; }; // Create object with fake `null` prototype: use iframe Object with cleared prototype var NullProtoObjectViaIFrame = function () { // Thrash, waste and sodomy: IE GC bug var iframe = documentCreateElement('iframe'); var JS = 'java' + SCRIPT + ':'; var iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); // https://github.com/zloirock/core-js/issues/475 iframe.src = String(JS); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(scriptTag('document.F=Object')); iframeDocument.close(); return iframeDocument.F; }; // Check for document.domain and active x support // No need to use active x approach when document.domain is not set // see https://github.com/es-shims/es5-shim/issues/150 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 // avoid IE GC bug var activeXDocument; var NullProtoObject = function () { try { /* global ActiveXObject */ activeXDocument = document.domain && new ActiveXObject('htmlfile'); } catch (error) { /* ignore */ } NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame(); var length = enumBugKeys.length; while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; return NullProtoObject(); }; hiddenKeys[IE_PROTO] = true; // `Object.create` method // https://tc39.github.io/ecma262/#sec-object.create module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { EmptyConstructor[PROTOTYPE] = anObject(O); result = new EmptyConstructor(); EmptyConstructor[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = NullProtoObject(); return Properties === undefined ? result : defineProperties(result, Properties); }; },{"../internals/an-object":5,"../internals/document-create-element":19,"../internals/enum-bug-keys":20,"../internals/hidden-keys":29,"../internals/html":30,"../internals/object-define-properties":46,"../internals/shared-key":63}],46:[function(require,module,exports){ var DESCRIPTORS = require('../internals/descriptors'); var definePropertyModule = require('../internals/object-define-property'); var anObject = require('../internals/an-object'); var objectKeys = require('../internals/object-keys'); // `Object.defineProperties` method // https://tc39.github.io/ecma262/#sec-object.defineproperties module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = objectKeys(Properties); var length = keys.length; var index = 0; var key; while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]); return O; }; },{"../internals/an-object":5,"../internals/descriptors":18,"../internals/object-define-property":47,"../internals/object-keys":53}],47:[function(require,module,exports){ var DESCRIPTORS = require('../internals/descriptors'); var IE8_DOM_DEFINE = require('../internals/ie8-dom-define'); var anObject = require('../internals/an-object'); var toPrimitive = require('../internals/to-primitive'); var nativeDefineProperty = Object.defineProperty; // `Object.defineProperty` method // https://tc39.github.io/ecma262/#sec-object.defineproperty exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return nativeDefineProperty(O, P, Attributes); } catch (error) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; },{"../internals/an-object":5,"../internals/descriptors":18,"../internals/ie8-dom-define":31,"../internals/to-primitive":73}],48:[function(require,module,exports){ var DESCRIPTORS = require('../internals/descriptors'); var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable'); var createPropertyDescriptor = require('../internals/create-property-descriptor'); var toIndexedObject = require('../internals/to-indexed-object'); var toPrimitive = require('../internals/to-primitive'); var has = require('../internals/has'); var IE8_DOM_DEFINE = require('../internals/ie8-dom-define'); var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPrimitive(P, true); if (IE8_DOM_DEFINE) try { return nativeGetOwnPropertyDescriptor(O, P); } catch (error) { /* empty */ } if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]); }; },{"../internals/create-property-descriptor":15,"../internals/descriptors":18,"../internals/has":28,"../internals/ie8-dom-define":31,"../internals/object-property-is-enumerable":54,"../internals/to-indexed-object":69,"../internals/to-primitive":73}],49:[function(require,module,exports){ var internalObjectKeys = require('../internals/object-keys-internal'); var enumBugKeys = require('../internals/enum-bug-keys'); var hiddenKeys = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return internalObjectKeys(O, hiddenKeys); }; },{"../internals/enum-bug-keys":20,"../internals/object-keys-internal":52}],50:[function(require,module,exports){ exports.f = Object.getOwnPropertySymbols; },{}],51:[function(require,module,exports){ var has = require('../internals/has'); var toObject = require('../internals/to-object'); var sharedKey = require('../internals/shared-key'); var CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter'); var IE_PROTO = sharedKey('IE_PROTO'); var ObjectPrototype = Object.prototype; // `Object.getPrototypeOf` method // https://tc39.github.io/ecma262/#sec-object.getprototypeof module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) { O = toObject(O); if (has(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectPrototype : null; }; },{"../internals/correct-prototype-getter":12,"../internals/has":28,"../internals/shared-key":63,"../internals/to-object":72}],52:[function(require,module,exports){ var has = require('../internals/has'); var toIndexedObject = require('../internals/to-indexed-object'); var indexOf = require('../internals/array-includes').indexOf; var hiddenKeys = require('../internals/hidden-keys'); module.exports = function (object, names) { var O = toIndexedObject(object); var i = 0; var result = []; var key; for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~indexOf(result, key) || result.push(key); } return result; }; },{"../internals/array-includes":7,"../internals/has":28,"../internals/hidden-keys":29,"../internals/to-indexed-object":69}],53:[function(require,module,exports){ var internalObjectKeys = require('../internals/object-keys-internal'); var enumBugKeys = require('../internals/enum-bug-keys'); // `Object.keys` method // https://tc39.github.io/ecma262/#sec-object.keys module.exports = Object.keys || function keys(O) { return internalObjectKeys(O, enumBugKeys); }; },{"../internals/enum-bug-keys":20,"../internals/object-keys-internal":52}],54:[function(require,module,exports){ 'use strict'; var nativePropertyIsEnumerable = {}.propertyIsEnumerable; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1); // `Object.prototype.propertyIsEnumerable` method implementation // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) { var descriptor = getOwnPropertyDescriptor(this, V); return !!descriptor && descriptor.enumerable; } : nativePropertyIsEnumerable; },{}],55:[function(require,module,exports){ var anObject = require('../internals/an-object'); var aPossiblePrototype = require('../internals/a-possible-prototype'); // `Object.setPrototypeOf` method // https://tc39.github.io/ecma262/#sec-object.setprototypeof // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () { var CORRECT_SETTER = false; var test = {}; var setter; try { setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set; setter.call(test, []); CORRECT_SETTER = test instanceof Array; } catch (error) { /* empty */ } return function setPrototypeOf(O, proto) { anObject(O); aPossiblePrototype(proto); if (CORRECT_SETTER) setter.call(O, proto); else O.__proto__ = proto; return O; }; }() : undefined); },{"../internals/a-possible-prototype":2,"../internals/an-object":5}],56:[function(require,module,exports){ var getBuiltIn = require('../internals/get-built-in'); var getOwnPropertyNamesModule = require('../internals/object-get-own-property-names'); var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols'); var anObject = require('../internals/an-object'); // all object keys, includes non-enumerable and symbols module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { var keys = getOwnPropertyNamesModule.f(anObject(it)); var getOwnPropertySymbols = getOwnPropertySymbolsModule.f; return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; }; },{"../internals/an-object":5,"../internals/get-built-in":24,"../internals/object-get-own-property-names":49,"../internals/object-get-own-property-symbols":50}],57:[function(require,module,exports){ var global = require('../internals/global'); module.exports = global; },{"../internals/global":27}],58:[function(require,module,exports){ var redefine = require('../internals/redefine'); module.exports = function (target, src, options) { for (var key in src) redefine(target, key, src[key], options); return target; }; },{"../internals/redefine":59}],59:[function(require,module,exports){ var global = require('../internals/global'); var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); var has = require('../internals/has'); var setGlobal = require('../internals/set-global'); var inspectSource = require('../internals/inspect-source'); var InternalStateModule = require('../internals/internal-state'); var getInternalState = InternalStateModule.get; var enforceInternalState = InternalStateModule.enforce; var TEMPLATE = String(String).split('String'); (module.exports = function (O, key, value, options) { var unsafe = options ? !!options.unsafe : false; var simple = options ? !!options.enumerable : false; var noTargetGet = options ? !!options.noTargetGet : false; if (typeof value == 'function') { if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key); enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : ''); } if (O === global) { if (simple) O[key] = value; else setGlobal(key, value); return; } else if (!unsafe) { delete O[key]; } else if (!noTargetGet && O[key]) { simple = true; } if (simple) O[key] = value; else createNonEnumerableProperty(O, key, value); // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, 'toString', function toString() { return typeof this == 'function' && getInternalState(this).source || inspectSource(this); }); },{"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/has":28,"../internals/inspect-source":33,"../internals/internal-state":34,"../internals/set-global":61}],60:[function(require,module,exports){ // `RequireObjectCoercible` abstract operation // https://tc39.github.io/ecma262/#sec-requireobjectcoercible module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; },{}],61:[function(require,module,exports){ var global = require('../internals/global'); var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); module.exports = function (key, value) { try { createNonEnumerableProperty(global, key, value); } catch (error) { global[key] = value; } return value; }; },{"../internals/create-non-enumerable-property":14,"../internals/global":27}],62:[function(require,module,exports){ var defineProperty = require('../internals/object-define-property').f; var has = require('../internals/has'); var wellKnownSymbol = require('../internals/well-known-symbol'); var TO_STRING_TAG = wellKnownSymbol('toStringTag'); module.exports = function (it, TAG, STATIC) { if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) { defineProperty(it, TO_STRING_TAG, { configurable: true, value: TAG }); } }; },{"../internals/has":28,"../internals/object-define-property":47,"../internals/well-known-symbol":77}],63:[function(require,module,exports){ var shared = require('../internals/shared'); var uid = require('../internals/uid'); var keys = shared('keys'); module.exports = function (key) { return keys[key] || (keys[key] = uid(key)); }; },{"../internals/shared":65,"../internals/uid":75}],64:[function(require,module,exports){ var global = require('../internals/global'); var setGlobal = require('../internals/set-global'); var SHARED = '__core-js_shared__'; var store = global[SHARED] || setGlobal(SHARED, {}); module.exports = store; },{"../internals/global":27,"../internals/set-global":61}],65:[function(require,module,exports){ var IS_PURE = require('../internals/is-pure'); var store = require('../internals/shared-store'); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: '3.6.4', mode: IS_PURE ? 'pure' : 'global', copyright: '© 2020 Denis Pushkarev (zloirock.ru)' }); },{"../internals/is-pure":38,"../internals/shared-store":64}],66:[function(require,module,exports){ var toInteger = require('../internals/to-integer'); var requireObjectCoercible = require('../internals/require-object-coercible'); // `String.prototype.{ codePointAt, at }` methods implementation var createMethod = function (CONVERT_TO_STRING) { return function ($this, pos) { var S = String(requireObjectCoercible($this)); var position = toInteger(pos); var size = S.length; var first, second; if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined; first = S.charCodeAt(position); return first < 0xD800 || first > 0xDBFF || position + 1 === size || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF ? CONVERT_TO_STRING ? S.charAt(position) : first : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000; }; }; module.exports = { // `String.prototype.codePointAt` method // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat codeAt: createMethod(false), // `String.prototype.at` method // https://github.com/mathiasbynens/String.prototype.at charAt: createMethod(true) }; },{"../internals/require-object-coercible":60,"../internals/to-integer":70}],67:[function(require,module,exports){ 'use strict'; // based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 var base = 36; var tMin = 1; var tMax = 26; var skew = 38; var damp = 700; var initialBias = 72; var initialN = 128; // 0x80 var delimiter = '-'; // '\x2D' var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process'; var baseMinusTMin = base - tMin; var floor = Math.floor; var stringFromCharCode = String.fromCharCode; /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. */ var ucs2decode = function (string) { var output = []; var counter = 0; var length = string.length; while (counter < length) { var value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // It's a high surrogate, and there is a next character. var extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // It's an unmatched surrogate; only append this code unit, in case the // next code unit is the high surrogate of a surrogate pair. output.push(value); counter--; } } else { output.push(value); } } return output; }; /** * Converts a digit/integer into a basic code point. */ var digitToBasic = function (digit) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26); }; /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 */ var adapt = function (delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. */ // eslint-disable-next-line max-statements var encode = function (input) { var output = []; // Convert the input in UCS-2 to an array of Unicode code points. input = ucs2decode(input); // Cache the length. var inputLength = input.length; // Initialize the state. var n = initialN; var delta = 0; var bias = initialBias; var i, currentValue; // Handle the basic code points. for (i = 0; i < input.length; i++) { currentValue = input[i]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } var basicLength = output.length; // number of basic code points. var handledCPCount = basicLength; // number of code points that have been handled; // Finish the basic string with a delimiter unless it's empty. if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next larger one: var m = maxInt; for (i = 0; i < input.length; i++) { currentValue = input[i]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, but guard against overflow. var handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { throw RangeError(OVERFLOW_ERROR); } delta += (m - n) * handledCPCountPlusOne; n = m; for (i = 0; i < input.length; i++) { currentValue = input[i]; if (currentValue < n && ++delta > maxInt) { throw RangeError(OVERFLOW_ERROR); } if (currentValue == n) { // Represent delta as a generalized variable-length integer. var q = delta; for (var k = base; /* no condition */; k += base) { var t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) break; var qMinusT = q - t; var baseMinusT = base - t; output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT))); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); }; module.exports = function (input) { var encoded = []; var labels = input.toLowerCase().replace(regexSeparators, '\u002E').split('.'); var i, label; for (i = 0; i < labels.length; i++) { label = labels[i]; encoded.push(regexNonASCII.test(label) ? 'xn--' + encode(label) : label); } return encoded.join('.'); }; },{}],68:[function(require,module,exports){ var toInteger = require('../internals/to-integer'); var max = Math.max; var min = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). module.exports = function (index, length) { var integer = toInteger(index); return integer < 0 ? max(integer + length, 0) : min(integer, length); }; },{"../internals/to-integer":70}],69:[function(require,module,exports){ // toObject with fallback for non-array-like ES3 strings var IndexedObject = require('../internals/indexed-object'); var requireObjectCoercible = require('../internals/require-object-coercible'); module.exports = function (it) { return IndexedObject(requireObjectCoercible(it)); }; },{"../internals/indexed-object":32,"../internals/require-object-coercible":60}],70:[function(require,module,exports){ var ceil = Math.ceil; var floor = Math.floor; // `ToInteger` abstract operation // https://tc39.github.io/ecma262/#sec-tointeger module.exports = function (argument) { return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument); }; },{}],71:[function(require,module,exports){ var toInteger = require('../internals/to-integer'); var min = Math.min; // `ToLength` abstract operation // https://tc39.github.io/ecma262/#sec-tolength module.exports = function (argument) { return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 }; },{"../internals/to-integer":70}],72:[function(require,module,exports){ var requireObjectCoercible = require('../internals/require-object-coercible'); // `ToObject` abstract operation // https://tc39.github.io/ecma262/#sec-toobject module.exports = function (argument) { return Object(requireObjectCoercible(argument)); }; },{"../internals/require-object-coercible":60}],73:[function(require,module,exports){ var isObject = require('../internals/is-object'); // `ToPrimitive` abstract operation // https://tc39.github.io/ecma262/#sec-toprimitive // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function (input, PREFERRED_STRING) { if (!isObject(input)) return input; var fn, val; if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val; if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; throw TypeError("Can't convert object to primitive value"); }; },{"../internals/is-object":37}],74:[function(require,module,exports){ var wellKnownSymbol = require('../internals/well-known-symbol'); var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var test = {}; test[TO_STRING_TAG] = 'z'; module.exports = String(test) === '[object z]'; },{"../internals/well-known-symbol":77}],75:[function(require,module,exports){ var id = 0; var postfix = Math.random(); module.exports = function (key) { return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36); }; },{}],76:[function(require,module,exports){ var NATIVE_SYMBOL = require('../internals/native-symbol'); module.exports = NATIVE_SYMBOL // eslint-disable-next-line no-undef && !Symbol.sham // eslint-disable-next-line no-undef && typeof Symbol.iterator == 'symbol'; },{"../internals/native-symbol":41}],77:[function(require,module,exports){ var global = require('../internals/global'); var shared = require('../internals/shared'); var has = require('../internals/has'); var uid = require('../internals/uid'); var NATIVE_SYMBOL = require('../internals/native-symbol'); var USE_SYMBOL_AS_UID = require('../internals/use-symbol-as-uid'); var WellKnownSymbolsStore = shared('wks'); var Symbol = global.Symbol; var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol : Symbol && Symbol.withoutSetter || uid; module.exports = function (name) { if (!has(WellKnownSymbolsStore, name)) { if (NATIVE_SYMBOL && has(Symbol, name)) WellKnownSymbolsStore[name] = Symbol[name]; else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name); } return WellKnownSymbolsStore[name]; }; },{"../internals/global":27,"../internals/has":28,"../internals/native-symbol":41,"../internals/shared":65,"../internals/uid":75,"../internals/use-symbol-as-uid":76}],78:[function(require,module,exports){ 'use strict'; var toIndexedObject = require('../internals/to-indexed-object'); var addToUnscopables = require('../internals/add-to-unscopables'); var Iterators = require('../internals/iterators'); var InternalStateModule = require('../internals/internal-state'); var defineIterator = require('../internals/define-iterator'); var ARRAY_ITERATOR = 'Array Iterator'; var setInternalState = InternalStateModule.set; var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR); // `Array.prototype.entries` method // https://tc39.github.io/ecma262/#sec-array.prototype.entries // `Array.prototype.keys` method // https://tc39.github.io/ecma262/#sec-array.prototype.keys // `Array.prototype.values` method // https://tc39.github.io/ecma262/#sec-array.prototype.values // `Array.prototype[@@iterator]` method // https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator // `CreateArrayIterator` internal method // https://tc39.github.io/ecma262/#sec-createarrayiterator module.exports = defineIterator(Array, 'Array', function (iterated, kind) { setInternalState(this, { type: ARRAY_ITERATOR, target: toIndexedObject(iterated), // target index: 0, // next index kind: kind // kind }); // `%ArrayIteratorPrototype%.next` method // https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next }, function () { var state = getInternalState(this); var target = state.target; var kind = state.kind; var index = state.index++; if (!target || index >= target.length) { state.target = undefined; return { value: undefined, done: true }; } if (kind == 'keys') return { value: index, done: false }; if (kind == 'values') return { value: target[index], done: false }; return { value: [index, target[index]], done: false }; }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% // https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject // https://tc39.github.io/ecma262/#sec-createmappedargumentsobject Iterators.Arguments = Iterators.Array; // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); },{"../internals/add-to-unscopables":3,"../internals/define-iterator":17,"../internals/internal-state":34,"../internals/iterators":40,"../internals/to-indexed-object":69}],79:[function(require,module,exports){ 'use strict'; var charAt = require('../internals/string-multibyte').charAt; var InternalStateModule = require('../internals/internal-state'); var defineIterator = require('../internals/define-iterator'); var STRING_ITERATOR = 'String Iterator'; var setInternalState = InternalStateModule.set; var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); // `String.prototype[@@iterator]` method // https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator defineIterator(String, 'String', function (iterated) { setInternalState(this, { type: STRING_ITERATOR, string: String(iterated), index: 0 }); // `%StringIteratorPrototype%.next` method // https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next }, function next() { var state = getInternalState(this); var string = state.string; var index = state.index; var point; if (index >= string.length) return { value: undefined, done: true }; point = charAt(string, index); state.index += point.length; return { value: point, done: false }; }); },{"../internals/define-iterator":17,"../internals/internal-state":34,"../internals/string-multibyte":66}],80:[function(require,module,exports){ 'use strict'; // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` require('../modules/es.array.iterator'); var $ = require('../internals/export'); var getBuiltIn = require('../internals/get-built-in'); var USE_NATIVE_URL = require('../internals/native-url'); var redefine = require('../internals/redefine'); var redefineAll = require('../internals/redefine-all'); var setToStringTag = require('../internals/set-to-string-tag'); var createIteratorConstructor = require('../internals/create-iterator-constructor'); var InternalStateModule = require('../internals/internal-state'); var anInstance = require('../internals/an-instance'); var hasOwn = require('../internals/has'); var bind = require('../internals/function-bind-context'); var classof = require('../internals/classof'); var anObject = require('../internals/an-object'); var isObject = require('../internals/is-object'); var create = require('../internals/object-create'); var createPropertyDescriptor = require('../internals/create-property-descriptor'); var getIterator = require('../internals/get-iterator'); var getIteratorMethod = require('../internals/get-iterator-method'); var wellKnownSymbol = require('../internals/well-known-symbol'); var $fetch = getBuiltIn('fetch'); var Headers = getBuiltIn('Headers'); var ITERATOR = wellKnownSymbol('iterator'); var URL_SEARCH_PARAMS = 'URLSearchParams'; var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator'; var setInternalState = InternalStateModule.set; var getInternalParamsState = InternalStateModule.getterFor(URL_SEARCH_PARAMS); var getInternalIteratorState = InternalStateModule.getterFor(URL_SEARCH_PARAMS_ITERATOR); var plus = /\+/g; var sequences = Array(4); var percentSequence = function (bytes) { return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp('((?:%[\\da-f]{2}){' + bytes + '})', 'gi')); }; var percentDecode = function (sequence) { try { return decodeURIComponent(sequence); } catch (error) { return sequence; } }; var deserialize = function (it) { var result = it.replace(plus, ' '); var bytes = 4; try { return decodeURIComponent(result); } catch (error) { while (bytes) { result = result.replace(percentSequence(bytes--), percentDecode); } return result; } }; var find = /[!'()~]|%20/g; var replace = { '!': '%21', "'": '%27', '(': '%28', ')': '%29', '~': '%7E', '%20': '+' }; var replacer = function (match) { return replace[match]; }; var serialize = function (it) { return encodeURIComponent(it).replace(find, replacer); }; var parseSearchParams = function (result, query) { if (query) { var attributes = query.split('&'); var index = 0; var attribute, entry; while (index < attributes.length) { attribute = attributes[index++]; if (attribute.length) { entry = attribute.split('='); result.push({ key: deserialize(entry.shift()), value: deserialize(entry.join('=')) }); } } } }; var updateSearchParams = function (query) { this.entries.length = 0; parseSearchParams(this.entries, query); }; var validateArgumentsLength = function (passed, required) { if (passed < required) throw TypeError('Not enough arguments'); }; var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) { setInternalState(this, { type: URL_SEARCH_PARAMS_ITERATOR, iterator: getIterator(getInternalParamsState(params).entries), kind: kind }); }, 'Iterator', function next() { var state = getInternalIteratorState(this); var kind = state.kind; var step = state.iterator.next(); var entry = step.value; if (!step.done) { step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [entry.key, entry.value]; } return step; }); // `URLSearchParams` constructor // https://url.spec.whatwg.org/#interface-urlsearchparams var URLSearchParamsConstructor = function URLSearchParams(/* init */) { anInstance(this, URLSearchParamsConstructor, URL_SEARCH_PARAMS); var init = arguments.length > 0 ? arguments[0] : undefined; var that = this; var entries = []; var iteratorMethod, iterator, next, step, entryIterator, entryNext, first, second, key; setInternalState(that, { type: URL_SEARCH_PARAMS, entries: entries, updateURL: function () { /* empty */ }, updateSearchParams: updateSearchParams }); if (init !== undefined) { if (isObject(init)) { iteratorMethod = getIteratorMethod(init); if (typeof iteratorMethod === 'function') { iterator = iteratorMethod.call(init); next = iterator.next; while (!(step = next.call(iterator)).done) { entryIterator = getIterator(anObject(step.value)); entryNext = entryIterator.next; if ( (first = entryNext.call(entryIterator)).done || (second = entryNext.call(entryIterator)).done || !entryNext.call(entryIterator).done ) throw TypeError('Expected sequence with length 2'); entries.push({ key: first.value + '', value: second.value + '' }); } } else for (key in init) if (hasOwn(init, key)) entries.push({ key: key, value: init[key] + '' }); } else { parseSearchParams(entries, typeof init === 'string' ? init.charAt(0) === '?' ? init.slice(1) : init : init + ''); } } }; var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype; redefineAll(URLSearchParamsPrototype, { // `URLSearchParams.prototype.appent` method // https://url.spec.whatwg.org/#dom-urlsearchparams-append append: function append(name, value) { validateArgumentsLength(arguments.length, 2); var state = getInternalParamsState(this); state.entries.push({ key: name + '', value: value + '' }); state.updateURL(); }, // `URLSearchParams.prototype.delete` method // https://url.spec.whatwg.org/#dom-urlsearchparams-delete 'delete': function (name) { validateArgumentsLength(arguments.length, 1); var state = getInternalParamsState(this); var entries = state.entries; var key = name + ''; var index = 0; while (index < entries.length) { if (entries[index].key === key) entries.splice(index, 1); else index++; } state.updateURL(); }, // `URLSearchParams.prototype.get` method // https://url.spec.whatwg.org/#dom-urlsearchparams-get get: function get(name) { validateArgumentsLength(arguments.length, 1); var entries = getInternalParamsState(this).entries; var key = name + ''; var index = 0; for (; index < entries.length; index++) { if (entries[index].key === key) return entries[index].value; } return null; }, // `URLSearchParams.prototype.getAll` method // https://url.spec.whatwg.org/#dom-urlsearchparams-getall getAll: function getAll(name) { validateArgumentsLength(arguments.length, 1); var entries = getInternalParamsState(this).entries; var key = name + ''; var result = []; var index = 0; for (; index < entries.length; index++) { if (entries[index].key === key) result.push(entries[index].value); } return result; }, // `URLSearchParams.prototype.has` method // https://url.spec.whatwg.org/#dom-urlsearchparams-has has: function has(name) { validateArgumentsLength(arguments.length, 1); var entries = getInternalParamsState(this).entries; var key = name + ''; var index = 0; while (index < entries.length) { if (entries[index++].key === key) return true; } return false; }, // `URLSearchParams.prototype.set` method // https://url.spec.whatwg.org/#dom-urlsearchparams-set set: function set(name, value) { validateArgumentsLength(arguments.length, 1); var state = getInternalParamsState(this); var entries = state.entries; var found = false; var key = name + ''; var val = value + ''; var index = 0; var entry; for (; index < entries.length; index++) { entry = entries[index]; if (entry.key === key) { if (found) entries.splice(index--, 1); else { found = true; entry.value = val; } } } if (!found) entries.push({ key: key, value: val }); state.updateURL(); }, // `URLSearchParams.prototype.sort` method // https://url.spec.whatwg.org/#dom-urlsearchparams-sort sort: function sort() { var state = getInternalParamsState(this); var entries = state.entries; // Array#sort is not stable in some engines var slice = entries.slice(); var entry, entriesIndex, sliceIndex; entries.length = 0; for (sliceIndex = 0; sliceIndex < slice.length; sliceIndex++) { entry = slice[sliceIndex]; for (entriesIndex = 0; entriesIndex < sliceIndex; entriesIndex++) { if (entries[entriesIndex].key > entry.key) { entries.splice(entriesIndex, 0, entry); break; } } if (entriesIndex === sliceIndex) entries.push(entry); } state.updateURL(); }, // `URLSearchParams.prototype.forEach` method forEach: function forEach(callback /* , thisArg */) { var entries = getInternalParamsState(this).entries; var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined, 3); var index = 0; var entry; while (index < entries.length) { entry = entries[index++]; boundFunction(entry.value, entry.key, this); } }, // `URLSearchParams.prototype.keys` method keys: function keys() { return new URLSearchParamsIterator(this, 'keys'); }, // `URLSearchParams.prototype.values` method values: function values() { return new URLSearchParamsIterator(this, 'values'); }, // `URLSearchParams.prototype.entries` method entries: function entries() { return new URLSearchParamsIterator(this, 'entries'); } }, { enumerable: true }); // `URLSearchParams.prototype[@@iterator]` method redefine(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries); // `URLSearchParams.prototype.toString` method // https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior redefine(URLSearchParamsPrototype, 'toString', function toString() { var entries = getInternalParamsState(this).entries; var result = []; var index = 0; var entry; while (index < entries.length) { entry = entries[index++]; result.push(serialize(entry.key) + '=' + serialize(entry.value)); } return result.join('&'); }, { enumerable: true }); setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS); $({ global: true, forced: !USE_NATIVE_URL }, { URLSearchParams: URLSearchParamsConstructor }); // Wrap `fetch` for correct work with polyfilled `URLSearchParams` // https://github.com/zloirock/core-js/issues/674 if (!USE_NATIVE_URL && typeof $fetch == 'function' && typeof Headers == 'function') { $({ global: true, enumerable: true, forced: true }, { fetch: function fetch(input /* , init */) { var args = [input]; var init, body, headers; if (arguments.length > 1) { init = arguments[1]; if (isObject(init)) { body = init.body; if (classof(body) === URL_SEARCH_PARAMS) { headers = init.headers ? new Headers(init.headers) : new Headers(); if (!headers.has('content-type')) { headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); } init = create(init, { body: createPropertyDescriptor(0, String(body)), headers: createPropertyDescriptor(0, headers) }); } } args.push(init); } return $fetch.apply(this, args); } }); } module.exports = { URLSearchParams: URLSearchParamsConstructor, getState: getInternalParamsState }; },{"../internals/an-instance":4,"../internals/an-object":5,"../internals/classof":10,"../internals/create-iterator-constructor":13,"../internals/create-property-descriptor":15,"../internals/export":21,"../internals/function-bind-context":23,"../internals/get-built-in":24,"../internals/get-iterator":26,"../internals/get-iterator-method":25,"../internals/has":28,"../internals/internal-state":34,"../internals/is-object":37,"../internals/native-url":42,"../internals/object-create":45,"../internals/redefine":59,"../internals/redefine-all":58,"../internals/set-to-string-tag":62,"../internals/well-known-symbol":77,"../modules/es.array.iterator":78}],81:[function(require,module,exports){ 'use strict'; // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env` require('../modules/es.string.iterator'); var $ = require('../internals/export'); var DESCRIPTORS = require('../internals/descriptors'); var USE_NATIVE_URL = require('../internals/native-url'); var global = require('../internals/global'); var defineProperties = require('../internals/object-define-properties'); var redefine = require('../internals/redefine'); var anInstance = require('../internals/an-instance'); var has = require('../internals/has'); var assign = require('../internals/object-assign'); var arrayFrom = require('../internals/array-from'); var codeAt = require('../internals/string-multibyte').codeAt; var toASCII = require('../internals/string-punycode-to-ascii'); var setToStringTag = require('../internals/set-to-string-tag'); var URLSearchParamsModule = require('../modules/web.url-search-params'); var InternalStateModule = require('../internals/internal-state'); var NativeURL = global.URL; var URLSearchParams = URLSearchParamsModule.URLSearchParams; var getInternalSearchParamsState = URLSearchParamsModule.getState; var setInternalState = InternalStateModule.set; var getInternalURLState = InternalStateModule.getterFor('URL'); var floor = Math.floor; var pow = Math.pow; var INVALID_AUTHORITY = 'Invalid authority'; var INVALID_SCHEME = 'Invalid scheme'; var INVALID_HOST = 'Invalid host'; var INVALID_PORT = 'Invalid port'; var ALPHA = /[A-Za-z]/; var ALPHANUMERIC = /[\d+\-.A-Za-z]/; var DIGIT = /\d/; var HEX_START = /^(0x|0X)/; var OCT = /^[0-7]+$/; var DEC = /^\d+$/; var HEX = /^[\dA-Fa-f]+$/; // eslint-disable-next-line no-control-regex var FORBIDDEN_HOST_CODE_POINT = /[\u0000\u0009\u000A\u000D #%/:?@[\\]]/; // eslint-disable-next-line no-control-regex var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\u0000\u0009\u000A\u000D #/:?@[\\]]/; // eslint-disable-next-line no-control-regex var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g; // eslint-disable-next-line no-control-regex var TAB_AND_NEW_LINE = /[\u0009\u000A\u000D]/g; var EOF; var parseHost = function (url, input) { var result, codePoints, index; if (input.charAt(0) == '[') { if (input.charAt(input.length - 1) != ']') return INVALID_HOST; result = parseIPv6(input.slice(1, -1)); if (!result) return INVALID_HOST; url.host = result; // opaque host } else if (!isSpecial(url)) { if (FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT.test(input)) return INVALID_HOST; result = ''; codePoints = arrayFrom(input); for (index = 0; index < codePoints.length; index++) { result += percentEncode(codePoints[index], C0ControlPercentEncodeSet); } url.host = result; } else { input = toASCII(input); if (FORBIDDEN_HOST_CODE_POINT.test(input)) return INVALID_HOST; result = parseIPv4(input); if (result === null) return INVALID_HOST; url.host = result; } }; var parseIPv4 = function (input) { var parts = input.split('.'); var partsLength, numbers, index, part, radix, number, ipv4; if (parts.length && parts[parts.length - 1] == '') { parts.pop(); } partsLength = parts.length; if (partsLength > 4) return input; numbers = []; for (index = 0; index < partsLength; index++) { part = parts[index]; if (part == '') return input; radix = 10; if (part.length > 1 && part.charAt(0) == '0') { radix = HEX_START.test(part) ? 16 : 8; part = part.slice(radix == 8 ? 1 : 2); } if (part === '') { number = 0; } else { if (!(radix == 10 ? DEC : radix == 8 ? OCT : HEX).test(part)) return input; number = parseInt(part, radix); } numbers.push(number); } for (index = 0; index < partsLength; index++) { number = numbers[index]; if (index == partsLength - 1) { if (number >= pow(256, 5 - partsLength)) return null; } else if (number > 255) return null; } ipv4 = numbers.pop(); for (index = 0; index < numbers.length; index++) { ipv4 += numbers[index] * pow(256, 3 - index); } return ipv4; }; // eslint-disable-next-line max-statements var parseIPv6 = function (input) { var address = [0, 0, 0, 0, 0, 0, 0, 0]; var pieceIndex = 0; var compress = null; var pointer = 0; var value, length, numbersSeen, ipv4Piece, number, swaps, swap; var char = function () { return input.charAt(pointer); }; if (char() == ':') { if (input.charAt(1) != ':') return; pointer += 2; pieceIndex++; compress = pieceIndex; } while (char()) { if (pieceIndex == 8) return; if (char() == ':') { if (compress !== null) return; pointer++; pieceIndex++; compress = pieceIndex; continue; } value = length = 0; while (length < 4 && HEX.test(char())) { value = value * 16 + parseInt(char(), 16); pointer++; length++; } if (char() == '.') { if (length == 0) return; pointer -= length; if (pieceIndex > 6) return; numbersSeen = 0; while (char()) { ipv4Piece = null; if (numbersSeen > 0) { if (char() == '.' && numbersSeen < 4) pointer++; else return; } if (!DIGIT.test(char())) return; while (DIGIT.test(char())) { number = parseInt(char(), 10); if (ipv4Piece === null) ipv4Piece = number; else if (ipv4Piece == 0) return; else ipv4Piece = ipv4Piece * 10 + number; if (ipv4Piece > 255) return; pointer++; } address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece; numbersSeen++; if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++; } if (numbersSeen != 4) return; break; } else if (char() == ':') { pointer++; if (!char()) return; } else if (char()) return; address[pieceIndex++] = value; } if (compress !== null) { swaps = pieceIndex - compress; pieceIndex = 7; while (pieceIndex != 0 && swaps > 0) { swap = address[pieceIndex]; address[pieceIndex--] = address[compress + swaps - 1]; address[compress + --swaps] = swap; } } else if (pieceIndex != 8) return; return address; }; var findLongestZeroSequence = function (ipv6) { var maxIndex = null; var maxLength = 1; var currStart = null; var currLength = 0; var index = 0; for (; index < 8; index++) { if (ipv6[index] !== 0) { if (currLength > maxLength) { maxIndex = currStart; maxLength = currLength; } currStart = null; currLength = 0; } else { if (currStart === null) currStart = index; ++currLength; } } if (currLength > maxLength) { maxIndex = currStart; maxLength = currLength; } return maxIndex; }; var serializeHost = function (host) { var result, index, compress, ignore0; // ipv4 if (typeof host == 'number') { result = []; for (index = 0; index < 4; index++) { result.unshift(host % 256); host = floor(host / 256); } return result.join('.'); // ipv6 } else if (typeof host == 'object') { result = ''; compress = findLongestZeroSequence(host); for (index = 0; index < 8; index++) { if (ignore0 && host[index] === 0) continue; if (ignore0) ignore0 = false; if (compress === index) { result += index ? ':' : '::'; ignore0 = true; } else { result += host[index].toString(16); if (index < 7) result += ':'; } } return '[' + result + ']'; } return host; }; var C0ControlPercentEncodeSet = {}; var fragmentPercentEncodeSet = assign({}, C0ControlPercentEncodeSet, { ' ': 1, '"': 1, '<': 1, '>': 1, '`': 1 }); var pathPercentEncodeSet = assign({}, fragmentPercentEncodeSet, { '#': 1, '?': 1, '{': 1, '}': 1 }); var userinfoPercentEncodeSet = assign({}, pathPercentEncodeSet, { '/': 1, ':': 1, ';': 1, '=': 1, '@': 1, '[': 1, '\\': 1, ']': 1, '^': 1, '|': 1 }); var percentEncode = function (char, set) { var code = codeAt(char, 0); return code > 0x20 && code < 0x7F && !has(set, char) ? char : encodeURIComponent(char); }; var specialSchemes = { ftp: 21, file: null, http: 80, https: 443, ws: 80, wss: 443 }; var isSpecial = function (url) { return has(specialSchemes, url.scheme); }; var includesCredentials = function (url) { return url.username != '' || url.password != ''; }; var cannotHaveUsernamePasswordPort = function (url) { return !url.host || url.cannotBeABaseURL || url.scheme == 'file'; }; var isWindowsDriveLetter = function (string, normalized) { var second; return string.length == 2 && ALPHA.test(string.charAt(0)) && ((second = string.charAt(1)) == ':' || (!normalized && second == '|')); }; var startsWithWindowsDriveLetter = function (string) { var third; return string.length > 1 && isWindowsDriveLetter(string.slice(0, 2)) && ( string.length == 2 || ((third = string.charAt(2)) === '/' || third === '\\' || third === '?' || third === '#') ); }; var shortenURLsPath = function (url) { var path = url.path; var pathSize = path.length; if (pathSize && (url.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) { path.pop(); } }; var isSingleDot = function (segment) { return segment === '.' || segment.toLowerCase() === '%2e'; }; var isDoubleDot = function (segment) { segment = segment.toLowerCase(); return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e'; }; // States: var SCHEME_START = {}; var SCHEME = {}; var NO_SCHEME = {}; var SPECIAL_RELATIVE_OR_AUTHORITY = {}; var PATH_OR_AUTHORITY = {}; var RELATIVE = {}; var RELATIVE_SLASH = {}; var SPECIAL_AUTHORITY_SLASHES = {}; var SPECIAL_AUTHORITY_IGNORE_SLASHES = {}; var AUTHORITY = {}; var HOST = {}; var HOSTNAME = {}; var PORT = {}; var FILE = {}; var FILE_SLASH = {}; var FILE_HOST = {}; var PATH_START = {}; var PATH = {}; var CANNOT_BE_A_BASE_URL_PATH = {}; var QUERY = {}; var FRAGMENT = {}; // eslint-disable-next-line max-statements var parseURL = function (url, input, stateOverride, base) { var state = stateOverride || SCHEME_START; var pointer = 0; var buffer = ''; var seenAt = false; var seenBracket = false; var seenPasswordToken = false; var codePoints, char, bufferCodePoints, failure; if (!stateOverride) { url.scheme = ''; url.username = ''; url.password = ''; url.host = null; url.port = null; url.path = []; url.query = null; url.fragment = null; url.cannotBeABaseURL = false; input = input.replace(LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE, ''); } input = input.replace(TAB_AND_NEW_LINE, ''); codePoints = arrayFrom(input); while (pointer <= codePoints.length) { char = codePoints[pointer]; switch (state) { case SCHEME_START: if (char && ALPHA.test(char)) { buffer += char.toLowerCase(); state = SCHEME; } else if (!stateOverride) { state = NO_SCHEME; continue; } else return INVALID_SCHEME; break; case SCHEME: if (char && (ALPHANUMERIC.test(char) || char == '+' || char == '-' || char == '.')) { buffer += char.toLowerCase(); } else if (char == ':') { if (stateOverride && ( (isSpecial(url) != has(specialSchemes, buffer)) || (buffer == 'file' && (includesCredentials(url) || url.port !== null)) || (url.scheme == 'file' && !url.host) )) return; url.scheme = buffer; if (stateOverride) { if (isSpecial(url) && specialSchemes[url.scheme] == url.port) url.port = null; return; } buffer = ''; if (url.scheme == 'file') { state = FILE; } else if (isSpecial(url) && base && base.scheme == url.scheme) { state = SPECIAL_RELATIVE_OR_AUTHORITY; } else if (isSpecial(url)) { state = SPECIAL_AUTHORITY_SLASHES; } else if (codePoints[pointer + 1] == '/') { state = PATH_OR_AUTHORITY; pointer++; } else { url.cannotBeABaseURL = true; url.path.push(''); state = CANNOT_BE_A_BASE_URL_PATH; } } else if (!stateOverride) { buffer = ''; state = NO_SCHEME; pointer = 0; continue; } else return INVALID_SCHEME; break; case NO_SCHEME: if (!base || (base.cannotBeABaseURL && char != '#')) return INVALID_SCHEME; if (base.cannotBeABaseURL && char == '#') { url.scheme = base.scheme; url.path = base.path.slice(); url.query = base.query; url.fragment = ''; url.cannotBeABaseURL = true; state = FRAGMENT; break; } state = base.scheme == 'file' ? FILE : RELATIVE; continue; case SPECIAL_RELATIVE_OR_AUTHORITY: if (char == '/' && codePoints[pointer + 1] == '/') { state = SPECIAL_AUTHORITY_IGNORE_SLASHES; pointer++; } else { state = RELATIVE; continue; } break; case PATH_OR_AUTHORITY: if (char == '/') { state = AUTHORITY; break; } else { state = PATH; continue; } case RELATIVE: url.scheme = base.scheme; if (char == EOF) { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.query = base.query; } else if (char == '/' || (char == '\\' && isSpecial(url))) { state = RELATIVE_SLASH; } else if (char == '?') { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.query = ''; state = QUERY; } else if (char == '#') { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.query = base.query; url.fragment = ''; state = FRAGMENT; } else { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; url.path = base.path.slice(); url.path.pop(); state = PATH; continue; } break; case RELATIVE_SLASH: if (isSpecial(url) && (char == '/' || char == '\\')) { state = SPECIAL_AUTHORITY_IGNORE_SLASHES; } else if (char == '/') { state = AUTHORITY; } else { url.username = base.username; url.password = base.password; url.host = base.host; url.port = base.port; state = PATH; continue; } break; case SPECIAL_AUTHORITY_SLASHES: state = SPECIAL_AUTHORITY_IGNORE_SLASHES; if (char != '/' || buffer.charAt(pointer + 1) != '/') continue; pointer++; break; case SPECIAL_AUTHORITY_IGNORE_SLASHES: if (char != '/' && char != '\\') { state = AUTHORITY; continue; } break; case AUTHORITY: if (char == '@') { if (seenAt) buffer = '%40' + buffer; seenAt = true; bufferCodePoints = arrayFrom(buffer); for (var i = 0; i < bufferCodePoints.length; i++) { var codePoint = bufferCodePoints[i]; if (codePoint == ':' && !seenPasswordToken) { seenPasswordToken = true; continue; } var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet); if (seenPasswordToken) url.password += encodedCodePoints; else url.username += encodedCodePoints; } buffer = ''; } else if ( char == EOF || char == '/' || char == '?' || char == '#' || (char == '\\' && isSpecial(url)) ) { if (seenAt && buffer == '') return INVALID_AUTHORITY; pointer -= arrayFrom(buffer).length + 1; buffer = ''; state = HOST; } else buffer += char; break; case HOST: case HOSTNAME: if (stateOverride && url.scheme == 'file') { state = FILE_HOST; continue; } else if (char == ':' && !seenBracket) { if (buffer == '') return INVALID_HOST; failure = parseHost(url, buffer); if (failure) return failure; buffer = ''; state = PORT; if (stateOverride == HOSTNAME) return; } else if ( char == EOF || char == '/' || char == '?' || char == '#' || (char == '\\' && isSpecial(url)) ) { if (isSpecial(url) && buffer == '') return INVALID_HOST; if (stateOverride && buffer == '' && (includesCredentials(url) || url.port !== null)) return; failure = parseHost(url, buffer); if (failure) return failure; buffer = ''; state = PATH_START; if (stateOverride) return; continue; } else { if (char == '[') seenBracket = true; else if (char == ']') seenBracket = false; buffer += char; } break; case PORT: if (DIGIT.test(char)) { buffer += char; } else if ( char == EOF || char == '/' || char == '?' || char == '#' || (char == '\\' && isSpecial(url)) || stateOverride ) { if (buffer != '') { var port = parseInt(buffer, 10); if (port > 0xFFFF) return INVALID_PORT; url.port = (isSpecial(url) && port === specialSchemes[url.scheme]) ? null : port; buffer = ''; } if (stateOverride) return; state = PATH_START; continue; } else return INVALID_PORT; break; case FILE: url.scheme = 'file'; if (char == '/' || char == '\\') state = FILE_SLASH; else if (base && base.scheme == 'file') { if (char == EOF) { url.host = base.host; url.path = base.path.slice(); url.query = base.query; } else if (char == '?') { url.host = base.host; url.path = base.path.slice(); url.query = ''; state = QUERY; } else if (char == '#') { url.host = base.host; url.path = base.path.slice(); url.query = base.query; url.fragment = ''; state = FRAGMENT; } else { if (!startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) { url.host = base.host; url.path = base.path.slice(); shortenURLsPath(url); } state = PATH; continue; } } else { state = PATH; continue; } break; case FILE_SLASH: if (char == '/' || char == '\\') { state = FILE_HOST; break; } if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) { if (isWindowsDriveLetter(base.path[0], true)) url.path.push(base.path[0]); else url.host = base.host; } state = PATH; continue; case FILE_HOST: if (char == EOF || char == '/' || char == '\\' || char == '?' || char == '#') { if (!stateOverride && isWindowsDriveLetter(buffer)) { state = PATH; } else if (buffer == '') { url.host = ''; if (stateOverride) return; state = PATH_START; } else { failure = parseHost(url, buffer); if (failure) return failure; if (url.host == 'localhost') url.host = ''; if (stateOverride) return; buffer = ''; state = PATH_START; } continue; } else buffer += char; break; case PATH_START: if (isSpecial(url)) { state = PATH; if (char != '/' && char != '\\') continue; } else if (!stateOverride && char == '?') { url.query = ''; state = QUERY; } else if (!stateOverride && char == '#') { url.fragment = ''; state = FRAGMENT; } else if (char != EOF) { state = PATH; if (char != '/') continue; } break; case PATH: if ( char == EOF || char == '/' || (char == '\\' && isSpecial(url)) || (!stateOverride && (char == '?' || char == '#')) ) { if (isDoubleDot(buffer)) { shortenURLsPath(url); if (char != '/' && !(char == '\\' && isSpecial(url))) { url.path.push(''); } } else if (isSingleDot(buffer)) { if (char != '/' && !(char == '\\' && isSpecial(url))) { url.path.push(''); } } else { if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) { if (url.host) url.host = ''; buffer = buffer.charAt(0) + ':'; // normalize windows drive letter } url.path.push(buffer); } buffer = ''; if (url.scheme == 'file' && (char == EOF || char == '?' || char == '#')) { while (url.path.length > 1 && url.path[0] === '') { url.path.shift(); } } if (char == '?') { url.query = ''; state = QUERY; } else if (char == '#') { url.fragment = ''; state = FRAGMENT; } } else { buffer += percentEncode(char, pathPercentEncodeSet); } break; case CANNOT_BE_A_BASE_URL_PATH: if (char == '?') { url.query = ''; state = QUERY; } else if (char == '#') { url.fragment = ''; state = FRAGMENT; } else if (char != EOF) { url.path[0] += percentEncode(char, C0ControlPercentEncodeSet); } break; case QUERY: if (!stateOverride && char == '#') { url.fragment = ''; state = FRAGMENT; } else if (char != EOF) { if (char == "'" && isSpecial(url)) url.query += '%27'; else if (char == '#') url.query += '%23'; else url.query += percentEncode(char, C0ControlPercentEncodeSet); } break; case FRAGMENT: if (char != EOF) url.fragment += percentEncode(char, fragmentPercentEncodeSet); break; } pointer++; } }; // `URL` constructor // https://url.spec.whatwg.org/#url-class var URLConstructor = function URL(url /* , base */) { var that = anInstance(this, URLConstructor, 'URL'); var base = arguments.length > 1 ? arguments[1] : undefined; var urlString = String(url); var state = setInternalState(that, { type: 'URL' }); var baseState, failure; if (base !== undefined) { if (base instanceof URLConstructor) baseState = getInternalURLState(base); else { failure = parseURL(baseState = {}, String(base)); if (failure) throw TypeError(failure); } } failure = parseURL(state, urlString, null, baseState); if (failure) throw TypeError(failure); var searchParams = state.searchParams = new URLSearchParams(); var searchParamsState = getInternalSearchParamsState(searchParams); searchParamsState.updateSearchParams(state.query); searchParamsState.updateURL = function () { state.query = String(searchParams) || null; }; if (!DESCRIPTORS) { that.href = serializeURL.call(that); that.origin = getOrigin.call(that); that.protocol = getProtocol.call(that); that.username = getUsername.call(that); that.password = getPassword.call(that); that.host = getHost.call(that); that.hostname = getHostname.call(that); that.port = getPort.call(that); that.pathname = getPathname.call(that); that.search = getSearch.call(that); that.searchParams = getSearchParams.call(that); that.hash = getHash.call(that); } }; var URLPrototype = URLConstructor.prototype; var serializeURL = function () { var url = getInternalURLState(this); var scheme = url.scheme; var username = url.username; var password = url.password; var host = url.host; var port = url.port; var path = url.path; var query = url.query; var fragment = url.fragment; var output = scheme + ':'; if (host !== null) { output += '//'; if (includesCredentials(url)) { output += username + (password ? ':' + password : '') + '@'; } output += serializeHost(host); if (port !== null) output += ':' + port; } else if (scheme == 'file') output += '//'; output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : ''; if (query !== null) output += '?' + query; if (fragment !== null) output += '#' + fragment; return output; }; var getOrigin = function () { var url = getInternalURLState(this); var scheme = url.scheme; var port = url.port; if (scheme == 'blob') try { return new URL(scheme.path[0]).origin; } catch (error) { return 'null'; } if (scheme == 'file' || !isSpecial(url)) return 'null'; return scheme + '://' + serializeHost(url.host) + (port !== null ? ':' + port : ''); }; var getProtocol = function () { return getInternalURLState(this).scheme + ':'; }; var getUsername = function () { return getInternalURLState(this).username; }; var getPassword = function () { return getInternalURLState(this).password; }; var getHost = function () { var url = getInternalURLState(this); var host = url.host; var port = url.port; return host === null ? '' : port === null ? serializeHost(host) : serializeHost(host) + ':' + port; }; var getHostname = function () { var host = getInternalURLState(this).host; return host === null ? '' : serializeHost(host); }; var getPort = function () { var port = getInternalURLState(this).port; return port === null ? '' : String(port); }; var getPathname = function () { var url = getInternalURLState(this); var path = url.path; return url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : ''; }; var getSearch = function () { var query = getInternalURLState(this).query; return query ? '?' + query : ''; }; var getSearchParams = function () { return getInternalURLState(this).searchParams; }; var getHash = function () { var fragment = getInternalURLState(this).fragment; return fragment ? '#' + fragment : ''; }; var accessorDescriptor = function (getter, setter) { return { get: getter, set: setter, configurable: true, enumerable: true }; }; if (DESCRIPTORS) { defineProperties(URLPrototype, { // `URL.prototype.href` accessors pair // https://url.spec.whatwg.org/#dom-url-href href: accessorDescriptor(serializeURL, function (href) { var url = getInternalURLState(this); var urlString = String(href); var failure = parseURL(url, urlString); if (failure) throw TypeError(failure); getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query); }), // `URL.prototype.origin` getter // https://url.spec.whatwg.org/#dom-url-origin origin: accessorDescriptor(getOrigin), // `URL.prototype.protocol` accessors pair // https://url.spec.whatwg.org/#dom-url-protocol protocol: accessorDescriptor(getProtocol, function (protocol) { var url = getInternalURLState(this); parseURL(url, String(protocol) + ':', SCHEME_START); }), // `URL.prototype.username` accessors pair // https://url.spec.whatwg.org/#dom-url-username username: accessorDescriptor(getUsername, function (username) { var url = getInternalURLState(this); var codePoints = arrayFrom(String(username)); if (cannotHaveUsernamePasswordPort(url)) return; url.username = ''; for (var i = 0; i < codePoints.length; i++) { url.username += percentEncode(codePoints[i], userinfoPercentEncodeSet); } }), // `URL.prototype.password` accessors pair // https://url.spec.whatwg.org/#dom-url-password password: accessorDescriptor(getPassword, function (password) { var url = getInternalURLState(this); var codePoints = arrayFrom(String(password)); if (cannotHaveUsernamePasswordPort(url)) return; url.password = ''; for (var i = 0; i < codePoints.length; i++) { url.password += percentEncode(codePoints[i], userinfoPercentEncodeSet); } }), // `URL.prototype.host` accessors pair // https://url.spec.whatwg.org/#dom-url-host host: accessorDescriptor(getHost, function (host) { var url = getInternalURLState(this); if (url.cannotBeABaseURL) return; parseURL(url, String(host), HOST); }), // `URL.prototype.hostname` accessors pair // https://url.spec.whatwg.org/#dom-url-hostname hostname: accessorDescriptor(getHostname, function (hostname) { var url = getInternalURLState(this); if (url.cannotBeABaseURL) return; parseURL(url, String(hostname), HOSTNAME); }), // `URL.prototype.port` accessors pair // https://url.spec.whatwg.org/#dom-url-port port: accessorDescriptor(getPort, function (port) { var url = getInternalURLState(this); if (cannotHaveUsernamePasswordPort(url)) return; port = String(port); if (port == '') url.port = null; else parseURL(url, port, PORT); }), // `URL.prototype.pathname` accessors pair // https://url.spec.whatwg.org/#dom-url-pathname pathname: accessorDescriptor(getPathname, function (pathname) { var url = getInternalURLState(this); if (url.cannotBeABaseURL) return; url.path = []; parseURL(url, pathname + '', PATH_START); }), // `URL.prototype.search` accessors pair // https://url.spec.whatwg.org/#dom-url-search search: accessorDescriptor(getSearch, function (search) { var url = getInternalURLState(this); search = String(search); if (search == '') { url.query = null; } else { if ('?' == search.charAt(0)) search = search.slice(1); url.query = ''; parseURL(url, search, QUERY); } getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query); }), // `URL.prototype.searchParams` getter // https://url.spec.whatwg.org/#dom-url-searchparams searchParams: accessorDescriptor(getSearchParams), // `URL.prototype.hash` accessors pair // https://url.spec.whatwg.org/#dom-url-hash hash: accessorDescriptor(getHash, function (hash) { var url = getInternalURLState(this); hash = String(hash); if (hash == '') { url.fragment = null; return; } if ('#' == hash.charAt(0)) hash = hash.slice(1); url.fragment = ''; parseURL(url, hash, FRAGMENT); }) }); } // `URL.prototype.toJSON` method // https://url.spec.whatwg.org/#dom-url-tojson redefine(URLPrototype, 'toJSON', function toJSON() { return serializeURL.call(this); }, { enumerable: true }); // `URL.prototype.toString` method // https://url.spec.whatwg.org/#URL-stringification-behavior redefine(URLPrototype, 'toString', function toString() { return serializeURL.call(this); }, { enumerable: true }); if (NativeURL) { var nativeCreateObjectURL = NativeURL.createObjectURL; var nativeRevokeObjectURL = NativeURL.revokeObjectURL; // `URL.createObjectURL` method // https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL // eslint-disable-next-line no-unused-vars if (nativeCreateObjectURL) redefine(URLConstructor, 'createObjectURL', function createObjectURL(blob) { return nativeCreateObjectURL.apply(NativeURL, arguments); }); // `URL.revokeObjectURL` method // https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL // eslint-disable-next-line no-unused-vars if (nativeRevokeObjectURL) redefine(URLConstructor, 'revokeObjectURL', function revokeObjectURL(url) { return nativeRevokeObjectURL.apply(NativeURL, arguments); }); } setToStringTag(URLConstructor, 'URL'); $({ global: true, forced: !USE_NATIVE_URL, sham: !DESCRIPTORS }, { URL: URLConstructor }); },{"../internals/an-instance":4,"../internals/array-from":6,"../internals/descriptors":18,"../internals/export":21,"../internals/global":27,"../internals/has":28,"../internals/internal-state":34,"../internals/native-url":42,"../internals/object-assign":44,"../internals/object-define-properties":46,"../internals/redefine":59,"../internals/set-to-string-tag":62,"../internals/string-multibyte":66,"../internals/string-punycode-to-ascii":67,"../modules/es.string.iterator":79,"../modules/web.url-search-params":80}],82:[function(require,module,exports){ 'use strict'; var $ = require('../internals/export'); // `URL.prototype.toJSON` method // https://url.spec.whatwg.org/#dom-url-tojson $({ target: 'URL', proto: true, enumerable: true }, { toJSON: function toJSON() { return URL.prototype.toString.call(this); } }); },{"../internals/export":21}],83:[function(require,module,exports){ require('../modules/web.url'); require('../modules/web.url.to-json'); require('../modules/web.url-search-params'); var path = require('../internals/path'); module.exports = path.URL; },{"../internals/path":57,"../modules/web.url":81,"../modules/web.url-search-params":80,"../modules/web.url.to-json":82}]},{},[83]); regenerator-runtime.min.js 0000604 00000014737 14720015030 0011662 0 ustar 00 var runtime=function(t){"use strict";var e,r=Object.prototype,n=r.hasOwnProperty,o=Object.defineProperty||function(t,e,r){t[e]=r.value},i=(w="function"==typeof Symbol?Symbol:{}).iterator||"@@iterator",a=w.asyncIterator||"@@asyncIterator",c=w.toStringTag||"@@toStringTag";function u(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{u({},"")}catch(r){u=function(t,e,r){return t[e]=r}}function h(t,r,n,i){var a,c,u,h;r=r&&r.prototype instanceof v?r:v,r=Object.create(r.prototype),i=new O(i||[]);return o(r,"_invoke",{value:(a=t,c=n,u=i,h=f,function(t,r){if(h===p)throw new Error("Generator is already running");if(h===y){if("throw"===t)throw r;return{value:e,done:!0}}for(u.method=t,u.arg=r;;){var n=u.delegate;if(n&&(n=function t(r,n){var o=n.method,i=r.iterator[o];return i===e?(n.delegate=null,"throw"===o&&r.iterator.return&&(n.method="return",n.arg=e,t(r,n),"throw"===n.method)||"return"!==o&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+o+"' method")),g):"throw"===(o=l(i,r.iterator,n.arg)).type?(n.method="throw",n.arg=o.arg,n.delegate=null,g):(i=o.arg)?i.done?(n[r.resultName]=i.value,n.next=r.nextLoc,"return"!==n.method&&(n.method="next",n.arg=e),n.delegate=null,g):i:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}(n,u),n)){if(n===g)continue;return n}if("next"===u.method)u.sent=u._sent=u.arg;else if("throw"===u.method){if(h===f)throw h=y,u.arg;u.dispatchException(u.arg)}else"return"===u.method&&u.abrupt("return",u.arg);if(h=p,"normal"===(n=l(a,c,u)).type){if(h=u.done?y:s,n.arg!==g)return{value:n.arg,done:u.done}}else"throw"===n.type&&(h=y,u.method="throw",u.arg=n.arg)}})}),r}function l(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var f="suspendedStart",s="suspendedYield",p="executing",y="completed",g={};function v(){}function d(){}function m(){}var w,b,L=((b=(b=(u(w={},i,(function(){return this})),Object.getPrototypeOf))&&b(b(k([]))))&&b!==r&&n.call(b,i)&&(w=b),m.prototype=v.prototype=Object.create(w));function x(t){["next","throw","return"].forEach((function(e){u(t,e,(function(t){return this._invoke(e,t)}))}))}function E(t,e){var r;o(this,"_invoke",{value:function(o,i){function a(){return new e((function(r,a){!function r(o,i,a,c){var u;if("throw"!==(o=l(t[o],t,i)).type)return(i=(u=o.arg).value)&&"object"==typeof i&&n.call(i,"__await")?e.resolve(i.__await).then((function(t){r("next",t,a,c)}),(function(t){r("throw",t,a,c)})):e.resolve(i).then((function(t){u.value=t,a(u)}),(function(t){return r("throw",t,a,c)}));c(o.arg)}(o,i,r,a)}))}return r=r?r.then(a,a):a()}})}function j(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function _(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(j,this),this.reset(!0)}function k(t){if(null!=t){var r,o=t[i];if(o)return o.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length))return r=-1,(o=function o(){for(;++r<t.length;)if(n.call(t,r))return o.value=t[r],o.done=!1,o;return o.value=e,o.done=!0,o}).next=o}throw new TypeError(typeof t+" is not iterable")}return o(L,"constructor",{value:d.prototype=m,configurable:!0}),o(m,"constructor",{value:d,configurable:!0}),d.displayName=u(m,c,"GeneratorFunction"),t.isGeneratorFunction=function(t){return!!(t="function"==typeof t&&t.constructor)&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,m):(t.__proto__=m,u(t,c,"GeneratorFunction")),t.prototype=Object.create(L),t},t.awrap=function(t){return{__await:t}},x(E.prototype),u(E.prototype,a,(function(){return this})),t.AsyncIterator=E,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var a=new E(h(e,r,n,o),i);return t.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},x(L),u(L,c,"Generator"),u(L,i,(function(){return this})),u(L,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e,r=Object(t),n=[];for(e in r)n.push(e);return n.reverse(),function t(){for(;n.length;){var e=n.pop();if(e in r)return t.value=e,t.done=!1,t}return t.done=!0,t}},t.values=k,O.prototype={constructor:O,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(_),!t)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=e)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var r=this;function o(n,o){return c.type="throw",c.arg=t,r.next=n,o&&(r.method="next",r.arg=e),!!o}for(var i=this.tryEntries.length-1;0<=i;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),h=n.call(a,"finallyLoc");if(u&&h){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!h)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;0<=r;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}var a=(i=i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc?null:i)?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),g},finish:function(t){for(var e=this.tryEntries.length-1;0<=e;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),_(r),g}},catch:function(t){for(var e=this.tryEntries.length-1;0<=e;--e){var r,n,o=this.tryEntries[e];if(o.tryLoc===t)return"throw"===(r=o.completion).type&&(n=r.arg,_(o)),n}throw new Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:k(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),g}},t}("object"==typeof module?module.exports:{});try{regeneratorRuntime=runtime}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=runtime:Function("r","regeneratorRuntime = r")(runtime)} react-jsx-runtime.min.js 0000644 00000001604 14720015030 0011236 0 ustar 00 /*! For license information please see react-jsx-runtime.min.js.LICENSE.txt */ (()=>{"use strict";var r={20:(r,e,t)=>{var o=t(594),n=Symbol.for("react.element"),s=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,f=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};function _(r,e,t){var o,s={},_=null,i=null;for(o in void 0!==t&&(_=""+t),void 0!==e.key&&(_=""+e.key),void 0!==e.ref&&(i=e.ref),e)a.call(e,o)&&!p.hasOwnProperty(o)&&(s[o]=e[o]);if(r&&r.defaultProps)for(o in e=r.defaultProps)void 0===s[o]&&(s[o]=e[o]);return{$$typeof:n,type:r,key:_,ref:i,props:s,_owner:f.current}}e.Fragment=s,e.jsx=_,e.jsxs=_},848:(r,e,t)=>{r.exports=t(20)},594:r=>{r.exports=React}},e={},t=function t(o){var n=e[o];if(void 0!==n)return n.exports;var s=e[o]={exports:{}};return r[o](s,s.exports,t),s.exports}(848);window.ReactJSXRuntime=t})(); wp-polyfill-dom-rect.js 0000644 00000003607 14720015030 0011066 0 ustar 00 // DOMRect (function (global) { function number(v) { return v === undefined ? 0 : Number(v); } function different(u, v) { return u !== v && !(isNaN(u) && isNaN(v)); } function DOMRect(xArg, yArg, wArg, hArg) { var x, y, width, height, left, right, top, bottom; x = number(xArg); y = number(yArg); width = number(wArg); height = number(hArg); Object.defineProperties(this, { x: { get: function () { return x; }, set: function (newX) { if (different(x, newX)) { x = newX; left = right = undefined; } }, enumerable: true }, y: { get: function () { return y; }, set: function (newY) { if (different(y, newY)) { y = newY; top = bottom = undefined; } }, enumerable: true }, width: { get: function () { return width; }, set: function (newWidth) { if (different(width, newWidth)) { width = newWidth; left = right = undefined; } }, enumerable: true }, height: { get: function () { return height; }, set: function (newHeight) { if (different(height, newHeight)) { height = newHeight; top = bottom = undefined; } }, enumerable: true }, left: { get: function () { if (left === undefined) { left = x + Math.min(0, width); } return left; }, enumerable: true }, right: { get: function () { if (right === undefined) { right = x + Math.max(0, width); } return right; }, enumerable: true }, top: { get: function () { if (top === undefined) { top = y + Math.min(0, height); } return top; }, enumerable: true }, bottom: { get: function () { if (bottom === undefined) { bottom = y + Math.max(0, height); } return bottom; }, enumerable: true } }); } global.DOMRect = DOMRect; }(self)); wp-polyfill-fetch.js 0000604 00000046547 14720015030 0010453 0 ustar 00 (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.WHATWGFetch = {}))); }(this, (function (exports) { 'use strict'; /* eslint-disable no-prototype-builtins */ var g = (typeof globalThis !== 'undefined' && globalThis) || (typeof self !== 'undefined' && self) || // eslint-disable-next-line no-undef (typeof global !== 'undefined' && global) || {}; var support = { searchParams: 'URLSearchParams' in g, iterable: 'Symbol' in g && 'iterator' in Symbol, blob: 'FileReader' in g && 'Blob' in g && (function() { try { new Blob(); return true } catch (e) { return false } })(), formData: 'FormData' in g, arrayBuffer: 'ArrayBuffer' in g }; function isDataView(obj) { return obj && DataView.prototype.isPrototypeOf(obj) } if (support.arrayBuffer) { var viewClasses = [ '[object Int8Array]', '[object Uint8Array]', '[object Uint8ClampedArray]', '[object Int16Array]', '[object Uint16Array]', '[object Int32Array]', '[object Uint32Array]', '[object Float32Array]', '[object Float64Array]' ]; var isArrayBufferView = ArrayBuffer.isView || function(obj) { return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 }; } function normalizeName(name) { if (typeof name !== 'string') { name = String(name); } if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === '') { throw new TypeError('Invalid character in header field name: "' + name + '"') } return name.toLowerCase() } function normalizeValue(value) { if (typeof value !== 'string') { value = String(value); } return value } // Build a destructive iterator for the value list function iteratorFor(items) { var iterator = { next: function() { var value = items.shift(); return {done: value === undefined, value: value} } }; if (support.iterable) { iterator[Symbol.iterator] = function() { return iterator }; } return iterator } function Headers(headers) { this.map = {}; if (headers instanceof Headers) { headers.forEach(function(value, name) { this.append(name, value); }, this); } else if (Array.isArray(headers)) { headers.forEach(function(header) { if (header.length != 2) { throw new TypeError('Headers constructor: expected name/value pair to be length 2, found' + header.length) } this.append(header[0], header[1]); }, this); } else if (headers) { Object.getOwnPropertyNames(headers).forEach(function(name) { this.append(name, headers[name]); }, this); } } Headers.prototype.append = function(name, value) { name = normalizeName(name); value = normalizeValue(value); var oldValue = this.map[name]; this.map[name] = oldValue ? oldValue + ', ' + value : value; }; Headers.prototype['delete'] = function(name) { delete this.map[normalizeName(name)]; }; Headers.prototype.get = function(name) { name = normalizeName(name); return this.has(name) ? this.map[name] : null }; Headers.prototype.has = function(name) { return this.map.hasOwnProperty(normalizeName(name)) }; Headers.prototype.set = function(name, value) { this.map[normalizeName(name)] = normalizeValue(value); }; Headers.prototype.forEach = function(callback, thisArg) { for (var name in this.map) { if (this.map.hasOwnProperty(name)) { callback.call(thisArg, this.map[name], name, this); } } }; Headers.prototype.keys = function() { var items = []; this.forEach(function(value, name) { items.push(name); }); return iteratorFor(items) }; Headers.prototype.values = function() { var items = []; this.forEach(function(value) { items.push(value); }); return iteratorFor(items) }; Headers.prototype.entries = function() { var items = []; this.forEach(function(value, name) { items.push([name, value]); }); return iteratorFor(items) }; if (support.iterable) { Headers.prototype[Symbol.iterator] = Headers.prototype.entries; } function consumed(body) { if (body._noBody) return if (body.bodyUsed) { return Promise.reject(new TypeError('Already read')) } body.bodyUsed = true; } function fileReaderReady(reader) { return new Promise(function(resolve, reject) { reader.onload = function() { resolve(reader.result); }; reader.onerror = function() { reject(reader.error); }; }) } function readBlobAsArrayBuffer(blob) { var reader = new FileReader(); var promise = fileReaderReady(reader); reader.readAsArrayBuffer(blob); return promise } function readBlobAsText(blob) { var reader = new FileReader(); var promise = fileReaderReady(reader); var match = /charset=([A-Za-z0-9_-]+)/.exec(blob.type); var encoding = match ? match[1] : 'utf-8'; reader.readAsText(blob, encoding); return promise } function readArrayBufferAsText(buf) { var view = new Uint8Array(buf); var chars = new Array(view.length); for (var i = 0; i < view.length; i++) { chars[i] = String.fromCharCode(view[i]); } return chars.join('') } function bufferClone(buf) { if (buf.slice) { return buf.slice(0) } else { var view = new Uint8Array(buf.byteLength); view.set(new Uint8Array(buf)); return view.buffer } } function Body() { this.bodyUsed = false; this._initBody = function(body) { /* fetch-mock wraps the Response object in an ES6 Proxy to provide useful test harness features such as flush. However, on ES5 browsers without fetch or Proxy support pollyfills must be used; the proxy-pollyfill is unable to proxy an attribute unless it exists on the object before the Proxy is created. This change ensures Response.bodyUsed exists on the instance, while maintaining the semantic of setting Request.bodyUsed in the constructor before _initBody is called. */ // eslint-disable-next-line no-self-assign this.bodyUsed = this.bodyUsed; this._bodyInit = body; if (!body) { this._noBody = true; this._bodyText = ''; } else if (typeof body === 'string') { this._bodyText = body; } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { this._bodyBlob = body; } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { this._bodyFormData = body; } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this._bodyText = body.toString(); } else if (support.arrayBuffer && support.blob && isDataView(body)) { this._bodyArrayBuffer = bufferClone(body.buffer); // IE 10-11 can't handle a DataView body. this._bodyInit = new Blob([this._bodyArrayBuffer]); } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { this._bodyArrayBuffer = bufferClone(body); } else { this._bodyText = body = Object.prototype.toString.call(body); } if (!this.headers.get('content-type')) { if (typeof body === 'string') { this.headers.set('content-type', 'text/plain;charset=UTF-8'); } else if (this._bodyBlob && this._bodyBlob.type) { this.headers.set('content-type', this._bodyBlob.type); } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); } } }; if (support.blob) { this.blob = function() { var rejected = consumed(this); if (rejected) { return rejected } if (this._bodyBlob) { return Promise.resolve(this._bodyBlob) } else if (this._bodyArrayBuffer) { return Promise.resolve(new Blob([this._bodyArrayBuffer])) } else if (this._bodyFormData) { throw new Error('could not read FormData body as blob') } else { return Promise.resolve(new Blob([this._bodyText])) } }; } this.arrayBuffer = function() { if (this._bodyArrayBuffer) { var isConsumed = consumed(this); if (isConsumed) { return isConsumed } else if (ArrayBuffer.isView(this._bodyArrayBuffer)) { return Promise.resolve( this._bodyArrayBuffer.buffer.slice( this._bodyArrayBuffer.byteOffset, this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength ) ) } else { return Promise.resolve(this._bodyArrayBuffer) } } else if (support.blob) { return this.blob().then(readBlobAsArrayBuffer) } else { throw new Error('could not read as ArrayBuffer') } }; this.text = function() { var rejected = consumed(this); if (rejected) { return rejected } if (this._bodyBlob) { return readBlobAsText(this._bodyBlob) } else if (this._bodyArrayBuffer) { return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) } else if (this._bodyFormData) { throw new Error('could not read FormData body as text') } else { return Promise.resolve(this._bodyText) } }; if (support.formData) { this.formData = function() { return this.text().then(decode) }; } this.json = function() { return this.text().then(JSON.parse) }; return this } // HTTP methods whose capitalization should be normalized var methods = ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE']; function normalizeMethod(method) { var upcased = method.toUpperCase(); return methods.indexOf(upcased) > -1 ? upcased : method } function Request(input, options) { if (!(this instanceof Request)) { throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.') } options = options || {}; var body = options.body; if (input instanceof Request) { if (input.bodyUsed) { throw new TypeError('Already read') } this.url = input.url; this.credentials = input.credentials; if (!options.headers) { this.headers = new Headers(input.headers); } this.method = input.method; this.mode = input.mode; this.signal = input.signal; if (!body && input._bodyInit != null) { body = input._bodyInit; input.bodyUsed = true; } } else { this.url = String(input); } this.credentials = options.credentials || this.credentials || 'same-origin'; if (options.headers || !this.headers) { this.headers = new Headers(options.headers); } this.method = normalizeMethod(options.method || this.method || 'GET'); this.mode = options.mode || this.mode || null; this.signal = options.signal || this.signal || (function () { if ('AbortController' in g) { var ctrl = new AbortController(); return ctrl.signal; } }()); this.referrer = null; if ((this.method === 'GET' || this.method === 'HEAD') && body) { throw new TypeError('Body not allowed for GET or HEAD requests') } this._initBody(body); if (this.method === 'GET' || this.method === 'HEAD') { if (options.cache === 'no-store' || options.cache === 'no-cache') { // Search for a '_' parameter in the query string var reParamSearch = /([?&])_=[^&]*/; if (reParamSearch.test(this.url)) { // If it already exists then set the value with the current time this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime()); } else { // Otherwise add a new '_' parameter to the end with the current time var reQueryString = /\?/; this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime(); } } } } Request.prototype.clone = function() { return new Request(this, {body: this._bodyInit}) }; function decode(body) { var form = new FormData(); body .trim() .split('&') .forEach(function(bytes) { if (bytes) { var split = bytes.split('='); var name = split.shift().replace(/\+/g, ' '); var value = split.join('=').replace(/\+/g, ' '); form.append(decodeURIComponent(name), decodeURIComponent(value)); } }); return form } function parseHeaders(rawHeaders) { var headers = new Headers(); // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space // https://tools.ietf.org/html/rfc7230#section-3.2 var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill // https://github.com/github/fetch/issues/748 // https://github.com/zloirock/core-js/issues/751 preProcessedHeaders .split('\r') .map(function(header) { return header.indexOf('\n') === 0 ? header.substr(1, header.length) : header }) .forEach(function(line) { var parts = line.split(':'); var key = parts.shift().trim(); if (key) { var value = parts.join(':').trim(); try { headers.append(key, value); } catch (error) { console.warn('Response ' + error.message); } } }); return headers } Body.call(Request.prototype); function Response(bodyInit, options) { if (!(this instanceof Response)) { throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.') } if (!options) { options = {}; } this.type = 'default'; this.status = options.status === undefined ? 200 : options.status; if (this.status < 200 || this.status > 599) { throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].") } this.ok = this.status >= 200 && this.status < 300; this.statusText = options.statusText === undefined ? '' : '' + options.statusText; this.headers = new Headers(options.headers); this.url = options.url || ''; this._initBody(bodyInit); } Body.call(Response.prototype); Response.prototype.clone = function() { return new Response(this._bodyInit, { status: this.status, statusText: this.statusText, headers: new Headers(this.headers), url: this.url }) }; Response.error = function() { var response = new Response(null, {status: 200, statusText: ''}); response.ok = false; response.status = 0; response.type = 'error'; return response }; var redirectStatuses = [301, 302, 303, 307, 308]; Response.redirect = function(url, status) { if (redirectStatuses.indexOf(status) === -1) { throw new RangeError('Invalid status code') } return new Response(null, {status: status, headers: {location: url}}) }; exports.DOMException = g.DOMException; try { new exports.DOMException(); } catch (err) { exports.DOMException = function(message, name) { this.message = message; this.name = name; var error = Error(message); this.stack = error.stack; }; exports.DOMException.prototype = Object.create(Error.prototype); exports.DOMException.prototype.constructor = exports.DOMException; } function fetch(input, init) { return new Promise(function(resolve, reject) { var request = new Request(input, init); if (request.signal && request.signal.aborted) { return reject(new exports.DOMException('Aborted', 'AbortError')) } var xhr = new XMLHttpRequest(); function abortXhr() { xhr.abort(); } xhr.onload = function() { var options = { statusText: xhr.statusText, headers: parseHeaders(xhr.getAllResponseHeaders() || '') }; // This check if specifically for when a user fetches a file locally from the file system // Only if the status is out of a normal range if (request.url.indexOf('file://') === 0 && (xhr.status < 200 || xhr.status > 599)) { options.status = 200; } else { options.status = xhr.status; } options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); var body = 'response' in xhr ? xhr.response : xhr.responseText; setTimeout(function() { resolve(new Response(body, options)); }, 0); }; xhr.onerror = function() { setTimeout(function() { reject(new TypeError('Network request failed')); }, 0); }; xhr.ontimeout = function() { setTimeout(function() { reject(new TypeError('Network request timed out')); }, 0); }; xhr.onabort = function() { setTimeout(function() { reject(new exports.DOMException('Aborted', 'AbortError')); }, 0); }; function fixUrl(url) { try { return url === '' && g.location.href ? g.location.href : url } catch (e) { return url } } xhr.open(request.method, fixUrl(request.url), true); if (request.credentials === 'include') { xhr.withCredentials = true; } else if (request.credentials === 'omit') { xhr.withCredentials = false; } if ('responseType' in xhr) { if (support.blob) { xhr.responseType = 'blob'; } else if ( support.arrayBuffer ) { xhr.responseType = 'arraybuffer'; } } if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers || (g.Headers && init.headers instanceof g.Headers))) { var names = []; Object.getOwnPropertyNames(init.headers).forEach(function(name) { names.push(normalizeName(name)); xhr.setRequestHeader(name, normalizeValue(init.headers[name])); }); request.headers.forEach(function(value, name) { if (names.indexOf(name) === -1) { xhr.setRequestHeader(name, value); } }); } else { request.headers.forEach(function(value, name) { xhr.setRequestHeader(name, value); }); } if (request.signal) { request.signal.addEventListener('abort', abortXhr); xhr.onreadystatechange = function() { // DONE (success or failure) if (xhr.readyState === 4) { request.signal.removeEventListener('abort', abortXhr); } }; } xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); }) } fetch.polyfill = true; if (!g.fetch) { g.fetch = fetch; g.Headers = Headers; g.Request = Request; g.Response = Response; } exports.Headers = Headers; exports.Request = Request; exports.Response = Response; exports.fetch = fetch; Object.defineProperty(exports, '__esModule', { value: true }); }))); wp-polyfill-object-fit.js 0000644 00000021741 14720015030 0011401 0 ustar 00 /*---------------------------------------- * objectFitPolyfill 2.3.5 * * Made by Constance Chen * Released under the ISC license * * https://github.com/constancecchen/object-fit-polyfill *--------------------------------------*/ (function() { 'use strict'; // if the page is being rendered on the server, don't continue if (typeof window === 'undefined') return; // Workaround for Edge 16-18, which only implemented object-fit for <img> tags var edgeMatch = window.navigator.userAgent.match(/Edge\/(\d{2})\./); var edgeVersion = edgeMatch ? parseInt(edgeMatch[1], 10) : null; var edgePartialSupport = edgeVersion ? edgeVersion >= 16 && edgeVersion <= 18 : false; // If the browser does support object-fit, we don't need to continue var hasSupport = 'objectFit' in document.documentElement.style !== false; if (hasSupport && !edgePartialSupport) { window.objectFitPolyfill = function() { return false; }; return; } /** * Check the container's parent element to make sure it will * correctly handle and clip absolutely positioned children * * @param {node} $container - parent element */ var checkParentContainer = function($container) { var styles = window.getComputedStyle($container, null); var position = styles.getPropertyValue('position'); var overflow = styles.getPropertyValue('overflow'); var display = styles.getPropertyValue('display'); if (!position || position === 'static') { $container.style.position = 'relative'; } if (overflow !== 'hidden') { $container.style.overflow = 'hidden'; } // Guesstimating that people want the parent to act like full width/height wrapper here. // Mostly attempts to target <picture> elements, which default to inline. if (!display || display === 'inline') { $container.style.display = 'block'; } if ($container.clientHeight === 0) { $container.style.height = '100%'; } // Add a CSS class hook, in case people need to override styles for any reason. if ($container.className.indexOf('object-fit-polyfill') === -1) { $container.className = $container.className + ' object-fit-polyfill'; } }; /** * Check for pre-set max-width/height, min-width/height, * positioning, or margins, which can mess up image calculations * * @param {node} $media - img/video element */ var checkMediaProperties = function($media) { var styles = window.getComputedStyle($media, null); var constraints = { 'max-width': 'none', 'max-height': 'none', 'min-width': '0px', 'min-height': '0px', top: 'auto', right: 'auto', bottom: 'auto', left: 'auto', 'margin-top': '0px', 'margin-right': '0px', 'margin-bottom': '0px', 'margin-left': '0px', }; for (var property in constraints) { var constraint = styles.getPropertyValue(property); if (constraint !== constraints[property]) { $media.style[property] = constraints[property]; } } }; /** * Calculate & set object-position * * @param {string} axis - either "x" or "y" * @param {node} $media - img or video element * @param {string} objectPosition - e.g. "50% 50%", "top left" */ var setPosition = function(axis, $media, objectPosition) { var position, other, start, end, side; objectPosition = objectPosition.split(' '); if (objectPosition.length < 2) { objectPosition[1] = objectPosition[0]; } /* istanbul ignore else */ if (axis === 'x') { position = objectPosition[0]; other = objectPosition[1]; start = 'left'; end = 'right'; side = $media.clientWidth; } else if (axis === 'y') { position = objectPosition[1]; other = objectPosition[0]; start = 'top'; end = 'bottom'; side = $media.clientHeight; } else { return; // Neither x or y axis specified } if (position === start || other === start) { $media.style[start] = '0'; return; } if (position === end || other === end) { $media.style[end] = '0'; return; } if (position === 'center' || position === '50%') { $media.style[start] = '50%'; $media.style['margin-' + start] = side / -2 + 'px'; return; } // Percentage values (e.g., 30% 10%) if (position.indexOf('%') >= 0) { position = parseInt(position, 10); if (position < 50) { $media.style[start] = position + '%'; $media.style['margin-' + start] = side * (position / -100) + 'px'; } else { position = 100 - position; $media.style[end] = position + '%'; $media.style['margin-' + end] = side * (position / -100) + 'px'; } return; } // Length-based values (e.g. 10px / 10em) else { $media.style[start] = position; } }; /** * Calculate & set object-fit * * @param {node} $media - img/video/picture element */ var objectFit = function($media) { // IE 10- data polyfill var fit = $media.dataset ? $media.dataset.objectFit : $media.getAttribute('data-object-fit'); var position = $media.dataset ? $media.dataset.objectPosition : $media.getAttribute('data-object-position'); // Default fallbacks fit = fit || 'cover'; position = position || '50% 50%'; // If necessary, make the parent container work with absolutely positioned elements var $container = $media.parentNode; checkParentContainer($container); // Check for any pre-set CSS which could mess up image calculations checkMediaProperties($media); // Reset any pre-set width/height CSS and handle fit positioning $media.style.position = 'absolute'; $media.style.width = 'auto'; $media.style.height = 'auto'; // `scale-down` chooses either `none` or `contain`, whichever is smaller if (fit === 'scale-down') { if ( $media.clientWidth < $container.clientWidth && $media.clientHeight < $container.clientHeight ) { fit = 'none'; } else { fit = 'contain'; } } // `none` (width/height auto) and `fill` (100%) and are straightforward if (fit === 'none') { setPosition('x', $media, position); setPosition('y', $media, position); return; } if (fit === 'fill') { $media.style.width = '100%'; $media.style.height = '100%'; setPosition('x', $media, position); setPosition('y', $media, position); return; } // `cover` and `contain` must figure out which side needs covering, and add CSS positioning & centering $media.style.height = '100%'; if ( (fit === 'cover' && $media.clientWidth > $container.clientWidth) || (fit === 'contain' && $media.clientWidth < $container.clientWidth) ) { $media.style.top = '0'; $media.style.marginTop = '0'; setPosition('x', $media, position); } else { $media.style.width = '100%'; $media.style.height = 'auto'; $media.style.left = '0'; $media.style.marginLeft = '0'; setPosition('y', $media, position); } }; /** * Initialize plugin * * @param {node} media - Optional specific DOM node(s) to be polyfilled */ var objectFitPolyfill = function(media) { if (typeof media === 'undefined' || media instanceof Event) { // If left blank, or a default event, all media on the page will be polyfilled. media = document.querySelectorAll('[data-object-fit]'); } else if (media && media.nodeName) { // If it's a single node, wrap it in an array so it works. media = [media]; } else if (typeof media === 'object' && media.length && media[0].nodeName) { // If it's an array of DOM nodes (e.g. a jQuery selector), it's fine as-is. media = media; } else { // Otherwise, if it's invalid or an incorrect type, return false to let people know. return false; } for (var i = 0; i < media.length; i++) { if (!media[i].nodeName) continue; var mediaType = media[i].nodeName.toLowerCase(); if (mediaType === 'img') { if (edgePartialSupport) continue; // Edge supports object-fit for images (but nothing else), so no need to polyfill if (media[i].complete) { objectFit(media[i]); } else { media[i].addEventListener('load', function() { objectFit(this); }); } } else if (mediaType === 'video') { if (media[i].readyState > 0) { objectFit(media[i]); } else { media[i].addEventListener('loadedmetadata', function() { objectFit(this); }); } } else { objectFit(media[i]); } } return true; }; if (document.readyState === 'loading') { // Loading hasn't finished yet document.addEventListener('DOMContentLoaded', objectFitPolyfill); } else { // `DOMContentLoaded` has already fired objectFitPolyfill(); } window.addEventListener('resize', objectFitPolyfill); window.objectFitPolyfill = objectFitPolyfill; })(); react-dom.js 0000604 00004075643 14720015030 0006764 0 ustar 00 /** * @license React * react-dom.development.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. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (global = global || self, factory(global.ReactDOM = {}, global.React)); }(this, (function (exports, React) { 'use strict'; var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; var suppressWarning = false; function setSuppressWarning(newSuppressWarning) { { suppressWarning = newSuppressWarning; } } // In DEV, calls to console.warn and console.error get replaced // by calls to these methods by a Babel plugin. // // In PROD (or in packages without access to React internals), // they are left as they are instead. function warn(format) { { if (!suppressWarning) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning('warn', format, args); } } } function error(format) { { if (!suppressWarning) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } // eslint-disable-next-line react-internal/safe-string-coercion var argsWithFormat = args.map(function (item) { return String(item); }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } var FunctionComponent = 0; var ClassComponent = 1; var IndeterminateComponent = 2; // Before we know whether it is function or class var HostRoot = 3; // Root of a host tree. Could be nested inside another node. var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. var HostComponent = 5; var HostText = 6; var Fragment = 7; var Mode = 8; var ContextConsumer = 9; var ContextProvider = 10; var ForwardRef = 11; var Profiler = 12; var SuspenseComponent = 13; var MemoComponent = 14; var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; var DehydratedFragment = 18; var SuspenseListComponent = 19; var ScopeComponent = 21; var OffscreenComponent = 22; var LegacyHiddenComponent = 23; var CacheComponent = 24; var TracingMarkerComponent = 25; // ----------------------------------------------------------------------------- var enableClientRenderFallbackOnTextMismatch = true; // TODO: Need to review this code one more time before landing // the react-reconciler package. var enableNewReconciler = false; // Support legacy Primer support on internal FB www var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics. var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz // React DOM Chopping Block // // Similar to main Chopping Block but only flags related to React DOM. These are // grouped because we will likely batch all of them into a single major release. // ----------------------------------------------------------------------------- // Disable support for comment nodes as React DOM containers. Already disabled // in open source, but www codebase still relies on it. Need to remove. var disableCommentsAsDOMContainers = true; // Disable javascript: URL strings in href for XSS protection. // and client rendering, mostly to allow JSX attributes to apply to the custom // element's object properties instead of only HTML attributes. // https://github.com/facebook/react/issues/11347 var enableCustomElementPropertySupport = false; // Disables children for <textarea> elements var warnAboutStringRefs = true; // ----------------------------------------------------------------------------- // Debugging and DevTools // ----------------------------------------------------------------------------- // Adds user timing marks for e.g. state updates, suspense, and work loop stuff, // for an experimental timeline tool. var enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState var enableProfilerTimer = true; // Record durations for commit and passive effects phases. var enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an "update" and a "cascading-update". var allNativeEvents = new Set(); /** * Mapping from registration name to event name */ var registrationNameDependencies = {}; /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in true. * @type {Object} */ var possibleRegistrationNames = {} ; // Trust the developer to only use possibleRegistrationNames in true function registerTwoPhaseEvent(registrationName, dependencies) { registerDirectEvent(registrationName, dependencies); registerDirectEvent(registrationName + 'Capture', dependencies); } function registerDirectEvent(registrationName, dependencies) { { if (registrationNameDependencies[registrationName]) { error('EventRegistry: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName); } } registrationNameDependencies[registrationName] = dependencies; { var lowerCasedName = registrationName.toLowerCase(); possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { possibleRegistrationNames.ondblclick = registrationName; } } for (var i = 0; i < dependencies.length; i++) { allNativeEvents.add(dependencies[i]); } } var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); var hasOwnProperty = Object.prototype.hasOwnProperty; /* * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol * and Temporal.* types. See https://github.com/facebook/react/pull/22064. * * The functions in this module will throw an easier-to-understand, * easier-to-debug exception with a clear errors message message explaining the * problem. (Instead of a confusing exception thrown inside the implementation * of the `value` object). */ // $FlowFixMe only called in DEV, so void return is not possible. function typeName(value) { { // toStringTag is needed for namespaced types like Temporal.Instant var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; return type; } } // $FlowFixMe only called in DEV, so void return is not possible. function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { // If you ended up here by following an exception call stack, here's what's // happened: you supplied an object or symbol value to React (as a prop, key, // DOM attribute, CSS property, string ref, etc.) and when React tried to // coerce it to a string using `'' + value`, an exception was thrown. // // The most common types that will cause this exception are `Symbol` instances // and Temporal objects like `Temporal.Instant`. But any object that has a // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this // exception. (Library authors do this to prevent users from using built-in // numeric operators like `+` or comparison operators like `>=` because custom // methods are needed to perform accurate arithmetic or comparison.) // // To fix the problem, coerce this object or symbol value to a string before // passing it to React. The most reliable way is usually `String(value)`. // // To find which value is throwing, check the browser or debugger console. // Before this exception was thrown, there should be `console.error` output // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the // problem and how that type was used: key, atrribute, input value prop, etc. // In most cases, this console output also shows the component and its // ancestor components where the exception happened. // // eslint-disable-next-line react-internal/safe-string-coercion return '' + value; } function checkAttributeStringCoercion(value, attributeName) { { if (willCoercionThrow(value)) { error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function checkPropStringCoercion(value, propName) { { if (willCoercionThrow(value)) { error('The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function checkCSSPropertyStringCoercion(value, propName) { { if (willCoercionThrow(value)) { error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function checkHtmlStringCoercion(value) { { if (willCoercionThrow(value)) { error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function checkFormFieldValueStringCoercion(value) { { if (willCoercionThrow(value)) { error('Form field values (value, checked, defaultValue, or defaultChecked props)' + ' must be strings, not %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } // A reserved attribute. // It is handled by React separately and shouldn't be written to the DOM. var RESERVED = 0; // A simple string attribute. // Attributes that aren't in the filter are presumed to have this type. var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called // "enumerated" attributes with "true" and "false" as possible values. // When true, it should be set to a "true" string. // When false, it should be set to a "false" string. var BOOLEANISH_STRING = 2; // A real boolean attribute. // When true, it should be present (set either to an empty string or its name). // When false, it should be omitted. var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value. // When true, it should be present (set either to an empty string or its name). // When false, it should be omitted. // For any other value, should be present with that value. var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric. // When falsy, it should be removed. var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric. // When falsy, it should be removed. var POSITIVE_NUMERIC = 6; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; /* eslint-enable max-len */ var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { return true; } if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; { error('Invalid attribute name: `%s`', attributeName); } return false; } function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { if (propertyInfo !== null) { return propertyInfo.type === RESERVED; } if (isCustomComponentTag) { return false; } if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { return true; } return false; } function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { if (propertyInfo !== null && propertyInfo.type === RESERVED) { return false; } switch (typeof value) { case 'function': // $FlowIssue symbol is perfectly valid here case 'symbol': // eslint-disable-line return true; case 'boolean': { if (isCustomComponentTag) { return false; } if (propertyInfo !== null) { return !propertyInfo.acceptsBooleans; } else { var prefix = name.toLowerCase().slice(0, 5); return prefix !== 'data-' && prefix !== 'aria-'; } } default: return false; } } function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { if (value === null || typeof value === 'undefined') { return true; } if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { return true; } if (isCustomComponentTag) { return false; } if (propertyInfo !== null) { switch (propertyInfo.type) { case BOOLEAN: return !value; case OVERLOADED_BOOLEAN: return value === false; case NUMERIC: return isNaN(value); case POSITIVE_NUMERIC: return isNaN(value) || value < 1; } } return false; } function getPropertyInfo(name) { return properties.hasOwnProperty(name) ? properties[name] : null; } function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) { this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; this.attributeName = attributeName; this.attributeNamespace = attributeNamespace; this.mustUseProperty = mustUseProperty; this.propertyName = name; this.type = type; this.sanitizeURL = sanitizeURL; this.removeEmptyString = removeEmptyString; } // When adding attributes to this list, be sure to also add them to // the `possibleStandardNames` module to ensure casing and incorrect // name warnings. var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM. var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular // elements (not just inputs). Now that ReactDOMInput assigns to the // defaultValue property -- do we need this? 'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; reservedProps.forEach(function (name) { properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // A few React string attributes have a different name. // This is a mapping from React prop names to the attribute names. [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { var name = _ref[0], attributeName = _ref[1]; properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are "enumerated" HTML attributes that accept "true" and "false". // In React, we let users pass `true` and `false` even though technically // these aren't boolean attributes (they are coerced to strings). ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are "enumerated" SVG attributes that accept "true" and "false". // In React, we let users pass `true` and `false` even though technically // these aren't boolean attributes (they are coerced to strings). // Since these are SVG attributes, their attribute names are case-sensitive. ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML boolean attributes. ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM // on the client side because the browsers are inconsistent. Instead we call focus(). 'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata 'itemScope'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are the few React props that we set as DOM properties // rather than attributes. These are all booleans. ['checked', // Note: `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. We have special logic for handling this. 'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML attributes that are "overloaded booleans": they behave like // booleans, but can also accept a string value. ['capture', 'download' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML attributes that must be positive numbers. ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These are HTML attributes that must be numbers. ['rowSpan', 'start'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); var CAMELIZE = /[\-\:]([a-z])/g; var capitalize = function (token) { return token[1].toUpperCase(); }; // This is a list of all SVG attributes that need special casing, namespacing, // or boolean value assignment. Regular attributes that just accept strings // and have the same names are omitted, just like in the HTML attribute filter. // Some of these attributes can be hard to find. This list was created by // scraping the MDN documentation. ['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, null, // attributeNamespace false, // sanitizeURL false); }); // String SVG attributes with the xlink namespace. ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL false); }); // String SVG attributes with the xml namespace. ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function (attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL false); }); // These attribute exists both in HTML and SVG. // The attribute name is case-sensitive in SVG so we can't just use // the React name like we do for attributes that exist only in HTML. ['tabIndex', 'crossOrigin'].forEach(function (attributeName) { properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty attributeName.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); // These attributes accept URLs. These must not allow javascript: URLS. // These will also need to accept Trusted Types object in the future. var xlinkHref = 'xlinkHref'; properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty 'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL false); ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty attributeName.toLowerCase(), // attributeName null, // attributeNamespace true, // sanitizeURL true); }); // and any newline or tab are filtered out as if they're not part of the URL. // https://url.spec.whatwg.org/#url-parsing // Tab or newline are defined as \r\n\t: // https://infra.spec.whatwg.org/#ascii-tab-or-newline // A C0 control is a code point in the range \u0000 NULL to \u001F // INFORMATION SEPARATOR ONE, inclusive: // https://infra.spec.whatwg.org/#c0-control-or-space /* eslint-disable max-len */ var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; var didWarn = false; function sanitizeURL(url) { { if (!didWarn && isJavaScriptProtocol.test(url)) { didWarn = true; error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url)); } } } /** * Get the value for a property on a node. Only used in DEV for SSR validation. * The "expected" argument is used as a hint of what the expected value is. * Some properties have multiple equivalent values. */ function getValueForProperty(node, name, expected, propertyInfo) { { if (propertyInfo.mustUseProperty) { var propertyName = propertyInfo.propertyName; return node[propertyName]; } else { // This check protects multiple uses of `expected`, which is why the // react-internal/safe-string-coercion rule is disabled in several spots // below. { checkAttributeStringCoercion(expected, name); } if ( propertyInfo.sanitizeURL) { // If we haven't fully disabled javascript: URLs, and if // the hydration is successful of a javascript: URL, we // still want to warn on the client. // eslint-disable-next-line react-internal/safe-string-coercion sanitizeURL('' + expected); } var attributeName = propertyInfo.attributeName; var stringValue = null; if (propertyInfo.type === OVERLOADED_BOOLEAN) { if (node.hasAttribute(attributeName)) { var value = node.getAttribute(attributeName); if (value === '') { return true; } if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { return value; } // eslint-disable-next-line react-internal/safe-string-coercion if (value === '' + expected) { return expected; } return value; } } else if (node.hasAttribute(attributeName)) { if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { // We had an attribute but shouldn't have had one, so read it // for the error message. return node.getAttribute(attributeName); } if (propertyInfo.type === BOOLEAN) { // If this was a boolean, it doesn't matter what the value is // the fact that we have it is the same as the expected. return expected; } // Even if this property uses a namespace we use getAttribute // because we assume its namespaced name is the same as our config. // To use getAttributeNS we need the local name which we don't have // in our config atm. stringValue = node.getAttribute(attributeName); } if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { return stringValue === null ? expected : stringValue; // eslint-disable-next-line react-internal/safe-string-coercion } else if (stringValue === '' + expected) { return expected; } else { return stringValue; } } } } /** * Get the value for a attribute on a node. Only used in DEV for SSR validation. * The third argument is used as a hint of what the expected value is. Some * attributes have multiple equivalent values. */ function getValueForAttribute(node, name, expected, isCustomComponentTag) { { if (!isAttributeNameSafe(name)) { return; } if (!node.hasAttribute(name)) { return expected === undefined ? undefined : null; } var value = node.getAttribute(name); { checkAttributeStringCoercion(expected, name); } if (value === '' + expected) { return expected; } return value; } } /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ function setValueForProperty(node, name, value, isCustomComponentTag) { var propertyInfo = getPropertyInfo(name); if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { return; } if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { value = null; } if (isCustomComponentTag || propertyInfo === null) { if (isAttributeNameSafe(name)) { var _attributeName = name; if (value === null) { node.removeAttribute(_attributeName); } else { { checkAttributeStringCoercion(value, name); } node.setAttribute(_attributeName, '' + value); } } return; } var mustUseProperty = propertyInfo.mustUseProperty; if (mustUseProperty) { var propertyName = propertyInfo.propertyName; if (value === null) { var type = propertyInfo.type; node[propertyName] = type === BOOLEAN ? false : ''; } else { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propertyName] = value; } return; } // The rest are treated as attributes with special cases. var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace; if (value === null) { node.removeAttribute(attributeName); } else { var _type = propertyInfo.type; var attributeValue; if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { // If attribute type is boolean, we know for sure it won't be an execution sink // and we won't require Trusted Type here. attributeValue = ''; } else { // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. { { checkAttributeStringCoercion(value, attributeName); } attributeValue = '' + value; } if (propertyInfo.sanitizeURL) { sanitizeURL(attributeValue.toString()); } } if (attributeNamespace) { node.setAttributeNS(attributeNamespace, attributeName, attributeValue); } else { node.setAttribute(attributeName, attributeValue); } } } // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. var REACT_ELEMENT_TYPE = Symbol.for('react.element'); var REACT_PORTAL_TYPE = Symbol.for('react.portal'); var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); var REACT_CONTEXT_TYPE = Symbol.for('react.context'); var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); var REACT_MEMO_TYPE = Symbol.for('react.memo'); var REACT_LAZY_TYPE = Symbol.for('react.lazy'); var REACT_SCOPE_TYPE = Symbol.for('react.scope'); var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode'); var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden'); var REACT_CACHE_TYPE = Symbol.for('react.cache'); var REACT_TRACING_MARKER_TYPE = Symbol.for('react.tracing_marker'); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } var assign = Object.assign; // Helpers to patch console.logs to avoid logging during side-effect free // replaying on render function. This currently only patches the object // lazily which won't cover if the log function was extracted eagerly. // We could also eagerly patch the method. var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() {} disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); /* eslint-enable react-internal/no-production-logging */ } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ var props = { configurable: true, enumerable: true, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); /* eslint-enable react-internal/no-production-logging */ } if (disabledDepth < 0) { error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); } } } var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === undefined) { // Extract the VM specific prefix used by each line. try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ''; } } // We use the prefix to ensure our stacks line up with native stack frames. return '\n' + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { // If something asked for a stack inside a fake render, it should get ignored. if ( !fn || reentry) { return ''; } { var frame = componentFrameCache.get(fn); if (frame !== undefined) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. Error.prepareStackTrace = undefined; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function // for warnings. ReactCurrentDispatcher.current = null; disableLogs(); } try { // This should throw. if (construct) { // Something should be setting the props in the constructor. var Fake = function () { throw Error(); }; // $FlowFixMe Object.defineProperty(Fake.prototype, 'props', { set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); } }); if (typeof Reflect === 'object' && Reflect.construct) { // We construct a different control for this case to include any extra // frames added by the construct call. try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { // This is inlined manually because closure doesn't do it for us. if (sample && control && typeof sample.stack === 'string') { // This extracts the first frame from the sample that isn't also in the control. // Skipping one frame that we assume is the frame that calls the two. var sampleLines = sample.stack.split('\n'); var controlLines = control.stack.split('\n'); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { // We expect at least one stack frame to be shared. // Typically this will be the root most one. However, stack frames may be // cut off due to maximum stack limits. In this case, one maybe cut off // earlier than the other. We assume that the sample is longer or the same // and there for cut off earlier. So we should find the root most frame in // the sample somewhere in the control. c--; } for (; s >= 1 && c >= 0; s--, c--) { // Next we find the first one that isn't the same which should be the // frame that called our sample function and the control. if (sampleLines[s] !== controlLines[c]) { // In V8, the first line is describing the message but other VMs don't. // If we're about to return the first line, and the control is also on the same // line, that's a pretty good indicator that our sample threw at same line as // the control. I.e. before we entered the sample frame. So we ignore this result. // This can happen if you passed a class to function component, or non-function. if (s !== 1 || c !== 1) { do { s--; c--; // We may still have similar intermediate frames from the construct call. // The next one that isn't the same should be our match though. if (c < 0 || sampleLines[s] !== controlLines[c]) { // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>" // but we have a user-provided "displayName" // splice it in to make the stack more readable. if (fn.displayName && _frame.includes('<anonymous>')) { _frame = _frame.replace('<anonymous>', fn.displayName); } { if (typeof fn === 'function') { componentFrameCache.set(fn, _frame); } } // Return the line we found. return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } // Fallback to just using the name if we couldn't make it throw. var name = fn ? fn.displayName || fn.name : ''; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; { if (typeof fn === 'function') { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeClassComponentFrame(ctor, source, ownerFn) { { return describeNativeComponentFrame(ctor, true); } } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ''; } if (typeof type === 'function') { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === 'string') { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame('Suspense'); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame('SuspenseList'); } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: // Memo may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); } catch (x) {} } } } return ''; } function describeFiber(fiber) { var owner = fiber._debugOwner ? fiber._debugOwner.type : null ; var source = fiber._debugSource ; switch (fiber.tag) { case HostComponent: return describeBuiltInComponentFrame(fiber.type); case LazyComponent: return describeBuiltInComponentFrame('Lazy'); case SuspenseComponent: return describeBuiltInComponentFrame('Suspense'); case SuspenseListComponent: return describeBuiltInComponentFrame('SuspenseList'); case FunctionComponent: case IndeterminateComponent: case SimpleMemoComponent: return describeFunctionComponentFrame(fiber.type); case ForwardRef: return describeFunctionComponentFrame(fiber.type.render); case ClassComponent: return describeClassComponentFrame(fiber.type); default: return ''; } } function getStackByFiberInDevAndProd(workInProgress) { try { var info = ''; var node = workInProgress; do { info += describeFiber(node); node = node.return; } while (node); return info; } catch (x) { return '\nError generating stack: ' + x.message + '\n' + x.stack; } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ''; return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; } // Keep in sync with react-reconciler/getComponentNameFromFiber function getContextName(type) { return type.displayName || 'Context'; } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. function getComponentNameFromType(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + '.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || 'Memo'; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return getComponentNameFromType(init(payload)); } catch (x) { return null; } } // eslint-disable-next-line no-fallthrough } } return null; } function getWrappedName$1(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } // Keep in sync with shared/getComponentNameFromType function getContextName$1(type) { return type.displayName || 'Context'; } function getComponentNameFromFiber(fiber) { var tag = fiber.tag, type = fiber.type; switch (tag) { case CacheComponent: return 'Cache'; case ContextConsumer: var context = type; return getContextName$1(context) + '.Consumer'; case ContextProvider: var provider = type; return getContextName$1(provider._context) + '.Provider'; case DehydratedFragment: return 'DehydratedFragment'; case ForwardRef: return getWrappedName$1(type, type.render, 'ForwardRef'); case Fragment: return 'Fragment'; case HostComponent: // Host component type is the display name (e.g. "div", "View") return type; case HostPortal: return 'Portal'; case HostRoot: return 'Root'; case HostText: return 'Text'; case LazyComponent: // Name comes from the type in this case; we don't have a tag. return getComponentNameFromType(type); case Mode: if (type === REACT_STRICT_MODE_TYPE) { // Don't be less specific than shared/getComponentNameFromType return 'StrictMode'; } return 'Mode'; case OffscreenComponent: return 'Offscreen'; case Profiler: return 'Profiler'; case ScopeComponent: return 'Scope'; case SuspenseComponent: return 'Suspense'; case SuspenseListComponent: return 'SuspenseList'; case TracingMarkerComponent: return 'TracingMarker'; // The display name for this tags come from the user-provided type: case ClassComponent: case FunctionComponent: case IncompleteClassComponent: case IndeterminateComponent: case MemoComponent: case SimpleMemoComponent: if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } break; } return null; } var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var current = null; var isRendering = false; function getCurrentFiberOwnerNameInDevOrNull() { { if (current === null) { return null; } var owner = current._debugOwner; if (owner !== null && typeof owner !== 'undefined') { return getComponentNameFromFiber(owner); } } return null; } function getCurrentFiberStackInDev() { { if (current === null) { return ''; } // Safe because if current fiber exists, we are reconciling, // and it is guaranteed to be the work-in-progress version. return getStackByFiberInDevAndProd(current); } } function resetCurrentFiber() { { ReactDebugCurrentFrame.getCurrentStack = null; current = null; isRendering = false; } } function setCurrentFiber(fiber) { { ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; current = fiber; isRendering = false; } } function getCurrentFiber() { { return current; } } function setIsRendering(rendering) { { isRendering = rendering; } } // Flow does not allow string concatenation of most non-string types. To work // around this limitation, we use an opaque type that can only be obtained by // passing the value through getToStringValue first. function toString(value) { // The coercion safety check is performed in getToStringValue(). // eslint-disable-next-line react-internal/safe-string-coercion return '' + value; } function getToStringValue(value) { switch (typeof value) { case 'boolean': case 'number': case 'string': case 'undefined': return value; case 'object': { checkFormFieldValueStringCoercion(value); } return value; default: // function, symbol are assigned as empty strings return ''; } } var hasReadOnlyValue = { button: true, checkbox: true, image: true, hidden: true, radio: true, reset: true, submit: true }; function checkControlledValueProps(tagName, props) { { if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); } if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); } } } function isCheckable(elem) { var type = elem.type; var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio'); } function getTracker(node) { return node._valueTracker; } function detachTracker(node) { node._valueTracker = null; } function getValueFromNode(node) { var value = ''; if (!node) { return value; } if (isCheckable(node)) { value = node.checked ? 'true' : 'false'; } else { value = node.value; } return value; } function trackValueOnNode(node) { var valueField = isCheckable(node) ? 'checked' : 'value'; var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); { checkFormFieldValueStringCoercion(node[valueField]); } var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail // and don't track value will cause over reporting of changes, // but it's better then a hard failure // (needed for certain tests that spyOn input values and Safari) if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') { return; } var get = descriptor.get, set = descriptor.set; Object.defineProperty(node, valueField, { configurable: true, get: function () { return get.call(this); }, set: function (value) { { checkFormFieldValueStringCoercion(value); } currentValue = '' + value; set.call(this, value); } }); // We could've passed this the first time // but it triggers a bug in IE11 and Edge 14/15. // Calling defineProperty() again should be equivalent. // https://github.com/facebook/react/issues/11768 Object.defineProperty(node, valueField, { enumerable: descriptor.enumerable }); var tracker = { getValue: function () { return currentValue; }, setValue: function (value) { { checkFormFieldValueStringCoercion(value); } currentValue = '' + value; }, stopTracking: function () { detachTracker(node); delete node[valueField]; } }; return tracker; } function track(node) { if (getTracker(node)) { return; } // TODO: Once it's just Fiber we can move this to node._wrapperState node._valueTracker = trackValueOnNode(node); } function updateValueIfChanged(node) { if (!node) { return false; } var tracker = getTracker(node); // if there is no tracker at this point it's unlikely // that trying again will succeed if (!tracker) { return true; } var lastValue = tracker.getValue(); var nextValue = getValueFromNode(node); if (nextValue !== lastValue) { tracker.setValue(nextValue); return true; } return false; } function getActiveElement(doc) { doc = doc || (typeof document !== 'undefined' ? document : undefined); if (typeof doc === 'undefined') { return null; } try { return doc.activeElement || doc.body; } catch (e) { return doc.body; } } var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function isControlled(props) { var usesChecked = props.type === 'checkbox' || props.type === 'radio'; return usesChecked ? props.checked != null : props.value != null; } /** * Implements an <input> host component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ function getHostProps(element, props) { var node = element; var checked = props.checked; var hostProps = assign({}, props, { defaultChecked: undefined, defaultValue: undefined, value: undefined, checked: checked != null ? checked : node._wrapperState.initialChecked }); return hostProps; } function initWrapperState(element, props) { { checkControlledValueProps('input', props); if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); didWarnValueDefaultValue = true; } } var node = element; var defaultValue = props.defaultValue == null ? '' : props.defaultValue; node._wrapperState = { initialChecked: props.checked != null ? props.checked : props.defaultChecked, initialValue: getToStringValue(props.value != null ? props.value : defaultValue), controlled: isControlled(props) }; } function updateChecked(element, props) { var node = element; var checked = props.checked; if (checked != null) { setValueForProperty(node, 'checked', checked, false); } } function updateWrapper(element, props) { var node = element; { var controlled = isControlled(props); if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { error('A component is changing an uncontrolled input to be controlled. ' + 'This is likely caused by the value changing from undefined to ' + 'a defined value, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components'); didWarnUncontrolledToControlled = true; } if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { error('A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components'); didWarnControlledToUncontrolled = true; } } updateChecked(element, props); var value = getToStringValue(props.value); var type = props.type; if (value != null) { if (type === 'number') { if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible. // eslint-disable-next-line node.value != value) { node.value = toString(value); } } else if (node.value !== toString(value)) { node.value = toString(value); } } else if (type === 'submit' || type === 'reset') { // Submit/reset inputs need the attribute removed completely to avoid // blank-text buttons. node.removeAttribute('value'); return; } { // When syncing the value attribute, the value comes from a cascade of // properties: // 1. The value React property // 2. The defaultValue React property // 3. Otherwise there should be no change if (props.hasOwnProperty('value')) { setDefaultValue(node, props.type, value); } else if (props.hasOwnProperty('defaultValue')) { setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); } } { // When syncing the checked attribute, it only changes when it needs // to be removed, such as transitioning from a checkbox into a text input if (props.checked == null && props.defaultChecked != null) { node.defaultChecked = !!props.defaultChecked; } } } function postMountWrapper(element, props, isHydrating) { var node = element; // Do not assign value if it is already set. This prevents user text input // from being lost during SSR hydration. if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) { var type = props.type; var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the // default value provided by the browser. See: #12872 if (isButton && (props.value === undefined || props.value === null)) { return; } var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input // from being lost during SSR hydration. if (!isHydrating) { { // When syncing the value attribute, the value property should use // the wrapperState._initialValue property. This uses: // // 1. The value React property when present // 2. The defaultValue React property when present // 3. An empty string if (initialValue !== node.value) { node.value = initialValue; } } } { // Otherwise, the value attribute is synchronized to the property, // so we assign defaultValue to the same thing as the value property // assignment step above. node.defaultValue = initialValue; } } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug // this is needed to work around a chrome bug where setting defaultChecked // will sometimes influence the value of checked (even after detachment). // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 // We need to temporarily unset name to avoid disrupting radio button groups. var name = node.name; if (name !== '') { node.name = ''; } { // When syncing the checked attribute, both the checked property and // attribute are assigned at the same time using defaultChecked. This uses: // // 1. The checked React property when present // 2. The defaultChecked React property when present // 3. Otherwise, false node.defaultChecked = !node.defaultChecked; node.defaultChecked = !!node._wrapperState.initialChecked; } if (name !== '') { node.name = name; } } function restoreControlledState(element, props) { var node = element; updateWrapper(node, props); updateNamedCousins(node, props); } function updateNamedCousins(rootNode, props) { var name = props.name; if (props.type === 'radio' && name != null) { var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form. It might not even be in the // document. Let's just use the local `querySelectorAll` to ensure we don't // miss anything. { checkAttributeStringCoercion(name, 'name'); } var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherProps = getFiberCurrentPropsFromNode(otherNode); if (!otherProps) { throw new Error('ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.'); } // We need update the tracked value on the named cousin since the value // was changed but the input saw no event or value set updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. updateWrapper(otherNode, otherProps); } } } // In Chrome, assigning defaultValue to certain input types triggers input validation. // For number inputs, the display value loses trailing decimal points. For email inputs, // Chrome raises "The specified value <x> is not a valid email address". // // Here we check to see if the defaultValue has actually changed, avoiding these problems // when the user is inputting text // // https://github.com/facebook/react/issues/7253 function setDefaultValue(node, type, value) { if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js type !== 'number' || getActiveElement(node.ownerDocument) !== node) { if (value == null) { node.defaultValue = toString(node._wrapperState.initialValue); } else if (node.defaultValue !== toString(value)) { node.defaultValue = toString(value); } } } var didWarnSelectedSetOnOption = false; var didWarnInvalidChild = false; var didWarnInvalidInnerHTML = false; /** * Implements an <option> host component that warns when `selected` is set. */ function validateProps(element, props) { { // If a value is not provided, then the children must be simple. if (props.value == null) { if (typeof props.children === 'object' && props.children !== null) { React.Children.forEach(props.children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { return; } if (!didWarnInvalidChild) { didWarnInvalidChild = true; error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.'); } }); } else if (props.dangerouslySetInnerHTML != null) { if (!didWarnInvalidInnerHTML) { didWarnInvalidInnerHTML = true; error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.'); } } } // TODO: Remove support for `selected` in <option>. if (props.selected != null && !didWarnSelectedSetOnOption) { error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.'); didWarnSelectedSetOnOption = true; } } } function postMountWrapper$1(element, props) { // value="" should make a value attribute (#6219) if (props.value != null) { element.setAttribute('value', toString(getToStringValue(props.value))); } } var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } var didWarnValueDefaultValue$1; { didWarnValueDefaultValue$1 = false; } function getDeclarationErrorAddendum() { var ownerName = getCurrentFiberOwnerNameInDevOrNull(); if (ownerName) { return '\n\nCheck the render method of `' + ownerName + '`.'; } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. */ function checkSelectPropTypes(props) { { checkControlledValueProps('select', props); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var propNameIsArray = isArray(props[propName]); if (props.multiple && !propNameIsArray) { error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum()); } else if (!props.multiple && propNameIsArray) { error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum()); } } } } function updateOptions(node, multiple, propValue, setDefaultSelected) { var options = node.options; if (multiple) { var selectedValues = propValue; var selectedValue = {}; for (var i = 0; i < selectedValues.length; i++) { // Prefix to avoid chaos with special keys. selectedValue['$' + selectedValues[i]] = true; } for (var _i = 0; _i < options.length; _i++) { var selected = selectedValue.hasOwnProperty('$' + options[_i].value); if (options[_i].selected !== selected) { options[_i].selected = selected; } if (selected && setDefaultSelected) { options[_i].defaultSelected = true; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. var _selectedValue = toString(getToStringValue(propValue)); var defaultSelected = null; for (var _i2 = 0; _i2 < options.length; _i2++) { if (options[_i2].value === _selectedValue) { options[_i2].selected = true; if (setDefaultSelected) { options[_i2].defaultSelected = true; } return; } if (defaultSelected === null && !options[_i2].disabled) { defaultSelected = options[_i2]; } } if (defaultSelected !== null) { defaultSelected.selected = true; } } } /** * Implements a <select> host component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ function getHostProps$1(element, props) { return assign({}, props, { value: undefined }); } function initWrapperState$1(element, props) { var node = element; { checkSelectPropTypes(props); } node._wrapperState = { wasMultiple: !!props.multiple }; { if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) { error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components'); didWarnValueDefaultValue$1 = true; } } } function postMountWrapper$2(element, props) { var node = element; node.multiple = !!props.multiple; var value = props.value; if (value != null) { updateOptions(node, !!props.multiple, value, false); } else if (props.defaultValue != null) { updateOptions(node, !!props.multiple, props.defaultValue, true); } } function postUpdateWrapper(element, props) { var node = element; var wasMultiple = node._wrapperState.wasMultiple; node._wrapperState.wasMultiple = !!props.multiple; var value = props.value; if (value != null) { updateOptions(node, !!props.multiple, value, false); } else if (wasMultiple !== !!props.multiple) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(node, !!props.multiple, props.defaultValue, true); } else { // Revert the select back to its default unselected state. updateOptions(node, !!props.multiple, props.multiple ? [] : '', false); } } } function restoreControlledState$1(element, props) { var node = element; var value = props.value; if (value != null) { updateOptions(node, !!props.multiple, value, false); } } var didWarnValDefaultVal = false; /** * Implements a <textarea> host component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ function getHostProps$2(element, props) { var node = element; if (props.dangerouslySetInnerHTML != null) { throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.'); } // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. We could add a check in setTextContent // to only set the value if/when the value differs from the node value (which would // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this // solution. The value can be a boolean or object so that's why it's forced // to be a string. var hostProps = assign({}, props, { value: undefined, defaultValue: undefined, children: toString(node._wrapperState.initialValue) }); return hostProps; } function initWrapperState$2(element, props) { var node = element; { checkControlledValueProps('textarea', props); if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component'); didWarnValDefaultVal = true; } } var initialValue = props.value; // Only bother fetching default value if we're going to use it if (initialValue == null) { var children = props.children, defaultValue = props.defaultValue; if (children != null) { { error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.'); } { if (defaultValue != null) { throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.'); } if (isArray(children)) { if (children.length > 1) { throw new Error('<textarea> can only have at most one child.'); } children = children[0]; } defaultValue = children; } } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } node._wrapperState = { initialValue: getToStringValue(initialValue) }; } function updateWrapper$1(element, props) { var node = element; var value = getToStringValue(props.value); var defaultValue = getToStringValue(props.defaultValue); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } if (props.defaultValue == null && node.defaultValue !== newValue) { node.defaultValue = newValue; } } if (defaultValue != null) { node.defaultValue = toString(defaultValue); } } function postMountWrapper$3(element, props) { var node = element; // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var textContent = node.textContent; // Only set node.value if textContent is equal to the expected // initial value. In IE10/IE11 there is a bug where the placeholder attribute // will populate textContent as well. // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/ if (textContent === node._wrapperState.initialValue) { if (textContent !== '' && textContent !== null) { node.value = textContent; } } } function restoreControlledState$2(element, props) { // DOM component is still mounted; update updateWrapper$1(element, props); } var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; // Assumes there is no parent namespace. function getIntrinsicNamespace(type) { switch (type) { case 'svg': return SVG_NAMESPACE; case 'math': return MATH_NAMESPACE; default: return HTML_NAMESPACE; } } function getChildNamespace(parentNamespace, type) { if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) { // No (or default) parent namespace: potential entry point. return getIntrinsicNamespace(type); } if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') { // We're leaving SVG. return HTML_NAMESPACE; } // By default, pass namespace below. return parentNamespace; } /* globals MSApp */ /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; var reusableSVGContainer; /** * Set the innerHTML property of a node * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { if (node.namespaceURI === SVG_NAMESPACE) { if (!('innerHTML' in node)) { // IE does not have innerHTML for SVG nodes, so instead we inject the // new markup in a temp node and then move the child nodes across into // the target node reusableSVGContainer = reusableSVGContainer || document.createElement('div'); reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>'; var svgNode = reusableSVGContainer.firstChild; while (node.firstChild) { node.removeChild(node.firstChild); } while (svgNode.firstChild) { node.appendChild(svgNode.firstChild); } return; } } node.innerHTML = html; }); /** * HTML nodeType values that represent the type of the node */ var ELEMENT_NODE = 1; var TEXT_NODE = 3; var COMMENT_NODE = 8; var DOCUMENT_NODE = 9; var DOCUMENT_FRAGMENT_NODE = 11; /** * Set the textContent property of a node. For text updates, it's faster * to set the `nodeValue` of the Text node directly instead of using * `.textContent` which will remove the existing node and create a new one. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { if (text) { var firstChild = node.firstChild; if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) { firstChild.nodeValue = text; return; } } node.textContent = text; }; // List derived from Gecko source code: // https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js var shorthandToLonghand = { animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'], background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'], backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'], border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'], borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'], borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'], borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'], borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'], borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'], borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'], borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'], borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'], borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'], borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'], borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'], borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'], borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'], columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'], columns: ['columnCount', 'columnWidth'], flex: ['flexBasis', 'flexGrow', 'flexShrink'], flexFlow: ['flexDirection', 'flexWrap'], font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'], fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'], gap: ['columnGap', 'rowGap'], grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'], gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'], gridColumn: ['gridColumnEnd', 'gridColumnStart'], gridColumnGap: ['columnGap'], gridGap: ['columnGap', 'rowGap'], gridRow: ['gridRowEnd', 'gridRowStart'], gridRowGap: ['rowGap'], gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'], listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'], margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'], marker: ['markerEnd', 'markerMid', 'markerStart'], mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'], maskPosition: ['maskPositionX', 'maskPositionY'], outline: ['outlineColor', 'outlineStyle', 'outlineWidth'], overflow: ['overflowX', 'overflowY'], padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'], placeContent: ['alignContent', 'justifyContent'], placeItems: ['alignItems', 'justifyItems'], placeSelf: ['alignSelf', 'justifySelf'], textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'], textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'], transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'], wordWrap: ['overflowWrap'] }; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, aspectRatio: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, columns: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridArea: true, gridRow: true, gridRowEnd: true, gridRowSpan: true, gridRowStart: true, gridColumn: true, gridColumnEnd: true, gridColumnSpan: true, gridColumnStart: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, isCustomProperty) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) { return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers } { checkCSSPropertyStringCoercion(value, name); } return ('' + value).trim(); } var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. */ function hyphenateStyleName(name) { return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } var warnValidStyle = function () {}; { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; var msPattern$1 = /^-ms-/; var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnedForInfinityValue = false; var camelize = function (string) { return string.replace(hyphenPattern, function (_, character) { return character.toUpperCase(); }); }; var warnHyphenatedStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix // is converted to lowercase `ms`. camelize(name.replace(msPattern$1, 'ms-'))); }; var warnBadVendoredStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)); }; var warnStyleValueWithSemicolon = function (name, value) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')); }; var warnStyleValueIsNaN = function (name, value) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; error('`NaN` is an invalid value for the `%s` css style property.', name); }; var warnStyleValueIsInfinity = function (name, value) { if (warnedForInfinityValue) { return; } warnedForInfinityValue = true; error('`Infinity` is an invalid value for the `%s` css style property.', name); }; warnValidStyle = function (name, value) { if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value); } if (typeof value === 'number') { if (isNaN(value)) { warnStyleValueIsNaN(name, value); } else if (!isFinite(value)) { warnStyleValueIsInfinity(name, value); } } }; } var warnValidStyle$1 = warnValidStyle; /** * Operations for dealing with CSS properties. */ /** * This creates a string that is expected to be equivalent to the style * attribute generated by server-side rendering. It by-passes warnings and * security checks so it's not safe to use this value for anything other than * comparison. It is only used in DEV for SSR validation. */ function createDangerousStringForStyles(styles) { { var serialized = ''; var delimiter = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (styleValue != null) { var isCustomProperty = styleName.indexOf('--') === 0; serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':'; serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty); delimiter = ';'; } } return serialized || null; } } /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles */ function setValueForStyles(node, styles) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var isCustomProperty = styleName.indexOf('--') === 0; { if (!isCustomProperty) { warnValidStyle$1(styleName, styles[styleName]); } } var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty); if (styleName === 'float') { styleName = 'cssFloat'; } if (isCustomProperty) { style.setProperty(styleName, styleValue); } else { style[styleName] = styleValue; } } } function isValueEmpty(value) { return value == null || typeof value === 'boolean' || value === ''; } /** * Given {color: 'red', overflow: 'hidden'} returns { * color: 'color', * overflowX: 'overflow', * overflowY: 'overflow', * }. This can be read as "the overflowY property was set by the overflow * shorthand". That is, the values are the property that each was derived from. */ function expandShorthandMap(styles) { var expanded = {}; for (var key in styles) { var longhands = shorthandToLonghand[key] || [key]; for (var i = 0; i < longhands.length; i++) { expanded[longhands[i]] = key; } } return expanded; } /** * When mixing shorthand and longhand property names, we warn during updates if * we expect an incorrect result to occur. In particular, we warn for: * * Updating a shorthand property (longhand gets overwritten): * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'} * becomes .style.font = 'baz' * Removing a shorthand property (longhand gets lost too): * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'} * becomes .style.font = '' * Removing a longhand property (should revert to shorthand; doesn't): * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'} * becomes .style.fontVariant = '' */ function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) { { if (!nextStyles) { return; } var expandedUpdates = expandShorthandMap(styleUpdates); var expandedStyles = expandShorthandMap(nextStyles); var warnedAbout = {}; for (var key in expandedUpdates) { var originalKey = expandedUpdates[key]; var correctOriginalKey = expandedStyles[key]; if (correctOriginalKey && originalKey !== correctOriginalKey) { var warningKey = originalKey + ',' + correctOriginalKey; if (warnedAbout[warningKey]) { continue; } warnedAbout[warningKey] = true; error('%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + "avoid this, don't mix shorthand and non-shorthand properties " + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey); } } } } // For HTML, certain tags should omit their close tag. We keep a list for // those special-case tags. var omittedCloseTags = { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems. }; // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = assign({ menuitem: true }, omittedCloseTags); var HTML = '__html'; function assertValidProps(tag, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[tag]) { if (props.children != null || props.dangerouslySetInnerHTML != null) { throw new Error(tag + " is a void element tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.'); } } if (props.dangerouslySetInnerHTML != null) { if (props.children != null) { throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.'); } if (typeof props.dangerouslySetInnerHTML !== 'object' || !(HTML in props.dangerouslySetInnerHTML)) { throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.'); } } { if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) { error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.'); } } if (props.style != null && typeof props.style !== 'object') { throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.'); } } function isCustomComponent(tagName, props) { if (tagName.indexOf('-') === -1) { return typeof props.is === 'string'; } switch (tagName) { // These are reserved SVG and MathML elements. // We don't mind this list too much because we expect it to never grow. // The alternative is to track the namespace in a few places which is convoluted. // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts case 'annotation-xml': case 'color-profile': case 'font-face': case 'font-face-src': case 'font-face-uri': case 'font-face-format': case 'font-face-name': case 'missing-glyph': return false; default: return true; } } // When adding attributes to the HTML or SVG allowed attribute list, be sure to // also add them to this module to ensure casing and incorrect name // warnings. var possibleStandardNames = { // HTML accept: 'accept', acceptcharset: 'acceptCharset', 'accept-charset': 'acceptCharset', accesskey: 'accessKey', action: 'action', allowfullscreen: 'allowFullScreen', alt: 'alt', as: 'as', async: 'async', autocapitalize: 'autoCapitalize', autocomplete: 'autoComplete', autocorrect: 'autoCorrect', autofocus: 'autoFocus', autoplay: 'autoPlay', autosave: 'autoSave', capture: 'capture', cellpadding: 'cellPadding', cellspacing: 'cellSpacing', challenge: 'challenge', charset: 'charSet', checked: 'checked', children: 'children', cite: 'cite', class: 'className', classid: 'classID', classname: 'className', cols: 'cols', colspan: 'colSpan', content: 'content', contenteditable: 'contentEditable', contextmenu: 'contextMenu', controls: 'controls', controlslist: 'controlsList', coords: 'coords', crossorigin: 'crossOrigin', dangerouslysetinnerhtml: 'dangerouslySetInnerHTML', data: 'data', datetime: 'dateTime', default: 'default', defaultchecked: 'defaultChecked', defaultvalue: 'defaultValue', defer: 'defer', dir: 'dir', disabled: 'disabled', disablepictureinpicture: 'disablePictureInPicture', disableremoteplayback: 'disableRemotePlayback', download: 'download', draggable: 'draggable', enctype: 'encType', enterkeyhint: 'enterKeyHint', for: 'htmlFor', form: 'form', formmethod: 'formMethod', formaction: 'formAction', formenctype: 'formEncType', formnovalidate: 'formNoValidate', formtarget: 'formTarget', frameborder: 'frameBorder', headers: 'headers', height: 'height', hidden: 'hidden', high: 'high', href: 'href', hreflang: 'hrefLang', htmlfor: 'htmlFor', httpequiv: 'httpEquiv', 'http-equiv': 'httpEquiv', icon: 'icon', id: 'id', imagesizes: 'imageSizes', imagesrcset: 'imageSrcSet', innerhtml: 'innerHTML', inputmode: 'inputMode', integrity: 'integrity', is: 'is', itemid: 'itemID', itemprop: 'itemProp', itemref: 'itemRef', itemscope: 'itemScope', itemtype: 'itemType', keyparams: 'keyParams', keytype: 'keyType', kind: 'kind', label: 'label', lang: 'lang', list: 'list', loop: 'loop', low: 'low', manifest: 'manifest', marginwidth: 'marginWidth', marginheight: 'marginHeight', max: 'max', maxlength: 'maxLength', media: 'media', mediagroup: 'mediaGroup', method: 'method', min: 'min', minlength: 'minLength', multiple: 'multiple', muted: 'muted', name: 'name', nomodule: 'noModule', nonce: 'nonce', novalidate: 'noValidate', open: 'open', optimum: 'optimum', pattern: 'pattern', placeholder: 'placeholder', playsinline: 'playsInline', poster: 'poster', preload: 'preload', profile: 'profile', radiogroup: 'radioGroup', readonly: 'readOnly', referrerpolicy: 'referrerPolicy', rel: 'rel', required: 'required', reversed: 'reversed', role: 'role', rows: 'rows', rowspan: 'rowSpan', sandbox: 'sandbox', scope: 'scope', scoped: 'scoped', scrolling: 'scrolling', seamless: 'seamless', selected: 'selected', shape: 'shape', size: 'size', sizes: 'sizes', span: 'span', spellcheck: 'spellCheck', src: 'src', srcdoc: 'srcDoc', srclang: 'srcLang', srcset: 'srcSet', start: 'start', step: 'step', style: 'style', summary: 'summary', tabindex: 'tabIndex', target: 'target', title: 'title', type: 'type', usemap: 'useMap', value: 'value', width: 'width', wmode: 'wmode', wrap: 'wrap', // SVG about: 'about', accentheight: 'accentHeight', 'accent-height': 'accentHeight', accumulate: 'accumulate', additive: 'additive', alignmentbaseline: 'alignmentBaseline', 'alignment-baseline': 'alignmentBaseline', allowreorder: 'allowReorder', alphabetic: 'alphabetic', amplitude: 'amplitude', arabicform: 'arabicForm', 'arabic-form': 'arabicForm', ascent: 'ascent', attributename: 'attributeName', attributetype: 'attributeType', autoreverse: 'autoReverse', azimuth: 'azimuth', basefrequency: 'baseFrequency', baselineshift: 'baselineShift', 'baseline-shift': 'baselineShift', baseprofile: 'baseProfile', bbox: 'bbox', begin: 'begin', bias: 'bias', by: 'by', calcmode: 'calcMode', capheight: 'capHeight', 'cap-height': 'capHeight', clip: 'clip', clippath: 'clipPath', 'clip-path': 'clipPath', clippathunits: 'clipPathUnits', cliprule: 'clipRule', 'clip-rule': 'clipRule', color: 'color', colorinterpolation: 'colorInterpolation', 'color-interpolation': 'colorInterpolation', colorinterpolationfilters: 'colorInterpolationFilters', 'color-interpolation-filters': 'colorInterpolationFilters', colorprofile: 'colorProfile', 'color-profile': 'colorProfile', colorrendering: 'colorRendering', 'color-rendering': 'colorRendering', contentscripttype: 'contentScriptType', contentstyletype: 'contentStyleType', cursor: 'cursor', cx: 'cx', cy: 'cy', d: 'd', datatype: 'datatype', decelerate: 'decelerate', descent: 'descent', diffuseconstant: 'diffuseConstant', direction: 'direction', display: 'display', divisor: 'divisor', dominantbaseline: 'dominantBaseline', 'dominant-baseline': 'dominantBaseline', dur: 'dur', dx: 'dx', dy: 'dy', edgemode: 'edgeMode', elevation: 'elevation', enablebackground: 'enableBackground', 'enable-background': 'enableBackground', end: 'end', exponent: 'exponent', externalresourcesrequired: 'externalResourcesRequired', fill: 'fill', fillopacity: 'fillOpacity', 'fill-opacity': 'fillOpacity', fillrule: 'fillRule', 'fill-rule': 'fillRule', filter: 'filter', filterres: 'filterRes', filterunits: 'filterUnits', floodopacity: 'floodOpacity', 'flood-opacity': 'floodOpacity', floodcolor: 'floodColor', 'flood-color': 'floodColor', focusable: 'focusable', fontfamily: 'fontFamily', 'font-family': 'fontFamily', fontsize: 'fontSize', 'font-size': 'fontSize', fontsizeadjust: 'fontSizeAdjust', 'font-size-adjust': 'fontSizeAdjust', fontstretch: 'fontStretch', 'font-stretch': 'fontStretch', fontstyle: 'fontStyle', 'font-style': 'fontStyle', fontvariant: 'fontVariant', 'font-variant': 'fontVariant', fontweight: 'fontWeight', 'font-weight': 'fontWeight', format: 'format', from: 'from', fx: 'fx', fy: 'fy', g1: 'g1', g2: 'g2', glyphname: 'glyphName', 'glyph-name': 'glyphName', glyphorientationhorizontal: 'glyphOrientationHorizontal', 'glyph-orientation-horizontal': 'glyphOrientationHorizontal', glyphorientationvertical: 'glyphOrientationVertical', 'glyph-orientation-vertical': 'glyphOrientationVertical', glyphref: 'glyphRef', gradienttransform: 'gradientTransform', gradientunits: 'gradientUnits', hanging: 'hanging', horizadvx: 'horizAdvX', 'horiz-adv-x': 'horizAdvX', horizoriginx: 'horizOriginX', 'horiz-origin-x': 'horizOriginX', ideographic: 'ideographic', imagerendering: 'imageRendering', 'image-rendering': 'imageRendering', in2: 'in2', in: 'in', inlist: 'inlist', intercept: 'intercept', k1: 'k1', k2: 'k2', k3: 'k3', k4: 'k4', k: 'k', kernelmatrix: 'kernelMatrix', kernelunitlength: 'kernelUnitLength', kerning: 'kerning', keypoints: 'keyPoints', keysplines: 'keySplines', keytimes: 'keyTimes', lengthadjust: 'lengthAdjust', letterspacing: 'letterSpacing', 'letter-spacing': 'letterSpacing', lightingcolor: 'lightingColor', 'lighting-color': 'lightingColor', limitingconeangle: 'limitingConeAngle', local: 'local', markerend: 'markerEnd', 'marker-end': 'markerEnd', markerheight: 'markerHeight', markermid: 'markerMid', 'marker-mid': 'markerMid', markerstart: 'markerStart', 'marker-start': 'markerStart', markerunits: 'markerUnits', markerwidth: 'markerWidth', mask: 'mask', maskcontentunits: 'maskContentUnits', maskunits: 'maskUnits', mathematical: 'mathematical', mode: 'mode', numoctaves: 'numOctaves', offset: 'offset', opacity: 'opacity', operator: 'operator', order: 'order', orient: 'orient', orientation: 'orientation', origin: 'origin', overflow: 'overflow', overlineposition: 'overlinePosition', 'overline-position': 'overlinePosition', overlinethickness: 'overlineThickness', 'overline-thickness': 'overlineThickness', paintorder: 'paintOrder', 'paint-order': 'paintOrder', panose1: 'panose1', 'panose-1': 'panose1', pathlength: 'pathLength', patterncontentunits: 'patternContentUnits', patterntransform: 'patternTransform', patternunits: 'patternUnits', pointerevents: 'pointerEvents', 'pointer-events': 'pointerEvents', points: 'points', pointsatx: 'pointsAtX', pointsaty: 'pointsAtY', pointsatz: 'pointsAtZ', prefix: 'prefix', preservealpha: 'preserveAlpha', preserveaspectratio: 'preserveAspectRatio', primitiveunits: 'primitiveUnits', property: 'property', r: 'r', radius: 'radius', refx: 'refX', refy: 'refY', renderingintent: 'renderingIntent', 'rendering-intent': 'renderingIntent', repeatcount: 'repeatCount', repeatdur: 'repeatDur', requiredextensions: 'requiredExtensions', requiredfeatures: 'requiredFeatures', resource: 'resource', restart: 'restart', result: 'result', results: 'results', rotate: 'rotate', rx: 'rx', ry: 'ry', scale: 'scale', security: 'security', seed: 'seed', shaperendering: 'shapeRendering', 'shape-rendering': 'shapeRendering', slope: 'slope', spacing: 'spacing', specularconstant: 'specularConstant', specularexponent: 'specularExponent', speed: 'speed', spreadmethod: 'spreadMethod', startoffset: 'startOffset', stddeviation: 'stdDeviation', stemh: 'stemh', stemv: 'stemv', stitchtiles: 'stitchTiles', stopcolor: 'stopColor', 'stop-color': 'stopColor', stopopacity: 'stopOpacity', 'stop-opacity': 'stopOpacity', strikethroughposition: 'strikethroughPosition', 'strikethrough-position': 'strikethroughPosition', strikethroughthickness: 'strikethroughThickness', 'strikethrough-thickness': 'strikethroughThickness', string: 'string', stroke: 'stroke', strokedasharray: 'strokeDasharray', 'stroke-dasharray': 'strokeDasharray', strokedashoffset: 'strokeDashoffset', 'stroke-dashoffset': 'strokeDashoffset', strokelinecap: 'strokeLinecap', 'stroke-linecap': 'strokeLinecap', strokelinejoin: 'strokeLinejoin', 'stroke-linejoin': 'strokeLinejoin', strokemiterlimit: 'strokeMiterlimit', 'stroke-miterlimit': 'strokeMiterlimit', strokewidth: 'strokeWidth', 'stroke-width': 'strokeWidth', strokeopacity: 'strokeOpacity', 'stroke-opacity': 'strokeOpacity', suppresscontenteditablewarning: 'suppressContentEditableWarning', suppresshydrationwarning: 'suppressHydrationWarning', surfacescale: 'surfaceScale', systemlanguage: 'systemLanguage', tablevalues: 'tableValues', targetx: 'targetX', targety: 'targetY', textanchor: 'textAnchor', 'text-anchor': 'textAnchor', textdecoration: 'textDecoration', 'text-decoration': 'textDecoration', textlength: 'textLength', textrendering: 'textRendering', 'text-rendering': 'textRendering', to: 'to', transform: 'transform', typeof: 'typeof', u1: 'u1', u2: 'u2', underlineposition: 'underlinePosition', 'underline-position': 'underlinePosition', underlinethickness: 'underlineThickness', 'underline-thickness': 'underlineThickness', unicode: 'unicode', unicodebidi: 'unicodeBidi', 'unicode-bidi': 'unicodeBidi', unicoderange: 'unicodeRange', 'unicode-range': 'unicodeRange', unitsperem: 'unitsPerEm', 'units-per-em': 'unitsPerEm', unselectable: 'unselectable', valphabetic: 'vAlphabetic', 'v-alphabetic': 'vAlphabetic', values: 'values', vectoreffect: 'vectorEffect', 'vector-effect': 'vectorEffect', version: 'version', vertadvy: 'vertAdvY', 'vert-adv-y': 'vertAdvY', vertoriginx: 'vertOriginX', 'vert-origin-x': 'vertOriginX', vertoriginy: 'vertOriginY', 'vert-origin-y': 'vertOriginY', vhanging: 'vHanging', 'v-hanging': 'vHanging', videographic: 'vIdeographic', 'v-ideographic': 'vIdeographic', viewbox: 'viewBox', viewtarget: 'viewTarget', visibility: 'visibility', vmathematical: 'vMathematical', 'v-mathematical': 'vMathematical', vocab: 'vocab', widths: 'widths', wordspacing: 'wordSpacing', 'word-spacing': 'wordSpacing', writingmode: 'writingMode', 'writing-mode': 'writingMode', x1: 'x1', x2: 'x2', x: 'x', xchannelselector: 'xChannelSelector', xheight: 'xHeight', 'x-height': 'xHeight', xlinkactuate: 'xlinkActuate', 'xlink:actuate': 'xlinkActuate', xlinkarcrole: 'xlinkArcrole', 'xlink:arcrole': 'xlinkArcrole', xlinkhref: 'xlinkHref', 'xlink:href': 'xlinkHref', xlinkrole: 'xlinkRole', 'xlink:role': 'xlinkRole', xlinkshow: 'xlinkShow', 'xlink:show': 'xlinkShow', xlinktitle: 'xlinkTitle', 'xlink:title': 'xlinkTitle', xlinktype: 'xlinkType', 'xlink:type': 'xlinkType', xmlbase: 'xmlBase', 'xml:base': 'xmlBase', xmllang: 'xmlLang', 'xml:lang': 'xmlLang', xmlns: 'xmlns', 'xml:space': 'xmlSpace', xmlnsxlink: 'xmlnsXlink', 'xmlns:xlink': 'xmlnsXlink', xmlspace: 'xmlSpace', y1: 'y1', y2: 'y2', y: 'y', ychannelselector: 'yChannelSelector', z: 'z', zoomandpan: 'zoomAndPan' }; var ariaProperties = { 'aria-current': 0, // state 'aria-description': 0, 'aria-details': 0, 'aria-disabled': 0, // state 'aria-hidden': 0, // state 'aria-invalid': 0, // state 'aria-keyshortcuts': 0, 'aria-label': 0, 'aria-roledescription': 0, // Widget Attributes 'aria-autocomplete': 0, 'aria-checked': 0, 'aria-expanded': 0, 'aria-haspopup': 0, 'aria-level': 0, 'aria-modal': 0, 'aria-multiline': 0, 'aria-multiselectable': 0, 'aria-orientation': 0, 'aria-placeholder': 0, 'aria-pressed': 0, 'aria-readonly': 0, 'aria-required': 0, 'aria-selected': 0, 'aria-sort': 0, 'aria-valuemax': 0, 'aria-valuemin': 0, 'aria-valuenow': 0, 'aria-valuetext': 0, // Live Region Attributes 'aria-atomic': 0, 'aria-busy': 0, 'aria-live': 0, 'aria-relevant': 0, // Drag-and-Drop Attributes 'aria-dropeffect': 0, 'aria-grabbed': 0, // Relationship Attributes 'aria-activedescendant': 0, 'aria-colcount': 0, 'aria-colindex': 0, 'aria-colspan': 0, 'aria-controls': 0, 'aria-describedby': 0, 'aria-errormessage': 0, 'aria-flowto': 0, 'aria-labelledby': 0, 'aria-owns': 0, 'aria-posinset': 0, 'aria-rowcount': 0, 'aria-rowindex': 0, 'aria-rowspan': 0, 'aria-setsize': 0 }; var warnedProperties = {}; var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); function validateProperty(tagName, name) { { if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) { return true; } if (rARIACamel.test(name)) { var ariaName = 'aria-' + name.slice(4).toLowerCase(); var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM // DOM properties, then it is an invalid aria-* attribute. if (correctName == null) { error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name); warnedProperties[name] = true; return true; } // aria-* attributes should be lowercase; suggest the lowercase version. if (name !== correctName) { error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName); warnedProperties[name] = true; return true; } } if (rARIA.test(name)) { var lowerCasedName = name.toLowerCase(); var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM // DOM properties, then it is an invalid aria-* attribute. if (standardName == null) { warnedProperties[name] = true; return false; } // aria-* attributes should be lowercase; suggest the lowercase version. if (name !== standardName) { error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName); warnedProperties[name] = true; return true; } } } return true; } function warnInvalidARIAProps(type, props) { { var invalidProps = []; for (var key in props) { var isValid = validateProperty(type, key); if (!isValid) { invalidProps.push(key); } } var unknownPropString = invalidProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (invalidProps.length === 1) { error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); } else if (invalidProps.length > 1) { error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); } } } function validateProperties(type, props) { if (isCustomComponent(type, props)) { return; } warnInvalidARIAProps(type, props); } var didWarnValueNull = false; function validateProperties$1(type, props) { { if (type !== 'input' && type !== 'textarea' && type !== 'select') { return; } if (props != null && props.value === null && !didWarnValueNull) { didWarnValueNull = true; if (type === 'select' && props.multiple) { error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type); } else { error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type); } } } } var validateProperty$1 = function () {}; { var warnedProperties$1 = {}; var EVENT_NAME_REGEX = /^on./; var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/; var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); validateProperty$1 = function (tagName, name, value, eventRegistry) { if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) { return true; } var lowerCasedName = name.toLowerCase(); if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') { error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.'); warnedProperties$1[name] = true; return true; } // We can't rely on the event system being injected on the server. if (eventRegistry != null) { var registrationNameDependencies = eventRegistry.registrationNameDependencies, possibleRegistrationNames = eventRegistry.possibleRegistrationNames; if (registrationNameDependencies.hasOwnProperty(name)) { return true; } var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null; if (registrationName != null) { error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName); warnedProperties$1[name] = true; return true; } if (EVENT_NAME_REGEX.test(name)) { error('Unknown event handler property `%s`. It will be ignored.', name); warnedProperties$1[name] = true; return true; } } else if (EVENT_NAME_REGEX.test(name)) { // If no event plugins have been injected, we are in a server environment. // So we can't tell if the event name is correct for sure, but we can filter // out known bad ones like `onclick`. We can't suggest a specific replacement though. if (INVALID_EVENT_NAME_REGEX.test(name)) { error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name); } warnedProperties$1[name] = true; return true; } // Let the ARIA attribute hook validate ARIA attributes if (rARIA$1.test(name) || rARIACamel$1.test(name)) { return true; } if (lowerCasedName === 'innerhtml') { error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'); warnedProperties$1[name] = true; return true; } if (lowerCasedName === 'aria') { error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.'); warnedProperties$1[name] = true; return true; } if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') { error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value); warnedProperties$1[name] = true; return true; } if (typeof value === 'number' && isNaN(value)) { error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name); warnedProperties$1[name] = true; return true; } var propertyInfo = getPropertyInfo(name); var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config. if (possibleStandardNames.hasOwnProperty(lowerCasedName)) { var standardName = possibleStandardNames[lowerCasedName]; if (standardName !== name) { error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName); warnedProperties$1[name] = true; return true; } } else if (!isReserved && name !== lowerCasedName) { // Unknown attributes should have lowercase casing since that's how they // will be cased anyway with server rendering. error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName); warnedProperties$1[name] = true; return true; } if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { if (value) { error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name); } else { error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name); } warnedProperties$1[name] = true; return true; } // Now that we've validated casing, do not validate // data types for reserved props if (isReserved) { return true; } // Warn when a known attribute is a bad type if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { warnedProperties$1[name] = true; return false; } // Warn when passing the strings 'false' or 'true' into a boolean prop if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) { error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value); warnedProperties$1[name] = true; return true; } return true; }; } var warnUnknownProperties = function (type, props, eventRegistry) { { var unknownProps = []; for (var key in props) { var isValid = validateProperty$1(type, key, props[key], eventRegistry); if (!isValid) { unknownProps.push(key); } } var unknownPropString = unknownProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (unknownProps.length === 1) { error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); } else if (unknownProps.length > 1) { error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); } } }; function validateProperties$2(type, props, eventRegistry) { if (isCustomComponent(type, props)) { return; } warnUnknownProperties(type, props, eventRegistry); } var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1; var IS_NON_DELEGATED = 1 << 1; var IS_CAPTURE_PHASE = 1 << 2; // set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when // we call willDeferLaterForLegacyFBSupport, thus not bailing out // will result in endless cycles like an infinite loop. // We also don't want to defer during event replaying. var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE; // This exists to avoid circular dependency between ReactDOMEventReplaying // and DOMPluginEventSystem. var currentReplayingEvent = null; function setReplayingEvent(event) { { if (currentReplayingEvent !== null) { error('Expected currently replaying event to be null. This error ' + 'is likely caused by a bug in React. Please file an issue.'); } } currentReplayingEvent = event; } function resetReplayingEvent() { { if (currentReplayingEvent === null) { error('Expected currently replaying event to not be null. This error ' + 'is likely caused by a bug in React. Please file an issue.'); } } currentReplayingEvent = null; } function isReplayingEvent(event) { return event === currentReplayingEvent; } /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { // Fallback to nativeEvent.srcElement for IE9 // https://github.com/facebook/react/issues/12506 var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === TEXT_NODE ? target.parentNode : target; } var restoreImpl = null; var restoreTarget = null; var restoreQueue = null; function restoreStateOfTarget(target) { // We perform this translation at the end of the event loop so that we // always receive the correct fiber here var internalInstance = getInstanceFromNode(target); if (!internalInstance) { // Unmounted return; } if (typeof restoreImpl !== 'function') { throw new Error('setRestoreImplementation() needs to be called to handle a target for controlled ' + 'events. This error is likely caused by a bug in React. Please file an issue.'); } var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted. if (stateNode) { var _props = getFiberCurrentPropsFromNode(stateNode); restoreImpl(internalInstance.stateNode, internalInstance.type, _props); } } function setRestoreImplementation(impl) { restoreImpl = impl; } function enqueueStateRestore(target) { if (restoreTarget) { if (restoreQueue) { restoreQueue.push(target); } else { restoreQueue = [target]; } } else { restoreTarget = target; } } function needsStateRestore() { return restoreTarget !== null || restoreQueue !== null; } function restoreStateIfNeeded() { if (!restoreTarget) { return; } var target = restoreTarget; var queuedTargets = restoreQueue; restoreTarget = null; restoreQueue = null; restoreStateOfTarget(target); if (queuedTargets) { for (var i = 0; i < queuedTargets.length; i++) { restoreStateOfTarget(queuedTargets[i]); } } } // the renderer. Such as when we're dispatching events or if third party // libraries need to call batchedUpdates. Eventually, this API will go away when // everything is batched by default. We'll then have a similar API to opt-out of // scheduled work and instead do synchronous work. // Defaults var batchedUpdatesImpl = function (fn, bookkeeping) { return fn(bookkeeping); }; var flushSyncImpl = function () {}; var isInsideEventHandler = false; function finishEventHandler() { // Here we wait until all updates have propagated, which is important // when using controlled components within layers: // https://github.com/facebook/react/issues/1698 // Then we restore state of any controlled component. var controlledComponentsHavePendingUpdates = needsStateRestore(); if (controlledComponentsHavePendingUpdates) { // If a controlled event was fired, we may need to restore the state of // the DOM node back to the controlled value. This is necessary when React // bails out of the update without touching the DOM. // TODO: Restore state in the microtask, after the discrete updates flush, // instead of early flushing them here. flushSyncImpl(); restoreStateIfNeeded(); } } function batchedUpdates(fn, a, b) { if (isInsideEventHandler) { // If we are currently inside another batch, we need to wait until it // fully completes before restoring state. return fn(a, b); } isInsideEventHandler = true; try { return batchedUpdatesImpl(fn, a, b); } finally { isInsideEventHandler = false; finishEventHandler(); } } // TODO: Replace with flushSync function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushSyncImpl) { batchedUpdatesImpl = _batchedUpdatesImpl; flushSyncImpl = _flushSyncImpl; } function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } function shouldPreventMouseEvent(name, type, props) { switch (name) { case 'onClick': case 'onClickCapture': case 'onDoubleClick': case 'onDoubleClickCapture': case 'onMouseDown': case 'onMouseDownCapture': case 'onMouseMove': case 'onMouseMoveCapture': case 'onMouseUp': case 'onMouseUpCapture': case 'onMouseEnter': return !!(props.disabled && isInteractive(type)); default: return false; } } /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ function getListener(inst, registrationName) { var stateNode = inst.stateNode; if (stateNode === null) { // Work in progress (ex: onload events in incremental mode). return null; } var props = getFiberCurrentPropsFromNode(stateNode); if (props === null) { // Work in progress. return null; } var listener = props[registrationName]; if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } if (listener && typeof listener !== 'function') { throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type."); } return listener; } var passiveBrowserEventsSupported = false; // Check if browser support events with passive listeners // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support if (canUseDOM) { try { var options = {}; // $FlowFixMe: Ignore Flow complaining about needing a value Object.defineProperty(options, 'passive', { get: function () { passiveBrowserEventsSupported = true; } }); window.addEventListener('test', options, options); window.removeEventListener('test', options, options); } catch (e) { passiveBrowserEventsSupported = false; } } function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) { var funcArgs = Array.prototype.slice.call(arguments, 3); try { func.apply(context, funcArgs); } catch (error) { this.onError(error); } } var invokeGuardedCallbackImpl = invokeGuardedCallbackProd; { // In DEV mode, we swap out invokeGuardedCallback for a special version // that plays more nicely with the browser's DevTools. The idea is to preserve // "Pause on exceptions" behavior. Because React wraps all user-provided // functions in invokeGuardedCallback, and the production version of // invokeGuardedCallback uses a try-catch, all user exceptions are treated // like caught exceptions, and the DevTools won't pause unless the developer // takes the extra step of enabling pause on caught exceptions. This is // unintuitive, though, because even though React has caught the error, from // the developer's perspective, the error is uncaught. // // To preserve the expected "Pause on exceptions" behavior, we don't use a // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake // DOM node, and call the user-provided callback from inside an event handler // for that fake event. If the callback throws, the error is "captured" using // a global event handler. But because the error happens in a different // event loop context, it does not interrupt the normal program flow. // Effectively, this gives us try-catch behavior without actually using // try-catch. Neat! // Check that the browser supports the APIs we need to implement our special // DEV version of invokeGuardedCallback if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) { // If document doesn't exist we know for sure we will crash in this method // when we call document.createEvent(). However this can cause confusing // errors: https://github.com/facebook/create-react-app/issues/3482 // So we preemptively throw with a better message instead. if (typeof document === 'undefined' || document === null) { throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.'); } var evt = document.createEvent('Event'); var didCall = false; // Keeps track of whether the user-provided callback threw an error. We // set this to true at the beginning, then set it to false right after // calling the function. If the function errors, `didError` will never be // set to false. This strategy works even if the browser is flaky and // fails to call our global error handler, because it doesn't rely on // the error event at all. var didError = true; // Keeps track of the value of window.event so that we can reset it // during the callback to let user code access window.event in the // browsers that support it. var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event // dispatching: https://github.com/facebook/react/issues/13688 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); function restoreAfterDispatch() { // We immediately remove the callback from event listeners so that // nested `invokeGuardedCallback` calls do not clash. Otherwise, a // nested call would trigger the fake event handlers of any call higher // in the stack. fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the // window.event assignment in both IE <= 10 as they throw an error // "Member not found" in strict mode, and in Firefox which does not // support window.event. if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) { window.event = windowEvent; } } // Create an event handler for our fake event. We will synchronously // dispatch our fake event using `dispatchEvent`. Inside the handler, we // call the user-provided callback. var funcArgs = Array.prototype.slice.call(arguments, 3); function callCallback() { didCall = true; restoreAfterDispatch(); func.apply(context, funcArgs); didError = false; } // Create a global error event handler. We use this to capture the value // that was thrown. It's possible that this error handler will fire more // than once; for example, if non-React code also calls `dispatchEvent` // and a handler for that event throws. We should be resilient to most of // those cases. Even if our error event handler fires more than once, the // last error event is always used. If the callback actually does error, // we know that the last error event is the correct one, because it's not // possible for anything else to have happened in between our callback // erroring and the code that follows the `dispatchEvent` call below. If // the callback doesn't error, but the error event was fired, we know to // ignore it because `didError` will be false, as described above. var error; // Use this to track whether the error event is ever called. var didSetError = false; var isCrossOriginError = false; function handleWindowError(event) { error = event.error; didSetError = true; if (error === null && event.colno === 0 && event.lineno === 0) { isCrossOriginError = true; } if (event.defaultPrevented) { // Some other error handler has prevented default. // Browsers silence the error report if this happens. // We'll remember this to later decide whether to log it or not. if (error != null && typeof error === 'object') { try { error._suppressLogging = true; } catch (inner) {// Ignore. } } } } // Create a fake event type. var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers window.addEventListener('error', handleWindowError); fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function // errors, it will trigger our global error handler. evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); if (windowEventDescriptor) { Object.defineProperty(window, 'event', windowEventDescriptor); } if (didCall && didError) { if (!didSetError) { // The callback errored, but the error event never fired. // eslint-disable-next-line react-internal/prod-error-codes error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); } else if (isCrossOriginError) { // eslint-disable-next-line react-internal/prod-error-codes error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.'); } this.onError(error); } // Remove our event listeners window.removeEventListener('error', handleWindowError); if (!didCall) { // Something went really wrong, and our event was not dispatched. // https://github.com/facebook/react/issues/16734 // https://github.com/facebook/react/issues/16585 // Fall back to the production implementation. restoreAfterDispatch(); return invokeGuardedCallbackProd.apply(this, arguments); } }; } } var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; var hasError = false; var caughtError = null; // Used by event system to capture/rethrow the first error. var hasRethrowError = false; var rethrowError = null; var reporter = { onError: function (error) { hasError = true; caughtError = error; } }; /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. * * In production, this is implemented using a try-catch. The reason we don't * use a try-catch directly is so that we can swap out a different * implementation in DEV mode. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { hasError = false; caughtError = null; invokeGuardedCallbackImpl$1.apply(reporter, arguments); } /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. * TODO: See if caughtError and rethrowError can be unified. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) { invokeGuardedCallback.apply(this, arguments); if (hasError) { var error = clearCaughtError(); if (!hasRethrowError) { hasRethrowError = true; rethrowError = error; } } } /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ function rethrowCaughtError() { if (hasRethrowError) { var error = rethrowError; hasRethrowError = false; rethrowError = null; throw error; } } function hasCaughtError() { return hasError; } function clearCaughtError() { if (hasError) { var error = caughtError; hasError = false; caughtError = null; return error; } else { throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.'); } } var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; var _ReactInternals$Sched = ReactInternals.Scheduler, unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback, unstable_now = _ReactInternals$Sched.unstable_now, unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback, unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield, unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint, unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode, unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority, unstable_next = _ReactInternals$Sched.unstable_next, unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution, unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution, unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel, unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority, unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority, unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority, unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority, unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority, unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate, unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting, unstable_yieldValue = _ReactInternals$Sched.unstable_yieldValue, unstable_setDisableYieldValue = _ReactInternals$Sched.unstable_setDisableYieldValue; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. * * Note that this module is currently shared and assumed to be stateless. * If this becomes an actual Map, that will break. */ function get(key) { return key._reactInternals; } function has(key) { return key._reactInternals !== undefined; } function set(key, value) { key._reactInternals = value; } // Don't change these two values. They're used by React Dev Tools. var NoFlags = /* */ 0; var PerformedWork = /* */ 1; // You can change the rest (and add more). var Placement = /* */ 2; var Update = /* */ 4; var ChildDeletion = /* */ 16; var ContentReset = /* */ 32; var Callback = /* */ 64; var DidCapture = /* */ 128; var ForceClientRender = /* */ 256; var Ref = /* */ 512; var Snapshot = /* */ 1024; var Passive = /* */ 2048; var Hydrating = /* */ 4096; var Visibility = /* */ 8192; var StoreConsistency = /* */ 16384; var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit) var HostEffectMask = /* */ 32767; // These are not really side effects, but we still reuse this field. var Incomplete = /* */ 32768; var ShouldCapture = /* */ 65536; var ForceUpdateForLegacySuspense = /* */ 131072; var Forked = /* */ 1048576; // Static tags describe aspects of a fiber that are not specific to a render, // e.g. a fiber uses a passive effect (even if there are no updates on this particular render). // This enables us to defer more work in the unmount case, // since we can defer traversing the tree during layout to look for Passive effects, // and instead rely on the static flag as a signal that there may be cleanup work. var RefStatic = /* */ 2097152; var LayoutStatic = /* */ 4194304; var PassiveStatic = /* */ 8388608; // These flags allow us to traverse to fibers that have effects on mount // without traversing the entire tree after every commit for // double invoking var MountLayoutDev = /* */ 16777216; var MountPassiveDev = /* */ 33554432; // Groups of flags that are used in the commit phase to skip over trees that // don't contain effects, by checking subtreeFlags. var BeforeMutationMask = // TODO: Remove Update flag from before mutation phase by re-landing Visibility // flag logic (see #20043) Update | Snapshot | ( 0); var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility; var LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask var PassiveMask = Passive | ChildDeletion; // Union of tags that don't get reset on clones. // This allows certain concepts to persist without recalculating them, // e.g. whether a subtree contains passive effects or portals. var StaticMask = LayoutStatic | PassiveStatic | RefStatic; var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; function getNearestMountedFiber(fiber) { var node = fiber; var nearestMounted = fiber; if (!fiber.alternate) { // If there is no alternate, this might be a new tree that isn't inserted // yet. If it is, then it will have a pending insertion effect on it. var nextNode = node; do { node = nextNode; if ((node.flags & (Placement | Hydrating)) !== NoFlags) { // This is an insertion or in-progress hydration. The nearest possible // mounted fiber is the parent but we need to continue to figure out // if that one is still mounted. nearestMounted = node.return; } nextNode = node.return; } while (nextNode); } else { while (node.return) { node = node.return; } } if (node.tag === HostRoot) { // TODO: Check if this was a nested HostRoot when used with // renderContainerIntoSubtree. return nearestMounted; } // If we didn't hit the root, that means that we're in an disconnected tree // that has been unmounted. return null; } function getSuspenseInstanceFromFiber(fiber) { if (fiber.tag === SuspenseComponent) { var suspenseState = fiber.memoizedState; if (suspenseState === null) { var current = fiber.alternate; if (current !== null) { suspenseState = current.memoizedState; } } if (suspenseState !== null) { return suspenseState.dehydrated; } } return null; } function getContainerFromFiber(fiber) { return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null; } function isFiberMounted(fiber) { return getNearestMountedFiber(fiber) === fiber; } function isMounted(component) { { var owner = ReactCurrentOwner.current; if (owner !== null && owner.tag === ClassComponent) { var ownerFiber = owner; var instance = ownerFiber.stateNode; if (!instance._warnedAboutRefsInRender) { error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromFiber(ownerFiber) || 'A component'); } instance._warnedAboutRefsInRender = true; } } var fiber = get(component); if (!fiber) { return false; } return getNearestMountedFiber(fiber) === fiber; } function assertIsMounted(fiber) { if (getNearestMountedFiber(fiber) !== fiber) { throw new Error('Unable to find node on an unmounted component.'); } } function findCurrentFiberUsingSlowPath(fiber) { var alternate = fiber.alternate; if (!alternate) { // If there is no alternate, then we only need to check if it is mounted. var nearestMounted = getNearestMountedFiber(fiber); if (nearestMounted === null) { throw new Error('Unable to find node on an unmounted component.'); } if (nearestMounted !== fiber) { return null; } return fiber; } // If we have two possible branches, we'll walk backwards up to the root // to see what path the root points to. On the way we may hit one of the // special cases and we'll deal with them. var a = fiber; var b = alternate; while (true) { var parentA = a.return; if (parentA === null) { // We're at the root. break; } var parentB = parentA.alternate; if (parentB === null) { // There is no alternate. This is an unusual case. Currently, it only // happens when a Suspense component is hidden. An extra fragment fiber // is inserted in between the Suspense fiber and its children. Skip // over this extra fragment fiber and proceed to the next parent. var nextParent = parentA.return; if (nextParent !== null) { a = b = nextParent; continue; } // If there's no parent, we're at the root. break; } // If both copies of the parent fiber point to the same child, we can // assume that the child is current. This happens when we bailout on low // priority: the bailed out fiber's child reuses the current child. if (parentA.child === parentB.child) { var child = parentA.child; while (child) { if (child === a) { // We've determined that A is the current branch. assertIsMounted(parentA); return fiber; } if (child === b) { // We've determined that B is the current branch. assertIsMounted(parentA); return alternate; } child = child.sibling; } // We should never have an alternate for any mounting node. So the only // way this could possibly happen is if this was unmounted, if at all. throw new Error('Unable to find node on an unmounted component.'); } if (a.return !== b.return) { // The return pointer of A and the return pointer of B point to different // fibers. We assume that return pointers never criss-cross, so A must // belong to the child set of A.return, and B must belong to the child // set of B.return. a = parentA; b = parentB; } else { // The return pointers point to the same fiber. We'll have to use the // default, slow path: scan the child sets of each parent alternate to see // which child belongs to which set. // // Search parent A's child set var didFindChild = false; var _child = parentA.child; while (_child) { if (_child === a) { didFindChild = true; a = parentA; b = parentB; break; } if (_child === b) { didFindChild = true; b = parentA; a = parentB; break; } _child = _child.sibling; } if (!didFindChild) { // Search parent B's child set _child = parentB.child; while (_child) { if (_child === a) { didFindChild = true; a = parentB; b = parentA; break; } if (_child === b) { didFindChild = true; b = parentB; a = parentA; break; } _child = _child.sibling; } if (!didFindChild) { throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.'); } } } if (a.alternate !== b) { throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.'); } } // If the root is not a host container, we're in a disconnected tree. I.e. // unmounted. if (a.tag !== HostRoot) { throw new Error('Unable to find node on an unmounted component.'); } if (a.stateNode.current === a) { // We've determined that A is the current branch. return fiber; } // Otherwise B has to be current branch. return alternate; } function findCurrentHostFiber(parent) { var currentParent = findCurrentFiberUsingSlowPath(parent); return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null; } function findCurrentHostFiberImpl(node) { // Next we'll drill down this component to find the first HostComponent/Text. if (node.tag === HostComponent || node.tag === HostText) { return node; } var child = node.child; while (child !== null) { var match = findCurrentHostFiberImpl(child); if (match !== null) { return match; } child = child.sibling; } return null; } function findCurrentHostFiberWithNoPortals(parent) { var currentParent = findCurrentFiberUsingSlowPath(parent); return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null; } function findCurrentHostFiberWithNoPortalsImpl(node) { // Next we'll drill down this component to find the first HostComponent/Text. if (node.tag === HostComponent || node.tag === HostText) { return node; } var child = node.child; while (child !== null) { if (child.tag !== HostPortal) { var match = findCurrentHostFiberWithNoPortalsImpl(child); if (match !== null) { return match; } } child = child.sibling; } return null; } // This module only exists as an ESM wrapper around the external CommonJS var scheduleCallback = unstable_scheduleCallback; var cancelCallback = unstable_cancelCallback; var shouldYield = unstable_shouldYield; var requestPaint = unstable_requestPaint; var now = unstable_now; var getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; var ImmediatePriority = unstable_ImmediatePriority; var UserBlockingPriority = unstable_UserBlockingPriority; var NormalPriority = unstable_NormalPriority; var LowPriority = unstable_LowPriority; var IdlePriority = unstable_IdlePriority; // this doesn't actually exist on the scheduler, but it *does* // on scheduler/unstable_mock, which we'll need for internal testing var unstable_yieldValue$1 = unstable_yieldValue; var unstable_setDisableYieldValue$1 = unstable_setDisableYieldValue; var rendererID = null; var injectedHook = null; var injectedProfilingHooks = null; var hasLoggedError = false; var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined'; function injectInternals(internals) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // No DevTools return false; } var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; if (hook.isDisabled) { // This isn't a real property on the hook, but it can be set to opt out // of DevTools integration and associated warnings and logs. // https://github.com/facebook/react/issues/3877 return true; } if (!hook.supportsFiber) { { error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools'); } // DevTools exists, even though it doesn't support Fiber. return true; } try { if (enableSchedulingProfiler) { // Conditionally inject these hooks only if Timeline profiler is supported by this build. // This gives DevTools a way to feature detect that isn't tied to version number // (since profiling and timeline are controlled by different feature flags). internals = assign({}, internals, { getLaneLabelMap: getLaneLabelMap, injectProfilingHooks: injectProfilingHooks }); } rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. injectedHook = hook; } catch (err) { // Catch all errors because it is unsafe to throw during initialization. { error('React instrumentation encountered an error: %s.', err); } } if (hook.checkDCE) { // This is the real DevTools. return true; } else { // This is likely a hook installed by Fast Refresh runtime. return false; } } function onScheduleRoot(root, children) { { if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') { try { injectedHook.onScheduleFiberRoot(rendererID, root, children); } catch (err) { if ( !hasLoggedError) { hasLoggedError = true; error('React instrumentation encountered an error: %s', err); } } } } } function onCommitRoot(root, eventPriority) { if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') { try { var didError = (root.current.flags & DidCapture) === DidCapture; if (enableProfilerTimer) { var schedulerPriority; switch (eventPriority) { case DiscreteEventPriority: schedulerPriority = ImmediatePriority; break; case ContinuousEventPriority: schedulerPriority = UserBlockingPriority; break; case DefaultEventPriority: schedulerPriority = NormalPriority; break; case IdleEventPriority: schedulerPriority = IdlePriority; break; default: schedulerPriority = NormalPriority; break; } injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError); } else { injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError); } } catch (err) { { if (!hasLoggedError) { hasLoggedError = true; error('React instrumentation encountered an error: %s', err); } } } } } function onPostCommitRoot(root) { if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function') { try { injectedHook.onPostCommitFiberRoot(rendererID, root); } catch (err) { { if (!hasLoggedError) { hasLoggedError = true; error('React instrumentation encountered an error: %s', err); } } } } } function onCommitUnmount(fiber) { if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') { try { injectedHook.onCommitFiberUnmount(rendererID, fiber); } catch (err) { { if (!hasLoggedError) { hasLoggedError = true; error('React instrumentation encountered an error: %s', err); } } } } } function setIsStrictModeForDevtools(newIsStrictMode) { { if (typeof unstable_yieldValue$1 === 'function') { // We're in a test because Scheduler.unstable_yieldValue only exists // in SchedulerMock. To reduce the noise in strict mode tests, // suppress warnings and disable scheduler yielding during the double render unstable_setDisableYieldValue$1(newIsStrictMode); setSuppressWarning(newIsStrictMode); } if (injectedHook && typeof injectedHook.setStrictMode === 'function') { try { injectedHook.setStrictMode(rendererID, newIsStrictMode); } catch (err) { { if (!hasLoggedError) { hasLoggedError = true; error('React instrumentation encountered an error: %s', err); } } } } } } // Profiler API hooks function injectProfilingHooks(profilingHooks) { injectedProfilingHooks = profilingHooks; } function getLaneLabelMap() { { var map = new Map(); var lane = 1; for (var index = 0; index < TotalLanes; index++) { var label = getLabelForLane(lane); map.set(lane, label); lane *= 2; } return map; } } function markCommitStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') { injectedProfilingHooks.markCommitStarted(lanes); } } } function markCommitStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function') { injectedProfilingHooks.markCommitStopped(); } } } function markComponentRenderStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') { injectedProfilingHooks.markComponentRenderStarted(fiber); } } } function markComponentRenderStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function') { injectedProfilingHooks.markComponentRenderStopped(); } } } function markComponentPassiveEffectMountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') { injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); } } } function markComponentPassiveEffectMountStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function') { injectedProfilingHooks.markComponentPassiveEffectMountStopped(); } } } function markComponentPassiveEffectUnmountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') { injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); } } } function markComponentPassiveEffectUnmountStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function') { injectedProfilingHooks.markComponentPassiveEffectUnmountStopped(); } } } function markComponentLayoutEffectMountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') { injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); } } } function markComponentLayoutEffectMountStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function') { injectedProfilingHooks.markComponentLayoutEffectMountStopped(); } } } function markComponentLayoutEffectUnmountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') { injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); } } } function markComponentLayoutEffectUnmountStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function') { injectedProfilingHooks.markComponentLayoutEffectUnmountStopped(); } } } function markComponentErrored(fiber, thrownValue, lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function') { injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes); } } } function markComponentSuspended(fiber, wakeable, lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function') { injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes); } } } function markLayoutEffectsStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') { injectedProfilingHooks.markLayoutEffectsStarted(lanes); } } } function markLayoutEffectsStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function') { injectedProfilingHooks.markLayoutEffectsStopped(); } } } function markPassiveEffectsStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') { injectedProfilingHooks.markPassiveEffectsStarted(lanes); } } } function markPassiveEffectsStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function') { injectedProfilingHooks.markPassiveEffectsStopped(); } } } function markRenderStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') { injectedProfilingHooks.markRenderStarted(lanes); } } } function markRenderYielded() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function') { injectedProfilingHooks.markRenderYielded(); } } } function markRenderStopped() { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function') { injectedProfilingHooks.markRenderStopped(); } } } function markRenderScheduled(lane) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function') { injectedProfilingHooks.markRenderScheduled(lane); } } } function markForceUpdateScheduled(fiber, lane) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function') { injectedProfilingHooks.markForceUpdateScheduled(fiber, lane); } } } function markStateUpdateScheduled(fiber, lane) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function') { injectedProfilingHooks.markStateUpdateScheduled(fiber, lane); } } } var NoMode = /* */ 0; // TODO: Remove ConcurrentMode by reading from the root tag instead var ConcurrentMode = /* */ 1; var ProfileMode = /* */ 2; var StrictLegacyMode = /* */ 8; var StrictEffectsMode = /* */ 16; // TODO: This is pretty well supported by browsers. Maybe we can drop it. var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. // Based on: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 var log = Math.log; var LN2 = Math.LN2; function clz32Fallback(x) { var asUint = x >>> 0; if (asUint === 0) { return 32; } return 31 - (log(asUint) / LN2 | 0) | 0; } // If those values are changed that package should be rebuilt and redeployed. var TotalLanes = 31; var NoLanes = /* */ 0; var NoLane = /* */ 0; var SyncLane = /* */ 1; var InputContinuousHydrationLane = /* */ 2; var InputContinuousLane = /* */ 4; var DefaultHydrationLane = /* */ 8; var DefaultLane = /* */ 16; var TransitionHydrationLane = /* */ 32; var TransitionLanes = /* */ 4194240; var TransitionLane1 = /* */ 64; var TransitionLane2 = /* */ 128; var TransitionLane3 = /* */ 256; var TransitionLane4 = /* */ 512; var TransitionLane5 = /* */ 1024; var TransitionLane6 = /* */ 2048; var TransitionLane7 = /* */ 4096; var TransitionLane8 = /* */ 8192; var TransitionLane9 = /* */ 16384; var TransitionLane10 = /* */ 32768; var TransitionLane11 = /* */ 65536; var TransitionLane12 = /* */ 131072; var TransitionLane13 = /* */ 262144; var TransitionLane14 = /* */ 524288; var TransitionLane15 = /* */ 1048576; var TransitionLane16 = /* */ 2097152; var RetryLanes = /* */ 130023424; var RetryLane1 = /* */ 4194304; var RetryLane2 = /* */ 8388608; var RetryLane3 = /* */ 16777216; var RetryLane4 = /* */ 33554432; var RetryLane5 = /* */ 67108864; var SomeRetryLane = RetryLane1; var SelectiveHydrationLane = /* */ 134217728; var NonIdleLanes = /* */ 268435455; var IdleHydrationLane = /* */ 268435456; var IdleLane = /* */ 536870912; var OffscreenLane = /* */ 1073741824; // This function is used for the experimental timeline (react-devtools-timeline) // It should be kept in sync with the Lanes values above. function getLabelForLane(lane) { { if (lane & SyncLane) { return 'Sync'; } if (lane & InputContinuousHydrationLane) { return 'InputContinuousHydration'; } if (lane & InputContinuousLane) { return 'InputContinuous'; } if (lane & DefaultHydrationLane) { return 'DefaultHydration'; } if (lane & DefaultLane) { return 'Default'; } if (lane & TransitionHydrationLane) { return 'TransitionHydration'; } if (lane & TransitionLanes) { return 'Transition'; } if (lane & RetryLanes) { return 'Retry'; } if (lane & SelectiveHydrationLane) { return 'SelectiveHydration'; } if (lane & IdleHydrationLane) { return 'IdleHydration'; } if (lane & IdleLane) { return 'Idle'; } if (lane & OffscreenLane) { return 'Offscreen'; } } } var NoTimestamp = -1; var nextTransitionLane = TransitionLane1; var nextRetryLane = RetryLane1; function getHighestPriorityLanes(lanes) { switch (getHighestPriorityLane(lanes)) { case SyncLane: return SyncLane; case InputContinuousHydrationLane: return InputContinuousHydrationLane; case InputContinuousLane: return InputContinuousLane; case DefaultHydrationLane: return DefaultHydrationLane; case DefaultLane: return DefaultLane; case TransitionHydrationLane: return TransitionHydrationLane; case TransitionLane1: case TransitionLane2: case TransitionLane3: case TransitionLane4: case TransitionLane5: case TransitionLane6: case TransitionLane7: case TransitionLane8: case TransitionLane9: case TransitionLane10: case TransitionLane11: case TransitionLane12: case TransitionLane13: case TransitionLane14: case TransitionLane15: case TransitionLane16: return lanes & TransitionLanes; case RetryLane1: case RetryLane2: case RetryLane3: case RetryLane4: case RetryLane5: return lanes & RetryLanes; case SelectiveHydrationLane: return SelectiveHydrationLane; case IdleHydrationLane: return IdleHydrationLane; case IdleLane: return IdleLane; case OffscreenLane: return OffscreenLane; default: { error('Should have found matching lanes. This is a bug in React.'); } // This shouldn't be reachable, but as a fallback, return the entire bitmask. return lanes; } } function getNextLanes(root, wipLanes) { // Early bailout if there's no pending work left. var pendingLanes = root.pendingLanes; if (pendingLanes === NoLanes) { return NoLanes; } var nextLanes = NoLanes; var suspendedLanes = root.suspendedLanes; var pingedLanes = root.pingedLanes; // Do not work on any idle work until all the non-idle work has finished, // even if the work is suspended. var nonIdlePendingLanes = pendingLanes & NonIdleLanes; if (nonIdlePendingLanes !== NoLanes) { var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; if (nonIdleUnblockedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); } else { var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; if (nonIdlePingedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); } } } else { // The only remaining work is Idle. var unblockedLanes = pendingLanes & ~suspendedLanes; if (unblockedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(unblockedLanes); } else { if (pingedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(pingedLanes); } } } if (nextLanes === NoLanes) { // This should only be reachable if we're suspended // TODO: Consider warning in this path if a fallback timer is not scheduled. return NoLanes; } // If we're already in the middle of a render, switching lanes will interrupt // it and we'll lose our progress. We should only do this if the new lanes are // higher priority. if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't // bother waiting until the root is complete. (wipLanes & suspendedLanes) === NoLanes) { var nextLane = getHighestPriorityLane(nextLanes); var wipLane = getHighestPriorityLane(wipLanes); if ( // Tests whether the next lane is equal or lower priority than the wip // one. This works because the bits decrease in priority as you go left. nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The // only difference between default updates and transition updates is that // default updates do not support refresh transitions. nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) { // Keep working on the existing in-progress tree. Do not interrupt. return wipLanes; } } if ((nextLanes & InputContinuousLane) !== NoLanes) { // When updates are sync by default, we entangle continuous priority updates // and default updates, so they render in the same batch. The only reason // they use separate lanes is because continuous updates should interrupt // transitions, but default updates should not. nextLanes |= pendingLanes & DefaultLane; } // Check for entangled lanes and add them to the batch. // // A lane is said to be entangled with another when it's not allowed to render // in a batch that does not also include the other lane. Typically we do this // when multiple updates have the same source, and we only want to respond to // the most recent event from that source. // // Note that we apply entanglements *after* checking for partial work above. // This means that if a lane is entangled during an interleaved event while // it's already rendering, we won't interrupt it. This is intentional, since // entanglement is usually "best effort": we'll try our best to render the // lanes in the same batch, but it's not worth throwing out partially // completed work in order to do it. // TODO: Reconsider this. The counter-argument is that the partial work // represents an intermediate state, which we don't want to show to the user. // And by spending extra time finishing it, we're increasing the amount of // time it takes to show the final state, which is what they are actually // waiting for. // // For those exceptions where entanglement is semantically important, like // useMutableSource, we should ensure that there is no partial work at the // time we apply the entanglement. var entangledLanes = root.entangledLanes; if (entangledLanes !== NoLanes) { var entanglements = root.entanglements; var lanes = nextLanes & entangledLanes; while (lanes > 0) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; nextLanes |= entanglements[index]; lanes &= ~lane; } } return nextLanes; } function getMostRecentEventTime(root, lanes) { var eventTimes = root.eventTimes; var mostRecentEventTime = NoTimestamp; while (lanes > 0) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; var eventTime = eventTimes[index]; if (eventTime > mostRecentEventTime) { mostRecentEventTime = eventTime; } lanes &= ~lane; } return mostRecentEventTime; } function computeExpirationTime(lane, currentTime) { switch (lane) { case SyncLane: case InputContinuousHydrationLane: case InputContinuousLane: // User interactions should expire slightly more quickly. // // NOTE: This is set to the corresponding constant as in Scheduler.js. // When we made it larger, a product metric in www regressed, suggesting // there's a user interaction that's being starved by a series of // synchronous updates. If that theory is correct, the proper solution is // to fix the starvation. However, this scenario supports the idea that // expiration times are an important safeguard when starvation // does happen. return currentTime + 250; case DefaultHydrationLane: case DefaultLane: case TransitionHydrationLane: case TransitionLane1: case TransitionLane2: case TransitionLane3: case TransitionLane4: case TransitionLane5: case TransitionLane6: case TransitionLane7: case TransitionLane8: case TransitionLane9: case TransitionLane10: case TransitionLane11: case TransitionLane12: case TransitionLane13: case TransitionLane14: case TransitionLane15: case TransitionLane16: return currentTime + 5000; case RetryLane1: case RetryLane2: case RetryLane3: case RetryLane4: case RetryLane5: // TODO: Retries should be allowed to expire if they are CPU bound for // too long, but when I made this change it caused a spike in browser // crashes. There must be some other underlying bug; not super urgent but // ideally should figure out why and fix it. Unfortunately we don't have // a repro for the crashes, only detected via production metrics. return NoTimestamp; case SelectiveHydrationLane: case IdleHydrationLane: case IdleLane: case OffscreenLane: // Anything idle priority or lower should never expire. return NoTimestamp; default: { error('Should have found matching lanes. This is a bug in React.'); } return NoTimestamp; } } function markStarvedLanesAsExpired(root, currentTime) { // TODO: This gets called every time we yield. We can optimize by storing // the earliest expiration time on the root. Then use that to quickly bail out // of this function. var pendingLanes = root.pendingLanes; var suspendedLanes = root.suspendedLanes; var pingedLanes = root.pingedLanes; var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their // expiration time. If so, we'll assume the update is being starved and mark // it as expired to force it to finish. var lanes = pendingLanes; while (lanes > 0) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; var expirationTime = expirationTimes[index]; if (expirationTime === NoTimestamp) { // Found a pending lane with no expiration time. If it's not suspended, or // if it's pinged, assume it's CPU-bound. Compute a new expiration time // using the current time. if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) { // Assumes timestamps are monotonically increasing. expirationTimes[index] = computeExpirationTime(lane, currentTime); } } else if (expirationTime <= currentTime) { // This lane expired root.expiredLanes |= lane; } lanes &= ~lane; } } // This returns the highest priority pending lanes regardless of whether they // are suspended. function getHighestPriorityPendingLanes(root) { return getHighestPriorityLanes(root.pendingLanes); } function getLanesToRetrySynchronouslyOnError(root) { var everythingButOffscreen = root.pendingLanes & ~OffscreenLane; if (everythingButOffscreen !== NoLanes) { return everythingButOffscreen; } if (everythingButOffscreen & OffscreenLane) { return OffscreenLane; } return NoLanes; } function includesSyncLane(lanes) { return (lanes & SyncLane) !== NoLanes; } function includesNonIdleWork(lanes) { return (lanes & NonIdleLanes) !== NoLanes; } function includesOnlyRetries(lanes) { return (lanes & RetryLanes) === lanes; } function includesOnlyNonUrgentLanes(lanes) { var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane; return (lanes & UrgentLanes) === NoLanes; } function includesOnlyTransitions(lanes) { return (lanes & TransitionLanes) === lanes; } function includesBlockingLane(root, lanes) { var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane; return (lanes & SyncDefaultLanes) !== NoLanes; } function includesExpiredLane(root, lanes) { // This is a separate check from includesBlockingLane because a lane can // expire after a render has already started. return (lanes & root.expiredLanes) !== NoLanes; } function isTransitionLane(lane) { return (lane & TransitionLanes) !== NoLanes; } function claimNextTransitionLane() { // Cycle through the lanes, assigning each new transition to the next lane. // In most cases, this means every transition gets its own lane, until we // run out of lanes and cycle back to the beginning. var lane = nextTransitionLane; nextTransitionLane <<= 1; if ((nextTransitionLane & TransitionLanes) === NoLanes) { nextTransitionLane = TransitionLane1; } return lane; } function claimNextRetryLane() { var lane = nextRetryLane; nextRetryLane <<= 1; if ((nextRetryLane & RetryLanes) === NoLanes) { nextRetryLane = RetryLane1; } return lane; } function getHighestPriorityLane(lanes) { return lanes & -lanes; } function pickArbitraryLane(lanes) { // This wrapper function gets inlined. Only exists so to communicate that it // doesn't matter which bit is selected; you can pick any bit without // affecting the algorithms where its used. Here I'm using // getHighestPriorityLane because it requires the fewest operations. return getHighestPriorityLane(lanes); } function pickArbitraryLaneIndex(lanes) { return 31 - clz32(lanes); } function laneToIndex(lane) { return pickArbitraryLaneIndex(lane); } function includesSomeLane(a, b) { return (a & b) !== NoLanes; } function isSubsetOfLanes(set, subset) { return (set & subset) === subset; } function mergeLanes(a, b) { return a | b; } function removeLanes(set, subset) { return set & ~subset; } function intersectLanes(a, b) { return a & b; } // Seems redundant, but it changes the type from a single lane (used for // updates) to a group of lanes (used for flushing work). function laneToLanes(lane) { return lane; } function higherPriorityLane(a, b) { // This works because the bit ranges decrease in priority as you go left. return a !== NoLane && a < b ? a : b; } function createLaneMap(initial) { // Intentionally pushing one by one. // https://v8.dev/blog/elements-kinds#avoid-creating-holes var laneMap = []; for (var i = 0; i < TotalLanes; i++) { laneMap.push(initial); } return laneMap; } function markRootUpdated(root, updateLane, eventTime) { root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update // could unblock them. Clear the suspended lanes so that we can try rendering // them again. // // TODO: We really only need to unsuspend only lanes that are in the // `subtreeLanes` of the updated fiber, or the update lanes of the return // path. This would exclude suspended updates in an unrelated sibling tree, // since there's no way for this update to unblock it. // // We don't do this if the incoming update is idle, because we never process // idle updates until after all the regular updates have finished; there's no // way it could unblock a transition. if (updateLane !== IdleLane) { root.suspendedLanes = NoLanes; root.pingedLanes = NoLanes; } var eventTimes = root.eventTimes; var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most // recent event, and we assume time is monotonically increasing. eventTimes[index] = eventTime; } function markRootSuspended(root, suspendedLanes) { root.suspendedLanes |= suspendedLanes; root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times. var expirationTimes = root.expirationTimes; var lanes = suspendedLanes; while (lanes > 0) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; expirationTimes[index] = NoTimestamp; lanes &= ~lane; } } function markRootPinged(root, pingedLanes, eventTime) { root.pingedLanes |= root.suspendedLanes & pingedLanes; } function markRootFinished(root, remainingLanes) { var noLongerPendingLanes = root.pendingLanes & ~remainingLanes; root.pendingLanes = remainingLanes; // Let's try everything again root.suspendedLanes = NoLanes; root.pingedLanes = NoLanes; root.expiredLanes &= remainingLanes; root.mutableReadLanes &= remainingLanes; root.entangledLanes &= remainingLanes; var entanglements = root.entanglements; var eventTimes = root.eventTimes; var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work var lanes = noLongerPendingLanes; while (lanes > 0) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; entanglements[index] = NoLanes; eventTimes[index] = NoTimestamp; expirationTimes[index] = NoTimestamp; lanes &= ~lane; } } function markRootEntangled(root, entangledLanes) { // In addition to entangling each of the given lanes with each other, we also // have to consider _transitive_ entanglements. For each lane that is already // entangled with *any* of the given lanes, that lane is now transitively // entangled with *all* the given lanes. // // Translated: If C is entangled with A, then entangling A with B also // entangles C with B. // // If this is hard to grasp, it might help to intentionally break this // function and look at the tests that fail in ReactTransition-test.js. Try // commenting out one of the conditions below. var rootEntangledLanes = root.entangledLanes |= entangledLanes; var entanglements = root.entanglements; var lanes = rootEntangledLanes; while (lanes) { var index = pickArbitraryLaneIndex(lanes); var lane = 1 << index; if ( // Is this one of the newly entangled lanes? lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes? entanglements[index] & entangledLanes) { entanglements[index] |= entangledLanes; } lanes &= ~lane; } } function getBumpedLaneForHydration(root, renderLanes) { var renderLane = getHighestPriorityLane(renderLanes); var lane; switch (renderLane) { case InputContinuousLane: lane = InputContinuousHydrationLane; break; case DefaultLane: lane = DefaultHydrationLane; break; case TransitionLane1: case TransitionLane2: case TransitionLane3: case TransitionLane4: case TransitionLane5: case TransitionLane6: case TransitionLane7: case TransitionLane8: case TransitionLane9: case TransitionLane10: case TransitionLane11: case TransitionLane12: case TransitionLane13: case TransitionLane14: case TransitionLane15: case TransitionLane16: case RetryLane1: case RetryLane2: case RetryLane3: case RetryLane4: case RetryLane5: lane = TransitionHydrationLane; break; case IdleLane: lane = IdleHydrationLane; break; default: // Everything else is already either a hydration lane, or shouldn't // be retried at a hydration lane. lane = NoLane; break; } // Check if the lane we chose is suspended. If so, that indicates that we // already attempted and failed to hydrate at that level. Also check if we're // already rendering that lane, which is rare but could happen. if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) { // Give up trying to hydrate and fall back to client render. return NoLane; } return lane; } function addFiberToLanesMap(root, fiber, lanes) { if (!isDevToolsPresent) { return; } var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; while (lanes > 0) { var index = laneToIndex(lanes); var lane = 1 << index; var updaters = pendingUpdatersLaneMap[index]; updaters.add(fiber); lanes &= ~lane; } } function movePendingFibersToMemoized(root, lanes) { if (!isDevToolsPresent) { return; } var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap; var memoizedUpdaters = root.memoizedUpdaters; while (lanes > 0) { var index = laneToIndex(lanes); var lane = 1 << index; var updaters = pendingUpdatersLaneMap[index]; if (updaters.size > 0) { updaters.forEach(function (fiber) { var alternate = fiber.alternate; if (alternate === null || !memoizedUpdaters.has(alternate)) { memoizedUpdaters.add(fiber); } }); updaters.clear(); } lanes &= ~lane; } } function getTransitionsForLanes(root, lanes) { { return null; } } var DiscreteEventPriority = SyncLane; var ContinuousEventPriority = InputContinuousLane; var DefaultEventPriority = DefaultLane; var IdleEventPriority = IdleLane; var currentUpdatePriority = NoLane; function getCurrentUpdatePriority() { return currentUpdatePriority; } function setCurrentUpdatePriority(newPriority) { currentUpdatePriority = newPriority; } function runWithPriority(priority, fn) { var previousPriority = currentUpdatePriority; try { currentUpdatePriority = priority; return fn(); } finally { currentUpdatePriority = previousPriority; } } function higherEventPriority(a, b) { return a !== 0 && a < b ? a : b; } function lowerEventPriority(a, b) { return a === 0 || a > b ? a : b; } function isHigherEventPriority(a, b) { return a !== 0 && a < b; } function lanesToEventPriority(lanes) { var lane = getHighestPriorityLane(lanes); if (!isHigherEventPriority(DiscreteEventPriority, lane)) { return DiscreteEventPriority; } if (!isHigherEventPriority(ContinuousEventPriority, lane)) { return ContinuousEventPriority; } if (includesNonIdleWork(lane)) { return DefaultEventPriority; } return IdleEventPriority; } // This is imported by the event replaying implementation in React DOM. It's // in a separate file to break a circular dependency between the renderer and // the reconciler. function isRootDehydrated(root) { var currentState = root.current.memoizedState; return currentState.isDehydrated; } var _attemptSynchronousHydration; function setAttemptSynchronousHydration(fn) { _attemptSynchronousHydration = fn; } function attemptSynchronousHydration(fiber) { _attemptSynchronousHydration(fiber); } var attemptContinuousHydration; function setAttemptContinuousHydration(fn) { attemptContinuousHydration = fn; } var attemptHydrationAtCurrentPriority; function setAttemptHydrationAtCurrentPriority(fn) { attemptHydrationAtCurrentPriority = fn; } var getCurrentUpdatePriority$1; function setGetCurrentUpdatePriority(fn) { getCurrentUpdatePriority$1 = fn; } var attemptHydrationAtPriority; function setAttemptHydrationAtPriority(fn) { attemptHydrationAtPriority = fn; } // TODO: Upgrade this definition once we're on a newer version of Flow that // has this definition built-in. var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed. var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout. // if the last target was dehydrated. var queuedFocus = null; var queuedDrag = null; var queuedMouse = null; // For pointer events there can be one latest event per pointerId. var queuedPointers = new Map(); var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too. var queuedExplicitHydrationTargets = []; var discreteReplayableEvents = ['mousedown', 'mouseup', 'touchcancel', 'touchend', 'touchstart', 'auxclick', 'dblclick', 'pointercancel', 'pointerdown', 'pointerup', 'dragend', 'dragstart', 'drop', 'compositionend', 'compositionstart', 'keydown', 'keypress', 'keyup', 'input', 'textInput', // Intentionally camelCase 'copy', 'cut', 'paste', 'click', 'change', 'contextmenu', 'reset', 'submit']; function isDiscreteEventThatRequiresHydration(eventType) { return discreteReplayableEvents.indexOf(eventType) > -1; } function createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) { return { blockedOn: blockedOn, domEventName: domEventName, eventSystemFlags: eventSystemFlags, nativeEvent: nativeEvent, targetContainers: [targetContainer] }; } function clearIfContinuousEvent(domEventName, nativeEvent) { switch (domEventName) { case 'focusin': case 'focusout': queuedFocus = null; break; case 'dragenter': case 'dragleave': queuedDrag = null; break; case 'mouseover': case 'mouseout': queuedMouse = null; break; case 'pointerover': case 'pointerout': { var pointerId = nativeEvent.pointerId; queuedPointers.delete(pointerId); break; } case 'gotpointercapture': case 'lostpointercapture': { var _pointerId = nativeEvent.pointerId; queuedPointerCaptures.delete(_pointerId); break; } } } function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) { if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) { var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent); if (blockedOn !== null) { var _fiber2 = getInstanceFromNode(blockedOn); if (_fiber2 !== null) { // Attempt to increase the priority of this target. attemptContinuousHydration(_fiber2); } } return queuedEvent; } // If we have already queued this exact event, then it's because // the different event systems have different DOM event listeners. // We can accumulate the flags, and the targetContainers, and // store a single event to be replayed. existingQueuedEvent.eventSystemFlags |= eventSystemFlags; var targetContainers = existingQueuedEvent.targetContainers; if (targetContainer !== null && targetContainers.indexOf(targetContainer) === -1) { targetContainers.push(targetContainer); } return existingQueuedEvent; } function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) { // These set relatedTarget to null because the replayed event will be treated as if we // moved from outside the window (no target) onto the target once it hydrates. // Instead of mutating we could clone the event. switch (domEventName) { case 'focusin': { var focusEvent = nativeEvent; queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent); return true; } case 'dragenter': { var dragEvent = nativeEvent; queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent); return true; } case 'mouseover': { var mouseEvent = nativeEvent; queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent); return true; } case 'pointerover': { var pointerEvent = nativeEvent; var pointerId = pointerEvent.pointerId; queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent)); return true; } case 'gotpointercapture': { var _pointerEvent = nativeEvent; var _pointerId2 = _pointerEvent.pointerId; queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, _pointerEvent)); return true; } } return false; } // Check if this target is unblocked. Returns true if it's unblocked. function attemptExplicitHydrationTarget(queuedTarget) { // TODO: This function shares a lot of logic with findInstanceBlockingEvent. // Try to unify them. It's a bit tricky since it would require two return // values. var targetInst = getClosestInstanceFromNode(queuedTarget.target); if (targetInst !== null) { var nearestMounted = getNearestMountedFiber(targetInst); if (nearestMounted !== null) { var tag = nearestMounted.tag; if (tag === SuspenseComponent) { var instance = getSuspenseInstanceFromFiber(nearestMounted); if (instance !== null) { // We're blocked on hydrating this boundary. // Increase its priority. queuedTarget.blockedOn = instance; attemptHydrationAtPriority(queuedTarget.priority, function () { attemptHydrationAtCurrentPriority(nearestMounted); }); return; } } else if (tag === HostRoot) { var root = nearestMounted.stateNode; if (isRootDehydrated(root)) { queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of // a root other than sync. return; } } } } queuedTarget.blockedOn = null; } function queueExplicitHydrationTarget(target) { // TODO: This will read the priority if it's dispatched by the React // event system but not native events. Should read window.event.type, like // we do for updates (getCurrentEventPriority). var updatePriority = getCurrentUpdatePriority$1(); var queuedTarget = { blockedOn: null, target: target, priority: updatePriority }; var i = 0; for (; i < queuedExplicitHydrationTargets.length; i++) { // Stop once we hit the first target with lower priority than if (!isHigherEventPriority(updatePriority, queuedExplicitHydrationTargets[i].priority)) { break; } } queuedExplicitHydrationTargets.splice(i, 0, queuedTarget); if (i === 0) { attemptExplicitHydrationTarget(queuedTarget); } } function attemptReplayContinuousQueuedEvent(queuedEvent) { if (queuedEvent.blockedOn !== null) { return false; } var targetContainers = queuedEvent.targetContainers; while (targetContainers.length > 0) { var targetContainer = targetContainers[0]; var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.domEventName, queuedEvent.eventSystemFlags, targetContainer, queuedEvent.nativeEvent); if (nextBlockedOn === null) { { var nativeEvent = queuedEvent.nativeEvent; var nativeEventClone = new nativeEvent.constructor(nativeEvent.type, nativeEvent); setReplayingEvent(nativeEventClone); nativeEvent.target.dispatchEvent(nativeEventClone); resetReplayingEvent(); } } else { // We're still blocked. Try again later. var _fiber3 = getInstanceFromNode(nextBlockedOn); if (_fiber3 !== null) { attemptContinuousHydration(_fiber3); } queuedEvent.blockedOn = nextBlockedOn; return false; } // This target container was successfully dispatched. Try the next. targetContainers.shift(); } return true; } function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) { if (attemptReplayContinuousQueuedEvent(queuedEvent)) { map.delete(key); } } function replayUnblockedEvents() { hasScheduledReplayAttempt = false; if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) { queuedFocus = null; } if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) { queuedDrag = null; } if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) { queuedMouse = null; } queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap); queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap); } function scheduleCallbackIfUnblocked(queuedEvent, unblocked) { if (queuedEvent.blockedOn === unblocked) { queuedEvent.blockedOn = null; if (!hasScheduledReplayAttempt) { hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are // now unblocked. This first might not actually be unblocked yet. // We could check it early to avoid scheduling an unnecessary callback. unstable_scheduleCallback(unstable_NormalPriority, replayUnblockedEvents); } } } function retryIfBlockedOn(unblocked) { // Mark anything that was blocked on this as no longer blocked // and eligible for a replay. if (queuedDiscreteEvents.length > 0) { scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's // worth it because we expect very few discrete events to queue up and once // we are actually fully unblocked it will be fast to replay them. for (var i = 1; i < queuedDiscreteEvents.length; i++) { var queuedEvent = queuedDiscreteEvents[i]; if (queuedEvent.blockedOn === unblocked) { queuedEvent.blockedOn = null; } } } if (queuedFocus !== null) { scheduleCallbackIfUnblocked(queuedFocus, unblocked); } if (queuedDrag !== null) { scheduleCallbackIfUnblocked(queuedDrag, unblocked); } if (queuedMouse !== null) { scheduleCallbackIfUnblocked(queuedMouse, unblocked); } var unblock = function (queuedEvent) { return scheduleCallbackIfUnblocked(queuedEvent, unblocked); }; queuedPointers.forEach(unblock); queuedPointerCaptures.forEach(unblock); for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) { var queuedTarget = queuedExplicitHydrationTargets[_i]; if (queuedTarget.blockedOn === unblocked) { queuedTarget.blockedOn = null; } } while (queuedExplicitHydrationTargets.length > 0) { var nextExplicitTarget = queuedExplicitHydrationTargets[0]; if (nextExplicitTarget.blockedOn !== null) { // We're still blocked. break; } else { attemptExplicitHydrationTarget(nextExplicitTarget); if (nextExplicitTarget.blockedOn === null) { // We're unblocked. queuedExplicitHydrationTargets.shift(); } } } } var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; // TODO: can we stop exporting these? var _enabled = true; // This is exported in FB builds for use by legacy FB layer infra. // We'd like to remove this but it's not clear if this is safe. function setEnabled(enabled) { _enabled = !!enabled; } function isEnabled() { return _enabled; } function createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags) { var eventPriority = getEventPriority(domEventName); var listenerWrapper; switch (eventPriority) { case DiscreteEventPriority: listenerWrapper = dispatchDiscreteEvent; break; case ContinuousEventPriority: listenerWrapper = dispatchContinuousEvent; break; case DefaultEventPriority: default: listenerWrapper = dispatchEvent; break; } return listenerWrapper.bind(null, domEventName, eventSystemFlags, targetContainer); } function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) { var previousPriority = getCurrentUpdatePriority(); var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = null; try { setCurrentUpdatePriority(DiscreteEventPriority); dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig.transition = prevTransition; } } function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) { var previousPriority = getCurrentUpdatePriority(); var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = null; try { setCurrentUpdatePriority(ContinuousEventPriority); dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig.transition = prevTransition; } } function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) { if (!_enabled) { return; } { dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent); } } function dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent) { var blockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent); if (blockedOn === null) { dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer); clearIfContinuousEvent(domEventName, nativeEvent); return; } if (queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent)) { nativeEvent.stopPropagation(); return; } // We need to clear only if we didn't queue because // queueing is accumulative. clearIfContinuousEvent(domEventName, nativeEvent); if (eventSystemFlags & IS_CAPTURE_PHASE && isDiscreteEventThatRequiresHydration(domEventName)) { while (blockedOn !== null) { var fiber = getInstanceFromNode(blockedOn); if (fiber !== null) { attemptSynchronousHydration(fiber); } var nextBlockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent); if (nextBlockedOn === null) { dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer); } if (nextBlockedOn === blockedOn) { break; } blockedOn = nextBlockedOn; } if (blockedOn !== null) { nativeEvent.stopPropagation(); } return; } // This is not replayable so we'll invoke it but without a target, // in case the event system needs to trace it. dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, null, targetContainer); } var return_targetInst = null; // Returns a SuspenseInstance or Container if it's blocked. // The return_targetInst field above is conceptually part of the return value. function findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) { // TODO: Warn if _enabled is false. return_targetInst = null; var nativeEventTarget = getEventTarget(nativeEvent); var targetInst = getClosestInstanceFromNode(nativeEventTarget); if (targetInst !== null) { var nearestMounted = getNearestMountedFiber(targetInst); if (nearestMounted === null) { // This tree has been unmounted already. Dispatch without a target. targetInst = null; } else { var tag = nearestMounted.tag; if (tag === SuspenseComponent) { var instance = getSuspenseInstanceFromFiber(nearestMounted); if (instance !== null) { // Queue the event to be replayed later. Abort dispatching since we // don't want this event dispatched twice through the event system. // TODO: If this is the first discrete event in the queue. Schedule an increased // priority for this boundary. return instance; } // This shouldn't happen, something went wrong but to avoid blocking // the whole system, dispatch the event without a target. // TODO: Warn. targetInst = null; } else if (tag === HostRoot) { var root = nearestMounted.stateNode; if (isRootDehydrated(root)) { // If this happens during a replay something went wrong and it might block // the whole system. return getContainerFromFiber(nearestMounted); } targetInst = null; } else if (nearestMounted !== targetInst) { // If we get an event (ex: img onload) before committing that // component's mount, ignore it for now (that is, treat it as if it was an // event on a non-React tree). We might also consider queueing events and // dispatching them after the mount. targetInst = null; } } } return_targetInst = targetInst; // We're not blocked on anything. return null; } function getEventPriority(domEventName) { switch (domEventName) { // Used by SimpleEventPlugin: case 'cancel': case 'click': case 'close': case 'contextmenu': case 'copy': case 'cut': case 'auxclick': case 'dblclick': case 'dragend': case 'dragstart': case 'drop': case 'focusin': case 'focusout': case 'input': case 'invalid': case 'keydown': case 'keypress': case 'keyup': case 'mousedown': case 'mouseup': case 'paste': case 'pause': case 'play': case 'pointercancel': case 'pointerdown': case 'pointerup': case 'ratechange': case 'reset': case 'resize': case 'seeked': case 'submit': case 'touchcancel': case 'touchend': case 'touchstart': case 'volumechange': // Used by polyfills: // eslint-disable-next-line no-fallthrough case 'change': case 'selectionchange': case 'textInput': case 'compositionstart': case 'compositionend': case 'compositionupdate': // Only enableCreateEventHandleAPI: // eslint-disable-next-line no-fallthrough case 'beforeblur': case 'afterblur': // Not used by React but could be by user code: // eslint-disable-next-line no-fallthrough case 'beforeinput': case 'blur': case 'fullscreenchange': case 'focus': case 'hashchange': case 'popstate': case 'select': case 'selectstart': return DiscreteEventPriority; case 'drag': case 'dragenter': case 'dragexit': case 'dragleave': case 'dragover': case 'mousemove': case 'mouseout': case 'mouseover': case 'pointermove': case 'pointerout': case 'pointerover': case 'scroll': case 'toggle': case 'touchmove': case 'wheel': // Not used by React but could be by user code: // eslint-disable-next-line no-fallthrough case 'mouseenter': case 'mouseleave': case 'pointerenter': case 'pointerleave': return ContinuousEventPriority; case 'message': { // We might be in the Scheduler callback. // Eventually this mechanism will be replaced by a check // of the current priority on the native scheduler. var schedulerPriority = getCurrentPriorityLevel(); switch (schedulerPriority) { case ImmediatePriority: return DiscreteEventPriority; case UserBlockingPriority: return ContinuousEventPriority; case NormalPriority: case LowPriority: // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration. return DefaultEventPriority; case IdlePriority: return IdleEventPriority; default: return DefaultEventPriority; } } default: return DefaultEventPriority; } } function addEventBubbleListener(target, eventType, listener) { target.addEventListener(eventType, listener, false); return listener; } function addEventCaptureListener(target, eventType, listener) { target.addEventListener(eventType, listener, true); return listener; } function addEventCaptureListenerWithPassiveFlag(target, eventType, listener, passive) { target.addEventListener(eventType, listener, { capture: true, passive: passive }); return listener; } function addEventBubbleListenerWithPassiveFlag(target, eventType, listener, passive) { target.addEventListener(eventType, listener, { passive: passive }); return listener; } /** * These variables store information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * */ var root = null; var startText = null; var fallbackText = null; function initialize(nativeEventTarget) { root = nativeEventTarget; startText = getText(); return true; } function reset() { root = null; startText = null; fallbackText = null; } function getData() { if (fallbackText) { return fallbackText; } var start; var startValue = startText; var startLength = startValue.length; var end; var endValue = getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; fallbackText = endValue.slice(start, sliceTail); return fallbackText; } function getText() { if ('value' in root) { return root.value; } return root.textContent; } /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux) // report Enter as charCode 10 when ctrl is pressed. if (charCode === 10) { charCode = 13; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } function functionThatReturnsTrue() { return true; } function functionThatReturnsFalse() { return false; } // This is intentionally a factory so that we have different returned constructors. // If we had a single constructor, it would be megamorphic and engines would deopt. function createSyntheticEvent(Interface) { /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. */ function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) { this._reactName = reactName; this._targetInst = targetInst; this.type = reactEventType; this.nativeEvent = nativeEvent; this.target = nativeEventTarget; this.currentTarget = null; for (var _propName in Interface) { if (!Interface.hasOwnProperty(_propName)) { continue; } var normalize = Interface[_propName]; if (normalize) { this[_propName] = normalize(nativeEvent); } else { this[_propName] = nativeEvent[_propName]; } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = functionThatReturnsTrue; } else { this.isDefaultPrevented = functionThatReturnsFalse; } this.isPropagationStopped = functionThatReturnsFalse; return this; } assign(SyntheticBaseEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE } else if (typeof event.returnValue !== 'unknown') { event.returnValue = false; } this.isDefaultPrevented = functionThatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE } else if (typeof event.cancelBubble !== 'unknown') { // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). event.cancelBubble = true; } this.isPropagationStopped = functionThatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () {// Modern event system doesn't use pooling. }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: functionThatReturnsTrue }); return SyntheticBaseEvent; } /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { eventPhase: 0, bubbles: 0, cancelable: 0, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: 0, isTrusted: 0 }; var SyntheticEvent = createSyntheticEvent(EventInterface); var UIEventInterface = assign({}, EventInterface, { view: 0, detail: 0 }); var SyntheticUIEvent = createSyntheticEvent(UIEventInterface); var lastMovementX; var lastMovementY; var lastMouseEvent; function updateMouseMovementPolyfillState(event) { if (event !== lastMouseEvent) { if (lastMouseEvent && event.type === 'mousemove') { lastMovementX = event.screenX - lastMouseEvent.screenX; lastMovementY = event.screenY - lastMouseEvent.screenY; } else { lastMovementX = 0; lastMovementY = 0; } lastMouseEvent = event; } } /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = assign({}, UIEventInterface, { screenX: 0, screenY: 0, clientX: 0, clientY: 0, pageX: 0, pageY: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, getModifierState: getEventModifierState, button: 0, buttons: 0, relatedTarget: function (event) { if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement; return event.relatedTarget; }, movementX: function (event) { if ('movementX' in event) { return event.movementX; } updateMouseMovementPolyfillState(event); return lastMovementX; }, movementY: function (event) { if ('movementY' in event) { return event.movementY; } // Don't need to call updateMouseMovementPolyfillState() here // because it's guaranteed to have already run when movementX // was copied. return lastMovementY; } }); var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = assign({}, MouseEventInterface, { dataTransfer: 0 }); var SyntheticDragEvent = createSyntheticEvent(DragEventInterface); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = assign({}, UIEventInterface, { relatedTarget: 0 }); var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface); /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = assign({}, EventInterface, { animationName: 0, elapsedTime: 0, pseudoElement: 0 }); var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = assign({}, EventInterface, { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }); var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = assign({}, EventInterface, { data: 0 }); var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ // Happens to share the same list for now. var SyntheticInputEvent = SyntheticCompositionEvent; /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { Esc: 'Escape', Spacebar: ' ', Left: 'ArrowLeft', Up: 'ArrowUp', Right: 'ArrowRight', Down: 'ArrowDown', Del: 'Delete', Win: 'OS', Menu: 'ContextMenu', Apps: 'ContextMenu', Scroll: 'ScrollLock', MozPrintableKey: 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { '8': 'Backspace', '9': 'Tab', '12': 'Clear', '13': 'Enter', '16': 'Shift', '17': 'Control', '18': 'Alt', '19': 'Pause', '20': 'CapsLock', '27': 'Escape', '32': ' ', '33': 'PageUp', '34': 'PageDown', '35': 'End', '36': 'Home', '37': 'ArrowLeft', '38': 'ArrowUp', '39': 'ArrowRight', '40': 'ArrowDown', '45': 'Insert', '46': 'Delete', '112': 'F1', '113': 'F2', '114': 'F3', '115': 'F4', '116': 'F5', '117': 'F6', '118': 'F7', '119': 'F8', '120': 'F9', '121': 'F10', '122': 'F11', '123': 'F12', '144': 'NumLock', '145': 'ScrollLock', '224': 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { Alt: 'altKey', Control: 'ctrlKey', Meta: 'metaKey', Shift: 'shiftKey' }; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support // getModifierState. If getModifierState is not supported, we map it to a set of // modifier keys exposed by the event. In this case, Lock-keys are not supported. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = assign({}, UIEventInterface, { key: getEventKey, code: 0, location: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, repeat: 0, locale: 0, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }); var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface); /** * @interface PointerEvent * @see http://www.w3.org/TR/pointerevents/ */ var PointerEventInterface = assign({}, MouseEventInterface, { pointerId: 0, width: 0, height: 0, pressure: 0, tangentialPressure: 0, tiltX: 0, tiltY: 0, twist: 0, pointerType: 0, isPrimary: 0 }); var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = assign({}, UIEventInterface, { touches: 0, targetTouches: 0, changedTouches: 0, altKey: 0, metaKey: 0, ctrlKey: 0, shiftKey: 0, getModifierState: getEventModifierState }); var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface); /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = assign({}, EventInterface, { propertyName: 0, elapsedTime: 0, pseudoElement: 0 }); var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = assign({}, MouseEventInterface, { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: 0, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: 0 }); var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); function registerEvents() { registerTwoPhaseEvent('onBeforeInput', ['compositionend', 'keypress', 'textInput', 'paste']); registerTwoPhaseEvent('onCompositionEnd', ['compositionend', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']); registerTwoPhaseEvent('onCompositionStart', ['compositionstart', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']); registerTwoPhaseEvent('onCompositionUpdate', ['compositionupdate', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']); } // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. */ function getCompositionEventType(domEventName) { switch (domEventName) { case 'compositionstart': return 'onCompositionStart'; case 'compositionend': return 'onCompositionEnd'; case 'compositionupdate': return 'onCompositionUpdate'; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? */ function isFallbackCompositionStart(domEventName, nativeEvent) { return domEventName === 'keydown' && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? */ function isFallbackCompositionEnd(domEventName, nativeEvent) { switch (domEventName) { case 'keyup': // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case 'keydown': // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case 'keypress': case 'mousedown': case 'focusout': // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } /** * Check if a composition event was triggered by Korean IME. * Our fallback mode does not work well with IE's Korean IME, * so just use native composition events when Korean IME is used. * Although CompositionEvent.locale property is deprecated, * it is available in IE, where our fallback mode is enabled. * * @param {object} nativeEvent * @return {boolean} */ function isUsingKoreanIME(nativeEvent) { return nativeEvent.locale === 'ko'; } // Track the current IME composition status, if any. var isComposing = false; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(domEventName); } else if (!isComposing) { if (isFallbackCompositionStart(domEventName, nativeEvent)) { eventType = 'onCompositionStart'; } } else if (isFallbackCompositionEnd(domEventName, nativeEvent)) { eventType = 'onCompositionEnd'; } if (!eventType) { return null; } if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!isComposing && eventType === 'onCompositionStart') { isComposing = initialize(nativeEventTarget); } else if (eventType === 'onCompositionEnd') { if (isComposing) { fallbackData = getData(); } } } var listeners = accumulateTwoPhaseListeners(targetInst, eventType); if (listeners.length > 0) { var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget); dispatchQueue.push({ event: event, listeners: listeners }); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } } } function getNativeBeforeInputChars(domEventName, nativeEvent) { switch (domEventName) { case 'compositionend': return getDataFromCustomEvent(nativeEvent); case 'keypress': /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case 'textInput': // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to ignore it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. */ function getFallbackBeforeInputChars(domEventName, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. // If composition event is available, we extract a string only at // compositionevent, otherwise extract it at fallback events. if (isComposing) { if (domEventName === 'compositionend' || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) { var chars = getData(); reset(); isComposing = false; return chars; } return null; } switch (domEventName) { case 'paste': // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case 'keypress': /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (!isKeypressCommand(nativeEvent)) { // IE fires the `keypress` event when a user types an emoji via // Touch keyboard of Windows. In such a case, the `char` property // holds an emoji character like `\uD83D\uDE0A`. Because its length // is 2, the property `which` does not represent an emoji correctly. // In such a case, we directly return the `char` property instead of // using `which`. if (nativeEvent.char && nativeEvent.char.length > 1) { return nativeEvent.char; } else if (nativeEvent.which) { return String.fromCharCode(nativeEvent.which); } } return null; case 'compositionend': return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(domEventName, nativeEvent); } else { chars = getFallbackBeforeInputChars(domEventName, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var listeners = accumulateTwoPhaseListeners(targetInst, 'onBeforeInput'); if (listeners.length > 0) { var event = new SyntheticInputEvent('onBeforeInput', 'beforeinput', null, nativeEvent, nativeEventTarget); dispatchQueue.push({ event: event, listeners: listeners }); event.data = chars; } } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); } /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { color: true, date: true, datetime: true, 'datetime-local': true, email: true, month: true, number: true, password: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); if (nodeName === 'input') { return !!supportedInputTypes[elem.type]; } if (nodeName === 'textarea') { return true; } return false; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix) { if (!canUseDOM) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = (eventName in document); if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } return isSupported; } function registerEvents$1() { registerTwoPhaseEvent('onChange', ['change', 'click', 'focusin', 'focusout', 'input', 'keydown', 'keyup', 'selectionchange']); } function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) { // Flag this event loop as needing state restore. enqueueStateRestore(target); var listeners = accumulateTwoPhaseListeners(inst, 'onChange'); if (listeners.length > 0) { var event = new SyntheticEvent('onChange', 'change', null, nativeEvent, target); dispatchQueue.push({ event: event, listeners: listeners }); } } /** * For IE shims */ var activeElement = null; var activeElementInst = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } function manualDispatchChangeEvent(nativeEvent) { var dispatchQueue = []; createAndAccumulateChangeEvent(dispatchQueue, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. batchedUpdates(runEventInBatch, dispatchQueue); } function runEventInBatch(dispatchQueue) { processDispatchQueue(dispatchQueue, 0); } function getInstIfValueChanged(targetInst) { var targetNode = getNodeFromInstance(targetInst); if (updateValueIfChanged(targetNode)) { return targetInst; } } function getTargetInstForChangeEvent(domEventName, targetInst) { if (domEventName === 'change') { return targetInst; } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9); } /** * (For IE <=9) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For IE <=9) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementInst = null; } /** * (For IE <=9) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } if (getInstIfValueChanged(activeElementInst)) { manualDispatchChangeEvent(nativeEvent); } } function handleEventsForInputEventPolyfill(domEventName, target, targetInst) { if (domEventName === 'focusin') { // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (domEventName === 'focusout') { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventPolyfill(domEventName, targetInst) { if (domEventName === 'selectionchange' || domEventName === 'keyup' || domEventName === 'keydown') { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. return getInstIfValueChanged(activeElementInst); } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(domEventName, targetInst) { if (domEventName === 'click') { return getInstIfValueChanged(targetInst); } } function getTargetInstForInputOrChangeEvent(domEventName, targetInst) { if (domEventName === 'input' || domEventName === 'change') { return getInstIfValueChanged(targetInst); } } function handleControlledInputBlur(node) { var state = node._wrapperState; if (!state || !state.controlled || node.type !== 'number') { return; } { // If controlled, assign the value attribute to the current value on blur setDefaultValue(node, 'number', node.value); } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { var targetNode = targetInst ? getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { getTargetInstFunc = getTargetInstForChangeEvent; } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputOrChangeEvent; } else { getTargetInstFunc = getTargetInstForInputEventPolyfill; handleEventFunc = handleEventsForInputEventPolyfill; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(domEventName, targetInst); if (inst) { createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget); return; } } if (handleEventFunc) { handleEventFunc(domEventName, targetNode, targetInst); } // When blurring, set the value attribute for number inputs if (domEventName === 'focusout') { handleControlledInputBlur(targetNode); } } function registerEvents$2() { registerDirectEvent('onMouseEnter', ['mouseout', 'mouseover']); registerDirectEvent('onMouseLeave', ['mouseout', 'mouseover']); registerDirectEvent('onPointerEnter', ['pointerout', 'pointerover']); registerDirectEvent('onPointerLeave', ['pointerout', 'pointerover']); } /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { var isOverEvent = domEventName === 'mouseover' || domEventName === 'pointerover'; var isOutEvent = domEventName === 'mouseout' || domEventName === 'pointerout'; if (isOverEvent && !isReplayingEvent(nativeEvent)) { // If this is an over event with a target, we might have already dispatched // the event in the out event of the other target. If this is replayed, // then it's because we couldn't dispatch against this target previously // so we have to do it now instead. var related = nativeEvent.relatedTarget || nativeEvent.fromElement; if (related) { // If the related node is managed by React, we can assume that we have // already dispatched the corresponding events during its mouseout. if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) { return; } } } if (!isOutEvent && !isOverEvent) { // Must not be a mouse or pointer in or out - ignoring. return; } var win; // TODO: why is this nullable in the types but we read from it? if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (isOutEvent) { var _related = nativeEvent.relatedTarget || nativeEvent.toElement; from = targetInst; to = _related ? getClosestInstanceFromNode(_related) : null; if (to !== null) { var nearestMounted = getNearestMountedFiber(to); if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) { to = null; } } } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return; } var SyntheticEventCtor = SyntheticMouseEvent; var leaveEventType = 'onMouseLeave'; var enterEventType = 'onMouseEnter'; var eventTypePrefix = 'mouse'; if (domEventName === 'pointerout' || domEventName === 'pointerover') { SyntheticEventCtor = SyntheticPointerEvent; leaveEventType = 'onPointerLeave'; enterEventType = 'onPointerEnter'; eventTypePrefix = 'pointer'; } var fromNode = from == null ? win : getNodeFromInstance(from); var toNode = to == null ? win : getNodeFromInstance(to); var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + 'leave', from, nativeEvent, nativeEventTarget); leave.target = fromNode; leave.relatedTarget = toNode; var enter = null; // We should only process this nativeEvent if we are processing // the first ancestor. Next time, we will ignore the event. var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget); if (nativeTargetInst === targetInst) { var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + 'enter', to, nativeEvent, nativeEventTarget); enterEvent.target = toNode; enterEvent.relatedTarget = fromNode; enter = enterEvent; } accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from, to); } /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare ; } var objectIs = typeof Object.is === 'function' ? Object.is : is; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (objectIs(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { var currentKey = keysA[i]; if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) { return false; } } return true; } /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === TEXT_NODE) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } /** * @param {DOMElement} outerNode * @return {?object} */ function getOffsets(outerNode) { var ownerDocument = outerNode.ownerDocument; var win = ownerDocument && ownerDocument.defaultView || window; var selection = win.getSelection && win.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode, anchorOffset = selection.anchorOffset, focusNode = selection.focusNode, focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the // up/down buttons on an <input type="number">. Anonymous divs do not seem to // expose properties, triggering a "Permission denied error" if any of its // properties are accessed. The only seemingly possible way to avoid erroring // is to access a property that typically works for non-anonymous divs and // catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ anchorNode.nodeType; focusNode.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset); } /** * Returns {start, end} where `start` is the character/codepoint index of * (anchorNode, anchorOffset) within the textContent of `outerNode`, and * `end` is the index of (focusNode, focusOffset). * * Returns null if you pass in garbage input but we should probably just crash. * * Exported only for testing. */ function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) { var length = 0; var start = -1; var end = -1; var indexWithinAnchor = 0; var indexWithinFocus = 0; var node = outerNode; var parentNode = null; outer: while (true) { var next = null; while (true) { if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) { start = length + anchorOffset; } if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) { end = length + focusOffset; } if (node.nodeType === TEXT_NODE) { length += node.nodeValue.length; } if ((next = node.firstChild) === null) { break; } // Moving from `node` to its first child `next`. parentNode = node; node = next; } while (true) { if (node === outerNode) { // If `outerNode` has children, this is always the second time visiting // it. If it has no children, this is still the first loop, and the only // valid selection is anchorNode and focusNode both equal to this node // and both offsets 0, in which case we will have handled above. break outer; } if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) { start = length; } if (parentNode === focusNode && ++indexWithinFocus === focusOffset) { end = length; } if ((next = node.nextSibling) !== null) { break; } node = parentNode; parentNode = node.parentNode; } // Moving from `node` to its next sibling `next`. node = next; } if (start === -1 || end === -1) { // This should never happen. (Would happen if the anchor/focus nodes aren't // actually inside the passed-in node.) return null; } return { start: start, end: end }; } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setOffsets(node, offsets) { var doc = node.ownerDocument || document; var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios. // (For instance: TinyMCE editor used in a list component that supports pasting to add more, // fails when pasting 100+ items) if (!win.getSelection) { return; } var selection = win.getSelection(); var length = node.textContent.length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) { return; } var range = doc.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } function isTextNode(node) { return node && node.nodeType === TEXT_NODE; } function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if ('contains' in outerNode) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } function isInDocument(node) { return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node); } function isSameOriginFrame(iframe) { try { // Accessing the contentDocument of a HTMLIframeElement can cause the browser // to throw, e.g. if it has a cross-origin src attribute. // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g: // iframe.contentDocument.defaultView; // A safety way is to access one of the cross origin properties: Window or Location // Which might result in "SecurityError" DOM Exception and it is compatible to Safari. // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl return typeof iframe.contentWindow.location.href === 'string'; } catch (err) { return false; } } function getActiveElementDeep() { var win = window; var element = getActiveElement(); while (element instanceof win.HTMLIFrameElement) { if (isSameOriginFrame(element)) { win = element.contentWindow; } else { return element; } element = getActiveElement(win.document); } return element; } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ /** * @hasSelectionCapabilities: we get the element types that support selection * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart` * and `selectionEnd` rows. */ function hasSelectionCapabilities(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true'); } function getSelectionInformation() { var focusedElem = getActiveElementDeep(); return { focusedElem: focusedElem, selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null }; } /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ function restoreSelection(priorSelectionInformation) { var curFocusedElem = getActiveElementDeep(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) { setSelection(priorFocusedElem, priorSelectionRange); } // Focusing a node can change the scroll position, which is undesirable var ancestors = []; var ancestor = priorFocusedElem; while (ancestor = ancestor.parentNode) { if (ancestor.nodeType === ELEMENT_NODE) { ancestors.push({ element: ancestor, left: ancestor.scrollLeft, top: ancestor.scrollTop }); } } if (typeof priorFocusedElem.focus === 'function') { priorFocusedElem.focus(); } for (var i = 0; i < ancestors.length; i++) { var info = ancestors[i]; info.element.scrollLeft = info.left; info.element.scrollTop = info.top; } } } /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ function getSelection(input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else { // Content editable or old IE textarea. selection = getOffsets(input); } return selection || { start: 0, end: 0 }; } /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ function setSelection(input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else { setOffsets(input, offsets); } } var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11; function registerEvents$3() { registerTwoPhaseEvent('onSelect', ['focusout', 'contextmenu', 'dragend', 'focusin', 'keydown', 'keyup', 'mousedown', 'mouseup', 'selectionchange']); } var activeElement$1 = null; var activeElementInst$1 = null; var lastSelection = null; var mouseDown = false; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. */ function getSelection$1(node) { if ('selectionStart' in node && hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else { var win = node.ownerDocument && node.ownerDocument.defaultView || window; var selection = win.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } } /** * Get document associated with the event target. */ function getEventTargetDocument(eventTarget) { return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument; } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @param {object} nativeEventTarget * @return {?SyntheticEvent} */ function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. var doc = getEventTargetDocument(nativeEventTarget); if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) { return; } // Only fire when selection has actually changed. var currentSelection = getSelection$1(activeElement$1); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var listeners = accumulateTwoPhaseListeners(activeElementInst$1, 'onSelect'); if (listeners.length > 0) { var event = new SyntheticEvent('onSelect', 'select', null, nativeEvent, nativeEventTarget); dispatchQueue.push({ event: event, listeners: listeners }); event.target = activeElement$1; } } } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { var targetNode = targetInst ? getNodeFromInstance(targetInst) : window; switch (domEventName) { // Track the input node that has focus. case 'focusin': if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement$1 = targetNode; activeElementInst$1 = targetInst; lastSelection = null; } break; case 'focusout': activeElement$1 = null; activeElementInst$1 = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case 'mousedown': mouseDown = true; break; case 'contextmenu': case 'mouseup': case 'dragend': mouseDown = false; constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget); break; // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case 'selectionchange': if (skipSelectionChangeEvent) { break; } // falls through case 'keydown': case 'keyup': constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget); } } /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return eventName; } var ANIMATION_END = getVendorPrefixedEventName('animationend'); var ANIMATION_ITERATION = getVendorPrefixedEventName('animationiteration'); var ANIMATION_START = getVendorPrefixedEventName('animationstart'); var TRANSITION_END = getVendorPrefixedEventName('transitionend'); var topLevelEventsToReactNames = new Map(); // NOTE: Capitalization is important in this list! // // E.g. it needs "pointerDown", not "pointerdown". // This is because we derive both React name ("onPointerDown") // and DOM name ("pointerdown") from the same list. // // Exceptions that don't match this convention are listed separately. // // prettier-ignore var simpleEventPluginEvents = ['abort', 'auxClick', 'cancel', 'canPlay', 'canPlayThrough', 'click', 'close', 'contextMenu', 'copy', 'cut', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'pointerCancel', 'pointerDown', 'pointerMove', 'pointerOut', 'pointerOver', 'pointerUp', 'progress', 'rateChange', 'reset', 'resize', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'scroll', 'toggle', 'touchMove', 'waiting', 'wheel']; function registerSimpleEvent(domEventName, reactName) { topLevelEventsToReactNames.set(domEventName, reactName); registerTwoPhaseEvent(reactName, [domEventName]); } function registerSimpleEvents() { for (var i = 0; i < simpleEventPluginEvents.length; i++) { var eventName = simpleEventPluginEvents[i]; var domEventName = eventName.toLowerCase(); var capitalizedEvent = eventName[0].toUpperCase() + eventName.slice(1); registerSimpleEvent(domEventName, 'on' + capitalizedEvent); } // Special cases where event names don't match. registerSimpleEvent(ANIMATION_END, 'onAnimationEnd'); registerSimpleEvent(ANIMATION_ITERATION, 'onAnimationIteration'); registerSimpleEvent(ANIMATION_START, 'onAnimationStart'); registerSimpleEvent('dblclick', 'onDoubleClick'); registerSimpleEvent('focusin', 'onFocus'); registerSimpleEvent('focusout', 'onBlur'); registerSimpleEvent(TRANSITION_END, 'onTransitionEnd'); } function extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { var reactName = topLevelEventsToReactNames.get(domEventName); if (reactName === undefined) { return; } var SyntheticEventCtor = SyntheticEvent; var reactEventType = domEventName; switch (domEventName) { case 'keypress': // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return; } /* falls through */ case 'keydown': case 'keyup': SyntheticEventCtor = SyntheticKeyboardEvent; break; case 'focusin': reactEventType = 'focus'; SyntheticEventCtor = SyntheticFocusEvent; break; case 'focusout': reactEventType = 'blur'; SyntheticEventCtor = SyntheticFocusEvent; break; case 'beforeblur': case 'afterblur': SyntheticEventCtor = SyntheticFocusEvent; break; case 'click': // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return; } /* falls through */ case 'auxclick': case 'dblclick': case 'mousedown': case 'mousemove': case 'mouseup': // TODO: Disabled elements should not respond to mouse events /* falls through */ case 'mouseout': case 'mouseover': case 'contextmenu': SyntheticEventCtor = SyntheticMouseEvent; break; case 'drag': case 'dragend': case 'dragenter': case 'dragexit': case 'dragleave': case 'dragover': case 'dragstart': case 'drop': SyntheticEventCtor = SyntheticDragEvent; break; case 'touchcancel': case 'touchend': case 'touchmove': case 'touchstart': SyntheticEventCtor = SyntheticTouchEvent; break; case ANIMATION_END: case ANIMATION_ITERATION: case ANIMATION_START: SyntheticEventCtor = SyntheticAnimationEvent; break; case TRANSITION_END: SyntheticEventCtor = SyntheticTransitionEvent; break; case 'scroll': SyntheticEventCtor = SyntheticUIEvent; break; case 'wheel': SyntheticEventCtor = SyntheticWheelEvent; break; case 'copy': case 'cut': case 'paste': SyntheticEventCtor = SyntheticClipboardEvent; break; case 'gotpointercapture': case 'lostpointercapture': case 'pointercancel': case 'pointerdown': case 'pointermove': case 'pointerout': case 'pointerover': case 'pointerup': SyntheticEventCtor = SyntheticPointerEvent; break; } var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0; { // Some events don't bubble in the browser. // In the past, React has always bubbled them, but this can be surprising. // We're going to try aligning closer to the browser behavior by not bubbling // them in React either. We'll start by not bubbling onScroll, and then expand. var accumulateTargetOnly = !inCapturePhase && // TODO: ideally, we'd eventually add all events from // nonDelegatedEvents list in DOMPluginEventSystem. // Then we can remove this special list. // This is a breaking change that can wait until React 18. domEventName === 'scroll'; var _listeners = accumulateSinglePhaseListeners(targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly); if (_listeners.length > 0) { // Intentionally create event lazily. var _event = new SyntheticEventCtor(reactName, reactEventType, null, nativeEvent, nativeEventTarget); dispatchQueue.push({ event: _event, listeners: _listeners }); } } } // TODO: remove top-level side effect. registerSimpleEvents(); registerEvents$2(); registerEvents$1(); registerEvents$3(); registerEvents(); function extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { // TODO: we should remove the concept of a "SimpleEventPlugin". // This is the basic functionality of the event system. All // the other plugins are essentially polyfills. So the plugin // should probably be inlined somewhere and have its logic // be core the to event system. This would potentially allow // us to ship builds of React without the polyfilled plugins below. extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags); var shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0; // We don't process these events unless we are in the // event's native "bubble" phase, which means that we're // not in the capture phase. That's because we emulate // the capture phase here still. This is a trade-off, // because in an ideal world we would not emulate and use // the phases properly, like we do with the SimpleEvent // plugin. However, the plugins below either expect // emulation (EnterLeave) or use state localized to that // plugin (BeforeInput, Change, Select). The state in // these modules complicates things, as you'll essentially // get the case where the capture phase event might change // state, only for the following bubble event to come in // later and not trigger anything as the state now // invalidates the heuristics of the event plugin. We // could alter all these plugins to work in such ways, but // that might cause other unknown side-effects that we // can't foresee right now. if (shouldProcessPolyfillPlugins) { extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); } } // List of events that need to be individually attached to media elements. var mediaEventTypes = ['abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'loadeddata', 'loadedmetadata', 'loadstart', 'pause', 'play', 'playing', 'progress', 'ratechange', 'resize', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting']; // We should not delegate these events to the container, but rather // set them on the actual target element itself. This is primarily // because these events do not consistently bubble in the DOM. var nonDelegatedEvents = new Set(['cancel', 'close', 'invalid', 'load', 'scroll', 'toggle'].concat(mediaEventTypes)); function executeDispatch(event, listener, currentTarget) { var type = event.type || 'unknown-event'; event.currentTarget = currentTarget; invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; } function processDispatchQueueItemsInOrder(event, dispatchListeners, inCapturePhase) { var previousInstance; if (inCapturePhase) { for (var i = dispatchListeners.length - 1; i >= 0; i--) { var _dispatchListeners$i = dispatchListeners[i], instance = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget, listener = _dispatchListeners$i.listener; if (instance !== previousInstance && event.isPropagationStopped()) { return; } executeDispatch(event, listener, currentTarget); previousInstance = instance; } } else { for (var _i = 0; _i < dispatchListeners.length; _i++) { var _dispatchListeners$_i = dispatchListeners[_i], _instance = _dispatchListeners$_i.instance, _currentTarget = _dispatchListeners$_i.currentTarget, _listener = _dispatchListeners$_i.listener; if (_instance !== previousInstance && event.isPropagationStopped()) { return; } executeDispatch(event, _listener, _currentTarget); previousInstance = _instance; } } } function processDispatchQueue(dispatchQueue, eventSystemFlags) { var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0; for (var i = 0; i < dispatchQueue.length; i++) { var _dispatchQueue$i = dispatchQueue[i], event = _dispatchQueue$i.event, listeners = _dispatchQueue$i.listeners; processDispatchQueueItemsInOrder(event, listeners, inCapturePhase); // event system doesn't use pooling. } // This would be a good time to rethrow if any of the event handlers threw. rethrowCaughtError(); } function dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) { var nativeEventTarget = getEventTarget(nativeEvent); var dispatchQueue = []; extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags); processDispatchQueue(dispatchQueue, eventSystemFlags); } function listenToNonDelegatedEvent(domEventName, targetElement) { { if (!nonDelegatedEvents.has(domEventName)) { error('Did not expect a listenToNonDelegatedEvent() call for "%s". ' + 'This is a bug in React. Please file an issue.', domEventName); } } var isCapturePhaseListener = false; var listenerSet = getEventListenerSet(targetElement); var listenerSetKey = getListenerSetKey(domEventName, isCapturePhaseListener); if (!listenerSet.has(listenerSetKey)) { addTrappedEventListener(targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener); listenerSet.add(listenerSetKey); } } function listenToNativeEvent(domEventName, isCapturePhaseListener, target) { { if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) { error('Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. ' + 'This is a bug in React. Please file an issue.', domEventName); } } var eventSystemFlags = 0; if (isCapturePhaseListener) { eventSystemFlags |= IS_CAPTURE_PHASE; } addTrappedEventListener(target, domEventName, eventSystemFlags, isCapturePhaseListener); } // This is only used by createEventHandle when the var listeningMarker = '_reactListening' + Math.random().toString(36).slice(2); function listenToAllSupportedEvents(rootContainerElement) { if (!rootContainerElement[listeningMarker]) { rootContainerElement[listeningMarker] = true; allNativeEvents.forEach(function (domEventName) { // We handle selectionchange separately because it // doesn't bubble and needs to be on the document. if (domEventName !== 'selectionchange') { if (!nonDelegatedEvents.has(domEventName)) { listenToNativeEvent(domEventName, false, rootContainerElement); } listenToNativeEvent(domEventName, true, rootContainerElement); } }); var ownerDocument = rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument; if (ownerDocument !== null) { // The selectionchange event also needs deduplication // but it is attached to the document. if (!ownerDocument[listeningMarker]) { ownerDocument[listeningMarker] = true; listenToNativeEvent('selectionchange', false, ownerDocument); } } } } function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener, isDeferredListenerForLegacyFBSupport) { var listener = createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags); // If passive option is not supported, then the event will be // active and not passive. var isPassiveListener = undefined; if (passiveBrowserEventsSupported) { // Browsers introduced an intervention, making these events // passive by default on document. React doesn't bind them // to document anymore, but changing this now would undo // the performance wins from the change. So we emulate // the existing behavior manually on the roots now. // https://github.com/facebook/react/issues/19651 if (domEventName === 'touchstart' || domEventName === 'touchmove' || domEventName === 'wheel') { isPassiveListener = true; } } targetContainer = targetContainer; var unsubscribeListener; // When legacyFBSupport is enabled, it's for when we if (isCapturePhaseListener) { if (isPassiveListener !== undefined) { unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener); } else { unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener); } } else { if (isPassiveListener !== undefined) { unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener); } else { unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener); } } } function isMatchingRootContainer(grandContainer, targetContainer) { return grandContainer === targetContainer || grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer; } function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) { var ancestorInst = targetInst; if ((eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0) { var targetContainerNode = targetContainer; // If we are using the legacy FB support flag, we if (targetInst !== null) { // The below logic attempts to work out if we need to change // the target fiber to a different ancestor. We had similar logic // in the legacy event system, except the big difference between // systems is that the modern event system now has an event listener // attached to each React Root and React Portal Root. Together, // the DOM nodes representing these roots are the "rootContainer". // To figure out which ancestor instance we should use, we traverse // up the fiber tree from the target instance and attempt to find // root boundaries that match that of our current "rootContainer". // If we find that "rootContainer", we find the parent fiber // sub-tree for that root and make that our ancestor instance. var node = targetInst; mainLoop: while (true) { if (node === null) { return; } var nodeTag = node.tag; if (nodeTag === HostRoot || nodeTag === HostPortal) { var container = node.stateNode.containerInfo; if (isMatchingRootContainer(container, targetContainerNode)) { break; } if (nodeTag === HostPortal) { // The target is a portal, but it's not the rootContainer we're looking for. // Normally portals handle their own events all the way down to the root. // So we should be able to stop now. However, we don't know if this portal // was part of *our* root. var grandNode = node.return; while (grandNode !== null) { var grandTag = grandNode.tag; if (grandTag === HostRoot || grandTag === HostPortal) { var grandContainer = grandNode.stateNode.containerInfo; if (isMatchingRootContainer(grandContainer, targetContainerNode)) { // This is the rootContainer we're looking for and we found it as // a parent of the Portal. That means we can ignore it because the // Portal will bubble through to us. return; } } grandNode = grandNode.return; } } // Now we need to find it's corresponding host fiber in the other // tree. To do this we can use getClosestInstanceFromNode, but we // need to validate that the fiber is a host instance, otherwise // we need to traverse up through the DOM till we find the correct // node that is from the other tree. while (container !== null) { var parentNode = getClosestInstanceFromNode(container); if (parentNode === null) { return; } var parentTag = parentNode.tag; if (parentTag === HostComponent || parentTag === HostText) { node = ancestorInst = parentNode; continue mainLoop; } container = container.parentNode; } } node = node.return; } } } batchedUpdates(function () { return dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, ancestorInst); }); } function createDispatchListener(instance, listener, currentTarget) { return { instance: instance, listener: listener, currentTarget: currentTarget }; } function accumulateSinglePhaseListeners(targetFiber, reactName, nativeEventType, inCapturePhase, accumulateTargetOnly, nativeEvent) { var captureName = reactName !== null ? reactName + 'Capture' : null; var reactEventName = inCapturePhase ? captureName : reactName; var listeners = []; var instance = targetFiber; var lastHostComponent = null; // Accumulate all instances and listeners via the target -> root path. while (instance !== null) { var _instance2 = instance, stateNode = _instance2.stateNode, tag = _instance2.tag; // Handle listeners that are on HostComponents (i.e. <div>) if (tag === HostComponent && stateNode !== null) { lastHostComponent = stateNode; // createEventHandle listeners if (reactEventName !== null) { var listener = getListener(instance, reactEventName); if (listener != null) { listeners.push(createDispatchListener(instance, listener, lastHostComponent)); } } } // If we are only accumulating events for the target, then we don't // continue to propagate through the React fiber tree to find other // listeners. if (accumulateTargetOnly) { break; } // If we are processing the onBeforeBlur event, then we need to take instance = instance.return; } return listeners; } // We should only use this function for: // - BeforeInputEventPlugin // - ChangeEventPlugin // - SelectEventPlugin // This is because we only process these plugins // in the bubble phase, so we need to accumulate two // phase event listeners (via emulation). function accumulateTwoPhaseListeners(targetFiber, reactName) { var captureName = reactName + 'Capture'; var listeners = []; var instance = targetFiber; // Accumulate all instances and listeners via the target -> root path. while (instance !== null) { var _instance3 = instance, stateNode = _instance3.stateNode, tag = _instance3.tag; // Handle listeners that are on HostComponents (i.e. <div>) if (tag === HostComponent && stateNode !== null) { var currentTarget = stateNode; var captureListener = getListener(instance, captureName); if (captureListener != null) { listeners.unshift(createDispatchListener(instance, captureListener, currentTarget)); } var bubbleListener = getListener(instance, reactName); if (bubbleListener != null) { listeners.push(createDispatchListener(instance, bubbleListener, currentTarget)); } } instance = instance.return; } return listeners; } function getParent(inst) { if (inst === null) { return null; } do { inst = inst.return; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); if (inst) { return inst; } return null; } /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { var nodeA = instA; var nodeB = instB; var depthA = 0; for (var tempA = nodeA; tempA; tempA = getParent(tempA)) { depthA++; } var depthB = 0; for (var tempB = nodeB; tempB; tempB = getParent(tempB)) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { nodeA = getParent(nodeA); depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { nodeB = getParent(nodeB); depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) { return nodeA; } nodeA = getParent(nodeA); nodeB = getParent(nodeB); } return null; } function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common, inCapturePhase) { var registrationName = event._reactName; var listeners = []; var instance = target; while (instance !== null) { if (instance === common) { break; } var _instance4 = instance, alternate = _instance4.alternate, stateNode = _instance4.stateNode, tag = _instance4.tag; if (alternate !== null && alternate === common) { break; } if (tag === HostComponent && stateNode !== null) { var currentTarget = stateNode; if (inCapturePhase) { var captureListener = getListener(instance, registrationName); if (captureListener != null) { listeners.unshift(createDispatchListener(instance, captureListener, currentTarget)); } } else if (!inCapturePhase) { var bubbleListener = getListener(instance, registrationName); if (bubbleListener != null) { listeners.push(createDispatchListener(instance, bubbleListener, currentTarget)); } } } instance = instance.return; } if (listeners.length !== 0) { dispatchQueue.push({ event: event, listeners: listeners }); } } // We should only use this function for: // - EnterLeaveEventPlugin // This is because we only process this plugin // in the bubble phase, so we need to accumulate two // phase event listeners. function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leaveEvent, enterEvent, from, to) { var common = from && to ? getLowestCommonAncestor(from, to) : null; if (from !== null) { accumulateEnterLeaveListenersForEvent(dispatchQueue, leaveEvent, from, common, false); } if (to !== null && enterEvent !== null) { accumulateEnterLeaveListenersForEvent(dispatchQueue, enterEvent, to, common, true); } } function getListenerSetKey(domEventName, capture) { return domEventName + "__" + (capture ? 'capture' : 'bubble'); } var didWarnInvalidHydration = false; var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML'; var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning'; var SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning'; var AUTOFOCUS = 'autoFocus'; var CHILDREN = 'children'; var STYLE = 'style'; var HTML$1 = '__html'; var warnedUnknownTags; var validatePropertiesInDevelopment; var warnForPropDifference; var warnForExtraAttributes; var warnForInvalidEventListener; var canDiffStyleForHydrationWarning; var normalizeHTML; { warnedUnknownTags = { // There are working polyfills for <dialog>. Let people use it. dialog: true, // Electron ships a custom <webview> tag to display external web content in // an isolated frame and process. // This tag is not present in non Electron environments such as JSDom which // is often used for testing purposes. // @see https://electronjs.org/docs/api/webview-tag webview: true }; validatePropertiesInDevelopment = function (type, props) { validateProperties(type, props); validateProperties$1(type, props); validateProperties$2(type, props, { registrationNameDependencies: registrationNameDependencies, possibleRegistrationNames: possibleRegistrationNames }); }; // IE 11 parses & normalizes the style attribute as opposed to other // browsers. It adds spaces and sorts the properties in some // non-alphabetical order. Handling that would require sorting CSS // properties in the client & server versions or applying // `expectedStyle` to a temporary DOM node to read its `style` attribute // normalized. Since it only affects IE, we're skipping style warnings // in that browser completely in favor of doing all that work. // See https://github.com/facebook/react/issues/11807 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; warnForPropDifference = function (propName, serverValue, clientValue) { if (didWarnInvalidHydration) { return; } var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue); var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue); if (normalizedServerValue === normalizedClientValue) { return; } didWarnInvalidHydration = true; error('Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue)); }; warnForExtraAttributes = function (attributeNames) { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; var names = []; attributeNames.forEach(function (name) { names.push(name); }); error('Extra attributes from the server: %s', names); }; warnForInvalidEventListener = function (registrationName, listener) { if (listener === false) { error('Expected `%s` listener to be a function, instead got `false`.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName); } else { error('Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener); } }; // Parse the HTML and read it back to normalize the HTML string so that it // can be used for comparison. normalizeHTML = function (parent, html) { // We could have created a separate document here to avoid // re-initializing custom elements if they exist. But this breaks // how <noscript> is being handled. So we use the same document. // See the discussion in https://github.com/facebook/react/pull/11157. var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName); testElement.innerHTML = html; return testElement.innerHTML; }; } // HTML parsing normalizes CR and CRLF to LF. // It also can turn \u0000 into \uFFFD inside attributes. // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream // If we have a mismatch, it might be caused by that. // We will still patch up in this case but not fire the warning. var NORMALIZE_NEWLINES_REGEX = /\r\n?/g; var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g; function normalizeMarkupForTextOrAttribute(markup) { { checkHtmlStringCoercion(markup); } var markupString = typeof markup === 'string' ? markup : '' + markup; return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, ''); } function checkForUnmatchedText(serverText, clientText, isConcurrentMode, shouldWarnDev) { var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText); var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText); if (normalizedServerText === normalizedClientText) { return; } if (shouldWarnDev) { { if (!didWarnInvalidHydration) { didWarnInvalidHydration = true; error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText); } } } if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) { // In concurrent roots, we throw when there's a text mismatch and revert to // client rendering, up to the nearest Suspense boundary. throw new Error('Text content does not match server-rendered HTML.'); } } function getOwnerDocumentFromRootContainer(rootContainerElement) { return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument; } function noop() {} function trapClickOnNonInteractiveElement(node) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. // https://www.quirksmode.org/blog/archives/2010/09/click_event_del.html // Just set it using the onclick property so that we don't have to manage any // bookkeeping for it. Not sure if we need to clear it when the listener is // removed. // TODO: Only do this for the relevant Safaris maybe? node.onclick = noop; } function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) { for (var propKey in nextProps) { if (!nextProps.hasOwnProperty(propKey)) { continue; } var nextProp = nextProps[propKey]; if (propKey === STYLE) { { if (nextProp) { // Freeze the next style object so that we can assume it won't be // mutated. We have already warned for this in the past. Object.freeze(nextProp); } } // Relies on `updateStylesByID` not mutating `styleUpdates`. setValueForStyles(domElement, nextProp); } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { var nextHtml = nextProp ? nextProp[HTML$1] : undefined; if (nextHtml != null) { setInnerHTML(domElement, nextHtml); } } else if (propKey === CHILDREN) { if (typeof nextProp === 'string') { // Avoid setting initial textContent when the text is empty. In IE11 setting // textContent on a <textarea> will cause the placeholder to not // show within the <textarea> until it has been focused and blurred again. // https://github.com/facebook/react/issues/6731#issuecomment-254874553 var canSetTextContent = tag !== 'textarea' || nextProp !== ''; if (canSetTextContent) { setTextContent(domElement, nextProp); } } else if (typeof nextProp === 'number') { setTextContent(domElement, '' + nextProp); } } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) { if (nextProp != null) { if ( typeof nextProp !== 'function') { warnForInvalidEventListener(propKey, nextProp); } if (propKey === 'onScroll') { listenToNonDelegatedEvent('scroll', domElement); } } } else if (nextProp != null) { setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag); } } } function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) { // TODO: Handle wasCustomComponentTag for (var i = 0; i < updatePayload.length; i += 2) { var propKey = updatePayload[i]; var propValue = updatePayload[i + 1]; if (propKey === STYLE) { setValueForStyles(domElement, propValue); } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { setInnerHTML(domElement, propValue); } else if (propKey === CHILDREN) { setTextContent(domElement, propValue); } else { setValueForProperty(domElement, propKey, propValue, isCustomComponentTag); } } } function createElement(type, props, rootContainerElement, parentNamespace) { var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement); var domElement; var namespaceURI = parentNamespace; if (namespaceURI === HTML_NAMESPACE) { namespaceURI = getIntrinsicNamespace(type); } if (namespaceURI === HTML_NAMESPACE) { { isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to // allow <SVG> or <mATH>. if (!isCustomComponentTag && type !== type.toLowerCase()) { error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type); } } if (type === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); div.innerHTML = '<script><' + '/script>'; // eslint-disable-line // This is guaranteed to yield a script element. var firstChild = div.firstChild; domElement = div.removeChild(firstChild); } else if (typeof props.is === 'string') { // $FlowIssue `createElement` should be updated for Web Components domElement = ownerDocument.createElement(type, { is: props.is }); } else { // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug. // See discussion in https://github.com/facebook/react/pull/6896 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240 domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size` // attributes on `select`s needs to be added before `option`s are inserted. // This prevents: // - a bug where the `select` does not scroll to the correct option because singular // `select` elements automatically pick the first item #13222 // - a bug where the `select` set the first item as selected despite the `size` attribute #14239 // See https://github.com/facebook/react/issues/13222 // and https://github.com/facebook/react/issues/14239 if (type === 'select') { var node = domElement; if (props.multiple) { node.multiple = true; } else if (props.size) { // Setting a size greater than 1 causes a select to behave like `multiple=true`, where // it is possible that no option is selected. // // This is only necessary when a select in "single selection mode". node.size = props.size; } } } } else { domElement = ownerDocument.createElementNS(namespaceURI, type); } { if (namespaceURI === HTML_NAMESPACE) { if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !hasOwnProperty.call(warnedUnknownTags, type)) { warnedUnknownTags[type] = true; error('The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type); } } } return domElement; } function createTextNode(text, rootContainerElement) { return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text); } function setInitialProperties(domElement, tag, rawProps, rootContainerElement) { var isCustomComponentTag = isCustomComponent(tag, rawProps); { validatePropertiesInDevelopment(tag, rawProps); } // TODO: Make sure that we check isMounted before firing any of these events. var props; switch (tag) { case 'dialog': listenToNonDelegatedEvent('cancel', domElement); listenToNonDelegatedEvent('close', domElement); props = rawProps; break; case 'iframe': case 'object': case 'embed': // We listen to this event in case to ensure emulated bubble // listeners still fire for the load event. listenToNonDelegatedEvent('load', domElement); props = rawProps; break; case 'video': case 'audio': // We listen to these events in case to ensure emulated bubble // listeners still fire for all the media events. for (var i = 0; i < mediaEventTypes.length; i++) { listenToNonDelegatedEvent(mediaEventTypes[i], domElement); } props = rawProps; break; case 'source': // We listen to this event in case to ensure emulated bubble // listeners still fire for the error event. listenToNonDelegatedEvent('error', domElement); props = rawProps; break; case 'img': case 'image': case 'link': // We listen to these events in case to ensure emulated bubble // listeners still fire for error and load events. listenToNonDelegatedEvent('error', domElement); listenToNonDelegatedEvent('load', domElement); props = rawProps; break; case 'details': // We listen to this event in case to ensure emulated bubble // listeners still fire for the toggle event. listenToNonDelegatedEvent('toggle', domElement); props = rawProps; break; case 'input': initWrapperState(domElement, rawProps); props = getHostProps(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; case 'option': validateProps(domElement, rawProps); props = rawProps; break; case 'select': initWrapperState$1(domElement, rawProps); props = getHostProps$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; case 'textarea': initWrapperState$2(domElement, rawProps); props = getHostProps$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; default: props = rawProps; } assertValidProps(tag, props); setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag); switch (tag) { case 'input': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper(domElement, rawProps, false); break; case 'textarea': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper$3(domElement); break; case 'option': postMountWrapper$1(domElement, rawProps); break; case 'select': postMountWrapper$2(domElement, rawProps); break; default: if (typeof props.onClick === 'function') { // TODO: This cast may not be sound for SVG, MathML or custom elements. trapClickOnNonInteractiveElement(domElement); } break; } } // Calculate the diff between the two objects. function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) { { validatePropertiesInDevelopment(tag, nextRawProps); } var updatePayload = null; var lastProps; var nextProps; switch (tag) { case 'input': lastProps = getHostProps(domElement, lastRawProps); nextProps = getHostProps(domElement, nextRawProps); updatePayload = []; break; case 'select': lastProps = getHostProps$1(domElement, lastRawProps); nextProps = getHostProps$1(domElement, nextRawProps); updatePayload = []; break; case 'textarea': lastProps = getHostProps$2(domElement, lastRawProps); nextProps = getHostProps$2(domElement, nextRawProps); updatePayload = []; break; default: lastProps = lastRawProps; nextProps = nextRawProps; if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') { // TODO: This cast may not be sound for SVG, MathML or custom elements. trapClickOnNonInteractiveElement(domElement); } break; } assertValidProps(tag, nextProps); var propKey; var styleName; var styleUpdates = null; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = lastProps[propKey]; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { if (!styleUpdates) { styleUpdates = {}; } styleUpdates[styleName] = ''; } } } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) { // This is a special case. If any listener updates we need to ensure // that the "current" fiber pointer gets updated so we need a commit // to update this element. if (!updatePayload) { updatePayload = []; } } else { // For all other deleted properties we add it to the queue. We use // the allowed property list in the commit phase instead. (updatePayload = updatePayload || []).push(propKey, null); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { { if (nextProp) { // Freeze the next style object so that we can assume it won't be // mutated. We have already warned for this in the past. Object.freeze(nextProp); } } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { if (!styleUpdates) { styleUpdates = {}; } styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { if (!styleUpdates) { styleUpdates = {}; } styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. if (!styleUpdates) { if (!updatePayload) { updatePayload = []; } updatePayload.push(propKey, styleUpdates); } styleUpdates = nextProp; } } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { var nextHtml = nextProp ? nextProp[HTML$1] : undefined; var lastHtml = lastProp ? lastProp[HTML$1] : undefined; if (nextHtml != null) { if (lastHtml !== nextHtml) { (updatePayload = updatePayload || []).push(propKey, nextHtml); } } } else if (propKey === CHILDREN) { if (typeof nextProp === 'string' || typeof nextProp === 'number') { (updatePayload = updatePayload || []).push(propKey, '' + nextProp); } } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) { if (nextProp != null) { // We eagerly listen to this even though we haven't committed yet. if ( typeof nextProp !== 'function') { warnForInvalidEventListener(propKey, nextProp); } if (propKey === 'onScroll') { listenToNonDelegatedEvent('scroll', domElement); } } if (!updatePayload && lastProp !== nextProp) { // This is a special case. If any listener updates we need to ensure // that the "current" props pointer gets updated so we need a commit // to update this element. updatePayload = []; } } else { // For any other property we always add it to the queue and then we // filter it out using the allowed property list during the commit. (updatePayload = updatePayload || []).push(propKey, nextProp); } } if (styleUpdates) { { validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]); } (updatePayload = updatePayload || []).push(STYLE, styleUpdates); } return updatePayload; } // Apply the diff. function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) { // Update checked *before* name. // In the middle of an update, it is possible to have multiple checked. // When a checked radio tries to change name, browser makes another radio's checked false. if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) { updateChecked(domElement, nextRawProps); } var wasCustomComponentTag = isCustomComponent(tag, lastRawProps); var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff. updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props // changed. switch (tag) { case 'input': // Update the wrapper around inputs *after* updating props. This has to // happen after `updateDOMProperties`. Otherwise HTML5 input validations // raise warnings and prevent the new value from being assigned. updateWrapper(domElement, nextRawProps); break; case 'textarea': updateWrapper$1(domElement, nextRawProps); break; case 'select': // <select> value update needs to occur after <option> children // reconciliation postUpdateWrapper(domElement, nextRawProps); break; } } function getPossibleStandardName(propName) { { var lowerCasedName = propName.toLowerCase(); if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) { return null; } return possibleStandardNames[lowerCasedName] || null; } } function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement, isConcurrentMode, shouldWarnDev) { var isCustomComponentTag; var extraAttributeNames; { isCustomComponentTag = isCustomComponent(tag, rawProps); validatePropertiesInDevelopment(tag, rawProps); } // TODO: Make sure that we check isMounted before firing any of these events. switch (tag) { case 'dialog': listenToNonDelegatedEvent('cancel', domElement); listenToNonDelegatedEvent('close', domElement); break; case 'iframe': case 'object': case 'embed': // We listen to this event in case to ensure emulated bubble // listeners still fire for the load event. listenToNonDelegatedEvent('load', domElement); break; case 'video': case 'audio': // We listen to these events in case to ensure emulated bubble // listeners still fire for all the media events. for (var i = 0; i < mediaEventTypes.length; i++) { listenToNonDelegatedEvent(mediaEventTypes[i], domElement); } break; case 'source': // We listen to this event in case to ensure emulated bubble // listeners still fire for the error event. listenToNonDelegatedEvent('error', domElement); break; case 'img': case 'image': case 'link': // We listen to these events in case to ensure emulated bubble // listeners still fire for error and load events. listenToNonDelegatedEvent('error', domElement); listenToNonDelegatedEvent('load', domElement); break; case 'details': // We listen to this event in case to ensure emulated bubble // listeners still fire for the toggle event. listenToNonDelegatedEvent('toggle', domElement); break; case 'input': initWrapperState(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; case 'option': validateProps(domElement, rawProps); break; case 'select': initWrapperState$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; case 'textarea': initWrapperState$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble // listeners still fire for the invalid event. listenToNonDelegatedEvent('invalid', domElement); break; } assertValidProps(tag, rawProps); { extraAttributeNames = new Set(); var attributes = domElement.attributes; for (var _i = 0; _i < attributes.length; _i++) { var name = attributes[_i].name.toLowerCase(); switch (name) { // Controlled attributes are not validated // TODO: Only ignore them on controlled tags. case 'value': break; case 'checked': break; case 'selected': break; default: // Intentionally use the original name. // See discussion in https://github.com/facebook/react/pull/10676. extraAttributeNames.add(attributes[_i].name); } } } var updatePayload = null; for (var propKey in rawProps) { if (!rawProps.hasOwnProperty(propKey)) { continue; } var nextProp = rawProps[propKey]; if (propKey === CHILDREN) { // For text content children we compare against textContent. This // might match additional HTML that is hidden when we read it using // textContent. E.g. "foo" will match "f<span>oo</span>" but that still // satisfies our requirement. Our requirement is not to produce perfect // HTML and attributes. Ideally we should preserve structure but it's // ok not to if the visible content is still enough to indicate what // even listeners these nodes might be wired up to. // TODO: Warn if there is more than a single textNode as a child. // TODO: Should we use domElement.firstChild.nodeValue to compare? if (typeof nextProp === 'string') { if (domElement.textContent !== nextProp) { if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) { checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev); } updatePayload = [CHILDREN, nextProp]; } } else if (typeof nextProp === 'number') { if (domElement.textContent !== '' + nextProp) { if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) { checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev); } updatePayload = [CHILDREN, '' + nextProp]; } } } else if (registrationNameDependencies.hasOwnProperty(propKey)) { if (nextProp != null) { if ( typeof nextProp !== 'function') { warnForInvalidEventListener(propKey, nextProp); } if (propKey === 'onScroll') { listenToNonDelegatedEvent('scroll', domElement); } } } else if (shouldWarnDev && true && // Convince Flow we've calculated it (it's DEV-only in this method.) typeof isCustomComponentTag === 'boolean') { // Validate that the properties correspond to their expected values. var serverValue = void 0; var propertyInfo = isCustomComponentTag && enableCustomElementPropertySupport ? null : getPropertyInfo(propKey); if (rawProps[SUPPRESS_HYDRATION_WARNING] === true) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated // TODO: Only ignore them on controlled tags. propKey === 'value' || propKey === 'checked' || propKey === 'selected') ; else if (propKey === DANGEROUSLY_SET_INNER_HTML) { var serverHTML = domElement.innerHTML; var nextHtml = nextProp ? nextProp[HTML$1] : undefined; if (nextHtml != null) { var expectedHTML = normalizeHTML(domElement, nextHtml); if (expectedHTML !== serverHTML) { warnForPropDifference(propKey, serverHTML, expectedHTML); } } } else if (propKey === STYLE) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey); if (canDiffStyleForHydrationWarning) { var expectedStyle = createDangerousStringForStyles(nextProp); serverValue = domElement.getAttribute('style'); if (expectedStyle !== serverValue) { warnForPropDifference(propKey, serverValue, expectedStyle); } } } else if (isCustomComponentTag && !enableCustomElementPropertySupport) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey.toLowerCase()); serverValue = getValueForAttribute(domElement, propKey, nextProp); if (nextProp !== serverValue) { warnForPropDifference(propKey, serverValue, nextProp); } } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) { var isMismatchDueToBadCasing = false; if (propertyInfo !== null) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propertyInfo.attributeName); serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo); } else { var ownNamespace = parentNamespace; if (ownNamespace === HTML_NAMESPACE) { ownNamespace = getIntrinsicNamespace(tag); } if (ownNamespace === HTML_NAMESPACE) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey.toLowerCase()); } else { var standardName = getPossibleStandardName(propKey); if (standardName !== null && standardName !== propKey) { // If an SVG prop is supplied with bad casing, it will // be successfully parsed from HTML, but will produce a mismatch // (and would be incorrectly rendered on the client). // However, we already warn about bad casing elsewhere. // So we'll skip the misleading extra mismatch warning in this case. isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(standardName); } // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey); } serverValue = getValueForAttribute(domElement, propKey, nextProp); } var dontWarnCustomElement = enableCustomElementPropertySupport ; if (!dontWarnCustomElement && nextProp !== serverValue && !isMismatchDueToBadCasing) { warnForPropDifference(propKey, serverValue, nextProp); } } } } { if (shouldWarnDev) { if ( // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.size > 0 && rawProps[SUPPRESS_HYDRATION_WARNING] !== true) { // $FlowFixMe - Should be inferred as not undefined. warnForExtraAttributes(extraAttributeNames); } } } switch (tag) { case 'input': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper(domElement, rawProps, true); break; case 'textarea': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper$3(domElement); break; case 'select': case 'option': // For input and textarea we current always set the value property at // post mount to force it to diverge from attributes. However, for // option and select we don't quite do the same thing and select // is not resilient to the DOM state changing so we don't do that here. // TODO: Consider not doing this for input and textarea. break; default: if (typeof rawProps.onClick === 'function') { // TODO: This cast may not be sound for SVG, MathML or custom elements. trapClickOnNonInteractiveElement(domElement); } break; } return updatePayload; } function diffHydratedText(textNode, text, isConcurrentMode) { var isDifferent = textNode.nodeValue !== text; return isDifferent; } function warnForDeletedHydratableElement(parentNode, child) { { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; error('Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase()); } } function warnForDeletedHydratableText(parentNode, child) { { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase()); } } function warnForInsertedHydratedElement(parentNode, tag, props) { { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; error('Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase()); } } function warnForInsertedHydratedText(parentNode, text) { { if (text === '') { // We expect to insert empty text nodes since they're not represented in // the HTML. // TODO: Remove this special case if we can just avoid inserting empty // text nodes. return; } if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase()); } } function restoreControlledState$3(domElement, tag, props) { switch (tag) { case 'input': restoreControlledState(domElement, props); return; case 'textarea': restoreControlledState$2(domElement, props); return; case 'select': restoreControlledState$1(domElement, props); return; } } var validateDOMNesting = function () {}; var updatedAncestorInfo = function () {}; { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; updatedAncestorInfo = function (oldInfo, tag) { var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body' || tag === 'frameset'; case 'frameset': return tag === 'frame'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frameset': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; var didWarn$1 = {}; validateDOMNesting = function (childTag, childText, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; if (childText != null) { if (childTag != null) { error('validateDOMNesting: when childText is passed, childTag should be null'); } childTag = '#text'; } var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var invalidParentOrAncestor = invalidParent || invalidAncestor; if (!invalidParentOrAncestor) { return; } var ancestorTag = invalidParentOrAncestor.tag; var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag; if (didWarn$1[warnKey]) { return; } didWarn$1[warnKey] = true; var tagDisplayName = childTag; var whitespaceInfo = ''; if (childTag === '#text') { if (/\S/.test(childText)) { tagDisplayName = 'Text nodes'; } else { tagDisplayName = 'Whitespace text nodes'; whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.'; } } else { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.'; } error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info); } else { error('validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag); } }; } var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning'; var SUSPENSE_START_DATA = '$'; var SUSPENSE_END_DATA = '/$'; var SUSPENSE_PENDING_START_DATA = '$?'; var SUSPENSE_FALLBACK_START_DATA = '$!'; var STYLE$1 = 'style'; var eventsEnabled = null; var selectionInformation = null; function getRootHostContext(rootContainerInstance) { var type; var namespace; var nodeType = rootContainerInstance.nodeType; switch (nodeType) { case DOCUMENT_NODE: case DOCUMENT_FRAGMENT_NODE: { type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment'; var root = rootContainerInstance.documentElement; namespace = root ? root.namespaceURI : getChildNamespace(null, ''); break; } default: { var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance; var ownNamespace = container.namespaceURI || null; type = container.tagName; namespace = getChildNamespace(ownNamespace, type); break; } } { var validatedTag = type.toLowerCase(); var ancestorInfo = updatedAncestorInfo(null, validatedTag); return { namespace: namespace, ancestorInfo: ancestorInfo }; } } function getChildHostContext(parentHostContext, type, rootContainerInstance) { { var parentHostContextDev = parentHostContext; var namespace = getChildNamespace(parentHostContextDev.namespace, type); var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type); return { namespace: namespace, ancestorInfo: ancestorInfo }; } } function getPublicInstance(instance) { return instance; } function prepareForCommit(containerInfo) { eventsEnabled = isEnabled(); selectionInformation = getSelectionInformation(); var activeInstance = null; setEnabled(false); return activeInstance; } function resetAfterCommit(containerInfo) { restoreSelection(selectionInformation); setEnabled(eventsEnabled); eventsEnabled = null; selectionInformation = null; } function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) { var parentNamespace; { // TODO: take namespace into account when validating. var hostContextDev = hostContext; validateDOMNesting(type, null, hostContextDev.ancestorInfo); if (typeof props.children === 'string' || typeof props.children === 'number') { var string = '' + props.children; var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type); validateDOMNesting(null, string, ownAncestorInfo); } parentNamespace = hostContextDev.namespace; } var domElement = createElement(type, props, rootContainerInstance, parentNamespace); precacheFiberNode(internalInstanceHandle, domElement); updateFiberProps(domElement, props); return domElement; } function appendInitialChild(parentInstance, child) { parentInstance.appendChild(child); } function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) { setInitialProperties(domElement, type, props, rootContainerInstance); switch (type) { case 'button': case 'input': case 'select': case 'textarea': return !!props.autoFocus; case 'img': return true; default: return false; } } function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) { { var hostContextDev = hostContext; if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) { var string = '' + newProps.children; var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type); validateDOMNesting(null, string, ownAncestorInfo); } } return diffProperties(domElement, type, oldProps, newProps); } function shouldSetTextContent(type, props) { return type === 'textarea' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null; } function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) { { var hostContextDev = hostContext; validateDOMNesting(null, text, hostContextDev.ancestorInfo); } var textNode = createTextNode(text, rootContainerInstance); precacheFiberNode(internalInstanceHandle, textNode); return textNode; } function getCurrentEventPriority() { var currentEvent = window.event; if (currentEvent === undefined) { return DefaultEventPriority; } return getEventPriority(currentEvent.type); } // if a component just imports ReactDOM (e.g. for findDOMNode). // Some environments might not have setTimeout or clearTimeout. var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined; var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined; var noTimeout = -1; var localPromise = typeof Promise === 'function' ? Promise : undefined; // ------------------- var scheduleMicrotask = typeof queueMicrotask === 'function' ? queueMicrotask : typeof localPromise !== 'undefined' ? function (callback) { return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick); } : scheduleTimeout; // TODO: Determine the best fallback here. function handleErrorInNextTick(error) { setTimeout(function () { throw error; }); } // ------------------- function commitMount(domElement, type, newProps, internalInstanceHandle) { // Despite the naming that might imply otherwise, this method only // fires if there is an `Update` effect scheduled during mounting. // This happens if `finalizeInitialChildren` returns `true` (which it // does to implement the `autoFocus` attribute on the client). But // there are also other cases when this might happen (such as patching // up text content during hydration mismatch). So we'll check this again. switch (type) { case 'button': case 'input': case 'select': case 'textarea': if (newProps.autoFocus) { domElement.focus(); } return; case 'img': { if (newProps.src) { domElement.src = newProps.src; } return; } } } function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) { // Apply the diff to the DOM node. updateProperties(domElement, updatePayload, type, oldProps, newProps); // Update the props handle so that we know which props are the ones with // with current event handlers. updateFiberProps(domElement, newProps); } function resetTextContent(domElement) { setTextContent(domElement, ''); } function commitTextUpdate(textInstance, oldText, newText) { textInstance.nodeValue = newText; } function appendChild(parentInstance, child) { parentInstance.appendChild(child); } function appendChildToContainer(container, child) { var parentNode; if (container.nodeType === COMMENT_NODE) { parentNode = container.parentNode; parentNode.insertBefore(child, container); } else { parentNode = container; parentNode.appendChild(child); } // This container might be used for a portal. // If something inside a portal is clicked, that click should bubble // through the React tree. However, on Mobile Safari the click would // never bubble through the *DOM* tree unless an ancestor with onclick // event exists. So we wouldn't see it and dispatch it. // This is why we ensure that non React root containers have inline onclick // defined. // https://github.com/facebook/react/issues/11918 var reactRootContainer = container._reactRootContainer; if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) { // TODO: This cast may not be sound for SVG, MathML or custom elements. trapClickOnNonInteractiveElement(parentNode); } } function insertBefore(parentInstance, child, beforeChild) { parentInstance.insertBefore(child, beforeChild); } function insertInContainerBefore(container, child, beforeChild) { if (container.nodeType === COMMENT_NODE) { container.parentNode.insertBefore(child, beforeChild); } else { container.insertBefore(child, beforeChild); } } function removeChild(parentInstance, child) { parentInstance.removeChild(child); } function removeChildFromContainer(container, child) { if (container.nodeType === COMMENT_NODE) { container.parentNode.removeChild(child); } else { container.removeChild(child); } } function clearSuspenseBoundary(parentInstance, suspenseInstance) { var node = suspenseInstance; // Delete all nodes within this suspense boundary. // There might be nested nodes so we need to keep track of how // deep we are and only break out when we're back on top. var depth = 0; do { var nextNode = node.nextSibling; parentInstance.removeChild(node); if (nextNode && nextNode.nodeType === COMMENT_NODE) { var data = nextNode.data; if (data === SUSPENSE_END_DATA) { if (depth === 0) { parentInstance.removeChild(nextNode); // Retry if any event replaying was blocked on this. retryIfBlockedOn(suspenseInstance); return; } else { depth--; } } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) { depth++; } } node = nextNode; } while (node); // TODO: Warn, we didn't find the end comment boundary. // Retry if any event replaying was blocked on this. retryIfBlockedOn(suspenseInstance); } function clearSuspenseBoundaryFromContainer(container, suspenseInstance) { if (container.nodeType === COMMENT_NODE) { clearSuspenseBoundary(container.parentNode, suspenseInstance); } else if (container.nodeType === ELEMENT_NODE) { clearSuspenseBoundary(container, suspenseInstance); } // Retry if any event replaying was blocked on this. retryIfBlockedOn(container); } function hideInstance(instance) { // TODO: Does this work for all element types? What about MathML? Should we // pass host context to this method? instance = instance; var style = instance.style; if (typeof style.setProperty === 'function') { style.setProperty('display', 'none', 'important'); } else { style.display = 'none'; } } function hideTextInstance(textInstance) { textInstance.nodeValue = ''; } function unhideInstance(instance, props) { instance = instance; var styleProp = props[STYLE$1]; var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null; instance.style.display = dangerousStyleValue('display', display); } function unhideTextInstance(textInstance, text) { textInstance.nodeValue = text; } function clearContainer(container) { if (container.nodeType === ELEMENT_NODE) { container.textContent = ''; } else if (container.nodeType === DOCUMENT_NODE) { if (container.documentElement) { container.removeChild(container.documentElement); } } } // ------------------- function canHydrateInstance(instance, type, props) { if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) { return null; } // This has now been refined to an element node. return instance; } function canHydrateTextInstance(instance, text) { if (text === '' || instance.nodeType !== TEXT_NODE) { // Empty strings are not parsed by HTML so there won't be a correct match here. return null; } // This has now been refined to a text node. return instance; } function canHydrateSuspenseInstance(instance) { if (instance.nodeType !== COMMENT_NODE) { // Empty strings are not parsed by HTML so there won't be a correct match here. return null; } // This has now been refined to a suspense node. return instance; } function isSuspenseInstancePending(instance) { return instance.data === SUSPENSE_PENDING_START_DATA; } function isSuspenseInstanceFallback(instance) { return instance.data === SUSPENSE_FALLBACK_START_DATA; } function getSuspenseInstanceFallbackErrorDetails(instance) { var dataset = instance.nextSibling && instance.nextSibling.dataset; var digest, message, stack; if (dataset) { digest = dataset.dgst; { message = dataset.msg; stack = dataset.stck; } } { return { message: message, digest: digest, stack: stack }; } // let value = {message: undefined, hash: undefined}; // const nextSibling = instance.nextSibling; // if (nextSibling) { // const dataset = ((nextSibling: any): HTMLTemplateElement).dataset; // value.message = dataset.msg; // value.hash = dataset.hash; // if (true) { // value.stack = dataset.stack; // } // } // return value; } function registerSuspenseInstanceRetry(instance, callback) { instance._reactRetry = callback; } function getNextHydratable(node) { // Skip non-hydratable nodes. for (; node != null; node = node.nextSibling) { var nodeType = node.nodeType; if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) { break; } if (nodeType === COMMENT_NODE) { var nodeData = node.data; if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) { break; } if (nodeData === SUSPENSE_END_DATA) { return null; } } } return node; } function getNextHydratableSibling(instance) { return getNextHydratable(instance.nextSibling); } function getFirstHydratableChild(parentInstance) { return getNextHydratable(parentInstance.firstChild); } function getFirstHydratableChildWithinContainer(parentContainer) { return getNextHydratable(parentContainer.firstChild); } function getFirstHydratableChildWithinSuspenseInstance(parentInstance) { return getNextHydratable(parentInstance.nextSibling); } function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle, shouldWarnDev) { precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events // get attached. updateFiberProps(instance, props); var parentNamespace; { var hostContextDev = hostContext; parentNamespace = hostContextDev.namespace; } // TODO: Temporary hack to check if we're in a concurrent root. We can delete // when the legacy root API is removed. var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode; return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance, isConcurrentMode, shouldWarnDev); } function hydrateTextInstance(textInstance, text, internalInstanceHandle, shouldWarnDev) { precacheFiberNode(internalInstanceHandle, textInstance); // TODO: Temporary hack to check if we're in a concurrent root. We can delete // when the legacy root API is removed. var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode; return diffHydratedText(textInstance, text); } function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) { precacheFiberNode(internalInstanceHandle, suspenseInstance); } function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) { var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary. // There might be nested nodes so we need to keep track of how // deep we are and only break out when we're back on top. var depth = 0; while (node) { if (node.nodeType === COMMENT_NODE) { var data = node.data; if (data === SUSPENSE_END_DATA) { if (depth === 0) { return getNextHydratableSibling(node); } else { depth--; } } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) { depth++; } } node = node.nextSibling; } // TODO: Warn, we didn't find the end comment boundary. return null; } // Returns the SuspenseInstance if this node is a direct child of a // SuspenseInstance. I.e. if its previous sibling is a Comment with // SUSPENSE_x_START_DATA. Otherwise, null. function getParentSuspenseInstance(targetInstance) { var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary. // There might be nested nodes so we need to keep track of how // deep we are and only break out when we're back on top. var depth = 0; while (node) { if (node.nodeType === COMMENT_NODE) { var data = node.data; if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) { if (depth === 0) { return node; } else { depth--; } } else if (data === SUSPENSE_END_DATA) { depth++; } } node = node.previousSibling; } return null; } function commitHydratedContainer(container) { // Retry if any event replaying was blocked on this. retryIfBlockedOn(container); } function commitHydratedSuspenseInstance(suspenseInstance) { // Retry if any event replaying was blocked on this. retryIfBlockedOn(suspenseInstance); } function shouldDeleteUnhydratedTailInstances(parentType) { return parentType !== 'head' && parentType !== 'body'; } function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text, isConcurrentMode) { var shouldWarnDev = true; checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev); } function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text, isConcurrentMode) { if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { var shouldWarnDev = true; checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev); } } function didNotHydrateInstanceWithinContainer(parentContainer, instance) { { if (instance.nodeType === ELEMENT_NODE) { warnForDeletedHydratableElement(parentContainer, instance); } else if (instance.nodeType === COMMENT_NODE) ; else { warnForDeletedHydratableText(parentContainer, instance); } } } function didNotHydrateInstanceWithinSuspenseInstance(parentInstance, instance) { { // $FlowFixMe: Only Element or Document can be parent nodes. var parentNode = parentInstance.parentNode; if (parentNode !== null) { if (instance.nodeType === ELEMENT_NODE) { warnForDeletedHydratableElement(parentNode, instance); } else if (instance.nodeType === COMMENT_NODE) ; else { warnForDeletedHydratableText(parentNode, instance); } } } } function didNotHydrateInstance(parentType, parentProps, parentInstance, instance, isConcurrentMode) { { if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { if (instance.nodeType === ELEMENT_NODE) { warnForDeletedHydratableElement(parentInstance, instance); } else if (instance.nodeType === COMMENT_NODE) ; else { warnForDeletedHydratableText(parentInstance, instance); } } } } function didNotFindHydratableInstanceWithinContainer(parentContainer, type, props) { { warnForInsertedHydratedElement(parentContainer, type); } } function didNotFindHydratableTextInstanceWithinContainer(parentContainer, text) { { warnForInsertedHydratedText(parentContainer, text); } } function didNotFindHydratableInstanceWithinSuspenseInstance(parentInstance, type, props) { { // $FlowFixMe: Only Element or Document can be parent nodes. var parentNode = parentInstance.parentNode; if (parentNode !== null) warnForInsertedHydratedElement(parentNode, type); } } function didNotFindHydratableTextInstanceWithinSuspenseInstance(parentInstance, text) { { // $FlowFixMe: Only Element or Document can be parent nodes. var parentNode = parentInstance.parentNode; if (parentNode !== null) warnForInsertedHydratedText(parentNode, text); } } function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props, isConcurrentMode) { { if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { warnForInsertedHydratedElement(parentInstance, type); } } } function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text, isConcurrentMode) { { if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { warnForInsertedHydratedText(parentInstance, text); } } } function errorHydratingContainer(parentContainer) { { // TODO: This gets logged by onRecoverableError, too, so we should be // able to remove it. error('An error occurred during hydration. The server HTML was replaced with client content in <%s>.', parentContainer.nodeName.toLowerCase()); } } function preparePortalMount(portalInstance) { listenToAllSupportedEvents(portalInstance); } var randomKey = Math.random().toString(36).slice(2); var internalInstanceKey = '__reactFiber$' + randomKey; var internalPropsKey = '__reactProps$' + randomKey; var internalContainerInstanceKey = '__reactContainer$' + randomKey; var internalEventHandlersKey = '__reactEvents$' + randomKey; var internalEventHandlerListenersKey = '__reactListeners$' + randomKey; var internalEventHandlesSetKey = '__reactHandles$' + randomKey; function detachDeletedInstance(node) { // TODO: This function is only called on host components. I don't think all of // these fields are relevant. delete node[internalInstanceKey]; delete node[internalPropsKey]; delete node[internalEventHandlersKey]; delete node[internalEventHandlerListenersKey]; delete node[internalEventHandlesSetKey]; } function precacheFiberNode(hostInst, node) { node[internalInstanceKey] = hostInst; } function markContainerAsRoot(hostRoot, node) { node[internalContainerInstanceKey] = hostRoot; } function unmarkContainerAsRoot(node) { node[internalContainerInstanceKey] = null; } function isContainerMarkedAsRoot(node) { return !!node[internalContainerInstanceKey]; } // Given a DOM node, return the closest HostComponent or HostText fiber ancestor. // If the target node is part of a hydrated or not yet rendered subtree, then // this may also return a SuspenseComponent or HostRoot to indicate that. // Conceptually the HostRoot fiber is a child of the Container node. So if you // pass the Container node as the targetNode, you will not actually get the // HostRoot back. To get to the HostRoot, you need to pass a child of it. // The same thing applies to Suspense boundaries. function getClosestInstanceFromNode(targetNode) { var targetInst = targetNode[internalInstanceKey]; if (targetInst) { // Don't return HostRoot or SuspenseComponent here. return targetInst; } // If the direct event target isn't a React owned DOM node, we need to look // to see if one of its parents is a React owned DOM node. var parentNode = targetNode.parentNode; while (parentNode) { // We'll check if this is a container root that could include // React nodes in the future. We need to check this first because // if we're a child of a dehydrated container, we need to first // find that inner container before moving on to finding the parent // instance. Note that we don't check this field on the targetNode // itself because the fibers are conceptually between the container // node and the first child. It isn't surrounding the container node. // If it's not a container, we check if it's an instance. targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey]; if (targetInst) { // Since this wasn't the direct target of the event, we might have // stepped past dehydrated DOM nodes to get here. However they could // also have been non-React nodes. We need to answer which one. // If we the instance doesn't have any children, then there can't be // a nested suspense boundary within it. So we can use this as a fast // bailout. Most of the time, when people add non-React children to // the tree, it is using a ref to a child-less DOM node. // Normally we'd only need to check one of the fibers because if it // has ever gone from having children to deleting them or vice versa // it would have deleted the dehydrated boundary nested inside already. // However, since the HostRoot starts out with an alternate it might // have one on the alternate so we need to check in case this was a // root. var alternate = targetInst.alternate; if (targetInst.child !== null || alternate !== null && alternate.child !== null) { // Next we need to figure out if the node that skipped past is // nested within a dehydrated boundary and if so, which one. var suspenseInstance = getParentSuspenseInstance(targetNode); while (suspenseInstance !== null) { // We found a suspense instance. That means that we haven't // hydrated it yet. Even though we leave the comments in the // DOM after hydrating, and there are boundaries in the DOM // that could already be hydrated, we wouldn't have found them // through this pass since if the target is hydrated it would // have had an internalInstanceKey on it. // Let's get the fiber associated with the SuspenseComponent // as the deepest instance. var targetSuspenseInst = suspenseInstance[internalInstanceKey]; if (targetSuspenseInst) { return targetSuspenseInst; } // If we don't find a Fiber on the comment, it might be because // we haven't gotten to hydrate it yet. There might still be a // parent boundary that hasn't above this one so we need to find // the outer most that is known. suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent // host component also hasn't hydrated yet. We can return it // below since it will bail out on the isMounted check later. } } return targetInst; } targetNode = parentNode; parentNode = targetNode.parentNode; } return null; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = node[internalInstanceKey] || node[internalContainerInstanceKey]; if (inst) { if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) { return inst; } else { return null; } } return null; } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { if (inst.tag === HostComponent || inst.tag === HostText) { // In Fiber this, is just the state node right now. We assume it will be // a host component or host text. return inst.stateNode; } // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. throw new Error('getNodeFromInstance: Invalid argument.'); } function getFiberCurrentPropsFromNode(node) { return node[internalPropsKey] || null; } function updateFiberProps(node, props) { node[internalPropsKey] = props; } function getEventListenerSet(node) { var elementListenerSet = node[internalEventHandlersKey]; if (elementListenerSet === undefined) { elementListenerSet = node[internalEventHandlersKey] = new Set(); } return elementListenerSet; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { // eslint-disable-next-line react-internal/prod-error-codes var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } var valueStack = []; var fiberStack; { fiberStack = []; } var index = -1; function createCursor(defaultValue) { return { current: defaultValue }; } function pop(cursor, fiber) { if (index < 0) { { error('Unexpected pop.'); } return; } { if (fiber !== fiberStack[index]) { error('Unexpected Fiber popped.'); } } cursor.current = valueStack[index]; valueStack[index] = null; { fiberStack[index] = null; } index--; } function push(cursor, value, fiber) { index++; valueStack[index] = cursor.current; { fiberStack[index] = fiber; } cursor.current = value; } var warnedAboutMissingGetChildContext; { warnedAboutMissingGetChildContext = {}; } var emptyContextObject = {}; { Object.freeze(emptyContextObject); } // A cursor to the current merged context object on the stack. var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. // We use this to get access to the parent context after we have already // pushed the next context provider, and now need to merge their contexts. var previousContext = emptyContextObject; function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) { { if (didPushOwnContextIfProvider && isContextProvider(Component)) { // If the fiber is a context provider itself, when we read its context // we may have already pushed its own child context on the stack. A context // provider should not "see" its own child context. Therefore we read the // previous (parent) context instead for a context provider. return previousContext; } return contextStackCursor.current; } } function cacheContext(workInProgress, unmaskedContext, maskedContext) { { var instance = workInProgress.stateNode; instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; instance.__reactInternalMemoizedMaskedChildContext = maskedContext; } } function getMaskedContext(workInProgress, unmaskedContext) { { var type = workInProgress.type; var contextTypes = type.contextTypes; if (!contextTypes) { return emptyContextObject; } // Avoid recreating masked context unless unmasked context has changed. // Failing to do this will result in unnecessary calls to componentWillReceiveProps. // This may trigger infinite loops if componentWillReceiveProps calls setState. var instance = workInProgress.stateNode; if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { return instance.__reactInternalMemoizedMaskedChildContext; } var context = {}; for (var key in contextTypes) { context[key] = unmaskedContext[key]; } { var name = getComponentNameFromFiber(workInProgress) || 'Unknown'; checkPropTypes(contextTypes, context, 'context', name); } // Cache unmasked context so we can avoid recreating masked context unless necessary. // Context is created before the class component is instantiated so check for instance. if (instance) { cacheContext(workInProgress, unmaskedContext, context); } return context; } } function hasContextChanged() { { return didPerformWorkStackCursor.current; } } function isContextProvider(type) { { var childContextTypes = type.childContextTypes; return childContextTypes !== null && childContextTypes !== undefined; } } function popContext(fiber) { { pop(didPerformWorkStackCursor, fiber); pop(contextStackCursor, fiber); } } function popTopLevelContextObject(fiber) { { pop(didPerformWorkStackCursor, fiber); pop(contextStackCursor, fiber); } } function pushTopLevelContextObject(fiber, context, didChange) { { if (contextStackCursor.current !== emptyContextObject) { throw new Error('Unexpected context found on stack. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); } } function processChildContext(fiber, type, parentContext) { { var instance = fiber.stateNode; var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. // It has only been added in Fiber to match the (unintentional) behavior in Stack. if (typeof instance.getChildContext !== 'function') { { var componentName = getComponentNameFromFiber(fiber) || 'Unknown'; if (!warnedAboutMissingGetChildContext[componentName]) { warnedAboutMissingGetChildContext[componentName] = true; error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); } } return parentContext; } var childContext = instance.getChildContext(); for (var contextKey in childContext) { if (!(contextKey in childContextTypes)) { throw new Error((getComponentNameFromFiber(fiber) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."); } } { var name = getComponentNameFromFiber(fiber) || 'Unknown'; checkPropTypes(childContextTypes, childContext, 'child context', name); } return assign({}, parentContext, childContext); } } function pushContextProvider(workInProgress) { { var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. // If the instance does not exist yet, we will push null at first, // and replace it on the stack later when invalidating the context. var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later. // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. previousContext = contextStackCursor.current; push(contextStackCursor, memoizedMergedChildContext, workInProgress); push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress); return true; } } function invalidateContextProvider(workInProgress, type, didChange) { { var instance = workInProgress.stateNode; if (!instance) { throw new Error('Expected to have an instance by this point. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } if (didChange) { // Merge parent and own context. // Skip this if we're not updating due to sCU. // This avoids unnecessarily recomputing memoized values. var mergedContext = processChildContext(workInProgress, type, previousContext); instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. // It is important to unwind the context in the reverse order. pop(didPerformWorkStackCursor, workInProgress); pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. push(contextStackCursor, mergedContext, workInProgress); push(didPerformWorkStackCursor, didChange, workInProgress); } else { pop(didPerformWorkStackCursor, workInProgress); push(didPerformWorkStackCursor, didChange, workInProgress); } } } function findCurrentUnmaskedContext(fiber) { { // Currently this is only used with renderSubtreeIntoContainer; not sure if it // makes sense elsewhere if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) { throw new Error('Expected subtree parent to be a mounted class component. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } var node = fiber; do { switch (node.tag) { case HostRoot: return node.stateNode.context; case ClassComponent: { var Component = node.type; if (isContextProvider(Component)) { return node.stateNode.__reactInternalMemoizedMergedChildContext; } break; } } node = node.return; } while (node !== null); throw new Error('Found unexpected detached subtree parent. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } } var LegacyRoot = 0; var ConcurrentRoot = 1; var syncQueue = null; var includesLegacySyncCallbacks = false; var isFlushingSyncQueue = false; function scheduleSyncCallback(callback) { // Push this callback into an internal queue. We'll flush these either in // the next tick, or earlier if something calls `flushSyncCallbackQueue`. if (syncQueue === null) { syncQueue = [callback]; } else { // Push onto existing queue. Don't need to schedule a callback because // we already scheduled one when we created the queue. syncQueue.push(callback); } } function scheduleLegacySyncCallback(callback) { includesLegacySyncCallbacks = true; scheduleSyncCallback(callback); } function flushSyncCallbacksOnlyInLegacyMode() { // Only flushes the queue if there's a legacy sync callback scheduled. // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So // it might make more sense for the queue to be a list of roots instead of a // list of generic callbacks. Then we can have two: one for legacy roots, one // for concurrent roots. And this method would only flush the legacy ones. if (includesLegacySyncCallbacks) { flushSyncCallbacks(); } } function flushSyncCallbacks() { if (!isFlushingSyncQueue && syncQueue !== null) { // Prevent re-entrance. isFlushingSyncQueue = true; var i = 0; var previousUpdatePriority = getCurrentUpdatePriority(); try { var isSync = true; var queue = syncQueue; // TODO: Is this necessary anymore? The only user code that runs in this // queue is in the render or commit phases. setCurrentUpdatePriority(DiscreteEventPriority); for (; i < queue.length; i++) { var callback = queue[i]; do { callback = callback(isSync); } while (callback !== null); } syncQueue = null; includesLegacySyncCallbacks = false; } catch (error) { // If something throws, leave the remaining callbacks on the queue. if (syncQueue !== null) { syncQueue = syncQueue.slice(i + 1); } // Resume flushing in the next tick scheduleCallback(ImmediatePriority, flushSyncCallbacks); throw error; } finally { setCurrentUpdatePriority(previousUpdatePriority); isFlushingSyncQueue = false; } } return null; } // TODO: Use the unified fiber stack module instead of this local one? // Intentionally not using it yet to derisk the initial implementation, because // the way we push/pop these values is a bit unusual. If there's a mistake, I'd // rather the ids be wrong than crash the whole reconciler. var forkStack = []; var forkStackIndex = 0; var treeForkProvider = null; var treeForkCount = 0; var idStack = []; var idStackIndex = 0; var treeContextProvider = null; var treeContextId = 1; var treeContextOverflow = ''; function isForkedChild(workInProgress) { warnIfNotHydrating(); return (workInProgress.flags & Forked) !== NoFlags; } function getForksAtLevel(workInProgress) { warnIfNotHydrating(); return treeForkCount; } function getTreeId() { var overflow = treeContextOverflow; var idWithLeadingBit = treeContextId; var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); return id.toString(32) + overflow; } function pushTreeFork(workInProgress, totalChildren) { // This is called right after we reconcile an array (or iterator) of child // fibers, because that's the only place where we know how many children in // the whole set without doing extra work later, or storing addtional // information on the fiber. // // That's why this function is separate from pushTreeId — it's called during // the render phase of the fork parent, not the child, which is where we push // the other context values. // // In the Fizz implementation this is much simpler because the child is // rendered in the same callstack as the parent. // // It might be better to just add a `forks` field to the Fiber type. It would // make this module simpler. warnIfNotHydrating(); forkStack[forkStackIndex++] = treeForkCount; forkStack[forkStackIndex++] = treeForkProvider; treeForkProvider = workInProgress; treeForkCount = totalChildren; } function pushTreeId(workInProgress, totalChildren, index) { warnIfNotHydrating(); idStack[idStackIndex++] = treeContextId; idStack[idStackIndex++] = treeContextOverflow; idStack[idStackIndex++] = treeContextProvider; treeContextProvider = workInProgress; var baseIdWithLeadingBit = treeContextId; var baseOverflow = treeContextOverflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part // of the id; we use it to account for leading 0s. var baseLength = getBitLength(baseIdWithLeadingBit) - 1; var baseId = baseIdWithLeadingBit & ~(1 << baseLength); var slot = index + 1; var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into // consideration the leading 1 we use to mark the end of the sequence. if (length > 30) { // We overflowed the bitwise-safe range. Fall back to slower algorithm. // This branch assumes the length of the base id is greater than 5; it won't // work for smaller ids, because you need 5 bits per character. // // We encode the id in multiple steps: first the base id, then the // remaining digits. // // Each 5 bit sequence corresponds to a single base 32 character. So for // example, if the current id is 23 bits long, we can convert 20 of those // bits into a string of 4 characters, with 3 bits left over. // // First calculate how many bits in the base id represent a complete // sequence of characters. var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits. var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. var restOfBaseId = baseId >> numberOfOverflowBits; var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because // we made more room, this time it won't overflow. var restOfLength = getBitLength(totalChildren) + restOfBaseLength; var restOfNewBits = slot << restOfBaseLength; var id = restOfNewBits | restOfBaseId; var overflow = newOverflow + baseOverflow; treeContextId = 1 << restOfLength | id; treeContextOverflow = overflow; } else { // Normal path var newBits = slot << baseLength; var _id = newBits | baseId; var _overflow = baseOverflow; treeContextId = 1 << length | _id; treeContextOverflow = _overflow; } } function pushMaterializedTreeId(workInProgress) { warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear // in its children. var returnFiber = workInProgress.return; if (returnFiber !== null) { var numberOfForks = 1; var slotIndex = 0; pushTreeFork(workInProgress, numberOfForks); pushTreeId(workInProgress, numberOfForks, slotIndex); } } function getBitLength(number) { return 32 - clz32(number); } function getLeadingBit(id) { return 1 << getBitLength(id) - 1; } function popTreeContext(workInProgress) { // Restore the previous values. // This is a bit more complicated than other context-like modules in Fiber // because the same Fiber may appear on the stack multiple times and for // different reasons. We have to keep popping until the work-in-progress is // no longer at the top of the stack. while (workInProgress === treeForkProvider) { treeForkProvider = forkStack[--forkStackIndex]; forkStack[forkStackIndex] = null; treeForkCount = forkStack[--forkStackIndex]; forkStack[forkStackIndex] = null; } while (workInProgress === treeContextProvider) { treeContextProvider = idStack[--idStackIndex]; idStack[idStackIndex] = null; treeContextOverflow = idStack[--idStackIndex]; idStack[idStackIndex] = null; treeContextId = idStack[--idStackIndex]; idStack[idStackIndex] = null; } } function getSuspendedTreeContext() { warnIfNotHydrating(); if (treeContextProvider !== null) { return { id: treeContextId, overflow: treeContextOverflow }; } else { return null; } } function restoreSuspendedTreeContext(workInProgress, suspendedContext) { warnIfNotHydrating(); idStack[idStackIndex++] = treeContextId; idStack[idStackIndex++] = treeContextOverflow; idStack[idStackIndex++] = treeContextProvider; treeContextId = suspendedContext.id; treeContextOverflow = suspendedContext.overflow; treeContextProvider = workInProgress; } function warnIfNotHydrating() { { if (!getIsHydrating()) { error('Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.'); } } } // This may have been an insertion or a hydration. var hydrationParentFiber = null; var nextHydratableInstance = null; var isHydrating = false; // This flag allows for warning supression when we expect there to be mismatches // due to earlier mismatches or a suspended fiber. var didSuspendOrErrorDEV = false; // Hydration errors that were thrown inside this boundary var hydrationErrors = null; function warnIfHydrating() { { if (isHydrating) { error('We should not be hydrating here. This is a bug in React. Please file a bug.'); } } } function markDidThrowWhileHydratingDEV() { { didSuspendOrErrorDEV = true; } } function didSuspendOrErrorWhileHydratingDEV() { { return didSuspendOrErrorDEV; } } function enterHydrationState(fiber) { var parentInstance = fiber.stateNode.containerInfo; nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance); hydrationParentFiber = fiber; isHydrating = true; hydrationErrors = null; didSuspendOrErrorDEV = false; return true; } function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) { nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance); hydrationParentFiber = fiber; isHydrating = true; hydrationErrors = null; didSuspendOrErrorDEV = false; if (treeContext !== null) { restoreSuspendedTreeContext(fiber, treeContext); } return true; } function warnUnhydratedInstance(returnFiber, instance) { { switch (returnFiber.tag) { case HostRoot: { didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance); break; } case HostComponent: { var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode); break; } case SuspenseComponent: { var suspenseState = returnFiber.memoizedState; if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance); break; } } } } function deleteHydratableInstance(returnFiber, instance) { warnUnhydratedInstance(returnFiber, instance); var childToDelete = createFiberFromHostInstanceForDeletion(); childToDelete.stateNode = instance; childToDelete.return = returnFiber; var deletions = returnFiber.deletions; if (deletions === null) { returnFiber.deletions = [childToDelete]; returnFiber.flags |= ChildDeletion; } else { deletions.push(childToDelete); } } function warnNonhydratedInstance(returnFiber, fiber) { { if (didSuspendOrErrorDEV) { // Inside a boundary that already suspended. We're currently rendering the // siblings of a suspended node. The mismatch may be due to the missing // data, so it's probably a false positive. return; } switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; switch (fiber.tag) { case HostComponent: var type = fiber.type; var props = fiber.pendingProps; didNotFindHydratableInstanceWithinContainer(parentContainer, type); break; case HostText: var text = fiber.pendingProps; didNotFindHydratableTextInstanceWithinContainer(parentContainer, text); break; } break; } case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; switch (fiber.tag) { case HostComponent: { var _type = fiber.type; var _props = fiber.pendingProps; var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode); break; } case HostText: { var _text = fiber.pendingProps; var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text, // TODO: Delete this argument when we remove the legacy root API. _isConcurrentMode); break; } } break; } case SuspenseComponent: { var suspenseState = returnFiber.memoizedState; var _parentInstance = suspenseState.dehydrated; if (_parentInstance !== null) switch (fiber.tag) { case HostComponent: var _type2 = fiber.type; var _props2 = fiber.pendingProps; didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2); break; case HostText: var _text2 = fiber.pendingProps; didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2); break; } break; } default: return; } } } function insertNonHydratedInstance(returnFiber, fiber) { fiber.flags = fiber.flags & ~Hydrating | Placement; warnNonhydratedInstance(returnFiber, fiber); } function tryHydrate(fiber, nextInstance) { switch (fiber.tag) { case HostComponent: { var type = fiber.type; var props = fiber.pendingProps; var instance = canHydrateInstance(nextInstance, type); if (instance !== null) { fiber.stateNode = instance; hydrationParentFiber = fiber; nextHydratableInstance = getFirstHydratableChild(instance); return true; } return false; } case HostText: { var text = fiber.pendingProps; var textInstance = canHydrateTextInstance(nextInstance, text); if (textInstance !== null) { fiber.stateNode = textInstance; hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate. nextHydratableInstance = null; return true; } return false; } case SuspenseComponent: { var suspenseInstance = canHydrateSuspenseInstance(nextInstance); if (suspenseInstance !== null) { var suspenseState = { dehydrated: suspenseInstance, treeContext: getSuspendedTreeContext(), retryLane: OffscreenLane }; fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. // This simplifies the code for getHostSibling and deleting nodes, // since it doesn't have to consider all Suspense boundaries and // check if they're dehydrated ones or not. var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance); dehydratedFragment.return = fiber; fiber.child = dehydratedFragment; hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into // it during the first pass. Instead, we'll reenter it later. nextHydratableInstance = null; return true; } return false; } default: return false; } } function shouldClientRenderOnMismatch(fiber) { return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags; } function throwOnHydrationMismatch(fiber) { throw new Error('Hydration failed because the initial UI does not match what was ' + 'rendered on the server.'); } function tryToClaimNextHydratableInstance(fiber) { if (!isHydrating) { return; } var nextInstance = nextHydratableInstance; if (!nextInstance) { if (shouldClientRenderOnMismatch(fiber)) { warnNonhydratedInstance(hydrationParentFiber, fiber); throwOnHydrationMismatch(); } // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); isHydrating = false; hydrationParentFiber = fiber; return; } var firstAttemptedInstance = nextInstance; if (!tryHydrate(fiber, nextInstance)) { if (shouldClientRenderOnMismatch(fiber)) { warnNonhydratedInstance(hydrationParentFiber, fiber); throwOnHydrationMismatch(); } // If we can't hydrate this instance let's try the next one. // We use this as a heuristic. It's based on intuition and not data so it // might be flawed or unnecessary. nextInstance = getNextHydratableSibling(firstAttemptedInstance); var prevHydrationParentFiber = hydrationParentFiber; if (!nextInstance || !tryHydrate(fiber, nextInstance)) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); isHydrating = false; hydrationParentFiber = fiber; return; } // We matched the next one, we'll now assume that the first one was // superfluous and we'll delete it. Since we can't eagerly delete it // we'll have to schedule a deletion. To do that, this node needs a dummy // fiber associated with it. deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); } } function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { var instance = fiber.stateNode; var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component. fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. if (updatePayload !== null) { return true; } return false; } function prepareToHydrateHostTextInstance(fiber) { var textInstance = fiber.stateNode; var textContent = fiber.memoizedProps; var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber); if (shouldUpdate) { // We assume that prepareToHydrateHostTextInstance is called in a context where the // hydration parent is the parent host component of this host text. var returnFiber = hydrationParentFiber; if (returnFiber !== null) { switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode); break; } case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. _isConcurrentMode2); break; } } } } return shouldUpdate; } function prepareToHydrateHostSuspenseInstance(fiber) { var suspenseState = fiber.memoizedState; var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; if (!suspenseInstance) { throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } hydrateSuspenseInstance(suspenseInstance, fiber); } function skipPastDehydratedSuspenseInstance(fiber) { var suspenseState = fiber.memoizedState; var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; if (!suspenseInstance) { throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); } function popToNextHostParent(fiber) { var parent = fiber.return; while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) { parent = parent.return; } hydrationParentFiber = parent; } function popHydrationState(fiber) { if (fiber !== hydrationParentFiber) { // We're deeper than the current hydration context, inside an inserted // tree. return false; } if (!isHydrating) { // If we're not currently hydrating but we're in a hydration context, then // we were an insertion and now need to pop up reenter hydration of our // siblings. popToNextHostParent(fiber); isHydrating = true; return false; } // If we have any remaining hydratable nodes, we need to delete them now. // We only do this deeper than head and body since they tend to have random // other nodes in them. We also ignore components with pure text content in // side of them. We also don't delete anything inside the root container. if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) { var nextInstance = nextHydratableInstance; if (nextInstance) { if (shouldClientRenderOnMismatch(fiber)) { warnIfUnhydratedTailNodes(fiber); throwOnHydrationMismatch(); } else { while (nextInstance) { deleteHydratableInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); } } } } popToNextHostParent(fiber); if (fiber.tag === SuspenseComponent) { nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); } else { nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; } return true; } function hasUnhydratedTailNodes() { return isHydrating && nextHydratableInstance !== null; } function warnIfUnhydratedTailNodes(fiber) { var nextInstance = nextHydratableInstance; while (nextInstance) { warnUnhydratedInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); } } function resetHydrationState() { hydrationParentFiber = null; nextHydratableInstance = null; isHydrating = false; didSuspendOrErrorDEV = false; } function upgradeHydrationErrorsToRecoverable() { if (hydrationErrors !== null) { // Successfully completed a forced client render. The errors that occurred // during the hydration attempt are now recovered. We will log them in // commit phase, once the entire tree has finished. queueRecoverableErrors(hydrationErrors); hydrationErrors = null; } } function getIsHydrating() { return isHydrating; } function queueHydrationError(error) { if (hydrationErrors === null) { hydrationErrors = [error]; } else { hydrationErrors.push(error); } } var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; var NoTransition = null; function requestCurrentTransition() { return ReactCurrentBatchConfig$1.transition; } var ReactStrictModeWarnings = { recordUnsafeLifecycleWarnings: function (fiber, instance) {}, flushPendingUnsafeLifecycleWarnings: function () {}, recordLegacyContextWarning: function (fiber, instance) {}, flushLegacyContextWarning: function () {}, discardPendingWarnings: function () {} }; { var findStrictRoot = function (fiber) { var maybeStrictRoot = null; var node = fiber; while (node !== null) { if (node.mode & StrictLegacyMode) { maybeStrictRoot = node; } node = node.return; } return maybeStrictRoot; }; var setToSortedString = function (set) { var array = []; set.forEach(function (value) { array.push(value); }); return array.sort().join(', '); }; var pendingComponentWillMountWarnings = []; var pendingUNSAFE_ComponentWillMountWarnings = []; var pendingComponentWillReceivePropsWarnings = []; var pendingUNSAFE_ComponentWillReceivePropsWarnings = []; var pendingComponentWillUpdateWarnings = []; var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about. var didWarnAboutUnsafeLifecycles = new Set(); ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) { // Dedupe strategy: Warn once per component. if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { return; } if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components. instance.componentWillMount.__suppressDeprecationWarning !== true) { pendingComponentWillMountWarnings.push(fiber); } if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function') { pendingUNSAFE_ComponentWillMountWarnings.push(fiber); } if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { pendingComponentWillReceivePropsWarnings.push(fiber); } if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') { pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber); } if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { pendingComponentWillUpdateWarnings.push(fiber); } if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function') { pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber); } }; ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () { // We do an initial pass to gather component names var componentWillMountUniqueNames = new Set(); if (pendingComponentWillMountWarnings.length > 0) { pendingComponentWillMountWarnings.forEach(function (fiber) { componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingComponentWillMountWarnings = []; } var UNSAFE_componentWillMountUniqueNames = new Set(); if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) { UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingUNSAFE_ComponentWillMountWarnings = []; } var componentWillReceivePropsUniqueNames = new Set(); if (pendingComponentWillReceivePropsWarnings.length > 0) { pendingComponentWillReceivePropsWarnings.forEach(function (fiber) { componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingComponentWillReceivePropsWarnings = []; } var UNSAFE_componentWillReceivePropsUniqueNames = new Set(); if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) { UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingUNSAFE_ComponentWillReceivePropsWarnings = []; } var componentWillUpdateUniqueNames = new Set(); if (pendingComponentWillUpdateWarnings.length > 0) { pendingComponentWillUpdateWarnings.forEach(function (fiber) { componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingComponentWillUpdateWarnings = []; } var UNSAFE_componentWillUpdateUniqueNames = new Set(); if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) { UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); pendingUNSAFE_ComponentWillUpdateWarnings = []; } // Finally, we flush all the warnings // UNSAFE_ ones before the deprecated ones, since they'll be 'louder' if (UNSAFE_componentWillMountUniqueNames.size > 0) { var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames); error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames); } if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) { var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames); error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames); } if (UNSAFE_componentWillUpdateUniqueNames.size > 0) { var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames); error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2); } if (componentWillMountUniqueNames.size > 0) { var _sortedNames3 = setToSortedString(componentWillMountUniqueNames); warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3); } if (componentWillReceivePropsUniqueNames.size > 0) { var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames); warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4); } if (componentWillUpdateUniqueNames.size > 0) { var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames); warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5); } }; var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. var didWarnAboutLegacyContext = new Set(); ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) { var strictRoot = findStrictRoot(fiber); if (strictRoot === null) { error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.'); return; } // Dedup strategy: Warn once per component. if (didWarnAboutLegacyContext.has(fiber.type)) { return; } var warningsForRoot = pendingLegacyContextWarning.get(strictRoot); if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') { if (warningsForRoot === undefined) { warningsForRoot = []; pendingLegacyContextWarning.set(strictRoot, warningsForRoot); } warningsForRoot.push(fiber); } }; ReactStrictModeWarnings.flushLegacyContextWarning = function () { pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) { if (fiberArray.length === 0) { return; } var firstFiber = fiberArray[0]; var uniqueNames = new Set(); fiberArray.forEach(function (fiber) { uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutLegacyContext.add(fiber.type); }); var sortedNames = setToSortedString(uniqueNames); try { setCurrentFiber(firstFiber); error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames); } finally { resetCurrentFiber(); } }); }; ReactStrictModeWarnings.discardPendingWarnings = function () { pendingComponentWillMountWarnings = []; pendingUNSAFE_ComponentWillMountWarnings = []; pendingComponentWillReceivePropsWarnings = []; pendingUNSAFE_ComponentWillReceivePropsWarnings = []; pendingComponentWillUpdateWarnings = []; pendingUNSAFE_ComponentWillUpdateWarnings = []; pendingLegacyContextWarning = new Map(); }; } var didWarnAboutMaps; var didWarnAboutGenerators; var didWarnAboutStringRefs; var ownerHasKeyUseWarning; var ownerHasFunctionTypeWarning; var warnForMissingKey = function (child, returnFiber) {}; { didWarnAboutMaps = false; didWarnAboutGenerators = false; didWarnAboutStringRefs = {}; /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ ownerHasKeyUseWarning = {}; ownerHasFunctionTypeWarning = {}; warnForMissingKey = function (child, returnFiber) { if (child === null || typeof child !== 'object') { return; } if (!child._store || child._store.validated || child.key != null) { return; } if (typeof child._store !== 'object') { throw new Error('React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } child._store.validated = true; var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; if (ownerHasKeyUseWarning[componentName]) { return; } ownerHasKeyUseWarning[componentName] = true; error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.'); }; } function isReactClass(type) { return type.prototype && type.prototype.isReactComponent; } function coerceRef(returnFiber, current, element) { var mixedRef = element.ref; if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') { { // TODO: Clean this up once we turn on the string ref warning for // everyone, because the strict mode case will no longer be relevant if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs // because these cannot be automatically converted to an arrow function // using a codemod. Therefore, we don't have to warn about string refs again. !(element._owner && element._self && element._owner.stateNode !== element._self) && // Will already throw with "Function components cannot have string refs" !(element._owner && element._owner.tag !== ClassComponent) && // Will already warn with "Function components cannot be given refs" !(typeof element.type === 'function' && !isReactClass(element.type)) && // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set" element._owner) { var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; if (!didWarnAboutStringRefs[componentName]) { { error('Component "%s" contains the string ref "%s". Support for string refs ' + 'will be removed in a future major release. We recommend using ' + 'useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, mixedRef); } didWarnAboutStringRefs[componentName] = true; } } } if (element._owner) { var owner = element._owner; var inst; if (owner) { var ownerFiber = owner; if (ownerFiber.tag !== ClassComponent) { throw new Error('Function components cannot have string refs. ' + 'We recommend using useRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref'); } inst = ownerFiber.stateNode; } if (!inst) { throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a " + 'bug in React. Please file an issue.'); } // Assigning this to a const so Flow knows it won't change in the closure var resolvedInst = inst; { checkPropStringCoercion(mixedRef, 'ref'); } var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) { return current.ref; } var ref = function (value) { var refs = resolvedInst.refs; if (value === null) { delete refs[stringRef]; } else { refs[stringRef] = value; } }; ref._stringRef = stringRef; return ref; } else { if (typeof mixedRef !== 'string') { throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.'); } if (!element._owner) { throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of" + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.'); } } } return mixedRef; } function throwOnInvalidObjectType(returnFiber, newChild) { var childString = Object.prototype.toString.call(newChild); throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); } function warnOnFunctionType(returnFiber) { { var componentName = getComponentNameFromFiber(returnFiber) || 'Component'; if (ownerHasFunctionTypeWarning[componentName]) { return; } ownerHasFunctionTypeWarning[componentName] = true; error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.'); } } function resolveLazy(lazyType) { var payload = lazyType._payload; var init = lazyType._init; return init(payload); } // This wrapper function exists because I expect to clone the code in each path // to be able to optimize each path individually by branching early. This needs // a compiler or we can do it manually. Helpers that don't need this branching // live outside of this function. function ChildReconciler(shouldTrackSideEffects) { function deleteChild(returnFiber, childToDelete) { if (!shouldTrackSideEffects) { // Noop. return; } var deletions = returnFiber.deletions; if (deletions === null) { returnFiber.deletions = [childToDelete]; returnFiber.flags |= ChildDeletion; } else { deletions.push(childToDelete); } } function deleteRemainingChildren(returnFiber, currentFirstChild) { if (!shouldTrackSideEffects) { // Noop. return null; } // TODO: For the shouldClone case, this could be micro-optimized a bit by // assuming that after the first child we've already added everything. var childToDelete = currentFirstChild; while (childToDelete !== null) { deleteChild(returnFiber, childToDelete); childToDelete = childToDelete.sibling; } return null; } function mapRemainingChildren(returnFiber, currentFirstChild) { // Add the remaining children to a temporary map so that we can find them by // keys quickly. Implicit (null) keys get added to this set with their index // instead. var existingChildren = new Map(); var existingChild = currentFirstChild; while (existingChild !== null) { if (existingChild.key !== null) { existingChildren.set(existingChild.key, existingChild); } else { existingChildren.set(existingChild.index, existingChild); } existingChild = existingChild.sibling; } return existingChildren; } function useFiber(fiber, pendingProps) { // We currently set sibling to null and index to 0 here because it is easy // to forget to do before returning it. E.g. for the single child case. var clone = createWorkInProgress(fiber, pendingProps); clone.index = 0; clone.sibling = null; return clone; } function placeChild(newFiber, lastPlacedIndex, newIndex) { newFiber.index = newIndex; if (!shouldTrackSideEffects) { // During hydration, the useId algorithm needs to know which fibers are // part of a list of children (arrays, iterators). newFiber.flags |= Forked; return lastPlacedIndex; } var current = newFiber.alternate; if (current !== null) { var oldIndex = current.index; if (oldIndex < lastPlacedIndex) { // This is a move. newFiber.flags |= Placement; return lastPlacedIndex; } else { // This item can stay in place. return oldIndex; } } else { // This is an insertion. newFiber.flags |= Placement; return lastPlacedIndex; } } function placeSingleChild(newFiber) { // This is simpler for the single child case. We only need to do a // placement for inserting new children. if (shouldTrackSideEffects && newFiber.alternate === null) { newFiber.flags |= Placement; } return newFiber; } function updateTextNode(returnFiber, current, textContent, lanes) { if (current === null || current.tag !== HostText) { // Insert var created = createFiberFromText(textContent, returnFiber.mode, lanes); created.return = returnFiber; return created; } else { // Update var existing = useFiber(current, textContent); existing.return = returnFiber; return existing; } } function updateElement(returnFiber, current, element, lanes) { var elementType = element.type; if (elementType === REACT_FRAGMENT_TYPE) { return updateFragment(returnFiber, current, element.props.children, lanes, element.key); } if (current !== null) { if (current.elementType === elementType || ( // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(current, element) ) || // Lazy types should reconcile their resolved type. // We need to do this after the Hot Reloading check above, // because hot reloading has different semantics than prod because // it doesn't resuspend. So we can't let the call below suspend. typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type) { // Move based on index var existing = useFiber(current, element.props); existing.ref = coerceRef(returnFiber, current, element); existing.return = returnFiber; { existing._debugSource = element._source; existing._debugOwner = element._owner; } return existing; } } // Insert var created = createFiberFromElement(element, returnFiber.mode, lanes); created.ref = coerceRef(returnFiber, current, element); created.return = returnFiber; return created; } function updatePortal(returnFiber, current, portal, lanes) { if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) { // Insert var created = createFiberFromPortal(portal, returnFiber.mode, lanes); created.return = returnFiber; return created; } else { // Update var existing = useFiber(current, portal.children || []); existing.return = returnFiber; return existing; } } function updateFragment(returnFiber, current, fragment, lanes, key) { if (current === null || current.tag !== Fragment) { // Insert var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key); created.return = returnFiber; return created; } else { // Update var existing = useFiber(current, fragment); existing.return = returnFiber; return existing; } } function createChild(returnFiber, newChild, lanes) { if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { // Text nodes don't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text // node. var created = createFiberFromText('' + newChild, returnFiber.mode, lanes); created.return = returnFiber; return created; } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { var _created = createFiberFromElement(newChild, returnFiber.mode, lanes); _created.ref = coerceRef(returnFiber, null, newChild); _created.return = returnFiber; return _created; } case REACT_PORTAL_TYPE: { var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes); _created2.return = returnFiber; return _created2; } case REACT_LAZY_TYPE: { var payload = newChild._payload; var init = newChild._init; return createChild(returnFiber, init(payload), lanes); } } if (isArray(newChild) || getIteratorFn(newChild)) { var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null); _created3.return = returnFiber; return _created3; } throwOnInvalidObjectType(returnFiber, newChild); } { if (typeof newChild === 'function') { warnOnFunctionType(returnFiber); } } return null; } function updateSlot(returnFiber, oldFiber, newChild, lanes) { // Update the fiber if the keys match, otherwise return null. var key = oldFiber !== null ? oldFiber.key : null; if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { // Text nodes don't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text // node. if (key !== null) { return null; } return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes); } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { if (newChild.key === key) { return updateElement(returnFiber, oldFiber, newChild, lanes); } else { return null; } } case REACT_PORTAL_TYPE: { if (newChild.key === key) { return updatePortal(returnFiber, oldFiber, newChild, lanes); } else { return null; } } case REACT_LAZY_TYPE: { var payload = newChild._payload; var init = newChild._init; return updateSlot(returnFiber, oldFiber, init(payload), lanes); } } if (isArray(newChild) || getIteratorFn(newChild)) { if (key !== null) { return null; } return updateFragment(returnFiber, oldFiber, newChild, lanes, null); } throwOnInvalidObjectType(returnFiber, newChild); } { if (typeof newChild === 'function') { warnOnFunctionType(returnFiber); } } return null; } function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) { if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { // Text nodes don't have keys, so we neither have to check the old nor // new node for the key. If both are text nodes, they match. var matchedFiber = existingChildren.get(newIdx) || null; return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes); } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; return updateElement(returnFiber, _matchedFiber, newChild, lanes); } case REACT_PORTAL_TYPE: { var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; return updatePortal(returnFiber, _matchedFiber2, newChild, lanes); } case REACT_LAZY_TYPE: var payload = newChild._payload; var init = newChild._init; return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes); } if (isArray(newChild) || getIteratorFn(newChild)) { var _matchedFiber3 = existingChildren.get(newIdx) || null; return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null); } throwOnInvalidObjectType(returnFiber, newChild); } { if (typeof newChild === 'function') { warnOnFunctionType(returnFiber); } } return null; } /** * Warns if there is a duplicate or missing key */ function warnOnInvalidKey(child, knownKeys, returnFiber) { { if (typeof child !== 'object' || child === null) { return knownKeys; } switch (child.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: warnForMissingKey(child, returnFiber); var key = child.key; if (typeof key !== 'string') { break; } if (knownKeys === null) { knownKeys = new Set(); knownKeys.add(key); break; } if (!knownKeys.has(key)) { knownKeys.add(key); break; } error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key); break; case REACT_LAZY_TYPE: var payload = child._payload; var init = child._init; warnOnInvalidKey(init(payload), knownKeys, returnFiber); break; } } return knownKeys; } function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) { // This algorithm can't optimize by searching from both ends since we // don't have backpointers on fibers. I'm trying to see how far we can get // with that model. If it ends up not being worth the tradeoffs, we can // add it later. // Even with a two ended optimization, we'd want to optimize for the case // where there are few changes and brute force the comparison instead of // going for the Map. It'd like to explore hitting that path first in // forward-only mode and only go for the Map once we notice that we need // lots of look ahead. This doesn't handle reversal as well as two ended // search but that's unusual. Besides, for the two ended optimization to // work on Iterables, we'd need to copy the whole set. // In this first iteration, we'll just live with hitting the bad case // (adding everything to a Map) in for every insert/move. // If you change this code, also update reconcileChildrenIterator() which // uses the same algorithm. { // First, validate keys. var knownKeys = null; for (var i = 0; i < newChildren.length; i++) { var child = newChildren[i]; knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); } } var resultingFirstChild = null; var previousNewFiber = null; var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; oldFiber = null; } else { nextOldFiber = oldFiber.sibling; } var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes); if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need // a better way to communicate whether this was a miss or null, // boolean, undefined, etc. if (oldFiber === null) { oldFiber = nextOldFiber; } break; } if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we // need to delete the existing child. deleteChild(returnFiber, oldFiber); } } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; } else { // TODO: Defer siblings if we're not at the right index for this slot. // I.e. if we had null values before, then we want to defer this // for each null value. However, we also don't want to call updateSlot // with the previous one. previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; oldFiber = nextOldFiber; } if (newIdx === newChildren.length) { // We've reached the end of the new children. We can delete the rest. deleteRemainingChildren(returnFiber, oldFiber); if (getIsHydrating()) { var numberOfForks = newIdx; pushTreeFork(returnFiber, numberOfForks); } return resultingFirstChild; } if (oldFiber === null) { // If we don't have any more existing children we can choose a fast path // since the rest will all be insertions. for (; newIdx < newChildren.length; newIdx++) { var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes); if (_newFiber === null) { continue; } lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber; } else { previousNewFiber.sibling = _newFiber; } previousNewFiber = _newFiber; } if (getIsHydrating()) { var _numberOfForks = newIdx; pushTreeFork(returnFiber, _numberOfForks); } return resultingFirstChild; } // Add all children to a key map for quick lookups. var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; newIdx < newChildren.length; newIdx++) { var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes); if (_newFiber2 !== null) { if (shouldTrackSideEffects) { if (_newFiber2.alternate !== null) { // The new fiber is a work in progress, but if there exists a // current, that means that we reused the fiber. We need to delete // it from the child list so that we don't add it to the deletion // list. existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key); } } lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); if (previousNewFiber === null) { resultingFirstChild = _newFiber2; } else { previousNewFiber.sibling = _newFiber2; } previousNewFiber = _newFiber2; } } if (shouldTrackSideEffects) { // Any existing children that weren't consumed above were deleted. We need // to add them to the deletion list. existingChildren.forEach(function (child) { return deleteChild(returnFiber, child); }); } if (getIsHydrating()) { var _numberOfForks2 = newIdx; pushTreeFork(returnFiber, _numberOfForks2); } return resultingFirstChild; } function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) { // This is the same implementation as reconcileChildrenArray(), // but using the iterator instead. var iteratorFn = getIteratorFn(newChildrenIterable); if (typeof iteratorFn !== 'function') { throw new Error('An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.'); } { // We don't support rendering Generators because it's a mutation. // See https://github.com/facebook/react/issues/12995 if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag newChildrenIterable[Symbol.toStringTag] === 'Generator') { if (!didWarnAboutGenerators) { error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.'); } didWarnAboutGenerators = true; } // Warn about using Maps as children if (newChildrenIterable.entries === iteratorFn) { if (!didWarnAboutMaps) { error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); } didWarnAboutMaps = true; } // First, validate keys. // We'll get a different iterator later for the main pass. var _newChildren = iteratorFn.call(newChildrenIterable); if (_newChildren) { var knownKeys = null; var _step = _newChildren.next(); for (; !_step.done; _step = _newChildren.next()) { var child = _step.value; knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); } } } var newChildren = iteratorFn.call(newChildrenIterable); if (newChildren == null) { throw new Error('An iterable object provided no iterator.'); } var resultingFirstChild = null; var previousNewFiber = null; var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; var step = newChildren.next(); for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; oldFiber = null; } else { nextOldFiber = oldFiber.sibling; } var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes); if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need // a better way to communicate whether this was a miss or null, // boolean, undefined, etc. if (oldFiber === null) { oldFiber = nextOldFiber; } break; } if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we // need to delete the existing child. deleteChild(returnFiber, oldFiber); } } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; } else { // TODO: Defer siblings if we're not at the right index for this slot. // I.e. if we had null values before, then we want to defer this // for each null value. However, we also don't want to call updateSlot // with the previous one. previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; oldFiber = nextOldFiber; } if (step.done) { // We've reached the end of the new children. We can delete the rest. deleteRemainingChildren(returnFiber, oldFiber); if (getIsHydrating()) { var numberOfForks = newIdx; pushTreeFork(returnFiber, numberOfForks); } return resultingFirstChild; } if (oldFiber === null) { // If we don't have any more existing children we can choose a fast path // since the rest will all be insertions. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber3 = createChild(returnFiber, step.value, lanes); if (_newFiber3 === null) { continue; } lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber3; } else { previousNewFiber.sibling = _newFiber3; } previousNewFiber = _newFiber3; } if (getIsHydrating()) { var _numberOfForks3 = newIdx; pushTreeFork(returnFiber, _numberOfForks3); } return resultingFirstChild; } // Add all children to a key map for quick lookups. var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes); if (_newFiber4 !== null) { if (shouldTrackSideEffects) { if (_newFiber4.alternate !== null) { // The new fiber is a work in progress, but if there exists a // current, that means that we reused the fiber. We need to delete // it from the child list so that we don't add it to the deletion // list. existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key); } } lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); if (previousNewFiber === null) { resultingFirstChild = _newFiber4; } else { previousNewFiber.sibling = _newFiber4; } previousNewFiber = _newFiber4; } } if (shouldTrackSideEffects) { // Any existing children that weren't consumed above were deleted. We need // to add them to the deletion list. existingChildren.forEach(function (child) { return deleteChild(returnFiber, child); }); } if (getIsHydrating()) { var _numberOfForks4 = newIdx; pushTreeFork(returnFiber, _numberOfForks4); } return resultingFirstChild; } function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) { // There's no need to check for keys on text nodes since we don't have a // way to define them. if (currentFirstChild !== null && currentFirstChild.tag === HostText) { // We already have an existing node so let's just update it and delete // the rest. deleteRemainingChildren(returnFiber, currentFirstChild.sibling); var existing = useFiber(currentFirstChild, textContent); existing.return = returnFiber; return existing; } // The existing first child is not a text node so we need to create one // and delete the existing ones. deleteRemainingChildren(returnFiber, currentFirstChild); var created = createFiberFromText(textContent, returnFiber.mode, lanes); created.return = returnFiber; return created; } function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) { var key = element.key; var child = currentFirstChild; while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. if (child.key === key) { var elementType = element.type; if (elementType === REACT_FRAGMENT_TYPE) { if (child.tag === Fragment) { deleteRemainingChildren(returnFiber, child.sibling); var existing = useFiber(child, element.props.children); existing.return = returnFiber; { existing._debugSource = element._source; existing._debugOwner = element._owner; } return existing; } } else { if (child.elementType === elementType || ( // Keep this check inline so it only runs on the false path: isCompatibleFamilyForHotReloading(child, element) ) || // Lazy types should reconcile their resolved type. // We need to do this after the Hot Reloading check above, // because hot reloading has different semantics than prod because // it doesn't resuspend. So we can't let the call below suspend. typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) { deleteRemainingChildren(returnFiber, child.sibling); var _existing = useFiber(child, element.props); _existing.ref = coerceRef(returnFiber, child, element); _existing.return = returnFiber; { _existing._debugSource = element._source; _existing._debugOwner = element._owner; } return _existing; } } // Didn't match. deleteRemainingChildren(returnFiber, child); break; } else { deleteChild(returnFiber, child); } child = child.sibling; } if (element.type === REACT_FRAGMENT_TYPE) { var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key); created.return = returnFiber; return created; } else { var _created4 = createFiberFromElement(element, returnFiber.mode, lanes); _created4.ref = coerceRef(returnFiber, currentFirstChild, element); _created4.return = returnFiber; return _created4; } } function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) { var key = portal.key; var child = currentFirstChild; while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. if (child.key === key) { if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { deleteRemainingChildren(returnFiber, child.sibling); var existing = useFiber(child, portal.children || []); existing.return = returnFiber; return existing; } else { deleteRemainingChildren(returnFiber, child); break; } } else { deleteChild(returnFiber, child); } child = child.sibling; } var created = createFiberFromPortal(portal, returnFiber.mode, lanes); created.return = returnFiber; return created; } // This API will tag the children with the side-effect of the reconciliation // itself. They will be added to the side-effect list as we pass through the // children and the parent. function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) { // This function is not recursive. // If the top level item is an array, we treat it as a set of children, // not as a fragment. Nested arrays on the other hand will be treated as // fragment nodes. Recursion happens at the normal flow. // Handle top level unkeyed fragments as if they were arrays. // This leads to an ambiguity between <>{[...]}</> and <>...</>. // We treat the ambiguous cases above the same. var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; if (isUnkeyedTopLevelFragment) { newChild = newChild.props.children; } // Handle object types if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes)); case REACT_PORTAL_TYPE: return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes)); case REACT_LAZY_TYPE: var payload = newChild._payload; var init = newChild._init; // TODO: This function is supposed to be non-recursive. return reconcileChildFibers(returnFiber, currentFirstChild, init(payload), lanes); } if (isArray(newChild)) { return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes); } if (getIteratorFn(newChild)) { return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes); } throwOnInvalidObjectType(returnFiber, newChild); } if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') { return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes)); } { if (typeof newChild === 'function') { warnOnFunctionType(returnFiber); } } // Remaining cases are all treated as empty. return deleteRemainingChildren(returnFiber, currentFirstChild); } return reconcileChildFibers; } var reconcileChildFibers = ChildReconciler(true); var mountChildFibers = ChildReconciler(false); function cloneChildFibers(current, workInProgress) { if (current !== null && workInProgress.child !== current.child) { throw new Error('Resuming work not yet implemented.'); } if (workInProgress.child === null) { return; } var currentChild = workInProgress.child; var newChild = createWorkInProgress(currentChild, currentChild.pendingProps); workInProgress.child = newChild; newChild.return = workInProgress; while (currentChild.sibling !== null) { currentChild = currentChild.sibling; newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps); newChild.return = workInProgress; } newChild.sibling = null; } // Reset a workInProgress child set to prepare it for a second pass. function resetChildFibers(workInProgress, lanes) { var child = workInProgress.child; while (child !== null) { resetWorkInProgress(child, lanes); child = child.sibling; } } var valueCursor = createCursor(null); var rendererSigil; { // Use this to detect multiple renderers using the same context rendererSigil = {}; } var currentlyRenderingFiber = null; var lastContextDependency = null; var lastFullyObservedContext = null; var isDisallowedContextReadInDEV = false; function resetContextDependencies() { // This is called right before React yields execution, to ensure `readContext` // cannot be called outside the render phase. currentlyRenderingFiber = null; lastContextDependency = null; lastFullyObservedContext = null; { isDisallowedContextReadInDEV = false; } } function enterDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = true; } } function exitDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = false; } } function pushProvider(providerFiber, context, nextValue) { { push(valueCursor, context._currentValue, providerFiber); context._currentValue = nextValue; { if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) { error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); } context._currentRenderer = rendererSigil; } } } function popProvider(context, providerFiber) { var currentValue = valueCursor.current; pop(valueCursor, providerFiber); { { context._currentValue = currentValue; } } } function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) { // Update the child lanes of all the ancestors, including the alternates. var node = parent; while (node !== null) { var alternate = node.alternate; if (!isSubsetOfLanes(node.childLanes, renderLanes)) { node.childLanes = mergeLanes(node.childLanes, renderLanes); if (alternate !== null) { alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); } } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) { alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes); } if (node === propagationRoot) { break; } node = node.return; } { if (node !== propagationRoot) { error('Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.'); } } } function propagateContextChange(workInProgress, context, renderLanes) { { propagateContextChange_eager(workInProgress, context, renderLanes); } } function propagateContextChange_eager(workInProgress, context, renderLanes) { var fiber = workInProgress.child; if (fiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. fiber.return = workInProgress; } while (fiber !== null) { var nextFiber = void 0; // Visit this fiber. var list = fiber.dependencies; if (list !== null) { nextFiber = fiber.child; var dependency = list.firstContext; while (dependency !== null) { // Check if the context matches. if (dependency.context === context) { // Match! Schedule an update on this fiber. if (fiber.tag === ClassComponent) { // Schedule a force update on the work-in-progress. var lane = pickArbitraryLane(renderLanes); var update = createUpdate(NoTimestamp, lane); update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the // update to the current fiber, too, which means it will persist even if // this render is thrown away. Since it's a race condition, not sure it's // worth fixing. // Inlined `enqueueUpdate` to remove interleaved update check var updateQueue = fiber.updateQueue; if (updateQueue === null) ; else { var sharedQueue = updateQueue.shared; var pending = sharedQueue.pending; if (pending === null) { // This is the first update. Create a circular list. update.next = update; } else { update.next = pending.next; pending.next = update; } sharedQueue.pending = update; } } fiber.lanes = mergeLanes(fiber.lanes, renderLanes); var alternate = fiber.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, renderLanes); } scheduleContextWorkOnParentPath(fiber.return, renderLanes, workInProgress); // Mark the updated lanes on the list, too. list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the // dependency list. break; } dependency = dependency.next; } } else if (fiber.tag === ContextProvider) { // Don't scan deeper if this is a matching provider nextFiber = fiber.type === workInProgress.type ? null : fiber.child; } else if (fiber.tag === DehydratedFragment) { // If a dehydrated suspense boundary is in this subtree, we don't know // if it will have any context consumers in it. The best we can do is // mark it as having updates. var parentSuspense = fiber.return; if (parentSuspense === null) { throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.'); } parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes); var _alternate = parentSuspense.alternate; if (_alternate !== null) { _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes); } // This is intentionally passing this fiber as the parent // because we want to schedule this fiber as having work // on its children. We'll use the childLanes on // this fiber to indicate that a context has changed. scheduleContextWorkOnParentPath(parentSuspense, renderLanes, workInProgress); nextFiber = fiber.sibling; } else { // Traverse down. nextFiber = fiber.child; } if (nextFiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. nextFiber.return = fiber; } else { // No child. Traverse to next sibling. nextFiber = fiber; while (nextFiber !== null) { if (nextFiber === workInProgress) { // We're back to the root of this subtree. Exit. nextFiber = null; break; } var sibling = nextFiber.sibling; if (sibling !== null) { // Set the return pointer of the sibling to the work-in-progress fiber. sibling.return = nextFiber.return; nextFiber = sibling; break; } // No more siblings. Traverse up. nextFiber = nextFiber.return; } } fiber = nextFiber; } } function prepareToReadContext(workInProgress, renderLanes) { currentlyRenderingFiber = workInProgress; lastContextDependency = null; lastFullyObservedContext = null; var dependencies = workInProgress.dependencies; if (dependencies !== null) { { var firstContext = dependencies.firstContext; if (firstContext !== null) { if (includesSomeLane(dependencies.lanes, renderLanes)) { // Context list has a pending update. Mark that this fiber performed work. markWorkInProgressReceivedUpdate(); } // Reset the work-in-progress list dependencies.firstContext = null; } } } } function readContext(context) { { // This warning would fire if you read context inside a Hook like useMemo. // Unlike the class check below, it's not enforced in production for perf. if (isDisallowedContextReadInDEV) { error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); } } var value = context._currentValue ; if (lastFullyObservedContext === context) ; else { var contextItem = { context: context, memoizedValue: value, next: null }; if (lastContextDependency === null) { if (currentlyRenderingFiber === null) { throw new Error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); } // This is the first dependency for this component. Create a new list. lastContextDependency = contextItem; currentlyRenderingFiber.dependencies = { lanes: NoLanes, firstContext: contextItem }; } else { // Append a new context item. lastContextDependency = lastContextDependency.next = contextItem; } } return value; } // render. When this render exits, either because it finishes or because it is // interrupted, the interleaved updates will be transferred onto the main part // of the queue. var concurrentQueues = null; function pushConcurrentUpdateQueue(queue) { if (concurrentQueues === null) { concurrentQueues = [queue]; } else { concurrentQueues.push(queue); } } function finishQueueingConcurrentUpdates() { // Transfer the interleaved updates onto the main queue. Each queue has a // `pending` field and an `interleaved` field. When they are not null, they // point to the last node in a circular linked list. We need to append the // interleaved list to the end of the pending list by joining them into a // single, circular list. if (concurrentQueues !== null) { for (var i = 0; i < concurrentQueues.length; i++) { var queue = concurrentQueues[i]; var lastInterleavedUpdate = queue.interleaved; if (lastInterleavedUpdate !== null) { queue.interleaved = null; var firstInterleavedUpdate = lastInterleavedUpdate.next; var lastPendingUpdate = queue.pending; if (lastPendingUpdate !== null) { var firstPendingUpdate = lastPendingUpdate.next; lastPendingUpdate.next = firstInterleavedUpdate; lastInterleavedUpdate.next = firstPendingUpdate; } queue.pending = lastInterleavedUpdate; } } concurrentQueues = null; } } function enqueueConcurrentHookUpdate(fiber, queue, update, lane) { var interleaved = queue.interleaved; if (interleaved === null) { // This is the first update. Create a circular list. update.next = update; // At the end of the current render, this queue's interleaved updates will // be transferred to the pending queue. pushConcurrentUpdateQueue(queue); } else { update.next = interleaved.next; interleaved.next = update; } queue.interleaved = update; return markUpdateLaneFromFiberToRoot(fiber, lane); } function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane) { var interleaved = queue.interleaved; if (interleaved === null) { // This is the first update. Create a circular list. update.next = update; // At the end of the current render, this queue's interleaved updates will // be transferred to the pending queue. pushConcurrentUpdateQueue(queue); } else { update.next = interleaved.next; interleaved.next = update; } queue.interleaved = update; } function enqueueConcurrentClassUpdate(fiber, queue, update, lane) { var interleaved = queue.interleaved; if (interleaved === null) { // This is the first update. Create a circular list. update.next = update; // At the end of the current render, this queue's interleaved updates will // be transferred to the pending queue. pushConcurrentUpdateQueue(queue); } else { update.next = interleaved.next; interleaved.next = update; } queue.interleaved = update; return markUpdateLaneFromFiberToRoot(fiber, lane); } function enqueueConcurrentRenderForLane(fiber, lane) { return markUpdateLaneFromFiberToRoot(fiber, lane); } // Calling this function outside this module should only be done for backwards // compatibility and should always be accompanied by a warning. var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot; function markUpdateLaneFromFiberToRoot(sourceFiber, lane) { // Update the source fiber's lanes sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane); var alternate = sourceFiber.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, lane); } { if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) { warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); } } // Walk the parent path to the root and update the child lanes. var node = sourceFiber; var parent = sourceFiber.return; while (parent !== null) { parent.childLanes = mergeLanes(parent.childLanes, lane); alternate = parent.alternate; if (alternate !== null) { alternate.childLanes = mergeLanes(alternate.childLanes, lane); } else { { if ((parent.flags & (Placement | Hydrating)) !== NoFlags) { warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber); } } } node = parent; parent = parent.return; } if (node.tag === HostRoot) { var root = node.stateNode; return root; } else { return null; } } var UpdateState = 0; var ReplaceState = 1; var ForceUpdate = 2; var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. // It should only be read right after calling `processUpdateQueue`, via // `checkHasForceUpdateAfterProcessing`. var hasForceUpdate = false; var didWarnUpdateInsideUpdate; var currentlyProcessingQueue; { didWarnUpdateInsideUpdate = false; currentlyProcessingQueue = null; } function initializeUpdateQueue(fiber) { var queue = { baseState: fiber.memoizedState, firstBaseUpdate: null, lastBaseUpdate: null, shared: { pending: null, interleaved: null, lanes: NoLanes }, effects: null }; fiber.updateQueue = queue; } function cloneUpdateQueue(current, workInProgress) { // Clone the update queue from current. Unless it's already a clone. var queue = workInProgress.updateQueue; var currentQueue = current.updateQueue; if (queue === currentQueue) { var clone = { baseState: currentQueue.baseState, firstBaseUpdate: currentQueue.firstBaseUpdate, lastBaseUpdate: currentQueue.lastBaseUpdate, shared: currentQueue.shared, effects: currentQueue.effects }; workInProgress.updateQueue = clone; } } function createUpdate(eventTime, lane) { var update = { eventTime: eventTime, lane: lane, tag: UpdateState, payload: null, callback: null, next: null }; return update; } function enqueueUpdate(fiber, update, lane) { var updateQueue = fiber.updateQueue; if (updateQueue === null) { // Only occurs if the fiber has been unmounted. return null; } var sharedQueue = updateQueue.shared; { if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) { error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.'); didWarnUpdateInsideUpdate = true; } } if (isUnsafeClassRenderPhaseUpdate()) { // This is an unsafe render phase update. Add directly to the update // queue so we can process it immediately during the current render. var pending = sharedQueue.pending; if (pending === null) { // This is the first update. Create a circular list. update.next = update; } else { update.next = pending.next; pending.next = update; } sharedQueue.pending = update; // Update the childLanes even though we're most likely already rendering // this fiber. This is for backwards compatibility in the case where you // update a different component during render phase than the one that is // currently renderings (a pattern that is accompanied by a warning). return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane); } else { return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane); } } function entangleTransitions(root, fiber, lane) { var updateQueue = fiber.updateQueue; if (updateQueue === null) { // Only occurs if the fiber has been unmounted. return; } var sharedQueue = updateQueue.shared; if (isTransitionLane(lane)) { var queueLanes = sharedQueue.lanes; // If any entangled lanes are no longer pending on the root, then they must // have finished. We can remove them from the shared queue, which represents // a superset of the actually pending lanes. In some cases we may entangle // more than we need to, but that's OK. In fact it's worse if we *don't* // entangle when we should. queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. var newQueueLanes = mergeLanes(queueLanes, lane); sharedQueue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if // the lane finished since the last time we entangled it. So we need to // entangle it again, just to be sure. markRootEntangled(root, newQueueLanes); } } function enqueueCapturedUpdate(workInProgress, capturedUpdate) { // Captured updates are updates that are thrown by a child during the render // phase. They should be discarded if the render is aborted. Therefore, // we should only put them on the work-in-progress queue, not the current one. var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone. var current = workInProgress.alternate; if (current !== null) { var currentQueue = current.updateQueue; if (queue === currentQueue) { // The work-in-progress queue is the same as current. This happens when // we bail out on a parent fiber that then captures an error thrown by // a child. Since we want to append the update only to the work-in // -progress queue, we need to clone the updates. We usually clone during // processUpdateQueue, but that didn't happen in this case because we // skipped over the parent when we bailed out. var newFirst = null; var newLast = null; var firstBaseUpdate = queue.firstBaseUpdate; if (firstBaseUpdate !== null) { // Loop through the updates and clone them. var update = firstBaseUpdate; do { var clone = { eventTime: update.eventTime, lane: update.lane, tag: update.tag, payload: update.payload, callback: update.callback, next: null }; if (newLast === null) { newFirst = newLast = clone; } else { newLast.next = clone; newLast = clone; } update = update.next; } while (update !== null); // Append the captured update the end of the cloned list. if (newLast === null) { newFirst = newLast = capturedUpdate; } else { newLast.next = capturedUpdate; newLast = capturedUpdate; } } else { // There are no base updates. newFirst = newLast = capturedUpdate; } queue = { baseState: currentQueue.baseState, firstBaseUpdate: newFirst, lastBaseUpdate: newLast, shared: currentQueue.shared, effects: currentQueue.effects }; workInProgress.updateQueue = queue; return; } } // Append the update to the end of the list. var lastBaseUpdate = queue.lastBaseUpdate; if (lastBaseUpdate === null) { queue.firstBaseUpdate = capturedUpdate; } else { lastBaseUpdate.next = capturedUpdate; } queue.lastBaseUpdate = capturedUpdate; } function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) { switch (update.tag) { case ReplaceState: { var payload = update.payload; if (typeof payload === 'function') { // Updater function { enterDisallowedContextReadInDEV(); } var nextState = payload.call(instance, prevState, nextProps); { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { payload.call(instance, prevState, nextProps); } finally { setIsStrictModeForDevtools(false); } } exitDisallowedContextReadInDEV(); } return nextState; } // State object return payload; } case CaptureUpdate: { workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture; } // Intentional fallthrough case UpdateState: { var _payload = update.payload; var partialState; if (typeof _payload === 'function') { // Updater function { enterDisallowedContextReadInDEV(); } partialState = _payload.call(instance, prevState, nextProps); { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { _payload.call(instance, prevState, nextProps); } finally { setIsStrictModeForDevtools(false); } } exitDisallowedContextReadInDEV(); } } else { // Partial state object partialState = _payload; } if (partialState === null || partialState === undefined) { // Null and undefined are treated as no-ops. return prevState; } // Merge the partial state and the previous state. return assign({}, prevState, partialState); } case ForceUpdate: { hasForceUpdate = true; return prevState; } } return prevState; } function processUpdateQueue(workInProgress, props, instance, renderLanes) { // This is always non-null on a ClassComponent or HostRoot var queue = workInProgress.updateQueue; hasForceUpdate = false; { currentlyProcessingQueue = queue.shared; } var firstBaseUpdate = queue.firstBaseUpdate; var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue. var pendingQueue = queue.shared.pending; if (pendingQueue !== null) { queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first // and last so that it's non-circular. var lastPendingUpdate = pendingQueue; var firstPendingUpdate = lastPendingUpdate.next; lastPendingUpdate.next = null; // Append pending updates to base queue if (lastBaseUpdate === null) { firstBaseUpdate = firstPendingUpdate; } else { lastBaseUpdate.next = firstPendingUpdate; } lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then // we need to transfer the updates to that queue, too. Because the base // queue is a singly-linked list with no cycles, we can append to both // lists and take advantage of structural sharing. // TODO: Pass `current` as argument var current = workInProgress.alternate; if (current !== null) { // This is always non-null on a ClassComponent or HostRoot var currentQueue = current.updateQueue; var currentLastBaseUpdate = currentQueue.lastBaseUpdate; if (currentLastBaseUpdate !== lastBaseUpdate) { if (currentLastBaseUpdate === null) { currentQueue.firstBaseUpdate = firstPendingUpdate; } else { currentLastBaseUpdate.next = firstPendingUpdate; } currentQueue.lastBaseUpdate = lastPendingUpdate; } } } // These values may change as we process the queue. if (firstBaseUpdate !== null) { // Iterate through the list of updates to compute the result. var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes // from the original lanes. var newLanes = NoLanes; var newBaseState = null; var newFirstBaseUpdate = null; var newLastBaseUpdate = null; var update = firstBaseUpdate; do { var updateLane = update.lane; var updateEventTime = update.eventTime; if (!isSubsetOfLanes(renderLanes, updateLane)) { // Priority is insufficient. Skip this update. If this is the first // skipped update, the previous update/state is the new base // update/state. var clone = { eventTime: updateEventTime, lane: updateLane, tag: update.tag, payload: update.payload, callback: update.callback, next: null }; if (newLastBaseUpdate === null) { newFirstBaseUpdate = newLastBaseUpdate = clone; newBaseState = newState; } else { newLastBaseUpdate = newLastBaseUpdate.next = clone; } // Update the remaining priority in the queue. newLanes = mergeLanes(newLanes, updateLane); } else { // This update does have sufficient priority. if (newLastBaseUpdate !== null) { var _clone = { eventTime: updateEventTime, // This update is going to be committed so we never want uncommit // it. Using NoLane works because 0 is a subset of all bitmasks, so // this will never be skipped by the check above. lane: NoLane, tag: update.tag, payload: update.payload, callback: update.callback, next: null }; newLastBaseUpdate = newLastBaseUpdate.next = _clone; } // Process this update. newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance); var callback = update.callback; if (callback !== null && // If the update was already committed, we should not queue its // callback again. update.lane !== NoLane) { workInProgress.flags |= Callback; var effects = queue.effects; if (effects === null) { queue.effects = [update]; } else { effects.push(update); } } } update = update.next; if (update === null) { pendingQueue = queue.shared.pending; if (pendingQueue === null) { break; } else { // An update was scheduled from inside a reducer. Add the new // pending updates to the end of the list and keep processing. var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we // unravel them when transferring them to the base queue. var _firstPendingUpdate = _lastPendingUpdate.next; _lastPendingUpdate.next = null; update = _firstPendingUpdate; queue.lastBaseUpdate = _lastPendingUpdate; queue.shared.pending = null; } } } while (true); if (newLastBaseUpdate === null) { newBaseState = newState; } queue.baseState = newBaseState; queue.firstBaseUpdate = newFirstBaseUpdate; queue.lastBaseUpdate = newLastBaseUpdate; // Interleaved updates are stored on a separate queue. We aren't going to // process them during this render, but we do need to track which lanes // are remaining. var lastInterleaved = queue.shared.interleaved; if (lastInterleaved !== null) { var interleaved = lastInterleaved; do { newLanes = mergeLanes(newLanes, interleaved.lane); interleaved = interleaved.next; } while (interleaved !== lastInterleaved); } else if (firstBaseUpdate === null) { // `queue.lanes` is used for entangling transitions. We can set it back to // zero once the queue is empty. queue.shared.lanes = NoLanes; } // Set the remaining expiration time to be whatever is remaining in the queue. // This should be fine because the only two other things that contribute to // expiration time are props and context. We're already in the middle of the // begin phase by the time we start processing the queue, so we've already // dealt with the props. Context in components that specify // shouldComponentUpdate is tricky; but we'll have to account for // that regardless. markSkippedUpdateLanes(newLanes); workInProgress.lanes = newLanes; workInProgress.memoizedState = newState; } { currentlyProcessingQueue = null; } } function callCallback(callback, context) { if (typeof callback !== 'function') { throw new Error('Invalid argument passed as callback. Expected a function. Instead ' + ("received: " + callback)); } callback.call(context); } function resetHasForceUpdateBeforeProcessing() { hasForceUpdate = false; } function checkHasForceUpdateAfterProcessing() { return hasForceUpdate; } function commitUpdateQueue(finishedWork, finishedQueue, instance) { // Commit the effects var effects = finishedQueue.effects; finishedQueue.effects = null; if (effects !== null) { for (var i = 0; i < effects.length; i++) { var effect = effects[i]; var callback = effect.callback; if (callback !== null) { effect.callback = null; callCallback(callback, instance); } } } } var NO_CONTEXT = {}; var contextStackCursor$1 = createCursor(NO_CONTEXT); var contextFiberStackCursor = createCursor(NO_CONTEXT); var rootInstanceStackCursor = createCursor(NO_CONTEXT); function requiredContext(c) { if (c === NO_CONTEXT) { throw new Error('Expected host context to exist. This error is likely caused by a bug ' + 'in React. Please file an issue.'); } return c; } function getRootHostContainer() { var rootInstance = requiredContext(rootInstanceStackCursor.current); return rootInstance; } function pushHostContainer(fiber, nextRootInstance) { // Push current root instance onto the stack; // This allows us to reset root when portals are popped. push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. // However, we can't just call getRootHostContext() and push it because // we'd have a different number of entries on the stack depending on // whether getRootHostContext() throws somewhere in renderer code or not. // So we push an empty value first. This lets us safely unwind on errors. push(contextStackCursor$1, NO_CONTEXT, fiber); var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. pop(contextStackCursor$1, fiber); push(contextStackCursor$1, nextRootContext, fiber); } function popHostContainer(fiber) { pop(contextStackCursor$1, fiber); pop(contextFiberStackCursor, fiber); pop(rootInstanceStackCursor, fiber); } function getHostContext() { var context = requiredContext(contextStackCursor$1.current); return context; } function pushHostContext(fiber) { var rootInstance = requiredContext(rootInstanceStackCursor.current); var context = requiredContext(contextStackCursor$1.current); var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique. if (context === nextContext) { return; } // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. push(contextFiberStackCursor, fiber, fiber); push(contextStackCursor$1, nextContext, fiber); } function popHostContext(fiber) { // Do not pop unless this Fiber provided the current context. // pushHostContext() only pushes Fibers that provide unique contexts. if (contextFiberStackCursor.current !== fiber) { return; } pop(contextStackCursor$1, fiber); pop(contextFiberStackCursor, fiber); } var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is // inherited deeply down the subtree. The upper bits only affect // this immediate suspense boundary and gets reset each new // boundary or suspense list. var SubtreeSuspenseContextMask = 1; // Subtree Flags: // InvisibleParentSuspenseContext indicates that one of our parent Suspense // boundaries is not currently showing visible main content. // Either because it is already showing a fallback or is not mounted at all. // We can use this to determine if it is desirable to trigger a fallback at // the parent. If not, then we might need to trigger undesirable boundaries // and/or suspend the commit to avoid hiding the parent content. var InvisibleParentSuspenseContext = 1; // Shallow Flags: // ForceSuspenseFallback can be used by SuspenseList to force newly added // items into their fallback state during one of the render passes. var ForceSuspenseFallback = 2; var suspenseStackCursor = createCursor(DefaultSuspenseContext); function hasSuspenseContext(parentContext, flag) { return (parentContext & flag) !== 0; } function setDefaultShallowSuspenseContext(parentContext) { return parentContext & SubtreeSuspenseContextMask; } function setShallowSuspenseContext(parentContext, shallowContext) { return parentContext & SubtreeSuspenseContextMask | shallowContext; } function addSubtreeSuspenseContext(parentContext, subtreeContext) { return parentContext | subtreeContext; } function pushSuspenseContext(fiber, newContext) { push(suspenseStackCursor, newContext, fiber); } function popSuspenseContext(fiber) { pop(suspenseStackCursor, fiber); } function shouldCaptureSuspense(workInProgress, hasInvisibleParent) { // If it was the primary children that just suspended, capture and render the // fallback. Otherwise, don't capture and bubble to the next boundary. var nextState = workInProgress.memoizedState; if (nextState !== null) { if (nextState.dehydrated !== null) { // A dehydrated boundary always captures. return true; } return false; } var props = workInProgress.memoizedProps; // Regular boundaries always capture. { return true; } // If it's a boundary we should avoid, then we prefer to bubble up to the } function findFirstSuspended(row) { var node = row; while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; if (state !== null) { var dehydrated = state.dehydrated; if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) { return node; } } } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't // keep track of whether it suspended or not. node.memoizedProps.revealOrder !== undefined) { var didSuspend = (node.flags & DidCapture) !== NoFlags; if (didSuspend) { return node; } } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === row) { return null; } while (node.sibling === null) { if (node.return === null || node.return === row) { return null; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } return null; } var NoFlags$1 = /* */ 0; // Represents whether effect should fire. var HasEffect = /* */ 1; // Represents the phase in which the effect (not the clean-up) fires. var Insertion = /* */ 2; var Layout = /* */ 4; var Passive$1 = /* */ 8; // and should be reset before starting a new render. // This tracks which mutable sources need to be reset after a render. var workInProgressSources = []; function resetWorkInProgressVersions() { for (var i = 0; i < workInProgressSources.length; i++) { var mutableSource = workInProgressSources[i]; { mutableSource._workInProgressVersionPrimary = null; } } workInProgressSources.length = 0; } // This ensures that the version used for server rendering matches the one // that is eventually read during hydration. // If they don't match there's a potential tear and a full deopt render is required. function registerMutableSourceForHydration(root, mutableSource) { var getVersion = mutableSource._getVersion; var version = getVersion(mutableSource._source); // TODO Clear this data once all pending hydration work is finished. // Retaining it forever may interfere with GC. if (root.mutableSourceEagerHydrationData == null) { root.mutableSourceEagerHydrationData = [mutableSource, version]; } else { root.mutableSourceEagerHydrationData.push(mutableSource, version); } } var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig; var didWarnAboutMismatchedHooksForComponent; var didWarnUncachedGetSnapshot; { didWarnAboutMismatchedHooksForComponent = new Set(); } // These are set right before calling the component. var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from // the work-in-progress hook. var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The // current hook list is the list that belongs to the current fiber. The // work-in-progress hook list is a new list that will be added to the // work-in-progress fiber. var currentHook = null; var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This // does not get reset if we do another render pass; only when we're completely // finished evaluating this component. This is an optimization so we know // whether we need to clear render phase updates after a throw. var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This // gets reset after each attempt. // TODO: Maybe there's some way to consolidate this with // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`. var didScheduleRenderPhaseUpdateDuringThisPass = false; // Counts the number of useId hooks in this component. var localIdCounter = 0; // Used for ids that are generated completely client-side (i.e. not during // hydration). This counter is global, so client ids are not stable across // render attempts. var globalClientIdCounter = 0; var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. // The list stores the order of hooks used during the initial render (mount). // Subsequent renders (updates) reference this list. var hookTypesDev = null; var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore // the dependencies for Hooks that need them (e.g. useEffect or useMemo). // When true, such Hooks will always be "remounted". Only used during hot reload. var ignorePreviousDependencies = false; function mountHookTypesDev() { { var hookName = currentHookNameInDev; if (hookTypesDev === null) { hookTypesDev = [hookName]; } else { hookTypesDev.push(hookName); } } } function updateHookTypesDev() { { var hookName = currentHookNameInDev; if (hookTypesDev !== null) { hookTypesUpdateIndexDev++; if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { warnOnHookMismatchInDev(hookName); } } } } function checkDepsAreArrayDev(deps) { { if (deps !== undefined && deps !== null && !isArray(deps)) { // Verify deps, but only on mount to avoid extra checks. // It's unlikely their type would change as usually you define them inline. error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps); } } } function warnOnHookMismatchInDev(currentHookName) { { var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1); if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { didWarnAboutMismatchedHooksForComponent.add(componentName); if (hookTypesDev !== null) { var table = ''; var secondColumnStart = 30; for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { var oldHookName = hookTypesDev[i]; var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up // lol @ IE not supporting String#repeat while (row.length < secondColumnStart) { row += ' '; } row += newHookName + '\n'; table += row; } error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table); } } } } function throwInvalidHookError() { throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); } function areHookInputsEqual(nextDeps, prevDeps) { { if (ignorePreviousDependencies) { // Only true when this component is being hot reloaded. return false; } } if (prevDeps === null) { { error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); } return false; } { // Don't bother comparing lengths in prod because these arrays should be // passed inline. if (nextDeps.length !== prevDeps.length) { error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]"); } } for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { if (objectIs(nextDeps[i], prevDeps[i])) { continue; } return false; } return true; } function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) { renderLanes = nextRenderLanes; currentlyRenderingFiber$1 = workInProgress; { hookTypesDev = current !== null ? current._debugHookTypes : null; hookTypesUpdateIndexDev = -1; // Used for hot reloading: ignorePreviousDependencies = current !== null && current.type !== workInProgress.type; } workInProgress.memoizedState = null; workInProgress.updateQueue = null; workInProgress.lanes = NoLanes; // The following should have already been reset // currentHook = null; // workInProgressHook = null; // didScheduleRenderPhaseUpdate = false; // localIdCounter = 0; // TODO Warn if no hooks are used at all during mount, then some are used during update. // Currently we will identify the update render as a mount because memoizedState === null. // This is tricky because it's valid for certain types of components (e.g. React.lazy) // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used. // Non-stateful hooks (e.g. context) don't get added to memoizedState, // so memoizedState would be null during updates and mounts. { if (current !== null && current.memoizedState !== null) { ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; } else if (hookTypesDev !== null) { // This dispatcher handles an edge case where a component is updating, // but no stateful hooks have been used. // We want to match the production code behavior (which will use HooksDispatcherOnMount), // but with the extra DEV validation to ensure hooks ordering hasn't changed. // This dispatcher does that. ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; } else { ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; } } var children = Component(props, secondArg); // Check if there was a render phase update if (didScheduleRenderPhaseUpdateDuringThisPass) { // Keep rendering in a loop for as long as render phase updates continue to // be scheduled. Use a counter to prevent infinite loops. var numberOfReRenders = 0; do { didScheduleRenderPhaseUpdateDuringThisPass = false; localIdCounter = 0; if (numberOfReRenders >= RE_RENDER_LIMIT) { throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.'); } numberOfReRenders += 1; { // Even when hot reloading, allow dependencies to stabilize // after first render to prevent infinite render phase updates. ignorePreviousDependencies = false; } // Start over from the beginning of the list currentHook = null; workInProgressHook = null; workInProgress.updateQueue = null; { // Also validate hook order for cascading updates. hookTypesUpdateIndexDev = -1; } ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV ; children = Component(props, secondArg); } while (didScheduleRenderPhaseUpdateDuringThisPass); } // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrance. ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; { workInProgress._debugHookTypes = hookTypesDev; } // This check uses currentHook so that it works the same in DEV and prod bundles. // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; renderLanes = NoLanes; currentlyRenderingFiber$1 = null; currentHook = null; workInProgressHook = null; { currentHookNameInDev = null; hookTypesDev = null; hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last // render. If this fires, it suggests that we incorrectly reset the static // flags in some other part of the codebase. This has happened before, for // example, in the SuspenseList implementation. if (current !== null && (current.flags & StaticMask) !== (workInProgress.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird // and creates false positives. To make this work in legacy mode, we'd // need to mark fibers that commit in an incomplete state, somehow. For // now I'll disable the warning that most of the bugs that would trigger // it are either exclusive to concurrent mode or exist in both. (current.mode & ConcurrentMode) !== NoMode) { error('Internal React error: Expected static flag was missing. Please ' + 'notify the React team.'); } } didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook // localIdCounter = 0; if (didRenderTooFewHooks) { throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.'); } return children; } function checkDidRenderIdHook() { // This should be called immediately after every renderWithHooks call. // Conceptually, it's part of the return value of renderWithHooks; it's only a // separate function to avoid using an array tuple. var didRenderIdHook = localIdCounter !== 0; localIdCounter = 0; return didRenderIdHook; } function bailoutHooks(current, workInProgress, lanes) { workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the // complete phase (bubbleProperties). if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { workInProgress.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update); } else { workInProgress.flags &= ~(Passive | Update); } current.lanes = removeLanes(current.lanes, lanes); } function resetHooksAfterThrow() { // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrance. ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; if (didScheduleRenderPhaseUpdate) { // There were render phase updates. These are only valid for this render // phase, which we are now aborting. Remove the updates from the queues so // they do not persist to the next render. Do not remove updates from hooks // that weren't processed. // // Only reset the updates from the queue if it has a clone. If it does // not have a clone, that means it wasn't processed, and the updates were // scheduled before we entered the render phase. var hook = currentlyRenderingFiber$1.memoizedState; while (hook !== null) { var queue = hook.queue; if (queue !== null) { queue.pending = null; } hook = hook.next; } didScheduleRenderPhaseUpdate = false; } renderLanes = NoLanes; currentlyRenderingFiber$1 = null; currentHook = null; workInProgressHook = null; { hookTypesDev = null; hookTypesUpdateIndexDev = -1; currentHookNameInDev = null; isUpdatingOpaqueValueInRenderPhase = false; } didScheduleRenderPhaseUpdateDuringThisPass = false; localIdCounter = 0; } function mountWorkInProgressHook() { var hook = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null }; if (workInProgressHook === null) { // This is the first hook in the list currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook; } else { // Append to the end of the list workInProgressHook = workInProgressHook.next = hook; } return workInProgressHook; } function updateWorkInProgressHook() { // This function is used both for updates and for re-renders triggered by a // render phase update. It assumes there is either a current hook we can // clone, or a work-in-progress hook from a previous render pass that we can // use as a base. When we reach the end of the base list, we must switch to // the dispatcher used for mounts. var nextCurrentHook; if (currentHook === null) { var current = currentlyRenderingFiber$1.alternate; if (current !== null) { nextCurrentHook = current.memoizedState; } else { nextCurrentHook = null; } } else { nextCurrentHook = currentHook.next; } var nextWorkInProgressHook; if (workInProgressHook === null) { nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState; } else { nextWorkInProgressHook = workInProgressHook.next; } if (nextWorkInProgressHook !== null) { // There's already a work-in-progress. Reuse it. workInProgressHook = nextWorkInProgressHook; nextWorkInProgressHook = workInProgressHook.next; currentHook = nextCurrentHook; } else { // Clone from the current hook. if (nextCurrentHook === null) { throw new Error('Rendered more hooks than during the previous render.'); } currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, baseState: currentHook.baseState, baseQueue: currentHook.baseQueue, queue: currentHook.queue, next: null }; if (workInProgressHook === null) { // This is the first hook in the list. currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook; } else { // Append to the end of the list. workInProgressHook = workInProgressHook.next = newHook; } } return workInProgressHook; } function createFunctionComponentUpdateQueue() { return { lastEffect: null, stores: null }; } function basicStateReducer(state, action) { // $FlowFixMe: Flow doesn't like mixed types return typeof action === 'function' ? action(state) : action; } function mountReducer(reducer, initialArg, init) { var hook = mountWorkInProgressHook(); var initialState; if (init !== undefined) { initialState = init(initialArg); } else { initialState = initialArg; } hook.memoizedState = hook.baseState = initialState; var queue = { pending: null, interleaved: null, lanes: NoLanes, dispatch: null, lastRenderedReducer: reducer, lastRenderedState: initialState }; hook.queue = queue; var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue); return [hook.memoizedState, dispatch]; } function updateReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; if (queue === null) { throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); } queue.lastRenderedReducer = reducer; var current = currentHook; // The last rebase update that is NOT part of the base state. var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet. var pendingQueue = queue.pending; if (pendingQueue !== null) { // We have new updates that haven't been processed yet. // We'll add them to the base queue. if (baseQueue !== null) { // Merge the pending queue and the base queue. var baseFirst = baseQueue.next; var pendingFirst = pendingQueue.next; baseQueue.next = pendingFirst; pendingQueue.next = baseFirst; } { if (current.baseQueue !== baseQueue) { // Internal invariant that should never happen, but feasibly could in // the future if we implement resuming, or some form of that. error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.'); } } current.baseQueue = baseQueue = pendingQueue; queue.pending = null; } if (baseQueue !== null) { // We have a queue to process. var first = baseQueue.next; var newState = current.baseState; var newBaseState = null; var newBaseQueueFirst = null; var newBaseQueueLast = null; var update = first; do { var updateLane = update.lane; if (!isSubsetOfLanes(renderLanes, updateLane)) { // Priority is insufficient. Skip this update. If this is the first // skipped update, the previous update/state is the new base // update/state. var clone = { lane: updateLane, action: update.action, hasEagerState: update.hasEagerState, eagerState: update.eagerState, next: null }; if (newBaseQueueLast === null) { newBaseQueueFirst = newBaseQueueLast = clone; newBaseState = newState; } else { newBaseQueueLast = newBaseQueueLast.next = clone; } // Update the remaining priority in the queue. // TODO: Don't need to accumulate this. Instead, we can remove // renderLanes from the original lanes. currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane); markSkippedUpdateLanes(updateLane); } else { // This update does have sufficient priority. if (newBaseQueueLast !== null) { var _clone = { // This update is going to be committed so we never want uncommit // it. Using NoLane works because 0 is a subset of all bitmasks, so // this will never be skipped by the check above. lane: NoLane, action: update.action, hasEagerState: update.hasEagerState, eagerState: update.eagerState, next: null }; newBaseQueueLast = newBaseQueueLast.next = _clone; } // Process this update. if (update.hasEagerState) { // If this update is a state update (not a reducer) and was processed eagerly, // we can use the eagerly computed state newState = update.eagerState; } else { var action = update.action; newState = reducer(newState, action); } } update = update.next; } while (update !== null && update !== first); if (newBaseQueueLast === null) { newBaseState = newState; } else { newBaseQueueLast.next = newBaseQueueFirst; } // Mark that the fiber performed work, but only if the new state is // different from the current state. if (!objectIs(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = newState; hook.baseState = newBaseState; hook.baseQueue = newBaseQueueLast; queue.lastRenderedState = newState; } // Interleaved updates are stored on a separate queue. We aren't going to // process them during this render, but we do need to track which lanes // are remaining. var lastInterleaved = queue.interleaved; if (lastInterleaved !== null) { var interleaved = lastInterleaved; do { var interleavedLane = interleaved.lane; currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane); markSkippedUpdateLanes(interleavedLane); interleaved = interleaved.next; } while (interleaved !== lastInterleaved); } else if (baseQueue === null) { // `queue.lanes` is used for entangling transitions. We can set it back to // zero once the queue is empty. queue.lanes = NoLanes; } var dispatch = queue.dispatch; return [hook.memoizedState, dispatch]; } function rerenderReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; if (queue === null) { throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.'); } queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous // work-in-progress hook. var dispatch = queue.dispatch; var lastRenderPhaseUpdate = queue.pending; var newState = hook.memoizedState; if (lastRenderPhaseUpdate !== null) { // The queue doesn't persist past this render pass. queue.pending = null; var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; var update = firstRenderPhaseUpdate; do { // Process this render phase update. We don't have to check the // priority because it will always be the same as the current // render's. var action = update.action; newState = reducer(newState, action); update = update.next; } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is // different from the current state. if (!objectIs(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to // the base state unless the queue is empty. // TODO: Not sure if this is the desired semantics, but it's what we // do for gDSFP. I can't remember why. if (hook.baseQueue === null) { hook.baseState = newState; } queue.lastRenderedState = newState; } return [newState, dispatch]; } function mountMutableSource(source, getSnapshot, subscribe) { { return undefined; } } function updateMutableSource(source, getSnapshot, subscribe) { { return undefined; } } function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var fiber = currentlyRenderingFiber$1; var hook = mountWorkInProgressHook(); var nextSnapshot; var isHydrating = getIsHydrating(); if (isHydrating) { if (getServerSnapshot === undefined) { throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); } nextSnapshot = getServerSnapshot(); { if (!didWarnUncachedGetSnapshot) { if (nextSnapshot !== getServerSnapshot()) { error('The result of getServerSnapshot should be cached to avoid an infinite loop'); didWarnUncachedGetSnapshot = true; } } } } else { nextSnapshot = getSnapshot(); { if (!didWarnUncachedGetSnapshot) { var cachedSnapshot = getSnapshot(); if (!objectIs(nextSnapshot, cachedSnapshot)) { error('The result of getSnapshot should be cached to avoid an infinite loop'); didWarnUncachedGetSnapshot = true; } } } // Unless we're rendering a blocking lane, schedule a consistency check. // Right before committing, we will walk the tree and check if any of the // stores were mutated. // // We won't do this if we're hydrating server-rendered content, because if // the content is stale, it's already visible anyway. Instead we'll patch // it up in a passive effect. var root = getWorkInProgressRoot(); if (root === null) { throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); } if (!includesBlockingLane(root, renderLanes)) { pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); } } // Read the current snapshot from the store on every render. This breaks the // normal rules of React, and only works because store updates are // always synchronous. hook.memoizedState = nextSnapshot; var inst = { value: nextSnapshot, getSnapshot: getSnapshot }; hook.queue = inst; // Schedule an effect to subscribe to the store. mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update // this whenever subscribe, getSnapshot, or value changes. Because there's no // clean-up function, and we track the deps correctly, we can call pushEffect // directly, without storing any additional state. For the same reason, we // don't need to set a static flag, either. // TODO: We can move this to the passive phase once we add a pre-commit // consistency check. See the next comment. fiber.flags |= Passive; pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); return nextSnapshot; } function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var fiber = currentlyRenderingFiber$1; var hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the // normal rules of React, and only works because store updates are // always synchronous. var nextSnapshot = getSnapshot(); { if (!didWarnUncachedGetSnapshot) { var cachedSnapshot = getSnapshot(); if (!objectIs(nextSnapshot, cachedSnapshot)) { error('The result of getSnapshot should be cached to avoid an infinite loop'); didWarnUncachedGetSnapshot = true; } } } var prevSnapshot = hook.memoizedState; var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot); if (snapshotChanged) { hook.memoizedState = nextSnapshot; markWorkInProgressReceivedUpdate(); } var inst = hook.queue; updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the // commit phase if there was an interleaved mutation. In concurrent mode // this can happen all the time, but even in synchronous mode, an earlier // effect may have mutated the store. if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by // checking whether we scheduled a subscription effect above. workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) { fiber.flags |= Passive; pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); // Unless we're rendering a blocking lane, schedule a consistency check. // Right before committing, we will walk the tree and check if any of the // stores were mutated. var root = getWorkInProgressRoot(); if (root === null) { throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); } if (!includesBlockingLane(root, renderLanes)) { pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); } } return nextSnapshot; } function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) { fiber.flags |= StoreConsistency; var check = { getSnapshot: getSnapshot, value: renderedSnapshot }; var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; componentUpdateQueue.stores = [check]; } else { var stores = componentUpdateQueue.stores; if (stores === null) { componentUpdateQueue.stores = [check]; } else { stores.push(check); } } } function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) { // These are updated in the passive phase inst.value = nextSnapshot; inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could // have been in an event that fired before the passive effects, or it could // have been in a layout effect. In that case, we would have used the old // snapsho and getSnapshot values to bail out. We need to check one more time. if (checkIfSnapshotChanged(inst)) { // Force a re-render. forceStoreRerender(fiber); } } function subscribeToStore(fiber, inst, subscribe) { var handleStoreChange = function () { // The store changed. Check if the snapshot changed since the last time we // read from the store. if (checkIfSnapshotChanged(inst)) { // Force a re-render. forceStoreRerender(fiber); } }; // Subscribe to the store and return a clean-up function. return subscribe(handleStoreChange); } function checkIfSnapshotChanged(inst) { var latestGetSnapshot = inst.getSnapshot; var prevValue = inst.value; try { var nextValue = latestGetSnapshot(); return !objectIs(prevValue, nextValue); } catch (error) { return true; } } function forceStoreRerender(fiber) { var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } } function mountState(initialState) { var hook = mountWorkInProgressHook(); if (typeof initialState === 'function') { // $FlowFixMe: Flow doesn't like mixed types initialState = initialState(); } hook.memoizedState = hook.baseState = initialState; var queue = { pending: null, interleaved: null, lanes: NoLanes, dispatch: null, lastRenderedReducer: basicStateReducer, lastRenderedState: initialState }; hook.queue = queue; var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue); return [hook.memoizedState, dispatch]; } function updateState(initialState) { return updateReducer(basicStateReducer); } function rerenderState(initialState) { return rerenderReducer(basicStateReducer); } function pushEffect(tag, create, destroy, deps) { var effect = { tag: tag, create: create, destroy: destroy, deps: deps, // Circular next: null }; var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue; if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); currentlyRenderingFiber$1.updateQueue = componentUpdateQueue; componentUpdateQueue.lastEffect = effect.next = effect; } else { var lastEffect = componentUpdateQueue.lastEffect; if (lastEffect === null) { componentUpdateQueue.lastEffect = effect.next = effect; } else { var firstEffect = lastEffect.next; lastEffect.next = effect; effect.next = firstEffect; componentUpdateQueue.lastEffect = effect; } } return effect; } function mountRef(initialValue) { var hook = mountWorkInProgressHook(); { var _ref2 = { current: initialValue }; hook.memoizedState = _ref2; return _ref2; } } function updateRef(initialValue) { var hook = updateWorkInProgressHook(); return hook.memoizedState; } function mountEffectImpl(fiberFlags, hookFlags, create, deps) { var hook = mountWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; currentlyRenderingFiber$1.flags |= fiberFlags; hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps); } function updateEffectImpl(fiberFlags, hookFlags, create, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var destroy = undefined; if (currentHook !== null) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (nextDeps !== null) { var prevDeps = prevEffect.deps; if (areHookInputsEqual(nextDeps, prevDeps)) { hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps); return; } } } currentlyRenderingFiber$1.flags |= fiberFlags; hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps); } function mountEffect(create, deps) { if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps); } else { return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps); } } function updateEffect(create, deps) { return updateEffectImpl(Passive, Passive$1, create, deps); } function mountInsertionEffect(create, deps) { return mountEffectImpl(Update, Insertion, create, deps); } function updateInsertionEffect(create, deps) { return updateEffectImpl(Update, Insertion, create, deps); } function mountLayoutEffect(create, deps) { var fiberFlags = Update; { fiberFlags |= LayoutStatic; } if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { fiberFlags |= MountLayoutDev; } return mountEffectImpl(fiberFlags, Layout, create, deps); } function updateLayoutEffect(create, deps) { return updateEffectImpl(Update, Layout, create, deps); } function imperativeHandleEffect(create, ref) { if (typeof ref === 'function') { var refCallback = ref; var _inst = create(); refCallback(_inst); return function () { refCallback(null); }; } else if (ref !== null && ref !== undefined) { var refObject = ref; { if (!refObject.hasOwnProperty('current')) { error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}'); } } var _inst2 = create(); refObject.current = _inst2; return function () { refObject.current = null; }; } } function mountImperativeHandle(ref, create, deps) { { if (typeof create !== 'function') { error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); } } // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; var fiberFlags = Update; { fiberFlags |= LayoutStatic; } if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) { fiberFlags |= MountLayoutDev; } return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); } function updateImperativeHandle(ref, create, deps) { { if (typeof create !== 'function') { error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null'); } } // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); } function mountDebugValue(value, formatterFn) {// This hook is normally a no-op. // The react-debug-hooks package injects its own implementation // so that e.g. DevTools can display custom hook values. } var updateDebugValue = mountDebugValue; function mountCallback(callback, deps) { var hook = mountWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; hook.memoizedState = [callback, nextDeps]; return callback; } function updateCallback(callback, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; if (prevState !== null) { if (nextDeps !== null) { var prevDeps = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } hook.memoizedState = [callback, nextDeps]; return callback; } function mountMemo(nextCreate, deps) { var hook = mountWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function updateMemo(nextCreate, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; if (prevState !== null) { // Assume these are defined. If they're not, areHookInputsEqual will warn. if (nextDeps !== null) { var prevDeps = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } var nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function mountDeferredValue(value) { var hook = mountWorkInProgressHook(); hook.memoizedState = value; return value; } function updateDeferredValue(value) { var hook = updateWorkInProgressHook(); var resolvedCurrentHook = currentHook; var prevValue = resolvedCurrentHook.memoizedState; return updateDeferredValueImpl(hook, prevValue, value); } function rerenderDeferredValue(value) { var hook = updateWorkInProgressHook(); if (currentHook === null) { // This is a rerender during a mount. hook.memoizedState = value; return value; } else { // This is a rerender during an update. var prevValue = currentHook.memoizedState; return updateDeferredValueImpl(hook, prevValue, value); } } function updateDeferredValueImpl(hook, prevValue, value) { var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes); if (shouldDeferValue) { // This is an urgent update. If the value has changed, keep using the // previous value and spawn a deferred render to update it later. if (!objectIs(value, prevValue)) { // Schedule a deferred render var deferredLane = claimNextTransitionLane(); currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane); markSkippedUpdateLanes(deferredLane); // Set this to true to indicate that the rendered value is inconsistent // from the latest value. The name "baseState" doesn't really match how we // use it because we're reusing a state hook field instead of creating a // new one. hook.baseState = true; } // Reuse the previous value return prevValue; } else { // This is not an urgent update, so we can use the latest value regardless // of what it is. No need to defer it. // However, if we're currently inside a spawned render, then we need to mark // this as an update to prevent the fiber from bailing out. // // `baseState` is true when the current value is different from the rendered // value. The name doesn't really match how we use it because we're reusing // a state hook field instead of creating a new one. if (hook.baseState) { // Flip this back to false. hook.baseState = false; markWorkInProgressReceivedUpdate(); } hook.memoizedState = value; return value; } } function startTransition(setPending, callback, options) { var previousPriority = getCurrentUpdatePriority(); setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority)); setPending(true); var prevTransition = ReactCurrentBatchConfig$2.transition; ReactCurrentBatchConfig$2.transition = {}; var currentTransition = ReactCurrentBatchConfig$2.transition; { ReactCurrentBatchConfig$2.transition._updatedFibers = new Set(); } try { setPending(false); callback(); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$2.transition = prevTransition; { if (prevTransition === null && currentTransition._updatedFibers) { var updatedFibersCount = currentTransition._updatedFibers.size; if (updatedFibersCount > 10) { warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); } currentTransition._updatedFibers.clear(); } } } } function mountTransition() { var _mountState = mountState(false), isPending = _mountState[0], setPending = _mountState[1]; // The `start` method never changes. var start = startTransition.bind(null, setPending); var hook = mountWorkInProgressHook(); hook.memoizedState = start; return [isPending, start]; } function updateTransition() { var _updateState = updateState(), isPending = _updateState[0]; var hook = updateWorkInProgressHook(); var start = hook.memoizedState; return [isPending, start]; } function rerenderTransition() { var _rerenderState = rerenderState(), isPending = _rerenderState[0]; var hook = updateWorkInProgressHook(); var start = hook.memoizedState; return [isPending, start]; } var isUpdatingOpaqueValueInRenderPhase = false; function getIsUpdatingOpaqueValueInRenderPhaseInDEV() { { return isUpdatingOpaqueValueInRenderPhase; } } function mountId() { var hook = mountWorkInProgressHook(); var root = getWorkInProgressRoot(); // TODO: In Fizz, id generation is specific to each server config. Maybe we // should do this in Fiber, too? Deferring this decision for now because // there's no other place to store the prefix except for an internal field on // the public createRoot object, which the fiber tree does not currently have // a reference to. var identifierPrefix = root.identifierPrefix; var id; if (getIsHydrating()) { var treeId = getTreeId(); // Use a captial R prefix for server-generated ids. id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end // that represents the position of this useId hook among all the useId // hooks for this fiber. var localId = localIdCounter++; if (localId > 0) { id += 'H' + localId.toString(32); } id += ':'; } else { // Use a lowercase r prefix for client-generated ids. var globalClientId = globalClientIdCounter++; id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':'; } hook.memoizedState = id; return id; } function updateId() { var hook = updateWorkInProgressHook(); var id = hook.memoizedState; return id; } function dispatchReducerAction(fiber, queue, action) { { if (typeof arguments[3] === 'function') { error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); } } var lane = requestUpdateLane(fiber); var update = { lane: lane, action: action, hasEagerState: false, eagerState: null, next: null }; if (isRenderPhaseUpdate(fiber)) { enqueueRenderPhaseUpdate(queue, update); } else { var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); if (root !== null) { var eventTime = requestEventTime(); scheduleUpdateOnFiber(root, fiber, lane, eventTime); entangleTransitionUpdate(root, queue, lane); } } markUpdateInDevTools(fiber, lane); } function dispatchSetState(fiber, queue, action) { { if (typeof arguments[3] === 'function') { error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().'); } } var lane = requestUpdateLane(fiber); var update = { lane: lane, action: action, hasEagerState: false, eagerState: null, next: null }; if (isRenderPhaseUpdate(fiber)) { enqueueRenderPhaseUpdate(queue, update); } else { var alternate = fiber.alternate; if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) { // The queue is currently empty, which means we can eagerly compute the // next state before entering the render phase. If the new state is the // same as the current state, we may be able to bail out entirely. var lastRenderedReducer = queue.lastRenderedReducer; if (lastRenderedReducer !== null) { var prevDispatcher; { prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; } try { var currentState = queue.lastRenderedState; var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute // it, on the update object. If the reducer hasn't changed by the // time we enter the render phase, then the eager state can be used // without calling the reducer again. update.hasEagerState = true; update.eagerState = eagerState; if (objectIs(eagerState, currentState)) { // Fast path. We can bail out without scheduling React to re-render. // It's still possible that we'll need to rebase this update later, // if the component re-renders for a different reason and by that // time the reducer has changed. // TODO: Do we still need to entangle transitions in this case? enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane); return; } } catch (error) {// Suppress the error. It will throw again in the render phase. } finally { { ReactCurrentDispatcher$1.current = prevDispatcher; } } } } var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane); if (root !== null) { var eventTime = requestEventTime(); scheduleUpdateOnFiber(root, fiber, lane, eventTime); entangleTransitionUpdate(root, queue, lane); } } markUpdateInDevTools(fiber, lane); } function isRenderPhaseUpdate(fiber) { var alternate = fiber.alternate; return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1; } function enqueueRenderPhaseUpdate(queue, update) { // This is a render phase update. Stash it in a lazily-created map of // queue -> linked list of updates. After this render pass, we'll restart // and apply the stashed updates on top of the work-in-progress hook. didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; var pending = queue.pending; if (pending === null) { // This is the first update. Create a circular list. update.next = update; } else { update.next = pending.next; pending.next = update; } queue.pending = update; } // TODO: Move to ReactFiberConcurrentUpdates? function entangleTransitionUpdate(root, queue, lane) { if (isTransitionLane(lane)) { var queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they // must have finished. We can remove them from the shared queue, which // represents a superset of the actually pending lanes. In some cases we // may entangle more than we need to, but that's OK. In fact it's worse if // we *don't* entangle when we should. queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes. var newQueueLanes = mergeLanes(queueLanes, lane); queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if // the lane finished since the last time we entangled it. So we need to // entangle it again, just to be sure. markRootEntangled(root, newQueueLanes); } } function markUpdateInDevTools(fiber, lane, action) { { markStateUpdateScheduled(fiber, lane); } } var ContextOnlyDispatcher = { readContext: readContext, useCallback: throwInvalidHookError, useContext: throwInvalidHookError, useEffect: throwInvalidHookError, useImperativeHandle: throwInvalidHookError, useInsertionEffect: throwInvalidHookError, useLayoutEffect: throwInvalidHookError, useMemo: throwInvalidHookError, useReducer: throwInvalidHookError, useRef: throwInvalidHookError, useState: throwInvalidHookError, useDebugValue: throwInvalidHookError, useDeferredValue: throwInvalidHookError, useTransition: throwInvalidHookError, useMutableSource: throwInvalidHookError, useSyncExternalStore: throwInvalidHookError, useId: throwInvalidHookError, unstable_isNewReconciler: enableNewReconciler }; var HooksDispatcherOnMountInDEV = null; var HooksDispatcherOnMountWithHookTypesInDEV = null; var HooksDispatcherOnUpdateInDEV = null; var HooksDispatcherOnRerenderInDEV = null; var InvalidNestedHooksDispatcherOnMountInDEV = null; var InvalidNestedHooksDispatcherOnUpdateInDEV = null; var InvalidNestedHooksDispatcherOnRerenderInDEV = null; { var warnInvalidContextAccess = function () { error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); }; var warnInvalidHookAccess = function () { error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); }; HooksDispatcherOnMountInDEV = { readContext: function (context) { return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; mountHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; mountHookTypesDev(); checkDepsAreArrayDev(deps); return mountLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; mountHookTypesDev(); checkDepsAreArrayDev(deps); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; mountHookTypesDev(); return mountRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; mountHookTypesDev(); return mountDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; mountHookTypesDev(); return mountDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; mountHookTypesDev(); return mountTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; mountHookTypesDev(); return mountMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; mountHookTypesDev(); return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; mountHookTypesDev(); return mountId(); }, unstable_isNewReconciler: enableNewReconciler }; HooksDispatcherOnMountWithHookTypesInDEV = { readContext: function (context) { return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return mountCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; updateHookTypesDev(); return mountInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return mountRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return mountDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; updateHookTypesDev(); return mountDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; updateHookTypesDev(); return mountTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; updateHookTypesDev(); return mountMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; updateHookTypesDev(); return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; updateHookTypesDev(); return mountId(); }, unstable_isNewReconciler: enableNewReconciler }; HooksDispatcherOnUpdateInDEV = { readContext: function (context) { return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return updateRef(); }, useState: function (initialState) { currentHookNameInDev = 'useState'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return updateDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; updateHookTypesDev(); return updateDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; updateHookTypesDev(); return updateTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; updateHookTypesDev(); return updateMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; updateHookTypesDev(); return updateId(); }, unstable_isNewReconciler: enableNewReconciler }; HooksDispatcherOnRerenderInDEV = { readContext: function (context) { return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; try { return rerenderReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return updateRef(); }, useState: function (initialState) { currentHookNameInDev = 'useState'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV; try { return rerenderState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return updateDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; updateHookTypesDev(); return rerenderDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; updateHookTypesDev(); return rerenderTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; updateHookTypesDev(); return updateMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; updateHookTypesDev(); return updateId(); }, unstable_isNewReconciler: enableNewReconciler }; InvalidNestedHooksDispatcherOnMountInDEV = { readContext: function (context) { warnInvalidContextAccess(); return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); mountHookTypesDev(); return mountCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); mountHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); mountHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); mountHookTypesDev(); return mountRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); mountHookTypesDev(); return mountDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; warnInvalidHookAccess(); mountHookTypesDev(); return mountDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; warnInvalidHookAccess(); mountHookTypesDev(); return mountTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; warnInvalidHookAccess(); mountHookTypesDev(); return mountMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; warnInvalidHookAccess(); mountHookTypesDev(); return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; warnInvalidHookAccess(); mountHookTypesDev(); return mountId(); }, unstable_isNewReconciler: enableNewReconciler }; InvalidNestedHooksDispatcherOnUpdateInDEV = { readContext: function (context) { warnInvalidContextAccess(); return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); updateHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); updateHookTypesDev(); return updateRef(); }, useState: function (initialState) { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); updateHookTypesDev(); return updateDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; warnInvalidHookAccess(); updateHookTypesDev(); return updateDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; warnInvalidHookAccess(); updateHookTypesDev(); return updateTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; warnInvalidHookAccess(); updateHookTypesDev(); return updateMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; warnInvalidHookAccess(); updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; warnInvalidHookAccess(); updateHookTypesDev(); return updateId(); }, unstable_isNewReconciler: enableNewReconciler }; InvalidNestedHooksDispatcherOnRerenderInDEV = { readContext: function (context) { warnInvalidContextAccess(); return readContext(context); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function (context) { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); updateHookTypesDev(); return readContext(context); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useInsertionEffect: function (create, deps) { currentHookNameInDev = 'useInsertionEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateInsertionEffect(create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return rerenderReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); updateHookTypesDev(); return updateRef(); }, useState: function (initialState) { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return rerenderState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); updateHookTypesDev(); return updateDebugValue(); }, useDeferredValue: function (value) { currentHookNameInDev = 'useDeferredValue'; warnInvalidHookAccess(); updateHookTypesDev(); return rerenderDeferredValue(value); }, useTransition: function () { currentHookNameInDev = 'useTransition'; warnInvalidHookAccess(); updateHookTypesDev(); return rerenderTransition(); }, useMutableSource: function (source, getSnapshot, subscribe) { currentHookNameInDev = 'useMutableSource'; warnInvalidHookAccess(); updateHookTypesDev(); return updateMutableSource(); }, useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) { currentHookNameInDev = 'useSyncExternalStore'; warnInvalidHookAccess(); updateHookTypesDev(); return updateSyncExternalStore(subscribe, getSnapshot); }, useId: function () { currentHookNameInDev = 'useId'; warnInvalidHookAccess(); updateHookTypesDev(); return updateId(); }, unstable_isNewReconciler: enableNewReconciler }; } var now$1 = unstable_now; var commitTime = 0; var layoutEffectStartTime = -1; var profilerStartTime = -1; var passiveEffectStartTime = -1; /** * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect). * * The overall sequence is: * 1. render * 2. commit (and call `onRender`, `onCommit`) * 3. check for nested updates * 4. flush passive effects (and call `onPostCommit`) * * Nested updates are identified in step 3 above, * but step 4 still applies to the work that was just committed. * We use two flags to track nested updates then: * one tracks whether the upcoming update is a nested update, * and the other tracks whether the current update was a nested update. * The first value gets synced to the second at the start of the render phase. */ var currentUpdateIsNested = false; var nestedUpdateScheduled = false; function isCurrentUpdateNested() { return currentUpdateIsNested; } function markNestedUpdateScheduled() { { nestedUpdateScheduled = true; } } function resetNestedUpdateFlag() { { currentUpdateIsNested = false; nestedUpdateScheduled = false; } } function syncNestedUpdateFlag() { { currentUpdateIsNested = nestedUpdateScheduled; nestedUpdateScheduled = false; } } function getCommitTime() { return commitTime; } function recordCommitTime() { commitTime = now$1(); } function startProfilerTimer(fiber) { profilerStartTime = now$1(); if (fiber.actualStartTime < 0) { fiber.actualStartTime = now$1(); } } function stopProfilerTimerIfRunning(fiber) { profilerStartTime = -1; } function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { if (profilerStartTime >= 0) { var elapsedTime = now$1() - profilerStartTime; fiber.actualDuration += elapsedTime; if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; } profilerStartTime = -1; } } function recordLayoutEffectDuration(fiber) { if (layoutEffectStartTime >= 0) { var elapsedTime = now$1() - layoutEffectStartTime; layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor // Or the root (for the DevTools Profiler to read) var parentFiber = fiber.return; while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: var root = parentFiber.stateNode; root.effectDuration += elapsedTime; return; case Profiler: var parentStateNode = parentFiber.stateNode; parentStateNode.effectDuration += elapsedTime; return; } parentFiber = parentFiber.return; } } } function recordPassiveEffectDuration(fiber) { if (passiveEffectStartTime >= 0) { var elapsedTime = now$1() - passiveEffectStartTime; passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor // Or the root (for the DevTools Profiler to read) var parentFiber = fiber.return; while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: var root = parentFiber.stateNode; if (root !== null) { root.passiveEffectDuration += elapsedTime; } return; case Profiler: var parentStateNode = parentFiber.stateNode; if (parentStateNode !== null) { // Detached fibers have their state node cleared out. // In this case, the return pointer is also cleared out, // so we won't be able to report the time spent in this Profiler's subtree. parentStateNode.passiveEffectDuration += elapsedTime; } return; } parentFiber = parentFiber.return; } } } function startLayoutEffectTimer() { layoutEffectStartTime = now$1(); } function startPassiveEffectTimer() { passiveEffectStartTime = now$1(); } function transferActualDuration(fiber) { // Transfer time spent rendering these children so we don't lose it // after we rerender. This is used as a helper in special cases // where we should count the work of multiple passes. var child = fiber.child; while (child) { fiber.actualDuration += child.actualDuration; child = child.sibling; } } function resolveDefaultProps(Component, baseProps) { if (Component && Component.defaultProps) { // Resolve default props. Taken from ReactElement var props = assign({}, baseProps); var defaultProps = Component.defaultProps; for (var propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } return props; } return baseProps; } var fakeInternalInstance = {}; var didWarnAboutStateAssignmentForComponent; var didWarnAboutUninitializedState; var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; var didWarnAboutLegacyLifecyclesAndDerivedState; var didWarnAboutUndefinedDerivedState; var warnOnUndefinedDerivedState; var warnOnInvalidCallback; var didWarnAboutDirectlyAssigningPropsToState; var didWarnAboutContextTypeAndContextTypes; var didWarnAboutInvalidateContextType; var didWarnAboutLegacyContext$1; { didWarnAboutStateAssignmentForComponent = new Set(); didWarnAboutUninitializedState = new Set(); didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); didWarnAboutDirectlyAssigningPropsToState = new Set(); didWarnAboutUndefinedDerivedState = new Set(); didWarnAboutContextTypeAndContextTypes = new Set(); didWarnAboutInvalidateContextType = new Set(); didWarnAboutLegacyContext$1 = new Set(); var didWarnOnInvalidCallback = new Set(); warnOnInvalidCallback = function (callback, callerName) { if (callback === null || typeof callback === 'function') { return; } var key = callerName + '_' + callback; if (!didWarnOnInvalidCallback.has(key)) { didWarnOnInvalidCallback.add(key); error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); } }; warnOnUndefinedDerivedState = function (type, partialState) { if (partialState === undefined) { var componentName = getComponentNameFromType(type) || 'Component'; if (!didWarnAboutUndefinedDerivedState.has(componentName)) { didWarnAboutUndefinedDerivedState.add(componentName); error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); } } }; // This is so gross but it's at least non-critical and can be removed if // it causes problems. This is meant to give a nicer error message for // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, // ...)) which otherwise throws a "_processChildContext is not a function" // exception. Object.defineProperty(fakeInternalInstance, '_processChildContext', { enumerable: false, value: function () { throw new Error('_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).'); } }); Object.freeze(fakeInternalInstance); } function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) { var prevState = workInProgress.memoizedState; var partialState = getDerivedStateFromProps(nextProps, prevState); { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { // Invoke the function an extra time to help detect side-effects. partialState = getDerivedStateFromProps(nextProps, prevState); } finally { setIsStrictModeForDevtools(false); } } warnOnUndefinedDerivedState(ctor, partialState); } // Merge the partial state and the previous state. var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the // base state. if (workInProgress.lanes === NoLanes) { // Queue is always non-null for classes var updateQueue = workInProgress.updateQueue; updateQueue.baseState = memoizedState; } } var classComponentUpdater = { isMounted: isMounted, enqueueSetState: function (inst, payload, callback) { var fiber = get(inst); var eventTime = requestEventTime(); var lane = requestUpdateLane(fiber); var update = createUpdate(eventTime, lane); update.payload = payload; if (callback !== undefined && callback !== null) { { warnOnInvalidCallback(callback, 'setState'); } update.callback = callback; } var root = enqueueUpdate(fiber, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane, eventTime); entangleTransitions(root, fiber, lane); } { markStateUpdateScheduled(fiber, lane); } }, enqueueReplaceState: function (inst, payload, callback) { var fiber = get(inst); var eventTime = requestEventTime(); var lane = requestUpdateLane(fiber); var update = createUpdate(eventTime, lane); update.tag = ReplaceState; update.payload = payload; if (callback !== undefined && callback !== null) { { warnOnInvalidCallback(callback, 'replaceState'); } update.callback = callback; } var root = enqueueUpdate(fiber, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane, eventTime); entangleTransitions(root, fiber, lane); } { markStateUpdateScheduled(fiber, lane); } }, enqueueForceUpdate: function (inst, callback) { var fiber = get(inst); var eventTime = requestEventTime(); var lane = requestUpdateLane(fiber); var update = createUpdate(eventTime, lane); update.tag = ForceUpdate; if (callback !== undefined && callback !== null) { { warnOnInvalidCallback(callback, 'forceUpdate'); } update.callback = callback; } var root = enqueueUpdate(fiber, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane, eventTime); entangleTransitions(root, fiber, lane); } { markForceUpdateScheduled(fiber, lane); } } }; function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) { var instance = workInProgress.stateNode; if (typeof instance.shouldComponentUpdate === 'function') { var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { // Invoke the function an extra time to help detect side-effects. shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); } finally { setIsStrictModeForDevtools(false); } } if (shouldUpdate === undefined) { error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component'); } } return shouldUpdate; } if (ctor.prototype && ctor.prototype.isPureReactComponent) { return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState); } return true; } function checkClassInstance(workInProgress, ctor, newProps) { var instance = workInProgress.stateNode; { var name = getComponentNameFromType(ctor) || 'Component'; var renderPresent = instance.render; if (!renderPresent) { if (ctor.prototype && typeof ctor.prototype.render === 'function') { error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); } else { error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); } } if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name); } if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name); } if (instance.propTypes) { error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name); } if (instance.contextType) { error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name); } { if (ctor.childContextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip // this one. (workInProgress.mode & StrictLegacyMode) === NoMode) { didWarnAboutLegacyContext$1.add(ctor); error('%s uses the legacy childContextTypes API which is no longer ' + 'supported and will be removed in the next major release. Use ' + 'React.createContext() instead\n\n.' + 'Learn more about this warning here: https://reactjs.org/link/legacy-context', name); } if (ctor.contextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip // this one. (workInProgress.mode & StrictLegacyMode) === NoMode) { didWarnAboutLegacyContext$1.add(ctor); error('%s uses the legacy contextTypes API which is no longer supported ' + 'and will be removed in the next major release. Use ' + 'React.createContext() with static contextType instead.\n\n' + 'Learn more about this warning here: https://reactjs.org/link/legacy-context', name); } if (instance.contextTypes) { error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name); } if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { didWarnAboutContextTypeAndContextTypes.add(ctor); error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); } } if (typeof instance.componentShouldUpdate === 'function') { error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name); } if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component'); } if (typeof instance.componentDidUnmount === 'function') { error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name); } if (typeof instance.componentDidReceiveProps === 'function') { error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name); } if (typeof instance.componentWillRecieveProps === 'function') { error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name); } if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name); } var hasMutatedProps = instance.props !== newProps; if (instance.props !== undefined && hasMutatedProps) { error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name); } if (instance.defaultProps) { error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name); } if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor)); } if (typeof instance.getDerivedStateFromProps === 'function') { error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); } if (typeof instance.getDerivedStateFromError === 'function') { error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); } if (typeof ctor.getSnapshotBeforeUpdate === 'function') { error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name); } var _state = instance.state; if (_state && (typeof _state !== 'object' || isArray(_state))) { error('%s.state: must be set to an object or null', name); } if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') { error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name); } } } function adoptClassInstance(workInProgress, instance) { instance.updater = classComponentUpdater; workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates set(instance, workInProgress); { instance._reactInternalInstance = fakeInternalInstance; } } function constructClassInstance(workInProgress, ctor, props) { var isLegacyContextConsumer = false; var unmaskedContext = emptyContextObject; var context = emptyContextObject; var contextType = ctor.contextType; { if ('contextType' in ctor) { var isValid = // Allow null for conditional declaration contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer> if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); var addendum = ''; if (contextType === undefined) { addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; } else if (typeof contextType !== 'object') { addendum = ' However, it is set to a ' + typeof contextType + '.'; } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { addendum = ' Did you accidentally pass the Context.Provider instead?'; } else if (contextType._context !== undefined) { // <Context.Consumer> addendum = ' Did you accidentally pass the Context.Consumer instead?'; } else { addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; } error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum); } } } if (typeof contextType === 'object' && contextType !== null) { context = readContext(contextType); } else { unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); var contextTypes = ctor.contextTypes; isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined; context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; } var instance = new ctor(props, context); // Instantiate twice to help detect side-effects. { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { instance = new ctor(props, context); // eslint-disable-line no-new } finally { setIsStrictModeForDevtools(false); } } } var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null; adoptClassInstance(workInProgress, instance); { if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) { var componentName = getComponentNameFromType(ctor) || 'Component'; if (!didWarnAboutUninitializedState.has(componentName)) { didWarnAboutUninitializedState.add(componentName); error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); } } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Warn about these lifecycles if they are present. // Don't warn about react-lifecycles-compat polyfilled methods though. if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { var foundWillMountName = null; var foundWillReceivePropsName = null; var foundWillUpdateName = null; if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { foundWillMountName = 'componentWillMount'; } else if (typeof instance.UNSAFE_componentWillMount === 'function') { foundWillMountName = 'UNSAFE_componentWillMount'; } if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { foundWillReceivePropsName = 'componentWillReceiveProps'; } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; } if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { foundWillUpdateName = 'componentWillUpdate'; } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { foundWillUpdateName = 'UNSAFE_componentWillUpdate'; } if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { var _componentName = getComponentNameFromType(ctor) || 'Component'; var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); } } } } // Cache unmasked context so we can avoid recreating masked context unless necessary. // ReactFiberContext usually updates this cache but can't for newly-created instances. if (isLegacyContextConsumer) { cacheContext(workInProgress, unmaskedContext, context); } return instance; } function callComponentWillMount(workInProgress, instance) { var oldState = instance.state; if (typeof instance.componentWillMount === 'function') { instance.componentWillMount(); } if (typeof instance.UNSAFE_componentWillMount === 'function') { instance.UNSAFE_componentWillMount(); } if (oldState !== instance.state) { { error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component'); } classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) { var oldState = instance.state; if (typeof instance.componentWillReceiveProps === 'function') { instance.componentWillReceiveProps(newProps, nextContext); } if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); } if (instance.state !== oldState) { { var componentName = getComponentNameFromFiber(workInProgress) || 'Component'; if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { didWarnAboutStateAssignmentForComponent.add(componentName); error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName); } } classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } // Invokes the mount life-cycles on a previously never rendered instance. function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { { checkClassInstance(workInProgress, ctor, newProps); } var instance = workInProgress.stateNode; instance.props = newProps; instance.state = workInProgress.memoizedState; instance.refs = {}; initializeUpdateQueue(workInProgress); var contextType = ctor.contextType; if (typeof contextType === 'object' && contextType !== null) { instance.context = readContext(contextType); } else { var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); instance.context = getMaskedContext(workInProgress, unmaskedContext); } { if (instance.state === newProps) { var componentName = getComponentNameFromType(ctor) || 'Component'; if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { didWarnAboutDirectlyAssigningPropsToState.add(componentName); error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); } } if (workInProgress.mode & StrictLegacyMode) { ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance); } { ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance); } } instance.state = workInProgress.memoizedState; var getDerivedStateFromProps = ctor.getDerivedStateFromProps; if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); instance.state = workInProgress.memoizedState; } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's // process them now. processUpdateQueue(workInProgress, newProps, instance, renderLanes); instance.state = workInProgress.memoizedState; } if (typeof instance.componentDidMount === 'function') { var fiberFlags = Update; { fiberFlags |= LayoutStatic; } if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { fiberFlags |= MountLayoutDev; } workInProgress.flags |= fiberFlags; } } function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) { var instance = workInProgress.stateNode; var oldProps = workInProgress.memoizedProps; instance.props = oldProps; var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; if (typeof contextType === 'object' && contextType !== null) { nextContext = readContext(contextType); } else { var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { if (oldProps !== newProps || oldContext !== nextContext) { callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); } } resetHasForceUpdateBeforeProcessing(); var oldState = workInProgress.memoizedState; var newState = instance.state = oldState; processUpdateQueue(workInProgress, newProps, instance, renderLanes); newState = workInProgress.memoizedState; if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === 'function') { var fiberFlags = Update; { fiberFlags |= LayoutStatic; } if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { fiberFlags |= MountLayoutDev; } workInProgress.flags |= fiberFlags; } return false; } if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); newState = workInProgress.memoizedState; } var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext); if (shouldUpdate) { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { if (typeof instance.componentWillMount === 'function') { instance.componentWillMount(); } if (typeof instance.UNSAFE_componentWillMount === 'function') { instance.UNSAFE_componentWillMount(); } } if (typeof instance.componentDidMount === 'function') { var _fiberFlags = Update; { _fiberFlags |= LayoutStatic; } if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { _fiberFlags |= MountLayoutDev; } workInProgress.flags |= _fiberFlags; } } else { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === 'function') { var _fiberFlags2 = Update; { _fiberFlags2 |= LayoutStatic; } if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { _fiberFlags2 |= MountLayoutDev; } workInProgress.flags |= _fiberFlags2; } // If shouldComponentUpdate returned false, we should still update the // memoized state to indicate that this work can be reused. workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. instance.props = newProps; instance.state = newState; instance.context = nextContext; return shouldUpdate; } // Invokes the update life-cycles and returns false if it shouldn't rerender. function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) { var instance = workInProgress.stateNode; cloneUpdateQueue(current, workInProgress); var unresolvedOldProps = workInProgress.memoizedProps; var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps); instance.props = oldProps; var unresolvedNewProps = workInProgress.pendingProps; var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; if (typeof contextType === 'object' && contextType !== null) { nextContext = readContext(contextType); } else { var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) { callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); } } resetHasForceUpdateBeforeProcessing(); var oldState = workInProgress.memoizedState; var newState = instance.state = oldState; processUpdateQueue(workInProgress, newProps, instance, renderLanes); newState = workInProgress.memoizedState; if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation )) { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidUpdate === 'function') { if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.flags |= Update; } } if (typeof instance.getSnapshotBeforeUpdate === 'function') { if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.flags |= Snapshot; } } return false; } if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); newState = workInProgress.memoizedState; } var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice, // both before and after `shouldComponentUpdate` has been called. Not ideal, // but I'm loath to refactor this function. This only happens for memoized // components so it's not that common. enableLazyContextPropagation ; if (shouldUpdate) { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) { if (typeof instance.componentWillUpdate === 'function') { instance.componentWillUpdate(newProps, newState, nextContext); } if (typeof instance.UNSAFE_componentWillUpdate === 'function') { instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); } } if (typeof instance.componentDidUpdate === 'function') { workInProgress.flags |= Update; } if (typeof instance.getSnapshotBeforeUpdate === 'function') { workInProgress.flags |= Snapshot; } } else { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidUpdate === 'function') { if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.flags |= Update; } } if (typeof instance.getSnapshotBeforeUpdate === 'function') { if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.flags |= Snapshot; } } // If shouldComponentUpdate returned false, we should still update the // memoized props/state to indicate that this work can be reused. workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. instance.props = newProps; instance.state = newState; instance.context = nextContext; return shouldUpdate; } function createCapturedValueAtFiber(value, source) { // If the value is an error, call this function immediately after it is thrown // so the stack is accurate. return { value: value, source: source, stack: getStackByFiberInDevAndProd(source), digest: null }; } function createCapturedValue(value, digest, stack) { return { value: value, source: null, stack: stack != null ? stack : null, digest: digest != null ? digest : null }; } // This module is forked in different environments. // By default, return `true` to log errors to the console. // Forks can return `false` if this isn't desirable. function showErrorDialog(boundary, errorInfo) { return true; } function logCapturedError(boundary, errorInfo) { try { var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging. // This enables renderers like ReactNative to better manage redbox behavior. if (logError === false) { return; } var error = errorInfo.value; if (true) { var source = errorInfo.source; var stack = errorInfo.stack; var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling // `preventDefault()` in window `error` handler. // We record this information as an expando on the error. if (error != null && error._suppressLogging) { if (boundary.tag === ClassComponent) { // The error is recoverable and was silenced. // Ignore it and don't print the stack addendum. // This is handy for testing error boundaries without noise. return; } // The error is fatal. Since the silencing might have // been accidental, we'll surface it anyway. // However, the browser would have silenced the original error // so we'll print it first, and then print the stack addendum. console['error'](error); // Don't transform to our wrapper // For a more detailed description of this block, see: // https://github.com/facebook/react/pull/13384 } var componentName = source ? getComponentNameFromFiber(source) : null; var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:'; var errorBoundaryMessage; if (boundary.tag === HostRoot) { errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.'; } else { var errorBoundaryName = getComponentNameFromFiber(boundary) || 'Anonymous'; errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + "."); } var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack. // We don't include the original error message and JS stack because the browser // has already printed it. Even if the application swallows the error, it is still // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. console['error'](combinedMessage); // Don't transform to our wrapper } else { // In production, we print the error directly. // This will include the message, the JS stack, and anything the browser wants to show. // We pass the error object instead of custom message so that the browser displays the error natively. console['error'](error); // Don't transform to our wrapper } } catch (e) { // This method must not throw, or React internal state will get messed up. // If console.error is overridden, or logCapturedError() shows a dialog that throws, // we want to report this error outside of the normal stack as a last resort. // https://github.com/facebook/react/issues/13188 setTimeout(function () { throw e; }); } } var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, lane) { var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null. update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property // being called "element". update.payload = { element: null }; var error = errorInfo.value; update.callback = function () { onUncaughtError(error); logCapturedError(fiber, errorInfo); }; return update; } function createClassErrorUpdate(fiber, errorInfo, lane) { var update = createUpdate(NoTimestamp, lane); update.tag = CaptureUpdate; var getDerivedStateFromError = fiber.type.getDerivedStateFromError; if (typeof getDerivedStateFromError === 'function') { var error$1 = errorInfo.value; update.payload = function () { return getDerivedStateFromError(error$1); }; update.callback = function () { { markFailedErrorBoundaryForHotReloading(fiber); } logCapturedError(fiber, errorInfo); }; } var inst = fiber.stateNode; if (inst !== null && typeof inst.componentDidCatch === 'function') { update.callback = function callback() { { markFailedErrorBoundaryForHotReloading(fiber); } logCapturedError(fiber, errorInfo); if (typeof getDerivedStateFromError !== 'function') { // To preserve the preexisting retry behavior of error boundaries, // we keep track of which ones already failed during this batch. // This gets reset before we yield back to the browser. // TODO: Warn in strict mode if getDerivedStateFromError is // not defined. markLegacyErrorBoundaryAsFailed(this); } var error$1 = errorInfo.value; var stack = errorInfo.stack; this.componentDidCatch(error$1, { componentStack: stack !== null ? stack : '' }); { if (typeof getDerivedStateFromError !== 'function') { // If componentDidCatch is the only error boundary method defined, // then it needs to call setState to recover from errors. // If no state update is scheduled then the boundary will swallow the error. if (!includesSomeLane(fiber.lanes, SyncLane)) { error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentNameFromFiber(fiber) || 'Unknown'); } } } }; } return update; } function attachPingListener(root, wakeable, lanes) { // Attach a ping listener // // The data might resolve before we have a chance to commit the fallback. Or, // in the case of a refresh, we'll never commit a fallback. So we need to // attach a listener now. When it resolves ("pings"), we can decide whether to // try rendering the tree again. // // Only attach a listener if one does not already exist for the lanes // we're currently rendering (which acts like a "thread ID" here). // // We only need to do this in concurrent mode. Legacy Suspense always // commits fallbacks synchronously, so there are no pings. var pingCache = root.pingCache; var threadIDs; if (pingCache === null) { pingCache = root.pingCache = new PossiblyWeakMap$1(); threadIDs = new Set(); pingCache.set(wakeable, threadIDs); } else { threadIDs = pingCache.get(wakeable); if (threadIDs === undefined) { threadIDs = new Set(); pingCache.set(wakeable, threadIDs); } } if (!threadIDs.has(lanes)) { // Memoize using the thread ID to prevent redundant listeners. threadIDs.add(lanes); var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes); { if (isDevToolsPresent) { // If we have pending work still, restore the original updaters restorePendingUpdaters(root, lanes); } } wakeable.then(ping, ping); } } function attachRetryListener(suspenseBoundary, root, wakeable, lanes) { // Retry listener // // If the fallback does commit, we need to attach a different type of // listener. This one schedules an update on the Suspense boundary to turn // the fallback state off. // // Stash the wakeable on the boundary fiber so we can access it in the // commit phase. // // When the wakeable resolves, we'll attempt to render the boundary // again ("retry"). var wakeables = suspenseBoundary.updateQueue; if (wakeables === null) { var updateQueue = new Set(); updateQueue.add(wakeable); suspenseBoundary.updateQueue = updateQueue; } else { wakeables.add(wakeable); } } function resetSuspendedComponent(sourceFiber, rootRenderLanes) { // A legacy mode Suspense quirk, only relevant to hook components. var tag = sourceFiber.tag; if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) { var currentSource = sourceFiber.alternate; if (currentSource) { sourceFiber.updateQueue = currentSource.updateQueue; sourceFiber.memoizedState = currentSource.memoizedState; sourceFiber.lanes = currentSource.lanes; } else { sourceFiber.updateQueue = null; sourceFiber.memoizedState = null; } } } function getNearestSuspenseBoundaryToCapture(returnFiber) { var node = returnFiber; do { if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) { return node; } // This boundary already captured during this render. Continue to the next // boundary. node = node.return; } while (node !== null); return null; } function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) { // This marks a Suspense boundary so that when we're unwinding the stack, // it captures the suspended "exception" and does a second (fallback) pass. if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) { // Legacy Mode Suspense // // If the boundary is in legacy mode, we should *not* // suspend the commit. Pretend as if the suspended component rendered // null and keep rendering. When the Suspense boundary completes, // we'll do a second pass to render the fallback. if (suspenseBoundary === returnFiber) { // Special case where we suspended while reconciling the children of // a Suspense boundary's inner Offscreen wrapper fiber. This happens // when a React.lazy component is a direct child of a // Suspense boundary. // // Suspense boundaries are implemented as multiple fibers, but they // are a single conceptual unit. The legacy mode behavior where we // pretend the suspended fiber committed as `null` won't work, // because in this case the "suspended" fiber is the inner // Offscreen wrapper. // // Because the contents of the boundary haven't started rendering // yet (i.e. nothing in the tree has partially rendered) we can // switch to the regular, concurrent mode behavior: mark the // boundary with ShouldCapture and enter the unwind phase. suspenseBoundary.flags |= ShouldCapture; } else { suspenseBoundary.flags |= DidCapture; sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete. // But we shouldn't call any lifecycle methods or callbacks. Remove // all lifecycle effect tags. sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete); if (sourceFiber.tag === ClassComponent) { var currentSourceFiber = sourceFiber.alternate; if (currentSourceFiber === null) { // This is a new mount. Change the tag so it's not mistaken for a // completed class component. For example, we should not call // componentWillUnmount if it is deleted. sourceFiber.tag = IncompleteClassComponent; } else { // When we try rendering again, we should not reuse the current fiber, // since it's known to be in an inconsistent state. Use a force update to // prevent a bail out. var update = createUpdate(NoTimestamp, SyncLane); update.tag = ForceUpdate; enqueueUpdate(sourceFiber, update, SyncLane); } } // The source fiber did not complete. Mark it with Sync priority to // indicate that it still has pending work. sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); } return suspenseBoundary; } // Confirmed that the boundary is in a concurrent mode tree. Continue // with the normal suspend path. // // After this we'll use a set of heuristics to determine whether this // render pass will run to completion or restart or "suspend" the commit. // The actual logic for this is spread out in different places. // // This first principle is that if we're going to suspend when we complete // a root, then we should also restart if we get an update or ping that // might unsuspend it, and vice versa. The only reason to suspend is // because you think you might want to restart before committing. However, // it doesn't make sense to restart only while in the period we're suspended. // // Restarting too aggressively is also not good because it starves out any // intermediate loading state. So we use heuristics to determine when. // Suspense Heuristics // // If nothing threw a Promise or all the same fallbacks are already showing, // then don't suspend/restart. // // If this is an initial render of a new tree of Suspense boundaries and // those trigger a fallback, then don't suspend/restart. We want to ensure // that we can show the initial loading state as quickly as possible. // // If we hit a "Delayed" case, such as when we'd switch from content back into // a fallback, then we should always suspend/restart. Transitions apply // to this case. If none is defined, JND is used instead. // // If we're already showing a fallback and it gets "retried", allowing us to show // another level, but there's still an inner boundary that would show a fallback, // then we suspend/restart for 500ms since the last time we showed a fallback // anywhere in the tree. This effectively throttles progressive loading into a // consistent train of commits. This also gives us an opportunity to restart to // get to the completed state slightly earlier. // // If there's ambiguity due to batching it's resolved in preference of: // 1) "delayed", 2) "initial render", 3) "retry". // // We want to ensure that a "busy" state doesn't get force committed. We want to // ensure that new initial loading states can commit as soon as possible. suspenseBoundary.flags |= ShouldCapture; // TODO: I think we can remove this, since we now use `DidCapture` in // the begin phase to prevent an early bailout. suspenseBoundary.lanes = rootRenderLanes; return suspenseBoundary; } function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) { // The source fiber did not complete. sourceFiber.flags |= Incomplete; { if (isDevToolsPresent) { // If we have pending work still, restore the original updaters restorePendingUpdaters(root, rootRenderLanes); } } if (value !== null && typeof value === 'object' && typeof value.then === 'function') { // This is a wakeable. The component suspended. var wakeable = value; resetSuspendedComponent(sourceFiber); { if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { markDidThrowWhileHydratingDEV(); } } var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); if (suspenseBoundary !== null) { suspenseBoundary.flags &= ~ForceClientRender; markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // We only attach ping listeners in concurrent mode. Legacy Suspense always // commits fallbacks synchronously, so there are no pings. if (suspenseBoundary.mode & ConcurrentMode) { attachPingListener(root, wakeable, rootRenderLanes); } attachRetryListener(suspenseBoundary, root, wakeable); return; } else { // No boundary was found. Unless this is a sync update, this is OK. // We can suspend and wait for more data to arrive. if (!includesSyncLane(rootRenderLanes)) { // This is not a sync update. Suspend. Since we're not activating a // Suspense boundary, this will unwind all the way to the root without // performing a second pass to render a fallback. (This is arguably how // refresh transitions should work, too, since we're not going to commit // the fallbacks anyway.) // // This case also applies to initial hydration. attachPingListener(root, wakeable, rootRenderLanes); renderDidSuspendDelayIfPossible(); return; } // This is a sync/discrete update. We treat this case like an error // because discrete renders are expected to produce a complete tree // synchronously to maintain consistency with external state. var uncaughtSuspenseError = new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To ' + 'fix, updates that suspend should be wrapped ' + 'with startTransition.'); // If we're outside a transition, fall through to the regular error path. // The error will be caught by the nearest suspense boundary. value = uncaughtSuspenseError; } } else { // This is a regular error, not a Suspense wakeable. if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { markDidThrowWhileHydratingDEV(); var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); // If the error was thrown during hydration, we may be able to recover by // discarding the dehydrated content and switching to a client render. // Instead of surfacing the error, find the nearest Suspense boundary // and render it again without hydration. if (_suspenseBoundary !== null) { if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) { // Set a flag to indicate that we should try rendering the normal // children again, not the fallback. _suspenseBoundary.flags |= ForceClientRender; } markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // Even though the user may not be affected by this error, we should // still log it so it can be fixed. queueHydrationError(createCapturedValueAtFiber(value, sourceFiber)); return; } } } value = createCapturedValueAtFiber(value, sourceFiber); renderDidError(value); // We didn't find a boundary that could handle this type of exception. Start // over and traverse parent path again, this time treating the exception // as an error. var workInProgress = returnFiber; do { switch (workInProgress.tag) { case HostRoot: { var _errorInfo = value; workInProgress.flags |= ShouldCapture; var lane = pickArbitraryLane(rootRenderLanes); workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); var update = createRootErrorUpdate(workInProgress, _errorInfo, lane); enqueueCapturedUpdate(workInProgress, update); return; } case ClassComponent: // Capture and retry var errorInfo = value; var ctor = workInProgress.type; var instance = workInProgress.stateNode; if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) { workInProgress.flags |= ShouldCapture; var _lane = pickArbitraryLane(rootRenderLanes); workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state var _update = createClassErrorUpdate(workInProgress, errorInfo, _lane); enqueueCapturedUpdate(workInProgress, _update); return; } break; } workInProgress = workInProgress.return; } while (workInProgress !== null); } function getSuspendedCache() { { return null; } // This function is called when a Suspense boundary suspends. It returns the } var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; var didReceiveUpdate = false; var didWarnAboutBadClass; var didWarnAboutModulePatternComponent; var didWarnAboutContextTypeOnFunctionComponent; var didWarnAboutGetDerivedStateOnFunctionComponent; var didWarnAboutFunctionRefs; var didWarnAboutReassigningProps; var didWarnAboutRevealOrder; var didWarnAboutTailOptions; var didWarnAboutDefaultPropsOnFunctionComponent; { didWarnAboutBadClass = {}; didWarnAboutModulePatternComponent = {}; didWarnAboutContextTypeOnFunctionComponent = {}; didWarnAboutGetDerivedStateOnFunctionComponent = {}; didWarnAboutFunctionRefs = {}; didWarnAboutReassigningProps = false; didWarnAboutRevealOrder = {}; didWarnAboutTailOptions = {}; didWarnAboutDefaultPropsOnFunctionComponent = {}; } function reconcileChildren(current, workInProgress, nextChildren, renderLanes) { if (current === null) { // If this is a fresh new component that hasn't been rendered yet, we // won't update its child set by applying minimal side-effects. Instead, // we will add them all to the child before it gets rendered. That means // we can optimize this reconciliation pass by not tracking side-effects. workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); } else { // If the current child is the same as the work in progress, it means that // we haven't yet started any work on these children. Therefore, we use // the clone algorithm to create a copy of all the current children. // If we had any progressed work already, that is invalid at this point so // let's throw it out. workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes); } } function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) { // This function is fork of reconcileChildren. It's used in cases where we // want to reconcile without matching against the existing set. This has the // effect of all current children being unmounted; even if the type and key // are the same, the old child is unmounted and a new child is created. // // To do this, we're going to go through the reconcile algorithm twice. In // the first pass, we schedule a deletion for all the current children by // passing null. workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we // pass null in place of where we usually pass the current child set. This has // the effect of remounting all children regardless of whether their // identities match. workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); } function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(Component)); } } } var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent var nextChildren; var hasId; prepareToReadContext(workInProgress, renderLanes); { markComponentRenderStarted(workInProgress); } { ReactCurrentOwner$1.current = workInProgress; setIsRendering(true); nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); hasId = checkDidRenderIdHook(); if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes); hasId = checkDidRenderIdHook(); } finally { setIsStrictModeForDevtools(false); } } setIsRendering(false); } { markComponentRenderStopped(); } if (current !== null && !didReceiveUpdate) { bailoutHooks(current, workInProgress, renderLanes); return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } if (getIsHydrating() && hasId) { pushMaterializedTreeId(workInProgress); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { if (current === null) { var type = Component.type; if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. Component.defaultProps === undefined) { var resolvedType = type; { resolvedType = resolveFunctionForHotReloading(type); } // If this is a plain function component without default props, // and with only the default shallow comparison, we upgrade it // to a SimpleMemoComponent to allow fast path updates. workInProgress.tag = SimpleMemoComponent; workInProgress.type = resolvedType; { validateFunctionComponentInDev(workInProgress, type); } return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, renderLanes); } { var innerPropTypes = type.propTypes; if (innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(type)); } if ( Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(type) || 'Unknown'; if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { error('%s: Support for defaultProps will be removed from memo components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName); didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; } } } var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes); child.ref = workInProgress.ref; child.return = workInProgress; workInProgress.child = child; return child; } { var _type = Component.type; var _innerPropTypes = _type.propTypes; if (_innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. checkPropTypes(_innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(_type)); } } var currentChild = current.child; // This is always exactly one child var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); if (!hasScheduledUpdateOrContext) { // This will be the props with resolved defaultProps, // unlike current.memoizedProps which will be the unresolved ones. var prevProps = currentChild.memoizedProps; // Default to shallow comparison var compare = Component.compare; compare = compare !== null ? compare : shallowEqual; if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) { return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; var newChild = createWorkInProgress(currentChild, nextProps); newChild.ref = workInProgress.ref; newChild.return = workInProgress; workInProgress.child = newChild; return newChild; } function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, renderLanes) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var outerMemoType = workInProgress.elementType; if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { // We warn when you define propTypes on lazy() // so let's just skip over it to find memo() outer wrapper. // Inner props for memo are validated later. var lazyComponent = outerMemoType; var payload = lazyComponent._payload; var init = lazyComponent._init; try { outerMemoType = init(payload); } catch (x) { outerMemoType = null; } // Inner propTypes will be validated in the function component path. var outerPropTypes = outerMemoType && outerMemoType.propTypes; if (outerPropTypes) { checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps) 'prop', getComponentNameFromType(outerMemoType)); } } } } if (current !== null) { var prevProps = current.memoizedProps; if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload. workInProgress.type === current.type )) { didReceiveUpdate = false; // The props are shallowly equal. Reuse the previous props object, like we // would during a normal fiber bailout. // // We don't have strong guarantees that the props object is referentially // equal during updates where we can't bail out anyway — like if the props // are shallowly equal, but there's a local state or context update in the // same batch. // // However, as a principle, we should aim to make the behavior consistent // across different ways of memoizing a component. For example, React.memo // has a different internal Fiber layout if you pass a normal function // component (SimpleMemoComponent) versus if you pass a different type // like forwardRef (MemoComponent). But this is an implementation detail. // Wrapping a component in forwardRef (or React.lazy, etc) shouldn't // affect whether the props object is reused during a bailout. workInProgress.pendingProps = nextProps = prevProps; if (!checkScheduledUpdateOrContext(current, renderLanes)) { // The pending lanes were cleared at the beginning of beginWork. We're // about to bail out, but there might be other lanes that weren't // included in the current render. Usually, the priority level of the // remaining updates is accumulated during the evaluation of the // component (i.e. when processing the update queue). But since since // we're bailing out early *without* evaluating the component, we need // to account for it here, too. Reset to the value of the current fiber. // NOTE: This only applies to SimpleMemoComponent, not MemoComponent, // because a MemoComponent fiber does not have hooks or an update queue; // rather, it wraps around an inner component, which may or may not // contains hooks. // TODO: Move the reset at in beginWork out of the common path so that // this is no longer necessary. workInProgress.lanes = current.lanes; return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { // This is a special case that only exists for legacy mode. // See https://github.com/facebook/react/pull/19216. didReceiveUpdate = true; } } } return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes); } function updateOffscreenComponent(current, workInProgress, renderLanes) { var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; var prevState = current !== null ? current.memoizedState : null; if (nextProps.mode === 'hidden' || enableLegacyHidden ) { // Rendering a hidden tree. if ((workInProgress.mode & ConcurrentMode) === NoMode) { // In legacy sync mode, don't defer the subtree. Render it now. // TODO: Consider how Offscreen should work with transitions in the future var nextState = { baseLanes: NoLanes, cachePool: null, transitions: null }; workInProgress.memoizedState = nextState; pushRenderLanes(workInProgress, renderLanes); } else if (!includesSomeLane(renderLanes, OffscreenLane)) { var spawnedCachePool = null; // We're hidden, and we're not rendering at Offscreen. We will bail out // and resume this tree later. var nextBaseLanes; if (prevState !== null) { var prevBaseLanes = prevState.baseLanes; nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes); } else { nextBaseLanes = renderLanes; } // Schedule this fiber to re-render at offscreen priority. Then bailout. workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane); var _nextState = { baseLanes: nextBaseLanes, cachePool: spawnedCachePool, transitions: null }; workInProgress.memoizedState = _nextState; workInProgress.updateQueue = null; // to avoid a push/pop misalignment. pushRenderLanes(workInProgress, nextBaseLanes); return null; } else { // This is the second render. The surrounding visible content has already // committed. Now we resume rendering the hidden tree. // Rendering at offscreen, so we can clear the base lanes. var _nextState2 = { baseLanes: NoLanes, cachePool: null, transitions: null }; workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out. var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes; pushRenderLanes(workInProgress, subtreeRenderLanes); } } else { // Rendering a visible tree. var _subtreeRenderLanes; if (prevState !== null) { // We're going from hidden -> visible. _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes); workInProgress.memoizedState = null; } else { // We weren't previously hidden, and we still aren't, so there's nothing // special to do. Need to push to the stack regardless, though, to avoid // a push/pop misalignment. _subtreeRenderLanes = renderLanes; } pushRenderLanes(workInProgress, _subtreeRenderLanes); } reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } // Note: These happen to have identical begin phases, for now. We shouldn't hold function updateFragment(current, workInProgress, renderLanes) { var nextChildren = workInProgress.pendingProps; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateMode(current, workInProgress, renderLanes) { var nextChildren = workInProgress.pendingProps.children; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateProfiler(current, workInProgress, renderLanes) { { workInProgress.flags |= Update; { // Reset effect durations for the next eventual effect phase. // These are reset during render to allow the DevTools commit hook a chance to read them, var stateNode = workInProgress.stateNode; stateNode.effectDuration = 0; stateNode.passiveEffectDuration = 0; } } var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function markRef(current, workInProgress) { var ref = workInProgress.ref; if (current === null && ref !== null || current !== null && current.ref !== ref) { // Schedule a Ref effect workInProgress.flags |= Ref; { workInProgress.flags |= RefStatic; } } } function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) { { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(Component)); } } } var context; { var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); context = getMaskedContext(workInProgress, unmaskedContext); } var nextChildren; var hasId; prepareToReadContext(workInProgress, renderLanes); { markComponentRenderStarted(workInProgress); } { ReactCurrentOwner$1.current = workInProgress; setIsRendering(true); nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); hasId = checkDidRenderIdHook(); if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes); hasId = checkDidRenderIdHook(); } finally { setIsStrictModeForDevtools(false); } } setIsRendering(false); } { markComponentRenderStopped(); } if (current !== null && !didReceiveUpdate) { bailoutHooks(current, workInProgress, renderLanes); return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } if (getIsHydrating() && hasId) { pushMaterializedTreeId(workInProgress); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) { { // This is used by DevTools to force a boundary to error. switch (shouldError(workInProgress)) { case false: { var _instance = workInProgress.stateNode; var ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack. // Is there a better way to do this? var tempInstance = new ctor(workInProgress.memoizedProps, _instance.context); var state = tempInstance.state; _instance.updater.enqueueSetState(_instance, state, null); break; } case true: { workInProgress.flags |= DidCapture; workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes var error$1 = new Error('Simulated error coming from DevTools'); var lane = pickArbitraryLane(renderLanes); workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state var update = createClassErrorUpdate(workInProgress, createCapturedValueAtFiber(error$1, workInProgress), lane); enqueueCapturedUpdate(workInProgress, update); break; } } if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentNameFromType(Component)); } } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext; if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } prepareToReadContext(workInProgress, renderLanes); var instance = workInProgress.stateNode; var shouldUpdate; if (instance === null) { resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); // In the initial pass we might need to construct the instance. constructClassInstance(workInProgress, Component, nextProps); mountClassInstance(workInProgress, Component, nextProps, renderLanes); shouldUpdate = true; } else if (current === null) { // In a resume, we'll already have an instance we can reuse. shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes); } else { shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes); } var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes); { var inst = workInProgress.stateNode; if (shouldUpdate && inst.props !== nextProps) { if (!didWarnAboutReassigningProps) { error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component'); } didWarnAboutReassigningProps = true; } } return nextUnitOfWork; } function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) { // Refs should update even if shouldComponentUpdate returns false markRef(current, workInProgress); var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags; if (!shouldUpdate && !didCaptureError) { // Context providers should defer to sCU for rendering if (hasContext) { invalidateContextProvider(workInProgress, Component, false); } return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } var instance = workInProgress.stateNode; // Rerender ReactCurrentOwner$1.current = workInProgress; var nextChildren; if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') { // If we captured an error, but getDerivedStateFromError is not defined, // unmount all the children. componentDidCatch will schedule an update to // re-render a fallback. This is temporary until we migrate everyone to // the new API. // TODO: Warn in a future release. nextChildren = null; { stopProfilerTimerIfRunning(); } } else { { markComponentRenderStarted(workInProgress); } { setIsRendering(true); nextChildren = instance.render(); if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { instance.render(); } finally { setIsStrictModeForDevtools(false); } } setIsRendering(false); } { markComponentRenderStopped(); } } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; if (current !== null && didCaptureError) { // If we're recovering from an error, reconcile without reusing any of // the existing children. Conceptually, the normal children and the children // that are shown on error are two different sets, so we shouldn't reuse // normal children even if their identities match. forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes); } else { reconcileChildren(current, workInProgress, nextChildren, renderLanes); } // Memoize state using the values we just used to render. // TODO: Restructure so we never read values from the instance. workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. if (hasContext) { invalidateContextProvider(workInProgress, Component, true); } return workInProgress.child; } function pushHostRootContext(workInProgress) { var root = workInProgress.stateNode; if (root.pendingContext) { pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context); } else if (root.context) { // Should always be set pushTopLevelContextObject(workInProgress, root.context, false); } pushHostContainer(workInProgress, root.containerInfo); } function updateHostRoot(current, workInProgress, renderLanes) { pushHostRootContext(workInProgress); if (current === null) { throw new Error('Should have a current fiber. This is a bug in React.'); } var nextProps = workInProgress.pendingProps; var prevState = workInProgress.memoizedState; var prevChildren = prevState.element; cloneUpdateQueue(current, workInProgress); processUpdateQueue(workInProgress, nextProps, null, renderLanes); var nextState = workInProgress.memoizedState; var root = workInProgress.stateNode; // being called "element". var nextChildren = nextState.element; if ( prevState.isDehydrated) { // This is a hydration root whose shell has not yet hydrated. We should // attempt to hydrate. // Flip isDehydrated to false to indicate that when this render // finishes, the root will no longer be dehydrated. var overrideState = { element: nextChildren, isDehydrated: false, cache: nextState.cache, pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries, transitions: nextState.transitions }; var updateQueue = workInProgress.updateQueue; // `baseState` can always be the last state because the root doesn't // have reducer functions so it doesn't need rebasing. updateQueue.baseState = overrideState; workInProgress.memoizedState = overrideState; if (workInProgress.flags & ForceClientRender) { // Something errored during a previous attempt to hydrate the shell, so we // forced a client render. var recoverableError = createCapturedValueAtFiber(new Error('There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + 'client rendering.'), workInProgress); return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError); } else if (nextChildren !== prevChildren) { var _recoverableError = createCapturedValueAtFiber(new Error('This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.'), workInProgress); return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, _recoverableError); } else { // The outermost shell has not hydrated yet. Start hydrating. enterHydrationState(workInProgress); var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes); workInProgress.child = child; var node = child; while (node) { // Mark each child as hydrating. This is a fast path to know whether this // tree is part of a hydrating tree. This is used to determine if a child // node has fully mounted yet, and for scheduling event replaying. // Conceptually this is similar to Placement in that a new subtree is // inserted into the React tree here. It just happens to not need DOM // mutations because it already exists. node.flags = node.flags & ~Placement | Hydrating; node = node.sibling; } } } else { // Root is not dehydrated. Either this is a client-only root, or it // already hydrated. resetHydrationState(); if (nextChildren === prevChildren) { return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } reconcileChildren(current, workInProgress, nextChildren, renderLanes); } return workInProgress.child; } function mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError) { // Revert to client rendering. resetHydrationState(); queueHydrationError(recoverableError); workInProgress.flags |= ForceClientRender; reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateHostComponent(current, workInProgress, renderLanes) { pushHostContext(workInProgress); if (current === null) { tryToClaimNextHydratableInstance(workInProgress); } var type = workInProgress.type; var nextProps = workInProgress.pendingProps; var prevProps = current !== null ? current.memoizedProps : null; var nextChildren = nextProps.children; var isDirectTextChild = shouldSetTextContent(type, nextProps); if (isDirectTextChild) { // We special case a direct text child of a host node. This is a common // case. We won't handle it as a reified child. We will instead handle // this in the host environment that also has access to this prop. That // avoids allocating another HostText fiber and traversing it. nextChildren = null; } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { // If we're switching from a direct text child to a normal child, or to // empty, we need to schedule the text content to be reset. workInProgress.flags |= ContentReset; } markRef(current, workInProgress); reconcileChildren(current, workInProgress, nextChildren, renderLanes); return workInProgress.child; } function updateHostText(current, workInProgress) { if (current === null) { tryToClaimNextHydratableInstance(workInProgress); } // Nothing to do here. This is terminal. We'll do the completion step // immediately after. return null; } function mountLazyComponent(_current, workInProgress, elementType, renderLanes) { resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); var props = workInProgress.pendingProps; var lazyComponent = elementType; var payload = lazyComponent._payload; var init = lazyComponent._init; var Component = init(payload); // Store the unwrapped component in the type. workInProgress.type = Component; var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component); var resolvedProps = resolveDefaultProps(Component, props); var child; switch (resolvedTag) { case FunctionComponent: { { validateFunctionComponentInDev(workInProgress, Component); workInProgress.type = Component = resolveFunctionForHotReloading(Component); } child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes); return child; } case ClassComponent: { { workInProgress.type = Component = resolveClassForHotReloading(Component); } child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes); return child; } case ForwardRef: { { workInProgress.type = Component = resolveForwardRefForHotReloading(Component); } child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes); return child; } case MemoComponent: { { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = Component.propTypes; if (outerPropTypes) { checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only 'prop', getComponentNameFromType(Component)); } } } child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too renderLanes); return child; } } var hint = ''; { if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) { hint = ' Did you wrap a component in React.lazy() more than once?'; } } // This message intentionally doesn't mention ForwardRef or MemoComponent // because the fact that it's a separate type of work is an // implementation detail. throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint)); } function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) { resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); // Promote the fiber to a class and try rendering again. workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext; if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } prepareToReadContext(workInProgress, renderLanes); constructClassInstance(workInProgress, Component, nextProps); mountClassInstance(workInProgress, Component, nextProps, renderLanes); return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); } function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) { resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); var props = workInProgress.pendingProps; var context; { var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); context = getMaskedContext(workInProgress, unmaskedContext); } prepareToReadContext(workInProgress, renderLanes); var value; var hasId; { markComponentRenderStarted(workInProgress); } { if (Component.prototype && typeof Component.prototype.render === 'function') { var componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutBadClass[componentName]) { error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); didWarnAboutBadClass[componentName] = true; } } if (workInProgress.mode & StrictLegacyMode) { ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null); } setIsRendering(true); ReactCurrentOwner$1.current = workInProgress; value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); hasId = checkDidRenderIdHook(); setIsRendering(false); } { markComponentRenderStopped(); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; { // Support for module components is deprecated and is removed behind a flag. // Whether or not it would crash later, we want to show a good message in DEV first. if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { var _componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutModulePatternComponent[_componentName]) { error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName); didWarnAboutModulePatternComponent[_componentName] = true; } } } if ( // Run these checks in production only if the flag is off. // Eventually we'll delete this branch altogether. typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { { var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutModulePatternComponent[_componentName2]) { error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2); didWarnAboutModulePatternComponent[_componentName2] = true; } } // Proceed under the assumption that this is a class instance workInProgress.tag = ClassComponent; // Throw out any hooks that were used. workInProgress.memoizedState = null; workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext = false; if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; initializeUpdateQueue(workInProgress); adoptClassInstance(workInProgress, value); mountClassInstance(workInProgress, Component, props, renderLanes); return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); } else { // Proceed under the assumption that this is a function component workInProgress.tag = FunctionComponent; { if ( workInProgress.mode & StrictLegacyMode) { setIsStrictModeForDevtools(true); try { value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes); hasId = checkDidRenderIdHook(); } finally { setIsStrictModeForDevtools(false); } } } if (getIsHydrating() && hasId) { pushMaterializedTreeId(workInProgress); } reconcileChildren(null, workInProgress, value, renderLanes); { validateFunctionComponentInDev(workInProgress, Component); } return workInProgress.child; } } function validateFunctionComponentInDev(workInProgress, Component) { { if (Component) { if (Component.childContextTypes) { error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component'); } } if (workInProgress.ref !== null) { var info = ''; var ownerName = getCurrentFiberOwnerNameInDevOrNull(); if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } var warningKey = ownerName || ''; var debugSource = workInProgress._debugSource; if (debugSource) { warningKey = debugSource.fileName + ':' + debugSource.lineNumber; } if (!didWarnAboutFunctionRefs[warningKey]) { didWarnAboutFunctionRefs[warningKey] = true; error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info); } } if ( Component.defaultProps !== undefined) { var componentName = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName); didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; } } if (typeof Component.getDerivedStateFromProps === 'function') { var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { error('%s: Function components do not support getDerivedStateFromProps.', _componentName3); didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; } } if (typeof Component.contextType === 'object' && Component.contextType !== null) { var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { error('%s: Function components do not support contextType.', _componentName4); didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; } } } } var SUSPENDED_MARKER = { dehydrated: null, treeContext: null, retryLane: NoLane }; function mountSuspenseOffscreenState(renderLanes) { return { baseLanes: renderLanes, cachePool: getSuspendedCache(), transitions: null }; } function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) { var cachePool = null; return { baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes), cachePool: cachePool, transitions: prevOffscreenState.transitions }; } // TODO: Probably should inline this back function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) { // If we're already showing a fallback, there are cases where we need to // remain on that fallback regardless of whether the content has resolved. // For example, SuspenseList coordinates when nested content appears. if (current !== null) { var suspenseState = current.memoizedState; if (suspenseState === null) { // Currently showing content. Don't hide it, even if ForceSuspenseFallback // is true. More precise name might be "ForceRemainSuspenseFallback". // Note: This is a factoring smell. Can't remain on a fallback if there's // no fallback to remain on. return false; } } // Not currently showing content. Consult the Suspense context. return hasSuspenseContext(suspenseContext, ForceSuspenseFallback); } function getRemainingWorkInPrimaryTree(current, renderLanes) { // TODO: Should not remove render lanes that were pinged during this render return removeLanes(current.childLanes, renderLanes); } function updateSuspenseComponent(current, workInProgress, renderLanes) { var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend. { if (shouldSuspend(workInProgress)) { workInProgress.flags |= DidCapture; } } var suspenseContext = suspenseStackCursor.current; var showFallback = false; var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags; if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) { // Something in this boundary's subtree already suspended. Switch to // rendering the fallback children. showFallback = true; workInProgress.flags &= ~DidCapture; } else { // Attempting the main content if (current === null || current.memoizedState !== null) { // This is a new mount or this boundary is already showing a fallback state. // Mark this subtree context as having at least one invisible parent that could // handle the fallback state. // Avoided boundaries are not considered since they cannot handle preferred fallback states. { suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext); } } } suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense // boundary's children. This involves some custom reconciliation logic. Two // main reasons this is so complicated. // // First, Legacy Mode has different semantics for backwards compatibility. The // primary tree will commit in an inconsistent state, so when we do the // second pass to render the fallback, we do some exceedingly, uh, clever // hacks to make that not totally break. Like transferring effects and // deletions from hidden tree. In Concurrent Mode, it's much simpler, // because we bailout on the primary tree completely and leave it in its old // state, no effects. Same as what we do for Offscreen (except that // Offscreen doesn't have the first render pass). // // Second is hydration. During hydration, the Suspense fiber has a slightly // different layout, where the child points to a dehydrated fragment, which // contains the DOM rendered by the server. // // Third, even if you set all that aside, Suspense is like error boundaries in // that we first we try to render one tree, and if that fails, we render again // and switch to a different tree. Like a try/catch block. So we have to track // which branch we're currently rendering. Ideally we would model this using // a stack. if (current === null) { // Initial mount // Special path for hydration // If we're currently hydrating, try to hydrate this boundary. tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component. var suspenseState = workInProgress.memoizedState; if (suspenseState !== null) { var dehydrated = suspenseState.dehydrated; if (dehydrated !== null) { return mountDehydratedSuspenseComponent(workInProgress, dehydrated); } } var nextPrimaryChildren = nextProps.children; var nextFallbackChildren = nextProps.fallback; if (showFallback) { var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes); var primaryChildFragment = workInProgress.child; primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes); workInProgress.memoizedState = SUSPENDED_MARKER; return fallbackFragment; } else { return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren); } } else { // This is an update. // Special path for hydration var prevState = current.memoizedState; if (prevState !== null) { var _dehydrated = prevState.dehydrated; if (_dehydrated !== null) { return updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, _dehydrated, prevState, renderLanes); } } if (showFallback) { var _nextFallbackChildren = nextProps.fallback; var _nextPrimaryChildren = nextProps.children; var fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren, _nextFallbackChildren, renderLanes); var _primaryChildFragment2 = workInProgress.child; var prevOffscreenState = current.child.memoizedState; _primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes); _primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); workInProgress.memoizedState = SUSPENDED_MARKER; return fallbackChildFragment; } else { var _nextPrimaryChildren2 = nextProps.children; var _primaryChildFragment3 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren2, renderLanes); workInProgress.memoizedState = null; return _primaryChildFragment3; } } } function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) { var mode = workInProgress.mode; var primaryChildProps = { mode: 'visible', children: primaryChildren }; var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); primaryChildFragment.return = workInProgress; workInProgress.child = primaryChildFragment; return primaryChildFragment; } function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) { var mode = workInProgress.mode; var progressedPrimaryFragment = workInProgress.child; var primaryChildProps = { mode: 'hidden', children: primaryChildren }; var primaryChildFragment; var fallbackChildFragment; if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) { // In legacy mode, we commit the primary tree as if it successfully // completed, even though it's in an inconsistent state. primaryChildFragment = progressedPrimaryFragment; primaryChildFragment.childLanes = NoLanes; primaryChildFragment.pendingProps = primaryChildProps; if ( workInProgress.mode & ProfileMode) { // Reset the durations from the first pass so they aren't included in the // final amounts. This seems counterintuitive, since we're intentionally // not measuring part of the render phase, but this makes it match what we // do in Concurrent Mode. primaryChildFragment.actualDuration = 0; primaryChildFragment.actualStartTime = -1; primaryChildFragment.selfBaseDuration = 0; primaryChildFragment.treeBaseDuration = 0; } fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); } else { primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); } primaryChildFragment.return = workInProgress; fallbackChildFragment.return = workInProgress; primaryChildFragment.sibling = fallbackChildFragment; workInProgress.child = primaryChildFragment; return fallbackChildFragment; } function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes) { // The props argument to `createFiberFromOffscreen` is `any` typed, so we use // this wrapper function to constrain it. return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); } function updateWorkInProgressOffscreenFiber(current, offscreenProps) { // The props argument to `createWorkInProgress` is `any` typed, so we use this // wrapper function to constrain it. return createWorkInProgress(current, offscreenProps); } function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) { var currentPrimaryChildFragment = current.child; var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, { mode: 'visible', children: primaryChildren }); if ((workInProgress.mode & ConcurrentMode) === NoMode) { primaryChildFragment.lanes = renderLanes; } primaryChildFragment.return = workInProgress; primaryChildFragment.sibling = null; if (currentFallbackChildFragment !== null) { // Delete the fallback child fragment var deletions = workInProgress.deletions; if (deletions === null) { workInProgress.deletions = [currentFallbackChildFragment]; workInProgress.flags |= ChildDeletion; } else { deletions.push(currentFallbackChildFragment); } } workInProgress.child = primaryChildFragment; return primaryChildFragment; } function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { var mode = workInProgress.mode; var currentPrimaryChildFragment = current.child; var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; var primaryChildProps = { mode: 'hidden', children: primaryChildren }; var primaryChildFragment; if ( // In legacy mode, we commit the primary tree as if it successfully // completed, even though it's in an inconsistent state. (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was // already cloned. In legacy mode, the only case where this isn't true is // when DevTools forces us to display a fallback; we skip the first render // pass entirely and go straight to rendering the fallback. (In Concurrent // Mode, SuspenseList can also trigger this scenario, but this is a legacy- // only codepath.) workInProgress.child !== currentPrimaryChildFragment) { var progressedPrimaryFragment = workInProgress.child; primaryChildFragment = progressedPrimaryFragment; primaryChildFragment.childLanes = NoLanes; primaryChildFragment.pendingProps = primaryChildProps; if ( workInProgress.mode & ProfileMode) { // Reset the durations from the first pass so they aren't included in the // final amounts. This seems counterintuitive, since we're intentionally // not measuring part of the render phase, but this makes it match what we // do in Concurrent Mode. primaryChildFragment.actualDuration = 0; primaryChildFragment.actualStartTime = -1; primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration; primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration; } // The fallback fiber was added as a deletion during the first pass. // However, since we're going to remain on the fallback, we no longer want // to delete it. workInProgress.deletions = null; } else { primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); // Since we're reusing a current tree, we need to reuse the flags, too. // (We don't do this in legacy mode, because in legacy mode we don't re-use // the current tree; see previous branch.) primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask; } var fallbackChildFragment; if (currentFallbackChildFragment !== null) { fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren); } else { fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already // mounted but this is a new fiber. fallbackChildFragment.flags |= Placement; } fallbackChildFragment.return = workInProgress; primaryChildFragment.return = workInProgress; primaryChildFragment.sibling = fallbackChildFragment; workInProgress.child = primaryChildFragment; return fallbackChildFragment; } function retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, recoverableError) { // Falling back to client rendering. Because this has performance // implications, it's considered a recoverable error, even though the user // likely won't observe anything wrong with the UI. // // The error is passed in as an argument to enforce that every caller provide // a custom message, or explicitly opt out (currently the only path that opts // out is legacy mode; every concurrent path provides an error). if (recoverableError !== null) { queueHydrationError(recoverableError); } // This will add the old fiber to the deletion list reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated. var nextProps = workInProgress.pendingProps; var primaryChildren = nextProps.children; var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Needs a placement effect because the parent (the Suspense boundary) already // mounted but this is a new fiber. primaryChildFragment.flags |= Placement; workInProgress.memoizedState = null; return primaryChildFragment; } function mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) { var fiberMode = workInProgress.mode; var primaryChildProps = { mode: 'visible', children: primaryChildren }; var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode); var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes, null); // Needs a placement effect because the parent (the Suspense // boundary) already mounted but this is a new fiber. fallbackChildFragment.flags |= Placement; primaryChildFragment.return = workInProgress; fallbackChildFragment.return = workInProgress; primaryChildFragment.sibling = fallbackChildFragment; workInProgress.child = primaryChildFragment; if ((workInProgress.mode & ConcurrentMode) !== NoMode) { // We will have dropped the effect list which contains the // deletion. We need to reconcile to delete the current child. reconcileChildFibers(workInProgress, current.child, null, renderLanes); } return fallbackChildFragment; } function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderLanes) { // During the first pass, we'll bail out and not drill into the children. // Instead, we'll leave the content in place and try to hydrate it later. if ((workInProgress.mode & ConcurrentMode) === NoMode) { { error('Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOMClient.hydrateRoot(container, <App />)' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.'); } workInProgress.lanes = laneToLanes(SyncLane); } else if (isSuspenseInstanceFallback(suspenseInstance)) { // This is a client-only boundary. Since we won't get any content from the server // for this, we need to schedule that at a higher priority based on when it would // have timed out. In theory we could render it in this pass but it would have the // wrong priority associated with it and will prevent hydration of parent path. // Instead, we'll leave work left on it to render it in a separate commit. // TODO This time should be the time at which the server rendered response that is // a parent to this boundary was displayed. However, since we currently don't have // a protocol to transfer that time, we'll just estimate it by using the current // time. This will mean that Suspense timeouts are slightly shifted to later than // they should be. // Schedule a normal pri update to render this content. workInProgress.lanes = laneToLanes(DefaultHydrationLane); } else { // We'll continue hydrating the rest at offscreen priority since we'll already // be showing the right content coming from the server, it is no rush. workInProgress.lanes = laneToLanes(OffscreenLane); } return null; } function updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes) { if (!didSuspend) { // This is the first render pass. Attempt to hydrate. // We should never be hydrating at this point because it is the first pass, // but after we've already committed once. warnIfHydrating(); if ((workInProgress.mode & ConcurrentMode) === NoMode) { return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: When we delete legacy mode, we should make this error argument // required — every concurrent mode path that causes hydration to // de-opt to client rendering should have an error message. null); } if (isSuspenseInstanceFallback(suspenseInstance)) { // This boundary is in a permanent fallback state. In this case, we'll never // get an update and we'll never be able to hydrate the final content. Let's just try the // client side render instead. var digest, message, stack; { var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance); digest = _getSuspenseInstanceF.digest; message = _getSuspenseInstanceF.message; stack = _getSuspenseInstanceF.stack; } var error; if (message) { // eslint-disable-next-line react-internal/prod-error-codes error = new Error(message); } else { error = new Error('The server could not finish this Suspense boundary, likely ' + 'due to an error during server rendering. Switched to ' + 'client rendering.'); } var capturedValue = createCapturedValue(error, digest, stack); return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, capturedValue); } // any context has changed, we need to treat is as if the input might have changed. var hasContextChanged = includesSomeLane(renderLanes, current.childLanes); if (didReceiveUpdate || hasContextChanged) { // This boundary has changed since the first render. This means that we are now unable to // hydrate it. We might still be able to hydrate it using a higher priority lane. var root = getWorkInProgressRoot(); if (root !== null) { var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes); if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) { // Intentionally mutating since this render will get interrupted. This // is one of the very rare times where we mutate the current tree // during the render phase. suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render var eventTime = NoTimestamp; enqueueConcurrentRenderForLane(current, attemptHydrationAtLane); scheduleUpdateOnFiber(root, current, attemptHydrationAtLane, eventTime); } } // If we have scheduled higher pri work above, this will probably just abort the render // since we now have higher priority work, but in case it doesn't, we need to prepare to // render something, if we time out. Even if that requires us to delete everything and // skip hydration. // Delay having to do this as long as the suspense timeout allows us. renderDidSuspendDelayIfPossible(); var _capturedValue = createCapturedValue(new Error('This Suspense boundary received an update before it finished ' + 'hydrating. This caused the boundary to switch to client rendering. ' + 'The usual way to fix this is to wrap the original update ' + 'in startTransition.')); return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue); } else if (isSuspenseInstancePending(suspenseInstance)) { // This component is still pending more data from the server, so we can't hydrate its // content. We treat it as if this component suspended itself. It might seem as if // we could just try to render it client-side instead. However, this will perform a // lot of unnecessary work and is unlikely to complete since it often will suspend // on missing data anyway. Additionally, the server might be able to render more // than we can on the client yet. In that case we'd end up with more fallback states // on the client than if we just leave it alone. If the server times out or errors // these should update this boundary to the permanent Fallback state instead. // Mark it as having captured (i.e. suspended). workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment. workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result. var retry = retryDehydratedSuspenseBoundary.bind(null, current); registerSuspenseInstanceRetry(suspenseInstance, retry); return null; } else { // This is the first attempt. reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance, suspenseState.treeContext); var primaryChildren = nextProps.children; var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Mark the children as hydrating. This is a fast path to know whether this // tree is part of a hydrating tree. This is used to determine if a child // node has fully mounted yet, and for scheduling event replaying. // Conceptually this is similar to Placement in that a new subtree is // inserted into the React tree here. It just happens to not need DOM // mutations because it already exists. primaryChildFragment.flags |= Hydrating; return primaryChildFragment; } } else { // This is the second render pass. We already attempted to hydrated, but // something either suspended or errored. if (workInProgress.flags & ForceClientRender) { // Something errored during hydration. Try again without hydrating. workInProgress.flags &= ~ForceClientRender; var _capturedValue2 = createCapturedValue(new Error('There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.')); return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue2); } else if (workInProgress.memoizedState !== null) { // Something suspended and we should still be in dehydrated mode. // Leave the existing child in place. workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there // but the normal suspense pass doesn't. workInProgress.flags |= DidCapture; return null; } else { // Suspended but we should no longer be in dehydrated mode. // Therefore we now have to render the fallback. var nextPrimaryChildren = nextProps.children; var nextFallbackChildren = nextProps.fallback; var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes); var _primaryChildFragment4 = workInProgress.child; _primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes); workInProgress.memoizedState = SUSPENDED_MARKER; return fallbackChildFragment; } } } function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) { fiber.lanes = mergeLanes(fiber.lanes, renderLanes); var alternate = fiber.alternate; if (alternate !== null) { alternate.lanes = mergeLanes(alternate.lanes, renderLanes); } scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot); } function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) { // Mark any Suspense boundaries with fallbacks as having work to do. // If they were previously forced into fallbacks, they may now be able // to unblock. var node = firstChild; while (node !== null) { if (node.tag === SuspenseComponent) { var state = node.memoizedState; if (state !== null) { scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); } } else if (node.tag === SuspenseListComponent) { // If the tail is hidden there might not be an Suspense boundaries // to schedule work on. In this case we have to schedule it on the // list itself. // We don't have to traverse to the children of the list since // the list will propagate the change when it rerenders. scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress); } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === workInProgress) { return; } while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } } function findLastContentRow(firstChild) { // This is going to find the last row among these children that is already // showing content on the screen, as opposed to being in fallback state or // new. If a row has multiple Suspense boundaries, any of them being in the // fallback state, counts as the whole row being in a fallback state. // Note that the "rows" will be workInProgress, but any nested children // will still be current since we haven't rendered them yet. The mounted // order may not be the same as the new order. We use the new order. var row = firstChild; var lastContentRow = null; while (row !== null) { var currentRow = row.alternate; // New rows can't be content rows. if (currentRow !== null && findFirstSuspended(currentRow) === null) { lastContentRow = row; } row = row.sibling; } return lastContentRow; } function validateRevealOrder(revealOrder) { { if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) { didWarnAboutRevealOrder[revealOrder] = true; if (typeof revealOrder === 'string') { switch (revealOrder.toLowerCase()) { case 'together': case 'forwards': case 'backwards': { error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase()); break; } case 'forward': case 'backward': { error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase()); break; } default: error('"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); break; } } else { error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder); } } } } function validateTailOptions(tailMode, revealOrder) { { if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) { if (tailMode !== 'collapsed' && tailMode !== 'hidden') { didWarnAboutTailOptions[tailMode] = true; error('"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode); } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') { didWarnAboutTailOptions[tailMode] = true; error('<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode); } } } } function validateSuspenseListNestedChild(childSlot, index) { { var isAnArray = isArray(childSlot); var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function'; if (isAnArray || isIterable) { var type = isAnArray ? 'array' : 'iterable'; error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type); return false; } } return true; } function validateSuspenseListChildren(children, revealOrder) { { if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) { if (isArray(children)) { for (var i = 0; i < children.length; i++) { if (!validateSuspenseListNestedChild(children[i], i)) { return; } } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === 'function') { var childrenIterator = iteratorFn.call(children); if (childrenIterator) { var step = childrenIterator.next(); var _i = 0; for (; !step.done; step = childrenIterator.next()) { if (!validateSuspenseListNestedChild(step.value, _i)) { return; } _i++; } } } else { error('A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder); } } } } } function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) { var renderState = workInProgress.memoizedState; if (renderState === null) { workInProgress.memoizedState = { isBackwards: isBackwards, rendering: null, renderingStartTime: 0, last: lastContentRow, tail: tail, tailMode: tailMode }; } else { // We can reuse the existing object from previous renders. renderState.isBackwards = isBackwards; renderState.rendering = null; renderState.renderingStartTime = 0; renderState.last = lastContentRow; renderState.tail = tail; renderState.tailMode = tailMode; } } // This can end up rendering this component multiple passes. // The first pass splits the children fibers into two sets. A head and tail. // We first render the head. If anything is in fallback state, we do another // pass through beginWork to rerender all children (including the tail) with // the force suspend context. If the first render didn't have anything in // in fallback state. Then we render each row in the tail one-by-one. // That happens in the completeWork phase without going back to beginWork. function updateSuspenseListComponent(current, workInProgress, renderLanes) { var nextProps = workInProgress.pendingProps; var revealOrder = nextProps.revealOrder; var tailMode = nextProps.tail; var newChildren = nextProps.children; validateRevealOrder(revealOrder); validateTailOptions(tailMode, revealOrder); validateSuspenseListChildren(newChildren, revealOrder); reconcileChildren(current, workInProgress, newChildren, renderLanes); var suspenseContext = suspenseStackCursor.current; var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback); if (shouldForceFallback) { suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); workInProgress.flags |= DidCapture; } else { var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags; if (didSuspendBefore) { // If we previously forced a fallback, we need to schedule work // on any nested boundaries to let them know to try to render // again. This is the same as context updating. propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes); } suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } pushSuspenseContext(workInProgress, suspenseContext); if ((workInProgress.mode & ConcurrentMode) === NoMode) { // In legacy mode, SuspenseList doesn't work so we just // use make it a noop by treating it as the default revealOrder. workInProgress.memoizedState = null; } else { switch (revealOrder) { case 'forwards': { var lastContentRow = findLastContentRow(workInProgress.child); var tail; if (lastContentRow === null) { // The whole list is part of the tail. // TODO: We could fast path by just rendering the tail now. tail = workInProgress.child; workInProgress.child = null; } else { // Disconnect the tail rows after the content row. // We're going to render them separately later. tail = lastContentRow.sibling; lastContentRow.sibling = null; } initSuspenseListRenderState(workInProgress, false, // isBackwards tail, lastContentRow, tailMode); break; } case 'backwards': { // We're going to find the first row that has existing content. // At the same time we're going to reverse the list of everything // we pass in the meantime. That's going to be our tail in reverse // order. var _tail = null; var row = workInProgress.child; workInProgress.child = null; while (row !== null) { var currentRow = row.alternate; // New rows can't be content rows. if (currentRow !== null && findFirstSuspended(currentRow) === null) { // This is the beginning of the main content. workInProgress.child = row; break; } var nextRow = row.sibling; row.sibling = _tail; _tail = row; row = nextRow; } // TODO: If workInProgress.child is null, we can continue on the tail immediately. initSuspenseListRenderState(workInProgress, true, // isBackwards _tail, null, // last tailMode); break; } case 'together': { initSuspenseListRenderState(workInProgress, false, // isBackwards null, // tail null, // last undefined); break; } default: { // The default reveal order is the same as not having // a boundary. workInProgress.memoizedState = null; } } } return workInProgress.child; } function updatePortalComponent(current, workInProgress, renderLanes) { pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); var nextChildren = workInProgress.pendingProps; if (current === null) { // Portals are special because we don't append the children during mount // but at commit. Therefore we need to track insertions which the normal // flow doesn't do during mount. This doesn't happen at the root because // the root always starts with a "current" with a null child. // TODO: Consider unifying this with how the root works. workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes); } else { reconcileChildren(current, workInProgress, nextChildren, renderLanes); } return workInProgress.child; } var hasWarnedAboutUsingNoValuePropOnContextProvider = false; function updateContextProvider(current, workInProgress, renderLanes) { var providerType = workInProgress.type; var context = providerType._context; var newProps = workInProgress.pendingProps; var oldProps = workInProgress.memoizedProps; var newValue = newProps.value; { if (!('value' in newProps)) { if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { hasWarnedAboutUsingNoValuePropOnContextProvider = true; error('The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?'); } } var providerPropTypes = workInProgress.type.propTypes; if (providerPropTypes) { checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider'); } } pushProvider(workInProgress, context, newValue); { if (oldProps !== null) { var oldValue = oldProps.value; if (objectIs(oldValue, newValue)) { // No change. Bailout early if children are the same. if (oldProps.children === newProps.children && !hasContextChanged()) { return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } } else { // The context value changed. Search for matching consumers and schedule // them to update. propagateContextChange(workInProgress, context, renderLanes); } } } var newChildren = newProps.children; reconcileChildren(current, workInProgress, newChildren, renderLanes); return workInProgress.child; } var hasWarnedAboutUsingContextAsConsumer = false; function updateContextConsumer(current, workInProgress, renderLanes) { var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In // DEV mode, we create a separate object for Context.Consumer that acts // like a proxy to Context. This proxy object adds unnecessary code in PROD // so we use the old behaviour (Context.Consumer references Context) to // reduce size and overhead. The separate object references context via // a property called "_context", which also gives us the ability to check // in DEV mode if this property exists or not and warn if it does not. { if (context._context === undefined) { // This may be because it's a Context (rather than a Consumer). // Or it may be because it's older React where they're the same thing. // We only want to warn if we're sure it's a new React. if (context !== context.Consumer) { if (!hasWarnedAboutUsingContextAsConsumer) { hasWarnedAboutUsingContextAsConsumer = true; error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } } } else { context = context._context; } } var newProps = workInProgress.pendingProps; var render = newProps.children; { if (typeof render !== 'function') { error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.'); } } prepareToReadContext(workInProgress, renderLanes); var newValue = readContext(context); { markComponentRenderStarted(workInProgress); } var newChildren; { ReactCurrentOwner$1.current = workInProgress; setIsRendering(true); newChildren = render(newValue); setIsRendering(false); } { markComponentRenderStopped(); } // React DevTools reads this flag. workInProgress.flags |= PerformedWork; reconcileChildren(current, workInProgress, newChildren, renderLanes); return workInProgress.child; } function markWorkInProgressReceivedUpdate() { didReceiveUpdate = true; } function resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress) { if ((workInProgress.mode & ConcurrentMode) === NoMode) { if (current !== null) { // A lazy component only mounts if it suspended inside a non- // concurrent tree, in an inconsistent state. We want to treat it like // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. current.alternate = null; workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect workInProgress.flags |= Placement; } } } function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) { if (current !== null) { // Reuse previous dependencies workInProgress.dependencies = current.dependencies; } { // Don't update "base" render times for bailouts. stopProfilerTimerIfRunning(); } markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work. if (!includesSomeLane(renderLanes, workInProgress.childLanes)) { // The children don't have any work either. We can skip them. // TODO: Once we add back resuming, we should check if the children are // a work-in-progress set. If so, we need to transfer their effects. { return null; } } // This fiber doesn't have work, but its subtree does. Clone the child // fibers and continue. cloneChildFibers(current, workInProgress); return workInProgress.child; } function remountFiber(current, oldWorkInProgress, newWorkInProgress) { { var returnFiber = oldWorkInProgress.return; if (returnFiber === null) { // eslint-disable-next-line react-internal/prod-error-codes throw new Error('Cannot swap the root fiber.'); } // Disconnect from the old current. // It will get deleted. current.alternate = null; oldWorkInProgress.alternate = null; // Connect to the new tree. newWorkInProgress.index = oldWorkInProgress.index; newWorkInProgress.sibling = oldWorkInProgress.sibling; newWorkInProgress.return = oldWorkInProgress.return; newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it. if (oldWorkInProgress === returnFiber.child) { returnFiber.child = newWorkInProgress; } else { var prevSibling = returnFiber.child; if (prevSibling === null) { // eslint-disable-next-line react-internal/prod-error-codes throw new Error('Expected parent to have a child.'); } while (prevSibling.sibling !== oldWorkInProgress) { prevSibling = prevSibling.sibling; if (prevSibling === null) { // eslint-disable-next-line react-internal/prod-error-codes throw new Error('Expected to find the previous sibling.'); } } prevSibling.sibling = newWorkInProgress; } // Delete the old fiber and place the new one. // Since the old fiber is disconnected, we have to schedule it manually. var deletions = returnFiber.deletions; if (deletions === null) { returnFiber.deletions = [current]; returnFiber.flags |= ChildDeletion; } else { deletions.push(current); } newWorkInProgress.flags |= Placement; // Restart work from the new fiber. return newWorkInProgress; } } function checkScheduledUpdateOrContext(current, renderLanes) { // Before performing an early bailout, we must check if there are pending // updates or context. var updateLanes = current.lanes; if (includesSomeLane(updateLanes, renderLanes)) { return true; } // No pending update, but because context is propagated lazily, we need return false; } function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes) { // This fiber does not have any pending work. Bailout without entering // the begin phase. There's still some bookkeeping we that needs to be done // in this optimized path, mostly pushing stuff onto the stack. switch (workInProgress.tag) { case HostRoot: pushHostRootContext(workInProgress); var root = workInProgress.stateNode; resetHydrationState(); break; case HostComponent: pushHostContext(workInProgress); break; case ClassComponent: { var Component = workInProgress.type; if (isContextProvider(Component)) { pushContextProvider(workInProgress); } break; } case HostPortal: pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case ContextProvider: { var newValue = workInProgress.memoizedProps.value; var context = workInProgress.type._context; pushProvider(workInProgress, context, newValue); break; } case Profiler: { // Profiler should only call onRender when one of its descendants actually rendered. var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); if (hasChildWork) { workInProgress.flags |= Update; } { // Reset effect durations for the next eventual effect phase. // These are reset during render to allow the DevTools commit hook a chance to read them, var stateNode = workInProgress.stateNode; stateNode.effectDuration = 0; stateNode.passiveEffectDuration = 0; } } break; case SuspenseComponent: { var state = workInProgress.memoizedState; if (state !== null) { if (state.dehydrated !== null) { pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has // been unsuspended it has committed as a resolved Suspense component. // If it needs to be retried, it should have work scheduled on it. workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork. return null; } // If this boundary is currently timed out, we need to decide // whether to retry the primary children, or to skip over it and // go straight to the fallback. Check the priority of the primary // child fragment. var primaryChildFragment = workInProgress.child; var primaryChildLanes = primaryChildFragment.childLanes; if (includesSomeLane(renderLanes, primaryChildLanes)) { // The primary children have pending work. Use the normal path // to attempt to render the primary children again. return updateSuspenseComponent(current, workInProgress, renderLanes); } else { // The primary child fragment does not have pending work marked // on it pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient // priority. Bailout. var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); if (child !== null) { // The fallback children have pending work. Skip over the // primary children and work on the fallback. return child.sibling; } else { // Note: We can return `null` here because we already checked // whether there were nested context consumers, via the call to // `bailoutOnAlreadyFinishedWork` above. return null; } } } else { pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); } break; } case SuspenseListComponent: { var didSuspendBefore = (current.flags & DidCapture) !== NoFlags; var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes); if (didSuspendBefore) { if (_hasChildWork) { // If something was in fallback state last time, and we have all the // same children then we're still in progressive loading state. // Something might get unblocked by state updates or retries in the // tree which will affect the tail. So we need to use the normal // path to compute the correct tail. return updateSuspenseListComponent(current, workInProgress, renderLanes); } // If none of the children had any work, that means that none of // them got retried so they'll still be blocked in the same way // as before. We can fast bail out. workInProgress.flags |= DidCapture; } // If nothing suspended before and we're rendering the same children, // then the tail doesn't matter. Anything new that suspends will work // in the "together" mode, so we can continue from the state we had. var renderState = workInProgress.memoizedState; if (renderState !== null) { // Reset to the "together" mode in case we've started a different // update in the past but didn't complete it. renderState.rendering = null; renderState.tail = null; renderState.lastEffect = null; } pushSuspenseContext(workInProgress, suspenseStackCursor.current); if (_hasChildWork) { break; } else { // If none of the children had any work, that means that none of // them got retried so they'll still be blocked in the same way // as before. We can fast bail out. return null; } } case OffscreenComponent: case LegacyHiddenComponent: { // Need to check if the tree still needs to be deferred. This is // almost identical to the logic used in the normal update path, // so we'll just enter that. The only difference is we'll bail out // at the next level instead of this one, because the child props // have not changed. Which is fine. // TODO: Probably should refactor `beginWork` to split the bailout // path from the normal path. I'm tempted to do a labeled break here // but I won't :) workInProgress.lanes = NoLanes; return updateOffscreenComponent(current, workInProgress, renderLanes); } } return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes); } function beginWork(current, workInProgress, renderLanes) { { if (workInProgress._debugNeedsRemount && current !== null) { // This will restart the begin phase with a new fiber. return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes)); } } if (current !== null) { var oldProps = current.memoizedProps; var newProps = workInProgress.pendingProps; if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload: workInProgress.type !== current.type )) { // If props or context changed, mark the fiber as having performed work. // This may be unset if the props are determined to be equal later (memo). didReceiveUpdate = true; } else { // Neither props nor legacy context changes. Check if there's a pending // update or context change. var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there // may not be work scheduled on `current`, so we check for this flag. (workInProgress.flags & DidCapture) === NoFlags) { // No pending updates or context. Bail out now. didReceiveUpdate = false; return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes); } if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { // This is a special case that only exists for legacy mode. // See https://github.com/facebook/react/pull/19216. didReceiveUpdate = true; } else { // An update was scheduled on this fiber, but there are no new props // nor legacy context. Set this to false. If an update queue or context // consumer produces a changed value, it will set this to true. Otherwise, // the component will assume the children have not changed and bail out. didReceiveUpdate = false; } } } else { didReceiveUpdate = false; if (getIsHydrating() && isForkedChild(workInProgress)) { // Check if this child belongs to a list of muliple children in // its parent. // // In a true multi-threaded implementation, we would render children on // parallel threads. This would represent the beginning of a new render // thread for this subtree. // // We only use this for id generation during hydration, which is why the // logic is located in this special branch. var slotIndex = workInProgress.index; var numberOfForks = getForksAtLevel(); pushTreeId(workInProgress, numberOfForks, slotIndex); } } // Before entering the begin phase, clear pending update priority. // TODO: This assumes that we're about to evaluate the component and process // the update queue. However, there's an exception: SimpleMemoComponent // sometimes bails out later in the begin phase. This indicates that we should // move this assignment out of the common path and into each branch. workInProgress.lanes = NoLanes; switch (workInProgress.tag) { case IndeterminateComponent: { return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes); } case LazyComponent: { var elementType = workInProgress.elementType; return mountLazyComponent(current, workInProgress, elementType, renderLanes); } case FunctionComponent: { var Component = workInProgress.type; var unresolvedProps = workInProgress.pendingProps; var resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); return updateFunctionComponent(current, workInProgress, Component, resolvedProps, renderLanes); } case ClassComponent: { var _Component = workInProgress.type; var _unresolvedProps = workInProgress.pendingProps; var _resolvedProps = workInProgress.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps); return updateClassComponent(current, workInProgress, _Component, _resolvedProps, renderLanes); } case HostRoot: return updateHostRoot(current, workInProgress, renderLanes); case HostComponent: return updateHostComponent(current, workInProgress, renderLanes); case HostText: return updateHostText(current, workInProgress); case SuspenseComponent: return updateSuspenseComponent(current, workInProgress, renderLanes); case HostPortal: return updatePortalComponent(current, workInProgress, renderLanes); case ForwardRef: { var type = workInProgress.type; var _unresolvedProps2 = workInProgress.pendingProps; var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes); } case Fragment: return updateFragment(current, workInProgress, renderLanes); case Mode: return updateMode(current, workInProgress, renderLanes); case Profiler: return updateProfiler(current, workInProgress, renderLanes); case ContextProvider: return updateContextProvider(current, workInProgress, renderLanes); case ContextConsumer: return updateContextConsumer(current, workInProgress, renderLanes); case MemoComponent: { var _type2 = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = _type2.propTypes; if (outerPropTypes) { checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only 'prop', getComponentNameFromType(_type2)); } } } _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, renderLanes); } case SimpleMemoComponent: { return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes); } case IncompleteClassComponent: { var _Component2 = workInProgress.type; var _unresolvedProps4 = workInProgress.pendingProps; var _resolvedProps4 = workInProgress.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4); return mountIncompleteClassComponent(current, workInProgress, _Component2, _resolvedProps4, renderLanes); } case SuspenseListComponent: { return updateSuspenseListComponent(current, workInProgress, renderLanes); } case ScopeComponent: { break; } case OffscreenComponent: { return updateOffscreenComponent(current, workInProgress, renderLanes); } } throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); } function markUpdate(workInProgress) { // Tag the fiber with an update effect. This turns a Placement into // a PlacementAndUpdate. workInProgress.flags |= Update; } function markRef$1(workInProgress) { workInProgress.flags |= Ref; { workInProgress.flags |= RefStatic; } } var appendAllChildren; var updateHostContainer; var updateHostComponent$1; var updateHostText$1; { // Mutation mode appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; while (node !== null) { if (node.tag === HostComponent || node.tag === HostText) { appendInitialChild(parent, node.stateNode); } else if (node.tag === HostPortal) ; else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === workInProgress) { return; } while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } }; updateHostContainer = function (current, workInProgress) {// Noop }; updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) { // If we have an alternate, that means this is an update and we need to // schedule a side-effect to do the updates. var oldProps = current.memoizedProps; if (oldProps === newProps) { // In mutation mode, this is sufficient for a bailout because // we won't touch this node even if children changed. return; } // If we get updated because one of our children updated, we don't // have newProps so we'll have to reuse them. // TODO: Split the update API as separate for the props vs. children. // Even better would be if children weren't special cased at all tho. var instance = workInProgress.stateNode; var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host // component is hitting the resume path. Figure out why. Possibly // related to `hidden`. var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component. workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. All the work is done in commitWork. if (updatePayload) { markUpdate(workInProgress); } }; updateHostText$1 = function (current, workInProgress, oldText, newText) { // If the text differs, mark it as an update. All the work in done in commitWork. if (oldText !== newText) { markUpdate(workInProgress); } }; } function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { if (getIsHydrating()) { // If we're hydrating, we should consume as many items as we can // so we don't leave any behind. return; } switch (renderState.tailMode) { case 'hidden': { // Any insertions at the end of the tail list after this point // should be invisible. If there are already mounted boundaries // anything before them are not considered for collapsing. // Therefore we need to go through the whole tail to find if // there are any. var tailNode = renderState.tail; var lastTailNode = null; while (tailNode !== null) { if (tailNode.alternate !== null) { lastTailNode = tailNode; } tailNode = tailNode.sibling; } // Next we're simply going to delete all insertions after the // last rendered item. if (lastTailNode === null) { // All remaining items in the tail are insertions. renderState.tail = null; } else { // Detach the insertion after the last node that was already // inserted. lastTailNode.sibling = null; } break; } case 'collapsed': { // Any insertions at the end of the tail list after this point // should be invisible. If there are already mounted boundaries // anything before them are not considered for collapsing. // Therefore we need to go through the whole tail to find if // there are any. var _tailNode = renderState.tail; var _lastTailNode = null; while (_tailNode !== null) { if (_tailNode.alternate !== null) { _lastTailNode = _tailNode; } _tailNode = _tailNode.sibling; } // Next we're simply going to delete all insertions after the // last rendered item. if (_lastTailNode === null) { // All remaining items in the tail are insertions. if (!hasRenderedATailFallback && renderState.tail !== null) { // We suspended during the head. We want to show at least one // row at the tail. So we'll keep on and cut off the rest. renderState.tail.sibling = null; } else { renderState.tail = null; } } else { // Detach the insertion after the last node that was already // inserted. _lastTailNode.sibling = null; } break; } } } function bubbleProperties(completedWork) { var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child; var newChildLanes = NoLanes; var subtreeFlags = NoFlags; if (!didBailout) { // Bubble up the earliest expiration time. if ( (completedWork.mode & ProfileMode) !== NoMode) { // In profiling mode, resetChildExpirationTime is also used to reset // profiler durations. var actualDuration = completedWork.actualDuration; var treeBaseDuration = completedWork.selfBaseDuration; var child = completedWork.child; while (child !== null) { newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes)); subtreeFlags |= child.subtreeFlags; subtreeFlags |= child.flags; // When a fiber is cloned, its actualDuration is reset to 0. This value will // only be updated if work is done on the fiber (i.e. it doesn't bailout). // When work is done, it should bubble to the parent's actualDuration. If // the fiber has not been cloned though, (meaning no work was done), then // this value will reflect the amount of time spent working on a previous // render. In that case it should not bubble. We determine whether it was // cloned by comparing the child pointer. actualDuration += child.actualDuration; treeBaseDuration += child.treeBaseDuration; child = child.sibling; } completedWork.actualDuration = actualDuration; completedWork.treeBaseDuration = treeBaseDuration; } else { var _child = completedWork.child; while (_child !== null) { newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes)); subtreeFlags |= _child.subtreeFlags; subtreeFlags |= _child.flags; // Update the return pointer so the tree is consistent. This is a code // smell because it assumes the commit phase is never concurrent with // the render phase. Will address during refactor to alternate model. _child.return = completedWork; _child = _child.sibling; } } completedWork.subtreeFlags |= subtreeFlags; } else { // Bubble up the earliest expiration time. if ( (completedWork.mode & ProfileMode) !== NoMode) { // In profiling mode, resetChildExpirationTime is also used to reset // profiler durations. var _treeBaseDuration = completedWork.selfBaseDuration; var _child2 = completedWork.child; while (_child2 !== null) { newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, // so we should bubble those up even during a bailout. All the other // flags have a lifetime only of a single render + commit, so we should // ignore them. subtreeFlags |= _child2.subtreeFlags & StaticMask; subtreeFlags |= _child2.flags & StaticMask; _treeBaseDuration += _child2.treeBaseDuration; _child2 = _child2.sibling; } completedWork.treeBaseDuration = _treeBaseDuration; } else { var _child3 = completedWork.child; while (_child3 !== null) { newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to, // so we should bubble those up even during a bailout. All the other // flags have a lifetime only of a single render + commit, so we should // ignore them. subtreeFlags |= _child3.subtreeFlags & StaticMask; subtreeFlags |= _child3.flags & StaticMask; // Update the return pointer so the tree is consistent. This is a code // smell because it assumes the commit phase is never concurrent with // the render phase. Will address during refactor to alternate model. _child3.return = completedWork; _child3 = _child3.sibling; } } completedWork.subtreeFlags |= subtreeFlags; } completedWork.childLanes = newChildLanes; return didBailout; } function completeDehydratedSuspenseBoundary(current, workInProgress, nextState) { if (hasUnhydratedTailNodes() && (workInProgress.mode & ConcurrentMode) !== NoMode && (workInProgress.flags & DidCapture) === NoFlags) { warnIfUnhydratedTailNodes(workInProgress); resetHydrationState(); workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture; return false; } var wasHydrated = popHydrationState(workInProgress); if (nextState !== null && nextState.dehydrated !== null) { // We might be inside a hydration state the first time we're picking up this // Suspense boundary, and also after we've reentered it for further hydration. if (current === null) { if (!wasHydrated) { throw new Error('A dehydrated suspense component was completed without a hydrated node. ' + 'This is probably a bug in React.'); } prepareToHydrateHostSuspenseInstance(workInProgress); bubbleProperties(workInProgress); { if ((workInProgress.mode & ProfileMode) !== NoMode) { var isTimedOutSuspense = nextState !== null; if (isTimedOutSuspense) { // Don't count time spent in a timed out Suspense subtree as part of the base duration. var primaryChildFragment = workInProgress.child; if (primaryChildFragment !== null) { // $FlowFixMe Flow doesn't support type casting in combination with the -= operator workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration; } } } } return false; } else { // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration // state since we're now exiting out of it. popHydrationState doesn't do that for us. resetHydrationState(); if ((workInProgress.flags & DidCapture) === NoFlags) { // This boundary did not suspend so it's now hydrated and unsuspended. workInProgress.memoizedState = null; } // If nothing suspended, we need to schedule an effect to mark this boundary // as having hydrated so events know that they're free to be invoked. // It's also a signal to replay events and the suspense callback. // If something suspended, schedule an effect to attach retry listeners. // So we might as well always mark this. workInProgress.flags |= Update; bubbleProperties(workInProgress); { if ((workInProgress.mode & ProfileMode) !== NoMode) { var _isTimedOutSuspense = nextState !== null; if (_isTimedOutSuspense) { // Don't count time spent in a timed out Suspense subtree as part of the base duration. var _primaryChildFragment = workInProgress.child; if (_primaryChildFragment !== null) { // $FlowFixMe Flow doesn't support type casting in combination with the -= operator workInProgress.treeBaseDuration -= _primaryChildFragment.treeBaseDuration; } } } } return false; } } else { // Successfully completed this tree. If this was a forced client render, // there may have been recoverable errors during first hydration // attempt. If so, add them to a queue so we can log them in the // commit phase. upgradeHydrationErrorsToRecoverable(); // Fall through to normal Suspense path return true; } } function completeWork(current, workInProgress, renderLanes) { var newProps = workInProgress.pendingProps; // Note: This intentionally doesn't check if we're hydrating because comparing // to the current tree provider fiber is just as fast and less error-prone. // Ideally we would have a special version of the work loop only // for hydration. popTreeContext(workInProgress); switch (workInProgress.tag) { case IndeterminateComponent: case LazyComponent: case SimpleMemoComponent: case FunctionComponent: case ForwardRef: case Fragment: case Mode: case Profiler: case ContextConsumer: case MemoComponent: bubbleProperties(workInProgress); return null; case ClassComponent: { var Component = workInProgress.type; if (isContextProvider(Component)) { popContext(workInProgress); } bubbleProperties(workInProgress); return null; } case HostRoot: { var fiberRoot = workInProgress.stateNode; popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); resetWorkInProgressVersions(); if (fiberRoot.pendingContext) { fiberRoot.context = fiberRoot.pendingContext; fiberRoot.pendingContext = null; } if (current === null || current.child === null) { // If we hydrated, pop so that we can delete any remaining children // that weren't hydrated. var wasHydrated = popHydrationState(workInProgress); if (wasHydrated) { // If we hydrated, then we'll need to schedule an update for // the commit side-effects on the root. markUpdate(workInProgress); } else { if (current !== null) { var prevState = current.memoizedState; if ( // Check if this is a client root !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error) (workInProgress.flags & ForceClientRender) !== NoFlags) { // Schedule an effect to clear this container at the start of the // next commit. This handles the case of React rendering into a // container with previous children. It's also safe to do for // updates too, because current.child would only be null if the // previous render was null (so the container would already // be empty). workInProgress.flags |= Snapshot; // If this was a forced client render, there may have been // recoverable errors during first hydration attempt. If so, add // them to a queue so we can log them in the commit phase. upgradeHydrationErrorsToRecoverable(); } } } } updateHostContainer(current, workInProgress); bubbleProperties(workInProgress); return null; } case HostComponent: { popHostContext(workInProgress); var rootContainerInstance = getRootHostContainer(); var type = workInProgress.type; if (current !== null && workInProgress.stateNode != null) { updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance); if (current.ref !== workInProgress.ref) { markRef$1(workInProgress); } } else { if (!newProps) { if (workInProgress.stateNode === null) { throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); } // This can happen when we abort work. bubbleProperties(workInProgress); return null; } var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context // "stack" as the parent. Then append children as we go in beginWork // or completeWork depending on whether we want to add them top->down or // bottom->up. Top->down is faster in IE11. var _wasHydrated = popHydrationState(workInProgress); if (_wasHydrated) { // TODO: Move this and createInstance step into the beginPhase // to consolidate. if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) { // If changes to the hydrated node need to be applied at the // commit-phase we mark this as such. markUpdate(workInProgress); } } else { var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress); appendAllChildren(instance, workInProgress, false, false); workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount. // (eg DOM renderer supports auto-focus for certain elements). // Make sure such renderers get scheduled for later work. if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) { markUpdate(workInProgress); } } if (workInProgress.ref !== null) { // If there is a ref on a host node we need to schedule a callback markRef$1(workInProgress); } } bubbleProperties(workInProgress); return null; } case HostText: { var newText = newProps; if (current && workInProgress.stateNode != null) { var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need // to schedule a side-effect to do the updates. updateHostText$1(current, workInProgress, oldText, newText); } else { if (typeof newText !== 'string') { if (workInProgress.stateNode === null) { throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.'); } // This can happen when we abort work. } var _rootContainerInstance = getRootHostContainer(); var _currentHostContext = getHostContext(); var _wasHydrated2 = popHydrationState(workInProgress); if (_wasHydrated2) { if (prepareToHydrateHostTextInstance(workInProgress)) { markUpdate(workInProgress); } } else { workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress); } } bubbleProperties(workInProgress); return null; } case SuspenseComponent: { popSuspenseContext(workInProgress); var nextState = workInProgress.memoizedState; // Special path for dehydrated boundaries. We may eventually move this // to its own fiber type so that we can add other kinds of hydration // boundaries that aren't associated with a Suspense tree. In anticipation // of such a refactor, all the hydration logic is contained in // this branch. if (current === null || current.memoizedState !== null && current.memoizedState.dehydrated !== null) { var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current, workInProgress, nextState); if (!fallthroughToNormalSuspensePath) { if (workInProgress.flags & ShouldCapture) { // Special case. There were remaining unhydrated nodes. We treat // this as a mismatch. Revert to client rendering. return workInProgress; } else { // Did not finish hydrating, either because this is the initial // render or because something suspended. return null; } } // Continue with the normal Suspense path. } if ((workInProgress.flags & DidCapture) !== NoFlags) { // Something suspended. Re-render with the fallback children. workInProgress.lanes = renderLanes; // Do not reset the effect list. if ( (workInProgress.mode & ProfileMode) !== NoMode) { transferActualDuration(workInProgress); } // Don't bubble properties in this case. return workInProgress; } var nextDidTimeout = nextState !== null; var prevDidTimeout = current !== null && current.memoizedState !== null; // a passive effect, which is when we process the transitions if (nextDidTimeout !== prevDidTimeout) { // an effect to toggle the subtree's visibility. When we switch from // fallback -> primary, the inner Offscreen fiber schedules this effect // as part of its normal complete phase. But when we switch from // primary -> fallback, the inner Offscreen fiber does not have a complete // phase. So we need to schedule its effect here. // // We also use this flag to connect/disconnect the effects, but the same // logic applies: when re-connecting, the Offscreen fiber's complete // phase will handle scheduling the effect. It's only when the fallback // is active that we have to do anything special. if (nextDidTimeout) { var _offscreenFiber2 = workInProgress.child; _offscreenFiber2.flags |= Visibility; // TODO: This will still suspend a synchronous tree if anything // in the concurrent tree already suspended during this render. // This is a known bug. if ((workInProgress.mode & ConcurrentMode) !== NoMode) { // TODO: Move this back to throwException because this is too late // if this is a large tree which is common for initial loads. We // don't know if we should restart a render or not until we get // this marker, and this is too late. // If this render already had a ping or lower pri updates, // and this is the first time we know we're going to suspend we // should be able to immediately restart from within throwException. var hasInvisibleChildContext = current === null && (workInProgress.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback); if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) { // If this was in an invisible tree or a new render, then showing // this boundary is ok. renderDidSuspend(); } else { // Otherwise, we're going to have to hide content so we should // suspend for longer if possible. renderDidSuspendDelayIfPossible(); } } } } var wakeables = workInProgress.updateQueue; if (wakeables !== null) { // Schedule an effect to attach a retry listener to the promise. // TODO: Move to passive phase workInProgress.flags |= Update; } bubbleProperties(workInProgress); { if ((workInProgress.mode & ProfileMode) !== NoMode) { if (nextDidTimeout) { // Don't count time spent in a timed out Suspense subtree as part of the base duration. var primaryChildFragment = workInProgress.child; if (primaryChildFragment !== null) { // $FlowFixMe Flow doesn't support type casting in combination with the -= operator workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration; } } } } return null; } case HostPortal: popHostContainer(workInProgress); updateHostContainer(current, workInProgress); if (current === null) { preparePortalMount(workInProgress.stateNode.containerInfo); } bubbleProperties(workInProgress); return null; case ContextProvider: // Pop provider fiber var context = workInProgress.type._context; popProvider(context, workInProgress); bubbleProperties(workInProgress); return null; case IncompleteClassComponent: { // Same as class component case. I put it down here so that the tags are // sequential to ensure this switch is compiled to a jump table. var _Component = workInProgress.type; if (isContextProvider(_Component)) { popContext(workInProgress); } bubbleProperties(workInProgress); return null; } case SuspenseListComponent: { popSuspenseContext(workInProgress); var renderState = workInProgress.memoizedState; if (renderState === null) { // We're running in the default, "independent" mode. // We don't do anything in this mode. bubbleProperties(workInProgress); return null; } var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags; var renderedTail = renderState.rendering; if (renderedTail === null) { // We just rendered the head. if (!didSuspendAlready) { // This is the first pass. We need to figure out if anything is still // suspended in the rendered set. // If new content unsuspended, but there's still some content that // didn't. Then we need to do a second pass that forces everything // to keep showing their fallbacks. // We might be suspended if something in this render pass suspended, or // something in the previous committed pass suspended. Otherwise, // there's no chance so we can skip the expensive call to // findFirstSuspended. var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags); if (!cannotBeSuspended) { var row = workInProgress.child; while (row !== null) { var suspended = findFirstSuspended(row); if (suspended !== null) { didSuspendAlready = true; workInProgress.flags |= DidCapture; cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as // part of the second pass. In that case nothing will subscribe to // its thenables. Instead, we'll transfer its thenables to the // SuspenseList so that it can retry if they resolve. // There might be multiple of these in the list but since we're // going to wait for all of them anyway, it doesn't really matter // which ones gets to ping. In theory we could get clever and keep // track of how many dependencies remain but it gets tricky because // in the meantime, we can add/remove/change items and dependencies. // We might bail out of the loop before finding any but that // doesn't matter since that means that the other boundaries that // we did find already has their listeners attached. var newThenables = suspended.updateQueue; if (newThenables !== null) { workInProgress.updateQueue = newThenables; workInProgress.flags |= Update; } // Rerender the whole list, but this time, we'll force fallbacks // to stay in place. // Reset the effect flags before doing the second pass since that's now invalid. // Reset the child fibers to their original state. workInProgress.subtreeFlags = NoFlags; resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately // rerender the children. pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); // Don't bubble properties in this case. return workInProgress.child; } row = row.sibling; } } if (renderState.tail !== null && now() > getRenderTargetTime()) { // We have already passed our CPU deadline but we still have rows // left in the tail. We'll just give up further attempts to render // the main content and only render fallbacks. workInProgress.flags |= DidCapture; didSuspendAlready = true; cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this // to get it started back up to attempt the next item. While in terms // of priority this work has the same priority as this current render, // it's not part of the same transition once the transition has // committed. If it's sync, we still want to yield so that it can be // painted. Conceptually, this is really the same as pinging. // We can use any RetryLane even if it's the one currently rendering // since we're leaving it behind on this node. workInProgress.lanes = SomeRetryLane; } } else { cutOffTailIfNeeded(renderState, false); } // Next we're going to render the tail. } else { // Append the rendered row to the child list. if (!didSuspendAlready) { var _suspended = findFirstSuspended(renderedTail); if (_suspended !== null) { workInProgress.flags |= DidCapture; didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't // get lost if this row ends up dropped during a second pass. var _newThenables = _suspended.updateQueue; if (_newThenables !== null) { workInProgress.updateQueue = _newThenables; workInProgress.flags |= Update; } cutOffTailIfNeeded(renderState, true); // This might have been modified. if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating. ) { // We're done. bubbleProperties(workInProgress); return null; } } else if ( // The time it took to render last row is greater than the remaining // time we have to render. So rendering one more row would likely // exceed it. now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) { // We have now passed our CPU deadline and we'll just give up further // attempts to render the main content and only render fallbacks. // The assumption is that this is usually faster. workInProgress.flags |= DidCapture; didSuspendAlready = true; cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this // to get it started back up to attempt the next item. While in terms // of priority this work has the same priority as this current render, // it's not part of the same transition once the transition has // committed. If it's sync, we still want to yield so that it can be // painted. Conceptually, this is really the same as pinging. // We can use any RetryLane even if it's the one currently rendering // since we're leaving it behind on this node. workInProgress.lanes = SomeRetryLane; } } if (renderState.isBackwards) { // The effect list of the backwards tail will have been added // to the end. This breaks the guarantee that life-cycles fire in // sibling order but that isn't a strong guarantee promised by React. // Especially since these might also just pop in during future commits. // Append to the beginning of the list. renderedTail.sibling = workInProgress.child; workInProgress.child = renderedTail; } else { var previousSibling = renderState.last; if (previousSibling !== null) { previousSibling.sibling = renderedTail; } else { workInProgress.child = renderedTail; } renderState.last = renderedTail; } } if (renderState.tail !== null) { // We still have tail rows to render. // Pop a row. var next = renderState.tail; renderState.rendering = next; renderState.tail = next.sibling; renderState.renderingStartTime = now(); next.sibling = null; // Restore the context. // TODO: We can probably just avoid popping it instead and only // setting it the first time we go from not suspended to suspended. var suspenseContext = suspenseStackCursor.current; if (didSuspendAlready) { suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); } else { suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); } pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row. // Don't bubble properties in this case. return next; } bubbleProperties(workInProgress); return null; } case ScopeComponent: { break; } case OffscreenComponent: case LegacyHiddenComponent: { popRenderLanes(workInProgress); var _nextState = workInProgress.memoizedState; var nextIsHidden = _nextState !== null; if (current !== null) { var _prevState = current.memoizedState; var prevIsHidden = _prevState !== null; if (prevIsHidden !== nextIsHidden && ( // LegacyHidden doesn't do any hiding — it only pre-renders. !enableLegacyHidden )) { workInProgress.flags |= Visibility; } } if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) { bubbleProperties(workInProgress); } else { // Don't bubble properties for hidden children unless we're rendering // at offscreen priority. if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) { bubbleProperties(workInProgress); { // Check if there was an insertion or update in the hidden subtree. // If so, we need to hide those nodes in the commit phase, so // schedule a visibility effect. if ( workInProgress.subtreeFlags & (Placement | Update)) { workInProgress.flags |= Visibility; } } } } return null; } case CacheComponent: { return null; } case TracingMarkerComponent: { return null; } } throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.'); } function unwindWork(current, workInProgress, renderLanes) { // Note: This intentionally doesn't check if we're hydrating because comparing // to the current tree provider fiber is just as fast and less error-prone. // Ideally we would have a special version of the work loop only // for hydration. popTreeContext(workInProgress); switch (workInProgress.tag) { case ClassComponent: { var Component = workInProgress.type; if (isContextProvider(Component)) { popContext(workInProgress); } var flags = workInProgress.flags; if (flags & ShouldCapture) { workInProgress.flags = flags & ~ShouldCapture | DidCapture; if ( (workInProgress.mode & ProfileMode) !== NoMode) { transferActualDuration(workInProgress); } return workInProgress; } return null; } case HostRoot: { var root = workInProgress.stateNode; popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); resetWorkInProgressVersions(); var _flags = workInProgress.flags; if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) { // There was an error during render that wasn't captured by a suspense // boundary. Do a second pass on the root to unmount the children. workInProgress.flags = _flags & ~ShouldCapture | DidCapture; return workInProgress; } // We unwound to the root without completing it. Exit. return null; } case HostComponent: { // TODO: popHydrationState popHostContext(workInProgress); return null; } case SuspenseComponent: { popSuspenseContext(workInProgress); var suspenseState = workInProgress.memoizedState; if (suspenseState !== null && suspenseState.dehydrated !== null) { if (workInProgress.alternate === null) { throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in ' + 'React. Please file an issue.'); } resetHydrationState(); } var _flags2 = workInProgress.flags; if (_flags2 & ShouldCapture) { workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary. if ( (workInProgress.mode & ProfileMode) !== NoMode) { transferActualDuration(workInProgress); } return workInProgress; } return null; } case SuspenseListComponent: { popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been // caught by a nested boundary. If not, it should bubble through. return null; } case HostPortal: popHostContainer(workInProgress); return null; case ContextProvider: var context = workInProgress.type._context; popProvider(context, workInProgress); return null; case OffscreenComponent: case LegacyHiddenComponent: popRenderLanes(workInProgress); return null; case CacheComponent: return null; default: return null; } } function unwindInterruptedWork(current, interruptedWork, renderLanes) { // Note: This intentionally doesn't check if we're hydrating because comparing // to the current tree provider fiber is just as fast and less error-prone. // Ideally we would have a special version of the work loop only // for hydration. popTreeContext(interruptedWork); switch (interruptedWork.tag) { case ClassComponent: { var childContextTypes = interruptedWork.type.childContextTypes; if (childContextTypes !== null && childContextTypes !== undefined) { popContext(interruptedWork); } break; } case HostRoot: { var root = interruptedWork.stateNode; popHostContainer(interruptedWork); popTopLevelContextObject(interruptedWork); resetWorkInProgressVersions(); break; } case HostComponent: { popHostContext(interruptedWork); break; } case HostPortal: popHostContainer(interruptedWork); break; case SuspenseComponent: popSuspenseContext(interruptedWork); break; case SuspenseListComponent: popSuspenseContext(interruptedWork); break; case ContextProvider: var context = interruptedWork.type._context; popProvider(context, interruptedWork); break; case OffscreenComponent: case LegacyHiddenComponent: popRenderLanes(interruptedWork); break; } } var didWarnAboutUndefinedSnapshotBeforeUpdate = null; { didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); } // Used during the commit phase to track the state of the Offscreen component stack. // Allows us to avoid traversing the return path to find the nearest Offscreen ancestor. // Only used when enableSuspenseLayoutEffectSemantics is enabled. var offscreenSubtreeIsHidden = false; var offscreenSubtreeWasHidden = false; var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; var nextEffect = null; // Used for Profiling builds to track updaters. var inProgressLanes = null; var inProgressRoot = null; function reportUncaughtErrorInDEV(error) { // Wrapping each small part of the commit phase into a guarded // callback is a bit too slow (https://github.com/facebook/react/pull/21666). // But we rely on it to surface errors to DEV tools like overlays // (https://github.com/facebook/react/issues/21712). // As a compromise, rethrow only caught errors in a guard. { invokeGuardedCallback(null, function () { throw error; }); clearCaughtError(); } } var callComponentWillUnmountWithTimer = function (current, instance) { instance.props = current.memoizedProps; instance.state = current.memoizedState; if ( current.mode & ProfileMode) { try { startLayoutEffectTimer(); instance.componentWillUnmount(); } finally { recordLayoutEffectDuration(current); } } else { instance.componentWillUnmount(); } }; // Capture errors so they don't interrupt mounting. function safelyCallCommitHookLayoutEffectListMount(current, nearestMountedAncestor) { try { commitHookEffectListMount(Layout, current); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } // Capture errors so they don't interrupt unmounting. function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) { try { callComponentWillUnmountWithTimer(current, instance); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } // Capture errors so they don't interrupt mounting. function safelyCallComponentDidMount(current, nearestMountedAncestor, instance) { try { instance.componentDidMount(); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } // Capture errors so they don't interrupt mounting. function safelyAttachRef(current, nearestMountedAncestor) { try { commitAttachRef(current); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } function safelyDetachRef(current, nearestMountedAncestor) { var ref = current.ref; if (ref !== null) { if (typeof ref === 'function') { var retVal; try { if (enableProfilerTimer && enableProfilerCommitHooks && current.mode & ProfileMode) { try { startLayoutEffectTimer(); retVal = ref(null); } finally { recordLayoutEffectDuration(current); } } else { retVal = ref(null); } } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } { if (typeof retVal === 'function') { error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current)); } } } else { ref.current = null; } } } function safelyCallDestroy(current, nearestMountedAncestor, destroy) { try { destroy(); } catch (error) { captureCommitPhaseError(current, nearestMountedAncestor, error); } } var focusedInstanceHandle = null; var shouldFireAfterActiveInstanceBlur = false; function commitBeforeMutationEffects(root, firstChild) { focusedInstanceHandle = prepareForCommit(root.containerInfo); nextEffect = firstChild; commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber var shouldFire = shouldFireAfterActiveInstanceBlur; shouldFireAfterActiveInstanceBlur = false; focusedInstanceHandle = null; return shouldFire; } function commitBeforeMutationEffects_begin() { while (nextEffect !== null) { var fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur. var child = fiber.child; if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) { child.return = fiber; nextEffect = child; } else { commitBeforeMutationEffects_complete(); } } } function commitBeforeMutationEffects_complete() { while (nextEffect !== null) { var fiber = nextEffect; setCurrentFiber(fiber); try { commitBeforeMutationEffectsOnFiber(fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } resetCurrentFiber(); var sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function commitBeforeMutationEffectsOnFiber(finishedWork) { var current = finishedWork.alternate; var flags = finishedWork.flags; if ((flags & Snapshot) !== NoFlags) { setCurrentFiber(finishedWork); switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { break; } case ClassComponent: { if (current !== null) { var prevProps = current.memoizedProps; var prevState = current.memoizedState; var instance = finishedWork.stateNode; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { if (instance.props !== finishedWork.memoizedProps) { error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } if (instance.state !== finishedWork.memoizedState) { error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } } } var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState); { var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { didWarnSet.add(finishedWork.type); error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork)); } } instance.__reactInternalSnapshotBeforeUpdate = snapshot; } break; } case HostRoot: { { var root = finishedWork.stateNode; clearContainer(root.containerInfo); } break; } case HostComponent: case HostText: case HostPortal: case IncompleteClassComponent: // Nothing to do for these component types break; default: { throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); } } resetCurrentFiber(); } } function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) { var updateQueue = finishedWork.updateQueue; var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; do { if ((effect.tag & flags) === flags) { // Unmount var destroy = effect.destroy; effect.destroy = undefined; if (destroy !== undefined) { { if ((flags & Passive$1) !== NoFlags$1) { markComponentPassiveEffectUnmountStarted(finishedWork); } else if ((flags & Layout) !== NoFlags$1) { markComponentLayoutEffectUnmountStarted(finishedWork); } } { if ((flags & Insertion) !== NoFlags$1) { setIsRunningInsertionEffect(true); } } safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); { if ((flags & Insertion) !== NoFlags$1) { setIsRunningInsertionEffect(false); } } { if ((flags & Passive$1) !== NoFlags$1) { markComponentPassiveEffectUnmountStopped(); } else if ((flags & Layout) !== NoFlags$1) { markComponentLayoutEffectUnmountStopped(); } } } } effect = effect.next; } while (effect !== firstEffect); } } function commitHookEffectListMount(flags, finishedWork) { var updateQueue = finishedWork.updateQueue; var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; do { if ((effect.tag & flags) === flags) { { if ((flags & Passive$1) !== NoFlags$1) { markComponentPassiveEffectMountStarted(finishedWork); } else if ((flags & Layout) !== NoFlags$1) { markComponentLayoutEffectMountStarted(finishedWork); } } // Mount var create = effect.create; { if ((flags & Insertion) !== NoFlags$1) { setIsRunningInsertionEffect(true); } } effect.destroy = create(); { if ((flags & Insertion) !== NoFlags$1) { setIsRunningInsertionEffect(false); } } { if ((flags & Passive$1) !== NoFlags$1) { markComponentPassiveEffectMountStopped(); } else if ((flags & Layout) !== NoFlags$1) { markComponentLayoutEffectMountStopped(); } } { var destroy = effect.destroy; if (destroy !== undefined && typeof destroy !== 'function') { var hookName = void 0; if ((effect.tag & Layout) !== NoFlags) { hookName = 'useLayoutEffect'; } else if ((effect.tag & Insertion) !== NoFlags) { hookName = 'useInsertionEffect'; } else { hookName = 'useEffect'; } var addendum = void 0; if (destroy === null) { addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).'; } else if (typeof destroy.then === 'function') { addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching'; } else { addendum = ' You returned: ' + destroy; } error('%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum); } } } effect = effect.next; } while (effect !== firstEffect); } } function commitPassiveEffectDurations(finishedRoot, finishedWork) { { // Only Profilers with work in their subtree will have an Update effect scheduled. if ((finishedWork.flags & Update) !== NoFlags) { switch (finishedWork.tag) { case Profiler: { var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration; var _finishedWork$memoize = finishedWork.memoizedProps, id = _finishedWork$memoize.id, onPostCommit = _finishedWork$memoize.onPostCommit; // This value will still reflect the previous commit phase. // It does not get reset until the start of the next commit phase. var commitTime = getCommitTime(); var phase = finishedWork.alternate === null ? 'mount' : 'update'; { if (isCurrentUpdateNested()) { phase = 'nested-update'; } } if (typeof onPostCommit === 'function') { onPostCommit(id, phase, passiveEffectDuration, commitTime); } // Bubble times to the next nearest ancestor Profiler. // After we process that Profiler, we'll bubble further up. var parentFiber = finishedWork.return; outer: while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: var root = parentFiber.stateNode; root.passiveEffectDuration += passiveEffectDuration; break outer; case Profiler: var parentStateNode = parentFiber.stateNode; parentStateNode.passiveEffectDuration += passiveEffectDuration; break outer; } parentFiber = parentFiber.return; } break; } } } } } function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) { if ((finishedWork.flags & LayoutMask) !== NoFlags) { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { if ( !offscreenSubtreeWasHidden) { // At this point layout effects have already been destroyed (during mutation phase). // This is done to prevent sibling component effects from interfering with each other, // e.g. a destroy function in one component should never override a ref set // by a create function in another component during the same commit. if ( finishedWork.mode & ProfileMode) { try { startLayoutEffectTimer(); commitHookEffectListMount(Layout | HasEffect, finishedWork); } finally { recordLayoutEffectDuration(finishedWork); } } else { commitHookEffectListMount(Layout | HasEffect, finishedWork); } } break; } case ClassComponent: { var instance = finishedWork.stateNode; if (finishedWork.flags & Update) { if (!offscreenSubtreeWasHidden) { if (current === null) { // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { if (instance.props !== finishedWork.memoizedProps) { error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } if (instance.state !== finishedWork.memoizedState) { error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } } } if ( finishedWork.mode & ProfileMode) { try { startLayoutEffectTimer(); instance.componentDidMount(); } finally { recordLayoutEffectDuration(finishedWork); } } else { instance.componentDidMount(); } } else { var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps); var prevState = current.memoizedState; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { if (instance.props !== finishedWork.memoizedProps) { error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } if (instance.state !== finishedWork.memoizedState) { error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } } } if ( finishedWork.mode & ProfileMode) { try { startLayoutEffectTimer(); instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); } finally { recordLayoutEffectDuration(finishedWork); } } else { instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); } } } } // TODO: I think this is now always non-null by the time it reaches the // commit phase. Consider removing the type check. var updateQueue = finishedWork.updateQueue; if (updateQueue !== null) { { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { if (instance.props !== finishedWork.memoizedProps) { error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } if (instance.state !== finishedWork.memoizedState) { error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance'); } } } // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. commitUpdateQueue(finishedWork, updateQueue, instance); } break; } case HostRoot: { // TODO: I think this is now always non-null by the time it reaches the // commit phase. Consider removing the type check. var _updateQueue = finishedWork.updateQueue; if (_updateQueue !== null) { var _instance = null; if (finishedWork.child !== null) { switch (finishedWork.child.tag) { case HostComponent: _instance = getPublicInstance(finishedWork.child.stateNode); break; case ClassComponent: _instance = finishedWork.child.stateNode; break; } } commitUpdateQueue(finishedWork, _updateQueue, _instance); } break; } case HostComponent: { var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted // (eg DOM renderer may schedule auto-focus for inputs and form controls). // These effects should only be committed when components are first mounted, // aka when there is no current/alternate. if (current === null && finishedWork.flags & Update) { var type = finishedWork.type; var props = finishedWork.memoizedProps; commitMount(_instance2, type, props); } break; } case HostText: { // We have no life-cycles associated with text. break; } case HostPortal: { // We have no life-cycles associated with portals. break; } case Profiler: { { var _finishedWork$memoize2 = finishedWork.memoizedProps, onCommit = _finishedWork$memoize2.onCommit, onRender = _finishedWork$memoize2.onRender; var effectDuration = finishedWork.stateNode.effectDuration; var commitTime = getCommitTime(); var phase = current === null ? 'mount' : 'update'; { if (isCurrentUpdateNested()) { phase = 'nested-update'; } } if (typeof onRender === 'function') { onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime); } { if (typeof onCommit === 'function') { onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime); } // Schedule a passive effect for this Profiler to call onPostCommit hooks. // This effect should be scheduled even if there is no onPostCommit callback for this Profiler, // because the effect is also where times bubble to parent Profilers. enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor. // Do not reset these values until the next render so DevTools has a chance to read them first. var parentFiber = finishedWork.return; outer: while (parentFiber !== null) { switch (parentFiber.tag) { case HostRoot: var root = parentFiber.stateNode; root.effectDuration += effectDuration; break outer; case Profiler: var parentStateNode = parentFiber.stateNode; parentStateNode.effectDuration += effectDuration; break outer; } parentFiber = parentFiber.return; } } } break; } case SuspenseComponent: { commitSuspenseHydrationCallbacks(finishedRoot, finishedWork); break; } case SuspenseListComponent: case IncompleteClassComponent: case ScopeComponent: case OffscreenComponent: case LegacyHiddenComponent: case TracingMarkerComponent: { break; } default: throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.'); } } if ( !offscreenSubtreeWasHidden) { { if (finishedWork.flags & Ref) { commitAttachRef(finishedWork); } } } } function reappearLayoutEffectsOnFiber(node) { // Turn on layout effects in a tree that previously disappeared. // TODO (Offscreen) Check: flags & LayoutStatic switch (node.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { if ( node.mode & ProfileMode) { try { startLayoutEffectTimer(); safelyCallCommitHookLayoutEffectListMount(node, node.return); } finally { recordLayoutEffectDuration(node); } } else { safelyCallCommitHookLayoutEffectListMount(node, node.return); } break; } case ClassComponent: { var instance = node.stateNode; if (typeof instance.componentDidMount === 'function') { safelyCallComponentDidMount(node, node.return, instance); } safelyAttachRef(node, node.return); break; } case HostComponent: { safelyAttachRef(node, node.return); break; } } } function hideOrUnhideAllChildren(finishedWork, isHidden) { // Only hide or unhide the top-most host nodes. var hostSubtreeRoot = null; { // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. var node = finishedWork; while (true) { if (node.tag === HostComponent) { if (hostSubtreeRoot === null) { hostSubtreeRoot = node; try { var instance = node.stateNode; if (isHidden) { hideInstance(instance); } else { unhideInstance(node.stateNode, node.memoizedProps); } } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } else if (node.tag === HostText) { if (hostSubtreeRoot === null) { try { var _instance3 = node.stateNode; if (isHidden) { hideTextInstance(_instance3); } else { unhideTextInstance(_instance3, node.memoizedProps); } } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === finishedWork) { return; } while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } if (hostSubtreeRoot === node) { hostSubtreeRoot = null; } node = node.return; } if (hostSubtreeRoot === node) { hostSubtreeRoot = null; } node.sibling.return = node.return; node = node.sibling; } } } function commitAttachRef(finishedWork) { var ref = finishedWork.ref; if (ref !== null) { var instance = finishedWork.stateNode; var instanceToUse; switch (finishedWork.tag) { case HostComponent: instanceToUse = getPublicInstance(instance); break; default: instanceToUse = instance; } // Moved outside to ensure DCE works with this flag if (typeof ref === 'function') { var retVal; if ( finishedWork.mode & ProfileMode) { try { startLayoutEffectTimer(); retVal = ref(instanceToUse); } finally { recordLayoutEffectDuration(finishedWork); } } else { retVal = ref(instanceToUse); } { if (typeof retVal === 'function') { error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(finishedWork)); } } } else { { if (!ref.hasOwnProperty('current')) { error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork)); } } ref.current = instanceToUse; } } } function detachFiberMutation(fiber) { // Cut off the return pointer to disconnect it from the tree. // This enables us to detect and warn against state updates on an unmounted component. // It also prevents events from bubbling from within disconnected components. // // Ideally, we should also clear the child pointer of the parent alternate to let this // get GC:ed but we don't know which for sure which parent is the current // one so we'll settle for GC:ing the subtree of this child. // This child itself will be GC:ed when the parent updates the next time. // // Note that we can't clear child or sibling pointers yet. // They're needed for passive effects and for findDOMNode. // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects). // // Don't reset the alternate yet, either. We need that so we can detach the // alternate's fields in the passive phase. Clearing the return pointer is // sufficient for findDOMNode semantics. var alternate = fiber.alternate; if (alternate !== null) { alternate.return = null; } fiber.return = null; } function detachFiberAfterEffects(fiber) { var alternate = fiber.alternate; if (alternate !== null) { fiber.alternate = null; detachFiberAfterEffects(alternate); } // Note: Defensively using negation instead of < in case // `deletedTreeCleanUpLevel` is undefined. { // Clear cyclical Fiber fields. This level alone is designed to roughly // approximate the planned Fiber refactor. In that world, `setState` will be // bound to a special "instance" object instead of a Fiber. The Instance // object will not have any of these fields. It will only be connected to // the fiber tree via a single link at the root. So if this level alone is // sufficient to fix memory issues, that bodes well for our plans. fiber.child = null; fiber.deletions = null; fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host // tree, which has its own pointers to children, parents, and siblings. // The other host nodes also point back to fibers, so we should detach that // one, too. if (fiber.tag === HostComponent) { var hostInstance = fiber.stateNode; if (hostInstance !== null) { detachDeletedInstance(hostInstance); } } fiber.stateNode = null; // I'm intentionally not clearing the `return` field in this level. We // already disconnect the `return` pointer at the root of the deleted // subtree (in `detachFiberMutation`). Besides, `return` by itself is not // cyclical — it's only cyclical when combined with `child`, `sibling`, and // `alternate`. But we'll clear it in the next level anyway, just in case. { fiber._debugOwner = null; } { // Theoretically, nothing in here should be necessary, because we already // disconnected the fiber from the tree. So even if something leaks this // particular fiber, it won't leak anything else // // The purpose of this branch is to be super aggressive so we can measure // if there's any difference in memory impact. If there is, that could // indicate a React leak we don't know about. fiber.return = null; fiber.dependencies = null; fiber.memoizedProps = null; fiber.memoizedState = null; fiber.pendingProps = null; fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead. fiber.updateQueue = null; } } } function getHostParentFiber(fiber) { var parent = fiber.return; while (parent !== null) { if (isHostParent(parent)) { return parent; } parent = parent.return; } throw new Error('Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.'); } function isHostParent(fiber) { return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal; } function getHostSibling(fiber) { // We're going to search forward into the tree until we find a sibling host // node. Unfortunately, if multiple insertions are done in a row we have to // search past them. This leads to exponential search for the next sibling. // TODO: Find a more efficient way to do this. var node = fiber; siblings: while (true) { // If we didn't find anything, let's try the next sibling. while (node.sibling === null) { if (node.return === null || isHostParent(node.return)) { // If we pop out of the root or hit the parent the fiber we are the // last sibling. return null; } node = node.return; } node.sibling.return = node.return; node = node.sibling; while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) { // If it is not host node and, we might have a host node inside it. // Try to search down until we find one. if (node.flags & Placement) { // If we don't have a child, try the siblings instead. continue siblings; } // If we don't have a child, try the siblings instead. // We also skip portals because they are not part of this host tree. if (node.child === null || node.tag === HostPortal) { continue siblings; } else { node.child.return = node; node = node.child; } } // Check if this host node is stable or about to be placed. if (!(node.flags & Placement)) { // Found it! return node.stateNode; } } } function commitPlacement(finishedWork) { var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. switch (parentFiber.tag) { case HostComponent: { var parent = parentFiber.stateNode; if (parentFiber.flags & ContentReset) { // Reset the text content of the parent before doing any insertions resetTextContent(parent); // Clear ContentReset from the effect tag parentFiber.flags &= ~ContentReset; } var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. insertOrAppendPlacementNode(finishedWork, before, parent); break; } case HostRoot: case HostPortal: { var _parent = parentFiber.stateNode.containerInfo; var _before = getHostSibling(finishedWork); insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent); break; } // eslint-disable-next-line-no-fallthrough default: throw new Error('Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.'); } } function insertOrAppendPlacementNodeIntoContainer(node, before, parent) { var tag = node.tag; var isHost = tag === HostComponent || tag === HostText; if (isHost) { var stateNode = node.stateNode; if (before) { insertInContainerBefore(parent, stateNode, before); } else { appendChildToContainer(parent, stateNode); } } else if (tag === HostPortal) ; else { var child = node.child; if (child !== null) { insertOrAppendPlacementNodeIntoContainer(child, before, parent); var sibling = child.sibling; while (sibling !== null) { insertOrAppendPlacementNodeIntoContainer(sibling, before, parent); sibling = sibling.sibling; } } } } function insertOrAppendPlacementNode(node, before, parent) { var tag = node.tag; var isHost = tag === HostComponent || tag === HostText; if (isHost) { var stateNode = node.stateNode; if (before) { insertBefore(parent, stateNode, before); } else { appendChild(parent, stateNode); } } else if (tag === HostPortal) ; else { var child = node.child; if (child !== null) { insertOrAppendPlacementNode(child, before, parent); var sibling = child.sibling; while (sibling !== null) { insertOrAppendPlacementNode(sibling, before, parent); sibling = sibling.sibling; } } } } // These are tracked on the stack as we recursively traverse a // deleted subtree. // TODO: Update these during the whole mutation phase, not just during // a deletion. var hostParent = null; var hostParentIsContainer = false; function commitDeletionEffects(root, returnFiber, deletedFiber) { { // We only have the top Fiber that was deleted but we need to recurse down its // children to find all the terminal nodes. // Recursively delete all host nodes from the parent, detach refs, clean // up mounted layout effects, and call componentWillUnmount. // We only need to remove the topmost host child in each branch. But then we // still need to keep traversing to unmount effects, refs, and cWU. TODO: We // could split this into two separate traversals functions, where the second // one doesn't include any removeChild logic. This is maybe the same // function as "disappearLayoutEffects" (or whatever that turns into after // the layout phase is refactored to use recursion). // Before starting, find the nearest host parent on the stack so we know // which instance/container to remove the children from. // TODO: Instead of searching up the fiber return path on every deletion, we // can track the nearest host component on the JS stack as we traverse the // tree during the commit phase. This would make insertions faster, too. var parent = returnFiber; findParent: while (parent !== null) { switch (parent.tag) { case HostComponent: { hostParent = parent.stateNode; hostParentIsContainer = false; break findParent; } case HostRoot: { hostParent = parent.stateNode.containerInfo; hostParentIsContainer = true; break findParent; } case HostPortal: { hostParent = parent.stateNode.containerInfo; hostParentIsContainer = true; break findParent; } } parent = parent.return; } if (hostParent === null) { throw new Error('Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.'); } commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber); hostParent = null; hostParentIsContainer = false; } detachFiberMutation(deletedFiber); } function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) { // TODO: Use a static flag to skip trees that don't have unmount effects var child = parent.child; while (child !== null) { commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child); child = child.sibling; } } function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) { onCommitUnmount(deletedFiber); // The cases in this outer switch modify the stack before they traverse // into their subtree. There are simpler cases in the inner switch // that don't modify the stack. switch (deletedFiber.tag) { case HostComponent: { if (!offscreenSubtreeWasHidden) { safelyDetachRef(deletedFiber, nearestMountedAncestor); } // Intentional fallthrough to next branch } // eslint-disable-next-line-no-fallthrough case HostText: { // We only need to remove the nearest host child. Set the host parent // to `null` on the stack to indicate that nested children don't // need to be removed. { var prevHostParent = hostParent; var prevHostParentIsContainer = hostParentIsContainer; hostParent = null; recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); hostParent = prevHostParent; hostParentIsContainer = prevHostParentIsContainer; if (hostParent !== null) { // Now that all the child effects have unmounted, we can remove the // node from the tree. if (hostParentIsContainer) { removeChildFromContainer(hostParent, deletedFiber.stateNode); } else { removeChild(hostParent, deletedFiber.stateNode); } } } return; } case DehydratedFragment: { // Delete the dehydrated suspense boundary and all of its content. { if (hostParent !== null) { if (hostParentIsContainer) { clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode); } else { clearSuspenseBoundary(hostParent, deletedFiber.stateNode); } } } return; } case HostPortal: { { // When we go into a portal, it becomes the parent to remove from. var _prevHostParent = hostParent; var _prevHostParentIsContainer = hostParentIsContainer; hostParent = deletedFiber.stateNode.containerInfo; hostParentIsContainer = true; recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); hostParent = _prevHostParent; hostParentIsContainer = _prevHostParentIsContainer; } return; } case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { if (!offscreenSubtreeWasHidden) { var updateQueue = deletedFiber.updateQueue; if (updateQueue !== null) { var lastEffect = updateQueue.lastEffect; if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; do { var _effect = effect, destroy = _effect.destroy, tag = _effect.tag; if (destroy !== undefined) { if ((tag & Insertion) !== NoFlags$1) { safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); } else if ((tag & Layout) !== NoFlags$1) { { markComponentLayoutEffectUnmountStarted(deletedFiber); } if ( deletedFiber.mode & ProfileMode) { startLayoutEffectTimer(); safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); recordLayoutEffectDuration(deletedFiber); } else { safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); } { markComponentLayoutEffectUnmountStopped(); } } } effect = effect.next; } while (effect !== firstEffect); } } } recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); return; } case ClassComponent: { if (!offscreenSubtreeWasHidden) { safelyDetachRef(deletedFiber, nearestMountedAncestor); var instance = deletedFiber.stateNode; if (typeof instance.componentWillUnmount === 'function') { safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance); } } recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); return; } case ScopeComponent: { recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); return; } case OffscreenComponent: { if ( // TODO: Remove this dead flag deletedFiber.mode & ConcurrentMode) { // If this offscreen component is hidden, we already unmounted it. Before // deleting the children, track that it's already unmounted so that we // don't attempt to unmount the effects again. // TODO: If the tree is hidden, in most cases we should be able to skip // over the nested children entirely. An exception is we haven't yet found // the topmost host node to delete, which we already track on the stack. // But the other case is portals, which need to be detached no matter how // deeply they are nested. We should use a subtree flag to track whether a // subtree includes a nested portal. var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null; recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; } else { recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); } break; } default: { recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); return; } } } function commitSuspenseCallback(finishedWork) { // TODO: Move this to passive phase var newState = finishedWork.memoizedState; } function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { var newState = finishedWork.memoizedState; if (newState === null) { var current = finishedWork.alternate; if (current !== null) { var prevState = current.memoizedState; if (prevState !== null) { var suspenseInstance = prevState.dehydrated; if (suspenseInstance !== null) { commitHydratedSuspenseInstance(suspenseInstance); } } } } } function attachSuspenseRetryListeners(finishedWork) { // If this boundary just timed out, then it will have a set of wakeables. // For each wakeable, attach a listener so that when it resolves, React // attempts to re-render the boundary in the primary (pre-timeout) state. var wakeables = finishedWork.updateQueue; if (wakeables !== null) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; if (retryCache === null) { retryCache = finishedWork.stateNode = new PossiblyWeakSet(); } wakeables.forEach(function (wakeable) { // Memoize using the boundary fiber to prevent redundant listeners. var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); if (!retryCache.has(wakeable)) { retryCache.add(wakeable); { if (isDevToolsPresent) { if (inProgressLanes !== null && inProgressRoot !== null) { // If we have pending work still, associate the original updaters with it. restorePendingUpdaters(inProgressRoot, inProgressLanes); } else { throw Error('Expected finished root and lanes to be set. This is a bug in React.'); } } } wakeable.then(retry, retry); } }); } } // This function detects when a Suspense boundary goes from visible to hidden. function commitMutationEffects(root, finishedWork, committedLanes) { inProgressLanes = committedLanes; inProgressRoot = root; setCurrentFiber(finishedWork); commitMutationEffectsOnFiber(finishedWork, root); setCurrentFiber(finishedWork); inProgressLanes = null; inProgressRoot = null; } function recursivelyTraverseMutationEffects(root, parentFiber, lanes) { // Deletions effects can be scheduled on any fiber type. They need to happen // before the children effects hae fired. var deletions = parentFiber.deletions; if (deletions !== null) { for (var i = 0; i < deletions.length; i++) { var childToDelete = deletions[i]; try { commitDeletionEffects(root, parentFiber, childToDelete); } catch (error) { captureCommitPhaseError(childToDelete, parentFiber, error); } } } var prevDebugFiber = getCurrentFiber(); if (parentFiber.subtreeFlags & MutationMask) { var child = parentFiber.child; while (child !== null) { setCurrentFiber(child); commitMutationEffectsOnFiber(child, root); child = child.sibling; } } setCurrentFiber(prevDebugFiber); } function commitMutationEffectsOnFiber(finishedWork, root, lanes) { var current = finishedWork.alternate; var flags = finishedWork.flags; // The effect flag should be checked *after* we refine the type of fiber, // because the fiber tag is more specific. An exception is any flag related // to reconcilation, because those can be set on all fiber types. switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Update) { try { commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); commitHookEffectListMount(Insertion | HasEffect, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } // Layout effects are destroyed during the mutation phase so that all // destroy functions for all fibers are called before any create functions. // This prevents sibling component effects from interfering with each other, // e.g. a destroy function in one component should never override a ref set // by a create function in another component during the same commit. if ( finishedWork.mode & ProfileMode) { try { startLayoutEffectTimer(); commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } recordLayoutEffectDuration(finishedWork); } else { try { commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } return; } case ClassComponent: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Ref) { if (current !== null) { safelyDetachRef(current, current.return); } } return; } case HostComponent: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Ref) { if (current !== null) { safelyDetachRef(current, current.return); } } { // TODO: ContentReset gets cleared by the children during the commit // phase. This is a refactor hazard because it means we must read // flags the flags after `commitReconciliationEffects` has already run; // the order matters. We should refactor so that ContentReset does not // rely on mutating the flag during commit. Like by setting a flag // during the render phase instead. if (finishedWork.flags & ContentReset) { var instance = finishedWork.stateNode; try { resetTextContent(instance); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } if (flags & Update) { var _instance4 = finishedWork.stateNode; if (_instance4 != null) { // Commit the work prepared earlier. var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. var oldProps = current !== null ? current.memoizedProps : newProps; var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. var updatePayload = finishedWork.updateQueue; finishedWork.updateQueue = null; if (updatePayload !== null) { try { commitUpdate(_instance4, updatePayload, type, oldProps, newProps, finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } } } return; } case HostText: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Update) { { if (finishedWork.stateNode === null) { throw new Error('This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.'); } var textInstance = finishedWork.stateNode; var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. var oldText = current !== null ? current.memoizedProps : newText; try { commitTextUpdate(textInstance, oldText, newText); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } return; } case HostRoot: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Update) { { if (current !== null) { var prevRootState = current.memoizedState; if (prevRootState.isDehydrated) { try { commitHydratedContainer(root.containerInfo); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } } } } } return; } case HostPortal: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); return; } case SuspenseComponent: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); var offscreenFiber = finishedWork.child; if (offscreenFiber.flags & Visibility) { var offscreenInstance = offscreenFiber.stateNode; var newState = offscreenFiber.memoizedState; var isHidden = newState !== null; // Track the current state on the Offscreen instance so we can // read it during an event offscreenInstance.isHidden = isHidden; if (isHidden) { var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null; if (!wasHidden) { // TODO: Move to passive phase markCommitTimeOfFallback(); } } } if (flags & Update) { try { commitSuspenseCallback(finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } attachSuspenseRetryListeners(finishedWork); } return; } case OffscreenComponent: { var _wasHidden = current !== null && current.memoizedState !== null; if ( // TODO: Remove this dead flag finishedWork.mode & ConcurrentMode) { // Before committing the children, track on the stack whether this // offscreen subtree was already hidden, so that we don't unmount the // effects again. var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden; recursivelyTraverseMutationEffects(root, finishedWork); offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; } else { recursivelyTraverseMutationEffects(root, finishedWork); } commitReconciliationEffects(finishedWork); if (flags & Visibility) { var _offscreenInstance = finishedWork.stateNode; var _newState = finishedWork.memoizedState; var _isHidden = _newState !== null; var offscreenBoundary = finishedWork; // Track the current state on the Offscreen instance so we can // read it during an event _offscreenInstance.isHidden = _isHidden; { if (_isHidden) { if (!_wasHidden) { if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) { nextEffect = offscreenBoundary; var offscreenChild = offscreenBoundary.child; while (offscreenChild !== null) { nextEffect = offscreenChild; disappearLayoutEffects_begin(offscreenChild); offscreenChild = offscreenChild.sibling; } } } } } { // TODO: This needs to run whenever there's an insertion or update // inside a hidden Offscreen tree. hideOrUnhideAllChildren(offscreenBoundary, _isHidden); } } return; } case SuspenseListComponent: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); if (flags & Update) { attachSuspenseRetryListeners(finishedWork); } return; } case ScopeComponent: { return; } default: { recursivelyTraverseMutationEffects(root, finishedWork); commitReconciliationEffects(finishedWork); return; } } } function commitReconciliationEffects(finishedWork) { // Placement effects (insertions, reorders) can be scheduled on any fiber // type. They needs to happen after the children effects have fired, but // before the effects on this fiber have fired. var flags = finishedWork.flags; if (flags & Placement) { try { commitPlacement(finishedWork); } catch (error) { captureCommitPhaseError(finishedWork, finishedWork.return, error); } // Clear the "placement" from effect tag so that we know that this is // inserted, before any life-cycles like componentDidMount gets called. // TODO: findDOMNode doesn't rely on this any more but isMounted does // and isMounted is deprecated anyway so we should be able to kill this. finishedWork.flags &= ~Placement; } if (flags & Hydrating) { finishedWork.flags &= ~Hydrating; } } function commitLayoutEffects(finishedWork, root, committedLanes) { inProgressLanes = committedLanes; inProgressRoot = root; nextEffect = finishedWork; commitLayoutEffects_begin(finishedWork, root, committedLanes); inProgressLanes = null; inProgressRoot = null; } function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) { // Suspense layout effects semantics don't change for legacy roots. var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode; while (nextEffect !== null) { var fiber = nextEffect; var firstChild = fiber.child; if ( fiber.tag === OffscreenComponent && isModernRoot) { // Keep track of the current Offscreen stack's state. var isHidden = fiber.memoizedState !== null; var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden; if (newOffscreenSubtreeIsHidden) { // The Offscreen tree is hidden. Skip over its layout effects. commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); continue; } else { // TODO (Offscreen) Also check: subtreeFlags & LayoutMask var current = fiber.alternate; var wasHidden = current !== null && current.memoizedState !== null; var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden; var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; // Traverse the Offscreen subtree with the current Offscreen as the root. offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { // This is the root of a reappearing boundary. Turn its layout effects // back on. nextEffect = fiber; reappearLayoutEffects_begin(fiber); } var child = firstChild; while (child !== null) { nextEffect = child; commitLayoutEffects_begin(child, // New root; bubble back up to here and stop. root, committedLanes); child = child.sibling; } // Restore Offscreen state and resume in our-progress traversal. nextEffect = fiber; offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); continue; } } if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) { firstChild.return = fiber; nextEffect = firstChild; } else { commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes); } } } function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) { while (nextEffect !== null) { var fiber = nextEffect; if ((fiber.flags & LayoutMask) !== NoFlags) { var current = fiber.alternate; setCurrentFiber(fiber); try { commitLayoutEffectOnFiber(root, current, fiber, committedLanes); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } resetCurrentFiber(); } if (fiber === subtreeRoot) { nextEffect = null; return; } var sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function disappearLayoutEffects_begin(subtreeRoot) { while (nextEffect !== null) { var fiber = nextEffect; var firstChild = fiber.child; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic) switch (fiber.tag) { case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { if ( fiber.mode & ProfileMode) { try { startLayoutEffectTimer(); commitHookEffectListUnmount(Layout, fiber, fiber.return); } finally { recordLayoutEffectDuration(fiber); } } else { commitHookEffectListUnmount(Layout, fiber, fiber.return); } break; } case ClassComponent: { // TODO (Offscreen) Check: flags & RefStatic safelyDetachRef(fiber, fiber.return); var instance = fiber.stateNode; if (typeof instance.componentWillUnmount === 'function') { safelyCallComponentWillUnmount(fiber, fiber.return, instance); } break; } case HostComponent: { safelyDetachRef(fiber, fiber.return); break; } case OffscreenComponent: { // Check if this is a var isHidden = fiber.memoizedState !== null; if (isHidden) { // Nested Offscreen tree is already hidden. Don't disappear // its effects. disappearLayoutEffects_complete(subtreeRoot); continue; } break; } } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic if (firstChild !== null) { firstChild.return = fiber; nextEffect = firstChild; } else { disappearLayoutEffects_complete(subtreeRoot); } } } function disappearLayoutEffects_complete(subtreeRoot) { while (nextEffect !== null) { var fiber = nextEffect; if (fiber === subtreeRoot) { nextEffect = null; return; } var sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function reappearLayoutEffects_begin(subtreeRoot) { while (nextEffect !== null) { var fiber = nextEffect; var firstChild = fiber.child; if (fiber.tag === OffscreenComponent) { var isHidden = fiber.memoizedState !== null; if (isHidden) { // Nested Offscreen tree is still hidden. Don't re-appear its effects. reappearLayoutEffects_complete(subtreeRoot); continue; } } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic if (firstChild !== null) { // This node may have been reused from a previous render, so we can't // assume its return pointer is correct. firstChild.return = fiber; nextEffect = firstChild; } else { reappearLayoutEffects_complete(subtreeRoot); } } } function reappearLayoutEffects_complete(subtreeRoot) { while (nextEffect !== null) { var fiber = nextEffect; // TODO (Offscreen) Check: flags & LayoutStatic setCurrentFiber(fiber); try { reappearLayoutEffectsOnFiber(fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } resetCurrentFiber(); if (fiber === subtreeRoot) { nextEffect = null; return; } var sibling = fiber.sibling; if (sibling !== null) { // This node may have been reused from a previous render, so we can't // assume its return pointer is correct. sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function commitPassiveMountEffects(root, finishedWork, committedLanes, committedTransitions) { nextEffect = finishedWork; commitPassiveMountEffects_begin(finishedWork, root, committedLanes, committedTransitions); } function commitPassiveMountEffects_begin(subtreeRoot, root, committedLanes, committedTransitions) { while (nextEffect !== null) { var fiber = nextEffect; var firstChild = fiber.child; if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { firstChild.return = fiber; nextEffect = firstChild; } else { commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions); } } } function commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions) { while (nextEffect !== null) { var fiber = nextEffect; if ((fiber.flags & Passive) !== NoFlags) { setCurrentFiber(fiber); try { commitPassiveMountOnFiber(root, fiber, committedLanes, committedTransitions); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } resetCurrentFiber(); } if (fiber === subtreeRoot) { nextEffect = null; return; } var sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { if ( finishedWork.mode & ProfileMode) { startPassiveEffectTimer(); try { commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); } finally { recordPassiveEffectDuration(finishedWork); } } else { commitHookEffectListMount(Passive$1 | HasEffect, finishedWork); } break; } } } function commitPassiveUnmountEffects(firstChild) { nextEffect = firstChild; commitPassiveUnmountEffects_begin(); } function commitPassiveUnmountEffects_begin() { while (nextEffect !== null) { var fiber = nextEffect; var child = fiber.child; if ((nextEffect.flags & ChildDeletion) !== NoFlags) { var deletions = fiber.deletions; if (deletions !== null) { for (var i = 0; i < deletions.length; i++) { var fiberToDelete = deletions[i]; nextEffect = fiberToDelete; commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber); } { // A fiber was deleted from this parent fiber, but it's still part of // the previous (alternate) parent fiber's list of children. Because // children are a linked list, an earlier sibling that's still alive // will be connected to the deleted fiber via its `alternate`: // // live fiber // --alternate--> previous live fiber // --sibling--> deleted fiber // // We can't disconnect `alternate` on nodes that haven't been deleted // yet, but we can disconnect the `sibling` and `child` pointers. var previousFiber = fiber.alternate; if (previousFiber !== null) { var detachedChild = previousFiber.child; if (detachedChild !== null) { previousFiber.child = null; do { var detachedSibling = detachedChild.sibling; detachedChild.sibling = null; detachedChild = detachedSibling; } while (detachedChild !== null); } } } nextEffect = fiber; } } if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) { child.return = fiber; nextEffect = child; } else { commitPassiveUnmountEffects_complete(); } } } function commitPassiveUnmountEffects_complete() { while (nextEffect !== null) { var fiber = nextEffect; if ((fiber.flags & Passive) !== NoFlags) { setCurrentFiber(fiber); commitPassiveUnmountOnFiber(fiber); resetCurrentFiber(); } var sibling = fiber.sibling; if (sibling !== null) { sibling.return = fiber.return; nextEffect = sibling; return; } nextEffect = fiber.return; } } function commitPassiveUnmountOnFiber(finishedWork) { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { if ( finishedWork.mode & ProfileMode) { startPassiveEffectTimer(); commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); recordPassiveEffectDuration(finishedWork); } else { commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return); } break; } } } function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) { while (nextEffect !== null) { var fiber = nextEffect; // Deletion effects fire in parent -> child order // TODO: Check if fiber has a PassiveStatic flag setCurrentFiber(fiber); commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); resetCurrentFiber(); var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we // do this, still need to handle `deletedTreeCleanUpLevel` correctly.) if (child !== null) { child.return = fiber; nextEffect = child; } else { commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot); } } } function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) { while (nextEffect !== null) { var fiber = nextEffect; var sibling = fiber.sibling; var returnFiber = fiber.return; { // Recursively traverse the entire deleted tree and clean up fiber fields. // This is more aggressive than ideal, and the long term goal is to only // have to detach the deleted tree at the root. detachFiberAfterEffects(fiber); if (fiber === deletedSubtreeRoot) { nextEffect = null; return; } } if (sibling !== null) { sibling.return = returnFiber; nextEffect = sibling; return; } nextEffect = returnFiber; } } function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) { switch (current.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { if ( current.mode & ProfileMode) { startPassiveEffectTimer(); commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); recordPassiveEffectDuration(current); } else { commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor); } break; } } } // TODO: Reuse reappearLayoutEffects traversal here? function invokeLayoutEffectMountInDEV(fiber) { { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListMount(Layout | HasEffect, fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } case ClassComponent: { var instance = fiber.stateNode; try { instance.componentDidMount(); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } } } } function invokePassiveEffectMountInDEV(fiber) { { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListMount(Passive$1 | HasEffect, fiber); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } } } } function invokeLayoutEffectUnmountInDEV(fiber) { { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } break; } case ClassComponent: { var instance = fiber.stateNode; if (typeof instance.componentWillUnmount === 'function') { safelyCallComponentWillUnmount(fiber, fiber.return, instance); } break; } } } } function invokePassiveEffectUnmountInDEV(fiber) { { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { try { commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return); } catch (error) { captureCommitPhaseError(fiber, fiber.return, error); } } } } } var COMPONENT_TYPE = 0; var HAS_PSEUDO_CLASS_TYPE = 1; var ROLE_TYPE = 2; var TEST_NAME_TYPE = 3; var TEXT_TYPE = 4; if (typeof Symbol === 'function' && Symbol.for) { var symbolFor = Symbol.for; COMPONENT_TYPE = symbolFor('selector.component'); HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class'); ROLE_TYPE = symbolFor('selector.role'); TEST_NAME_TYPE = symbolFor('selector.test_id'); TEXT_TYPE = symbolFor('selector.text'); } var commitHooks = []; function onCommitRoot$1() { { commitHooks.forEach(function (commitHook) { return commitHook(); }); } } var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue; function isLegacyActEnvironment(fiber) { { // Legacy mode. We preserve the behavior of React 17's act. It assumes an // act environment whenever `jest` is defined, but you can still turn off // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly // to false. var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest var jestIsDefined = typeof jest !== 'undefined'; return jestIsDefined && isReactActEnvironmentGlobal !== false; } } function isConcurrentActEnvironment() { { var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { // TODO: Include link to relevant documentation page. error('The current testing environment is not configured to support ' + 'act(...)'); } return isReactActEnvironmentGlobal; } } var ceil = Math.ceil; var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, ReactCurrentBatchConfig$3 = ReactSharedInternals.ReactCurrentBatchConfig, ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue; var NoContext = /* */ 0; var BatchedContext = /* */ 1; var RenderContext = /* */ 2; var CommitContext = /* */ 4; var RootInProgress = 0; var RootFatalErrored = 1; var RootErrored = 2; var RootSuspended = 3; var RootSuspendedWithDelay = 4; var RootCompleted = 5; var RootDidNotComplete = 6; // Describes where we are in the React execution stack var executionContext = NoContext; // The root we're working on var workInProgressRoot = null; // The fiber we're working on var workInProgress = null; // The lanes we're rendering var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree // This is a superset of the lanes we started working on at the root. The only // case where it's different from `workInProgressRootRenderLanes` is when we // enter a subtree that is hidden and needs to be unhidden: Suspense and // Offscreen component. // // Most things in the work loop should deal with workInProgressRootRenderLanes. // Most things in begin/complete phases should deal with subtreeRenderLanes. var subtreeRenderLanes = NoLanes; var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc. var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's // slightly different than `renderLanes` because `renderLanes` can change as you // enter and exit an Offscreen tree. This value is the combination of all render // lanes for the entire render phase. var workInProgressRootIncludedLanes = NoLanes; // The work left over by components that were visited during this render. Only // includes unprocessed updates, not work in bailed out children. var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render. var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event). var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase. var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI. // We will log them once the tree commits. var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train // model where we don't commit new loading states in too quick succession. var globalMostRecentFallbackTime = 0; var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering // more and prefer CPU suspense heuristics instead. var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU // suspense heuristics and opt out of rendering more content. var RENDER_TIMEOUT_MS = 500; var workInProgressTransitions = null; function resetRenderTimer() { workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS; } function getRenderTargetTime() { return workInProgressRootRenderTargetTime; } var hasUncaughtError = false; var firstUncaughtError = null; var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true; var rootDoesHavePassiveEffects = false; var rootWithPendingPassiveEffects = null; var pendingPassiveEffectsLanes = NoLanes; var pendingPassiveProfilerEffects = []; var pendingPassiveTransitions = null; // Use these to prevent an infinite loop of nested updates var NESTED_UPDATE_LIMIT = 50; var nestedUpdateCount = 0; var rootWithNestedUpdates = null; var isFlushingPassiveEffects = false; var didScheduleUpdateDuringPassiveEffects = false; var NESTED_PASSIVE_UPDATE_LIMIT = 50; var nestedPassiveUpdateCount = 0; var rootWithPassiveNestedUpdates = null; // If two updates are scheduled within the same event, we should treat their // event times as simultaneous, even if the actual clock time has advanced // between the first and second call. var currentEventTime = NoTimestamp; var currentEventTransitionLane = NoLanes; var isRunningInsertionEffect = false; function getWorkInProgressRoot() { return workInProgressRoot; } function requestEventTime() { if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { // We're inside React, so it's fine to read the actual time. return now(); } // We're not inside React, so we may be in the middle of a browser event. if (currentEventTime !== NoTimestamp) { // Use the same start time for all updates until we enter React again. return currentEventTime; } // This is the first update since React yielded. Compute a new start time. currentEventTime = now(); return currentEventTime; } function requestUpdateLane(fiber) { // Special cases var mode = fiber.mode; if ((mode & ConcurrentMode) === NoMode) { return SyncLane; } else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) { // This is a render phase update. These are not officially supported. The // old behavior is to give this the same "thread" (lanes) as // whatever is currently rendering. So if you call `setState` on a component // that happens later in the same render, it will flush. Ideally, we want to // remove the special case and treat them as if they came from an // interleaved event. Regardless, this pattern is not officially supported. // This behavior is only a fallback. The flag only exists until we can roll // out the setState warning, since existing code might accidentally rely on // the current behavior. return pickArbitraryLane(workInProgressRootRenderLanes); } var isTransition = requestCurrentTransition() !== NoTransition; if (isTransition) { if ( ReactCurrentBatchConfig$3.transition !== null) { var transition = ReactCurrentBatchConfig$3.transition; if (!transition._updatedFibers) { transition._updatedFibers = new Set(); } transition._updatedFibers.add(fiber); } // The algorithm for assigning an update to a lane should be stable for all // updates at the same priority within the same event. To do this, the // inputs to the algorithm must be the same. // // The trick we use is to cache the first of each of these inputs within an // event. Then reset the cached values once we can be sure the event is // over. Our heuristic for that is whenever we enter a concurrent work loop. if (currentEventTransitionLane === NoLane) { // All transitions within the same event are assigned the same lane. currentEventTransitionLane = claimNextTransitionLane(); } return currentEventTransitionLane; } // Updates originating inside certain React methods, like flushSync, have // their priority set by tracking it with a context variable. // // The opaque type returned by the host config is internally a lane, so we can // use that directly. // TODO: Move this type conversion to the event priority module. var updateLane = getCurrentUpdatePriority(); if (updateLane !== NoLane) { return updateLane; } // This update originated outside React. Ask the host environment for an // appropriate priority, based on the type of event. // // The opaque type returned by the host config is internally a lane, so we can // use that directly. // TODO: Move this type conversion to the event priority module. var eventLane = getCurrentEventPriority(); return eventLane; } function requestRetryLane(fiber) { // This is a fork of `requestUpdateLane` designed specifically for Suspense // "retries" — a special update that attempts to flip a Suspense boundary // from its placeholder state to its primary/resolved state. // Special cases var mode = fiber.mode; if ((mode & ConcurrentMode) === NoMode) { return SyncLane; } return claimNextRetryLane(); } function scheduleUpdateOnFiber(root, fiber, lane, eventTime) { checkForNestedUpdates(); { if (isRunningInsertionEffect) { error('useInsertionEffect must not schedule updates.'); } } { if (isFlushingPassiveEffects) { didScheduleUpdateDuringPassiveEffects = true; } } // Mark that the root has a pending update. markRootUpdated(root, lane, eventTime); if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) { // This update was dispatched during the render phase. This is a mistake // if the update originates from user space (with the exception of local // hook updates, which are handled differently and don't reach this // function), but there are some internal React features that use this as // an implementation detail, like selective hydration. warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase } else { // This is a normal update, scheduled from outside the render phase. For // example, during an input event. { if (isDevToolsPresent) { addFiberToLanesMap(root, fiber, lane); } } warnIfUpdatesNotWrappedWithActDEV(fiber); if (root === workInProgressRoot) { // Received an update to a tree that's in the middle of rendering. Mark // that there was an interleaved update work on this root. Unless the // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render // phase update. In that case, we don't treat render phase updates as if // they were interleaved, for backwards compat reasons. if ( (executionContext & RenderContext) === NoContext) { workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane); } if (workInProgressRootExitStatus === RootSuspendedWithDelay) { // The root already suspended with a delay, which means this render // definitely won't finish. Since we have a new update, let's mark it as // suspended now, right before marking the incoming update. This has the // effect of interrupting the current render and switching to the update. // TODO: Make sure this doesn't override pings that happen while we've // already started rendering. markRootSuspended$1(root, workInProgressRootRenderLanes); } } ensureRootIsScheduled(root, eventTime); if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. !( ReactCurrentActQueue$1.isBatchingLegacy)) { // Flush the synchronous work now, unless we're already working or inside // a batch. This is intentionally inside scheduleUpdateOnFiber instead of // scheduleCallbackForFiber to preserve the ability to schedule a callback // without immediately flushing it. We only do this for user-initiated // updates, to preserve historical behavior of legacy mode. resetRenderTimer(); flushSyncCallbacksOnlyInLegacyMode(); } } } function scheduleInitialHydrationOnRoot(root, lane, eventTime) { // This is a special fork of scheduleUpdateOnFiber that is only used to // schedule the initial hydration of a root that has just been created. Most // of the stuff in scheduleUpdateOnFiber can be skipped. // // The main reason for this separate path, though, is to distinguish the // initial children from subsequent updates. In fully client-rendered roots // (createRoot instead of hydrateRoot), all top-level renders are modeled as // updates, but hydration roots are special because the initial render must // match what was rendered on the server. var current = root.current; current.lanes = lane; markRootUpdated(root, lane, eventTime); ensureRootIsScheduled(root, eventTime); } function isUnsafeClassRenderPhaseUpdate(fiber) { // Check if this is a render phase update. Only called by class components, // which special (deprecated) behavior for UNSAFE_componentWillReceive props. return (// TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We // decided not to enable it. (executionContext & RenderContext) !== NoContext ); } // Use this function to schedule a task for a root. There's only one task per // root; if a task was already scheduled, we'll check to make sure the priority // of the existing task is the same as the priority of the next level that the // root has work on. This function is called on every update, and right before // exiting a task. function ensureRootIsScheduled(root, currentTime) { var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as // expired so we know to work on those next. markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority. var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); if (nextLanes === NoLanes) { // Special case: There's nothing to work on. if (existingCallbackNode !== null) { cancelCallback$1(existingCallbackNode); } root.callbackNode = null; root.callbackPriority = NoLane; return; } // We use the highest priority lane to represent the priority of the callback. var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it. var existingCallbackPriority = root.callbackPriority; if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a // Scheduler task, rather than an `act` task, cancel it and re-scheduled // on the `act` queue. !( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) { { // If we're going to re-use an existing task, it needs to exist. // Assume that discrete update microtasks are non-cancellable and null. // TODO: Temporary until we confirm this warning is not fired. if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) { error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.'); } } // The priority hasn't changed. We can reuse the existing task. Exit. return; } if (existingCallbackNode != null) { // Cancel the existing callback. We'll schedule a new one below. cancelCallback$1(existingCallbackNode); } // Schedule a new callback. var newCallbackNode; if (newCallbackPriority === SyncLane) { // Special case: Sync React callbacks are scheduled on a special // internal queue if (root.tag === LegacyRoot) { if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) { ReactCurrentActQueue$1.didScheduleLegacyUpdate = true; } scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root)); } else { scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root)); } { // Flush the queue in a microtask. if ( ReactCurrentActQueue$1.current !== null) { // Inside `act`, use our internal `act` queue so that these get flushed // at the end of the current scope even when using the sync version // of `act`. ReactCurrentActQueue$1.current.push(flushSyncCallbacks); } else { scheduleMicrotask(function () { // In Safari, appending an iframe forces microtasks to run. // https://github.com/facebook/react/issues/22459 // We don't support running callbacks in the middle of render // or commit so we need to check against that. if ((executionContext & (RenderContext | CommitContext)) === NoContext) { // Note that this would still prematurely flush the callbacks // if this happens outside render or commit phase (e.g. in an event). flushSyncCallbacks(); } }); } } newCallbackNode = null; } else { var schedulerPriorityLevel; switch (lanesToEventPriority(nextLanes)) { case DiscreteEventPriority: schedulerPriorityLevel = ImmediatePriority; break; case ContinuousEventPriority: schedulerPriorityLevel = UserBlockingPriority; break; case DefaultEventPriority: schedulerPriorityLevel = NormalPriority; break; case IdleEventPriority: schedulerPriorityLevel = IdlePriority; break; default: schedulerPriorityLevel = NormalPriority; break; } newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root)); } root.callbackPriority = newCallbackPriority; root.callbackNode = newCallbackNode; } // This is the entry point for every concurrent task, i.e. anything that // goes through Scheduler. function performConcurrentWorkOnRoot(root, didTimeout) { { resetNestedUpdateFlag(); } // Since we know we're in a React event, we can clear the current // event time. The next update will compute a new event time. currentEventTime = NoTimestamp; currentEventTransitionLane = NoLanes; if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { throw new Error('Should not already be working.'); } // Flush any pending passive effects before deciding which lanes to work on, // in case they schedule additional work. var originalCallbackNode = root.callbackNode; var didFlushPassiveEffects = flushPassiveEffects(); if (didFlushPassiveEffects) { // Something in the passive effect phase may have canceled the current task. // Check if the task node for this root was changed. if (root.callbackNode !== originalCallbackNode) { // The current task was canceled. Exit. We don't need to call // `ensureRootIsScheduled` because the check above implies either that // there's a new task, or that there's no remaining work on this root. return null; } } // Determine the next lanes to work on, using the fields stored // on the root. var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); if (lanes === NoLanes) { // Defensive coding. This is never expected to happen. return null; } // We disable time-slicing in some cases: if the work has been CPU-bound // for too long ("expired" work, to prevent starvation), or we're in // sync-updates-by-default mode. // TODO: We only check `didTimeout` defensively, to account for a Scheduler // bug we're still investigating. Once the bug in Scheduler is fixed, // we can remove this, since we track expiration ourselves. var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout); var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes); if (exitStatus !== RootInProgress) { if (exitStatus === RootErrored) { // If something threw an error, try rendering one more time. We'll // render synchronously to block concurrent data mutations, and we'll // includes all pending updates are included. If it still fails after // the second attempt, we'll give up and commit the resulting tree. var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); if (errorRetryLanes !== NoLanes) { lanes = errorRetryLanes; exitStatus = recoverFromConcurrentError(root, errorRetryLanes); } } if (exitStatus === RootFatalErrored) { var fatalError = workInProgressRootFatalError; prepareFreshStack(root, NoLanes); markRootSuspended$1(root, lanes); ensureRootIsScheduled(root, now()); throw fatalError; } if (exitStatus === RootDidNotComplete) { // The render unwound without completing the tree. This happens in special // cases where need to exit the current render without producing a // consistent tree or committing. // // This should only happen during a concurrent render, not a discrete or // synchronous update. We should have already checked for this when we // unwound the stack. markRootSuspended$1(root, lanes); } else { // The render completed. // Check if this render may have yielded to a concurrent event, and if so, // confirm that any newly rendered stores are consistent. // TODO: It's possible that even a concurrent render may never have yielded // to the main thread, if it was fast enough, or if it expired. We could // skip the consistency check in that case, too. var renderWasConcurrent = !includesBlockingLane(root, lanes); var finishedWork = root.current.alternate; if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) { // A store was mutated in an interleaved event. Render again, // synchronously, to block further mutations. exitStatus = renderRootSync(root, lanes); // We need to check again if something threw if (exitStatus === RootErrored) { var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); if (_errorRetryLanes !== NoLanes) { lanes = _errorRetryLanes; exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any // concurrent events. } } if (exitStatus === RootFatalErrored) { var _fatalError = workInProgressRootFatalError; prepareFreshStack(root, NoLanes); markRootSuspended$1(root, lanes); ensureRootIsScheduled(root, now()); throw _fatalError; } } // We now have a consistent tree. The next step is either to commit it, // or, if something suspended, wait to commit it after a timeout. root.finishedWork = finishedWork; root.finishedLanes = lanes; finishConcurrentRender(root, exitStatus, lanes); } } ensureRootIsScheduled(root, now()); if (root.callbackNode === originalCallbackNode) { // The task node scheduled for this root is the same one that's // currently executed. Need to return a continuation. return performConcurrentWorkOnRoot.bind(null, root); } return null; } function recoverFromConcurrentError(root, errorRetryLanes) { // If an error occurred during hydration, discard server response and fall // back to client side render. // Before rendering again, save the errors from the previous attempt. var errorsFromFirstAttempt = workInProgressRootConcurrentErrors; if (isRootDehydrated(root)) { // The shell failed to hydrate. Set a flag to force a client rendering // during the next attempt. To do this, we call prepareFreshStack now // to create the root work-in-progress fiber. This is a bit weird in terms // of factoring, because it relies on renderRootSync not calling // prepareFreshStack again in the call below, which happens because the // root and lanes haven't changed. // // TODO: I think what we should do is set ForceClientRender inside // throwException, like we do for nested Suspense boundaries. The reason // it's here instead is so we can switch to the synchronous work loop, too. // Something to consider for a future refactor. var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes); rootWorkInProgress.flags |= ForceClientRender; { errorHydratingContainer(root.containerInfo); } } var exitStatus = renderRootSync(root, errorRetryLanes); if (exitStatus !== RootErrored) { // Successfully finished rendering on retry // The errors from the failed first attempt have been recovered. Add // them to the collection of recoverable errors. We'll log them in the // commit phase. var errorsFromSecondAttempt = workInProgressRootRecoverableErrors; workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors // from the first attempt, to preserve the causal sequence. if (errorsFromSecondAttempt !== null) { queueRecoverableErrors(errorsFromSecondAttempt); } } return exitStatus; } function queueRecoverableErrors(errors) { if (workInProgressRootRecoverableErrors === null) { workInProgressRootRecoverableErrors = errors; } else { workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors); } } function finishConcurrentRender(root, exitStatus, lanes) { switch (exitStatus) { case RootInProgress: case RootFatalErrored: { throw new Error('Root did not complete. This is a bug in React.'); } // Flow knows about invariant, so it complains if I add a break // statement, but eslint doesn't know about invariant, so it complains // if I do. eslint-disable-next-line no-fallthrough case RootErrored: { // We should have already attempted to retry this tree. If we reached // this point, it errored again. Commit it. commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); break; } case RootSuspended: { markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we // should immediately commit it or wait a bit. if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope !shouldForceFlushFallbacksInDEV()) { // This render only included retries, no updates. Throttle committing // retries so that we don't show too many loading states too quickly. var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time. if (msUntilTimeout > 10) { var nextLanes = getNextLanes(root, NoLanes); if (nextLanes !== NoLanes) { // There's additional work on this root. break; } var suspendedLanes = root.suspendedLanes; if (!isSubsetOfLanes(suspendedLanes, lanes)) { // We should prefer to render the fallback of at the last // suspended level. Ping the last suspended level to try // rendering it again. // FIXME: What if the suspended lanes are Idle? Should not restart. var eventTime = requestEventTime(); markRootPinged(root, suspendedLanes); break; } // The render is suspended, it hasn't timed out, and there's no // lower priority work to do. Instead of committing the fallback // immediately, wait for more data to arrive. root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout); break; } } // The work expired. Commit immediately. commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); break; } case RootSuspendedWithDelay: { markRootSuspended$1(root, lanes); if (includesOnlyTransitions(lanes)) { // This is a transition, so we should exit without committing a // placeholder and without scheduling a timeout. Delay indefinitely // until we receive more data. break; } if (!shouldForceFlushFallbacksInDEV()) { // This is not a transition, but we did trigger an avoided state. // Schedule a placeholder to display after a short delay, using the Just // Noticeable Difference. // TODO: Is the JND optimization worth the added complexity? If this is // the only reason we track the event time, then probably not. // Consider removing. var mostRecentEventTime = getMostRecentEventTime(root, lanes); var eventTimeMs = mostRecentEventTime; var timeElapsedMs = now() - eventTimeMs; var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time. if (_msUntilTimeout > 10) { // Instead of committing the fallback immediately, wait for more data // to arrive. root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout); break; } } // Commit the placeholder. commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); break; } case RootCompleted: { // The work completed. Ready to commit. commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); break; } default: { throw new Error('Unknown root exit status.'); } } } function isRenderConsistentWithExternalStores(finishedWork) { // Search the rendered tree for external store reads, and check whether the // stores were mutated in a concurrent event. Intentionally using an iterative // loop instead of recursion so we can exit early. var node = finishedWork; while (true) { if (node.flags & StoreConsistency) { var updateQueue = node.updateQueue; if (updateQueue !== null) { var checks = updateQueue.stores; if (checks !== null) { for (var i = 0; i < checks.length; i++) { var check = checks[i]; var getSnapshot = check.getSnapshot; var renderedValue = check.value; try { if (!objectIs(getSnapshot(), renderedValue)) { // Found an inconsistent store. return false; } } catch (error) { // If `getSnapshot` throws, return `false`. This will schedule // a re-render, and the error will be rethrown during render. return false; } } } } } var child = node.child; if (node.subtreeFlags & StoreConsistency && child !== null) { child.return = node; node = child; continue; } if (node === finishedWork) { return true; } while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return true; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } // Flow doesn't know this is unreachable, but eslint does // eslint-disable-next-line no-unreachable return true; } function markRootSuspended$1(root, suspendedLanes) { // When suspending, we should always exclude lanes that were pinged or (more // rarely, since we try to avoid it) updated during the render phase. // TODO: Lol maybe there's a better way to factor this besides this // obnoxiously named function :) suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes); markRootSuspended(root, suspendedLanes); } // This is the entry point for synchronous tasks that don't go // through Scheduler function performSyncWorkOnRoot(root) { { syncNestedUpdateFlag(); } if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { throw new Error('Should not already be working.'); } flushPassiveEffects(); var lanes = getNextLanes(root, NoLanes); if (!includesSomeLane(lanes, SyncLane)) { // There's no remaining sync work left. ensureRootIsScheduled(root, now()); return null; } var exitStatus = renderRootSync(root, lanes); if (root.tag !== LegacyRoot && exitStatus === RootErrored) { // If something threw an error, try rendering one more time. We'll render // synchronously to block concurrent data mutations, and we'll includes // all pending updates are included. If it still fails after the second // attempt, we'll give up and commit the resulting tree. var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root); if (errorRetryLanes !== NoLanes) { lanes = errorRetryLanes; exitStatus = recoverFromConcurrentError(root, errorRetryLanes); } } if (exitStatus === RootFatalErrored) { var fatalError = workInProgressRootFatalError; prepareFreshStack(root, NoLanes); markRootSuspended$1(root, lanes); ensureRootIsScheduled(root, now()); throw fatalError; } if (exitStatus === RootDidNotComplete) { throw new Error('Root did not complete. This is a bug in React.'); } // We now have a consistent tree. Because this is a sync render, we // will commit it even if something suspended. var finishedWork = root.current.alternate; root.finishedWork = finishedWork; root.finishedLanes = lanes; commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); // Before exiting, make sure there's a callback scheduled for the next // pending level. ensureRootIsScheduled(root, now()); return null; } function flushRoot(root, lanes) { if (lanes !== NoLanes) { markRootEntangled(root, mergeLanes(lanes, SyncLane)); ensureRootIsScheduled(root, now()); if ((executionContext & (RenderContext | CommitContext)) === NoContext) { resetRenderTimer(); flushSyncCallbacks(); } } } function batchedUpdates$1(fn, a) { var prevExecutionContext = executionContext; executionContext |= BatchedContext; try { return fn(a); } finally { executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer // most batchedUpdates-like method. if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode. !( ReactCurrentActQueue$1.isBatchingLegacy)) { resetRenderTimer(); flushSyncCallbacksOnlyInLegacyMode(); } } } function discreteUpdates(fn, a, b, c, d) { var previousPriority = getCurrentUpdatePriority(); var prevTransition = ReactCurrentBatchConfig$3.transition; try { ReactCurrentBatchConfig$3.transition = null; setCurrentUpdatePriority(DiscreteEventPriority); return fn(a, b, c, d); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$3.transition = prevTransition; if (executionContext === NoContext) { resetRenderTimer(); } } } // Overload the definition to the two valid signatures. // Warning, this opts-out of checking the function body. // eslint-disable-next-line no-redeclare function flushSync(fn) { // In legacy mode, we flush pending passive effects at the beginning of the // next event, not at the end of the previous one. if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) { flushPassiveEffects(); } var prevExecutionContext = executionContext; executionContext |= BatchedContext; var prevTransition = ReactCurrentBatchConfig$3.transition; var previousPriority = getCurrentUpdatePriority(); try { ReactCurrentBatchConfig$3.transition = null; setCurrentUpdatePriority(DiscreteEventPriority); if (fn) { return fn(); } else { return undefined; } } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$3.transition = prevTransition; executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch. // Note that this will happen even if batchedUpdates is higher up // the stack. if ((executionContext & (RenderContext | CommitContext)) === NoContext) { flushSyncCallbacks(); } } } function isAlreadyRendering() { // Used by the renderer to print a warning if certain APIs are called from // the wrong context. return (executionContext & (RenderContext | CommitContext)) !== NoContext; } function pushRenderLanes(fiber, lanes) { push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber); subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes); workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes); } function popRenderLanes(fiber) { subtreeRenderLanes = subtreeRenderLanesCursor.current; pop(subtreeRenderLanesCursor, fiber); } function prepareFreshStack(root, lanes) { root.finishedWork = null; root.finishedLanes = NoLanes; var timeoutHandle = root.timeoutHandle; if (timeoutHandle !== noTimeout) { // The root previous suspended and scheduled a timeout to commit a fallback // state. Now that we have additional work, cancel the timeout. root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above cancelTimeout(timeoutHandle); } if (workInProgress !== null) { var interruptedWork = workInProgress.return; while (interruptedWork !== null) { var current = interruptedWork.alternate; unwindInterruptedWork(current, interruptedWork); interruptedWork = interruptedWork.return; } } workInProgressRoot = root; var rootWorkInProgress = createWorkInProgress(root.current, null); workInProgress = rootWorkInProgress; workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes; workInProgressRootExitStatus = RootInProgress; workInProgressRootFatalError = null; workInProgressRootSkippedLanes = NoLanes; workInProgressRootInterleavedUpdatedLanes = NoLanes; workInProgressRootPingedLanes = NoLanes; workInProgressRootConcurrentErrors = null; workInProgressRootRecoverableErrors = null; finishQueueingConcurrentUpdates(); { ReactStrictModeWarnings.discardPendingWarnings(); } return rootWorkInProgress; } function handleError(root, thrownValue) { do { var erroredWork = workInProgress; try { // Reset module-level state that was set during the render phase. resetContextDependencies(); resetHooksAfterThrow(); resetCurrentFiber(); // TODO: I found and added this missing line while investigating a // separate issue. Write a regression test using string refs. ReactCurrentOwner$2.current = null; if (erroredWork === null || erroredWork.return === null) { // Expected to be working on a non-root fiber. This is a fatal error // because there's no ancestor that can handle it; the root is // supposed to capture all errors that weren't caught by an error // boundary. workInProgressRootExitStatus = RootFatalErrored; workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next // sibling, or the parent if there are no siblings. But since the root // has no siblings nor a parent, we set it to null. Usually this is // handled by `completeUnitOfWork` or `unwindWork`, but since we're // intentionally not calling those, we need set it here. // TODO: Consider calling `unwindWork` to pop the contexts. workInProgress = null; return; } if (enableProfilerTimer && erroredWork.mode & ProfileMode) { // Record the time spent rendering before an error was thrown. This // avoids inaccurate Profiler durations in the case of a // suspended render. stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true); } if (enableSchedulingProfiler) { markComponentRenderStopped(); if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') { var wakeable = thrownValue; markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes); } else { markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes); } } throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes); completeUnitOfWork(erroredWork); } catch (yetAnotherThrownValue) { // Something in the return path also threw. thrownValue = yetAnotherThrownValue; if (workInProgress === erroredWork && erroredWork !== null) { // If this boundary has already errored, then we had trouble processing // the error. Bubble it to the next boundary. erroredWork = erroredWork.return; workInProgress = erroredWork; } else { erroredWork = workInProgress; } continue; } // Return to the normal work loop. return; } while (true); } function pushDispatcher() { var prevDispatcher = ReactCurrentDispatcher$2.current; ReactCurrentDispatcher$2.current = ContextOnlyDispatcher; if (prevDispatcher === null) { // The React isomorphic package does not include a default dispatcher. // Instead the first renderer will lazily attach one, in order to give // nicer error messages. return ContextOnlyDispatcher; } else { return prevDispatcher; } } function popDispatcher(prevDispatcher) { ReactCurrentDispatcher$2.current = prevDispatcher; } function markCommitTimeOfFallback() { globalMostRecentFallbackTime = now(); } function markSkippedUpdateLanes(lane) { workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes); } function renderDidSuspend() { if (workInProgressRootExitStatus === RootInProgress) { workInProgressRootExitStatus = RootSuspended; } } function renderDidSuspendDelayIfPossible() { if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) { workInProgressRootExitStatus = RootSuspendedWithDelay; } // Check if there are updates that we skipped tree that might have unblocked // this render. if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) { // Mark the current render as suspended so that we switch to working on // the updates that were skipped. Usually we only suspend at the end of // the render phase. // TODO: We should probably always mark the root as suspended immediately // (inside this function), since by suspending at the end of the render // phase introduces a potential mistake where we suspend lanes that were // pinged or updated while we were rendering. markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes); } } function renderDidError(error) { if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { workInProgressRootExitStatus = RootErrored; } if (workInProgressRootConcurrentErrors === null) { workInProgressRootConcurrentErrors = [error]; } else { workInProgressRootConcurrentErrors.push(error); } } // Called during render to determine if anything has suspended. // Returns false if we're not sure. function renderHasNotSuspendedYet() { // If something errored or completed, we can't really be sure, // so those are false. return workInProgressRootExitStatus === RootInProgress; } function renderRootSync(root, lanes) { var prevExecutionContext = executionContext; executionContext |= RenderContext; var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack // and prepare a fresh one. Otherwise we'll continue where we left off. if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { { if (isDevToolsPresent) { var memoizedUpdaters = root.memoizedUpdaters; if (memoizedUpdaters.size > 0) { restorePendingUpdaters(root, workInProgressRootRenderLanes); memoizedUpdaters.clear(); } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. // If we bailout on this work, we'll move them back (like above). // It's important to move them now in case the work spawns more work at the same priority with different updaters. // That way we can keep the current update and future updates separate. movePendingFibersToMemoized(root, lanes); } } workInProgressTransitions = getTransitionsForLanes(); prepareFreshStack(root, lanes); } { markRenderStarted(lanes); } do { try { workLoopSync(); break; } catch (thrownValue) { handleError(root, thrownValue); } } while (true); resetContextDependencies(); executionContext = prevExecutionContext; popDispatcher(prevDispatcher); if (workInProgress !== null) { // This is a sync render, so we should have finished the whole tree. throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.'); } { markRenderStopped(); } // Set this to null to indicate there's no in-progress render. workInProgressRoot = null; workInProgressRootRenderLanes = NoLanes; return workInProgressRootExitStatus; } // The work loop is an extremely hot path. Tell Closure not to inline it. /** @noinline */ function workLoopSync() { // Already timed out, so perform work without checking if we need to yield. while (workInProgress !== null) { performUnitOfWork(workInProgress); } } function renderRootConcurrent(root, lanes) { var prevExecutionContext = executionContext; executionContext |= RenderContext; var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack // and prepare a fresh one. Otherwise we'll continue where we left off. if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) { { if (isDevToolsPresent) { var memoizedUpdaters = root.memoizedUpdaters; if (memoizedUpdaters.size > 0) { restorePendingUpdaters(root, workInProgressRootRenderLanes); memoizedUpdaters.clear(); } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set. // If we bailout on this work, we'll move them back (like above). // It's important to move them now in case the work spawns more work at the same priority with different updaters. // That way we can keep the current update and future updates separate. movePendingFibersToMemoized(root, lanes); } } workInProgressTransitions = getTransitionsForLanes(); resetRenderTimer(); prepareFreshStack(root, lanes); } { markRenderStarted(lanes); } do { try { workLoopConcurrent(); break; } catch (thrownValue) { handleError(root, thrownValue); } } while (true); resetContextDependencies(); popDispatcher(prevDispatcher); executionContext = prevExecutionContext; if (workInProgress !== null) { // Still work remaining. { markRenderYielded(); } return RootInProgress; } else { // Completed the tree. { markRenderStopped(); } // Set this to null to indicate there's no in-progress render. workInProgressRoot = null; workInProgressRootRenderLanes = NoLanes; // Return the final exit status. return workInProgressRootExitStatus; } } /** @noinline */ function workLoopConcurrent() { // Perform work until Scheduler asks us to yield while (workInProgress !== null && !shouldYield()) { performUnitOfWork(workInProgress); } } function performUnitOfWork(unitOfWork) { // The current, flushed, state of this fiber is the alternate. Ideally // nothing should rely on this, but relying on it here means that we don't // need an additional field on the work in progress. var current = unitOfWork.alternate; setCurrentFiber(unitOfWork); var next; if ( (unitOfWork.mode & ProfileMode) !== NoMode) { startProfilerTimer(unitOfWork); next = beginWork$1(current, unitOfWork, subtreeRenderLanes); stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); } else { next = beginWork$1(current, unitOfWork, subtreeRenderLanes); } resetCurrentFiber(); unitOfWork.memoizedProps = unitOfWork.pendingProps; if (next === null) { // If this doesn't spawn new work, complete the current work. completeUnitOfWork(unitOfWork); } else { workInProgress = next; } ReactCurrentOwner$2.current = null; } function completeUnitOfWork(unitOfWork) { // Attempt to complete the current unit of work, then move to the next // sibling. If there are no more siblings, return to the parent fiber. var completedWork = unitOfWork; do { // The current, flushed, state of this fiber is the alternate. Ideally // nothing should rely on this, but relying on it here means that we don't // need an additional field on the work in progress. var current = completedWork.alternate; var returnFiber = completedWork.return; // Check if the work completed or if something threw. if ((completedWork.flags & Incomplete) === NoFlags) { setCurrentFiber(completedWork); var next = void 0; if ( (completedWork.mode & ProfileMode) === NoMode) { next = completeWork(current, completedWork, subtreeRenderLanes); } else { startProfilerTimer(completedWork); next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error. stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); } resetCurrentFiber(); if (next !== null) { // Completing this fiber spawned new work. Work on that next. workInProgress = next; return; } } else { // This fiber did not complete because something threw. Pop values off // the stack without entering the complete phase. If this is a boundary, // capture values if possible. var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes. if (_next !== null) { // If completing this work spawned new work, do that next. We'll come // back here again. // Since we're restarting, remove anything that is not a host effect // from the effect tag. _next.flags &= HostEffectMask; workInProgress = _next; return; } if ( (completedWork.mode & ProfileMode) !== NoMode) { // Record the render duration for the fiber that errored. stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing. var actualDuration = completedWork.actualDuration; var child = completedWork.child; while (child !== null) { actualDuration += child.actualDuration; child = child.sibling; } completedWork.actualDuration = actualDuration; } if (returnFiber !== null) { // Mark the parent fiber as incomplete and clear its subtree flags. returnFiber.flags |= Incomplete; returnFiber.subtreeFlags = NoFlags; returnFiber.deletions = null; } else { // We've unwound all the way to the root. workInProgressRootExitStatus = RootDidNotComplete; workInProgress = null; return; } } var siblingFiber = completedWork.sibling; if (siblingFiber !== null) { // If there is more work to do in this returnFiber, do that next. workInProgress = siblingFiber; return; } // Otherwise, return to the parent completedWork = returnFiber; // Update the next thing we're working on in case something throws. workInProgress = completedWork; } while (completedWork !== null); // We've reached the root. if (workInProgressRootExitStatus === RootInProgress) { workInProgressRootExitStatus = RootCompleted; } } function commitRoot(root, recoverableErrors, transitions) { // TODO: This no longer makes any sense. We already wrap the mutation and // layout phases. Should be able to remove. var previousUpdateLanePriority = getCurrentUpdatePriority(); var prevTransition = ReactCurrentBatchConfig$3.transition; try { ReactCurrentBatchConfig$3.transition = null; setCurrentUpdatePriority(DiscreteEventPriority); commitRootImpl(root, recoverableErrors, transitions, previousUpdateLanePriority); } finally { ReactCurrentBatchConfig$3.transition = prevTransition; setCurrentUpdatePriority(previousUpdateLanePriority); } return null; } function commitRootImpl(root, recoverableErrors, transitions, renderPriorityLevel) { do { // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which // means `flushPassiveEffects` will sometimes result in additional // passive effects. So we need to keep flushing in a loop until there are // no more pending effects. // TODO: Might be better if `flushPassiveEffects` did not automatically // flush synchronous work at the end, to avoid factoring hazards like this. flushPassiveEffects(); } while (rootWithPendingPassiveEffects !== null); flushRenderPhaseStrictModeWarningsInDEV(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { throw new Error('Should not already be working.'); } var finishedWork = root.finishedWork; var lanes = root.finishedLanes; { markCommitStarted(lanes); } if (finishedWork === null) { { markCommitStopped(); } return null; } else { { if (lanes === NoLanes) { error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.'); } } } root.finishedWork = null; root.finishedLanes = NoLanes; if (finishedWork === root.current) { throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.'); } // commitRoot never returns a continuation; it always finishes synchronously. // So we can clear these now to allow a new callback to be scheduled. root.callbackNode = null; root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first // pending time is whatever is left on the root fiber. var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); markRootFinished(root, remainingLanes); if (root === workInProgressRoot) { // We can reset these now that they are finished. workInProgressRoot = null; workInProgress = null; workInProgressRootRenderLanes = NoLanes; } // If there are pending passive effects, schedule a callback to process them. // Do this as early as possible, so it is queued before anything else that // might get scheduled in the commit phase. (See #16714.) // TODO: Delete all other places that schedule the passive effect callback // They're redundant. if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) { if (!rootDoesHavePassiveEffects) { rootDoesHavePassiveEffects = true; // to store it in pendingPassiveTransitions until they get processed // We need to pass this through as an argument to commitRoot // because workInProgressTransitions might have changed between // the previous render and commit if we throttle the commit // with setTimeout pendingPassiveTransitions = transitions; scheduleCallback$1(NormalPriority, function () { flushPassiveEffects(); // This render triggered passive effects: release the root cache pool // *after* passive effects fire to avoid freeing a cache pool that may // be referenced by a node in the tree (HostRoot, Cache boundary etc) return null; }); } } // Check if there are any effects in the whole tree. // TODO: This is left over from the effect list implementation, where we had // to check for the existence of `firstEffect` to satisfy Flow. I think the // only other reason this optimization exists is because it affects profiling. // Reconsider whether this is necessary. var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; if (subtreeHasEffects || rootHasEffect) { var prevTransition = ReactCurrentBatchConfig$3.transition; ReactCurrentBatchConfig$3.transition = null; var previousPriority = getCurrentUpdatePriority(); setCurrentUpdatePriority(DiscreteEventPriority); var prevExecutionContext = executionContext; executionContext |= CommitContext; // Reset this to null before calling lifecycles ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass // of the effect list for each phase: all mutation effects come before all // layout effects, and so on. // The first phase a "before mutation" phase. We use this phase to read the // state of the host tree right before we mutate it. This is where // getSnapshotBeforeUpdate is called. var shouldFireAfterActiveInstanceBlur = commitBeforeMutationEffects(root, finishedWork); { // Mark the current commit time to be shared by all Profilers in this // batch. This enables them to be grouped later. recordCommitTime(); } commitMutationEffects(root, finishedWork, lanes); resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after // the mutation phase, so that the previous tree is still current during // componentWillUnmount, but before the layout phase, so that the finished // work is current during componentDidMount/Update. root.current = finishedWork; // The next phase is the layout phase, where we call effects that read { markLayoutEffectsStarted(lanes); } commitLayoutEffects(finishedWork, root, lanes); { markLayoutEffectsStopped(); } // opportunity to paint. requestPaint(); executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value. setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$3.transition = prevTransition; } else { // No effects. root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were // no effects. // TODO: Maybe there's a better way to report this. { recordCommitTime(); } } var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; if (rootDoesHavePassiveEffects) { // This commit has passive effects. Stash a reference to them. But don't // schedule a callback until after flushing layout work. rootDoesHavePassiveEffects = false; rootWithPendingPassiveEffects = root; pendingPassiveEffectsLanes = lanes; } else { { nestedPassiveUpdateCount = 0; rootWithPassiveNestedUpdates = null; } } // Read this again, since an effect might have updated it remainingLanes = root.pendingLanes; // Check if there's remaining work on this root // TODO: This is part of the `componentDidCatch` implementation. Its purpose // is to detect whether something might have called setState inside // `componentDidCatch`. The mechanism is known to be flawed because `setState` // inside `componentDidCatch` is itself flawed — that's why we recommend // `getDerivedStateFromError` instead. However, it could be improved by // checking if remainingLanes includes Sync work, instead of whether there's // any work remaining at all (which would also include stuff like Suspense // retries or transitions). It's been like this for a while, though, so fixing // it probably isn't that urgent. if (remainingLanes === NoLanes) { // If there's no remaining work, we can clear the set of already failed // error boundaries. legacyErrorBoundariesThatAlreadyFailed = null; } { if (!rootDidHavePassiveEffects) { commitDoubleInvokeEffectsInDEV(root.current, false); } } onCommitRoot(finishedWork.stateNode, renderPriorityLevel); { if (isDevToolsPresent) { root.memoizedUpdaters.clear(); } } { onCommitRoot$1(); } // Always call this before exiting `commitRoot`, to ensure that any // additional work on this root is scheduled. ensureRootIsScheduled(root, now()); if (recoverableErrors !== null) { // There were errors during this render, but recovered from them without // needing to surface it to the UI. We log them here. var onRecoverableError = root.onRecoverableError; for (var i = 0; i < recoverableErrors.length; i++) { var recoverableError = recoverableErrors[i]; var componentStack = recoverableError.stack; var digest = recoverableError.digest; onRecoverableError(recoverableError.value, { componentStack: componentStack, digest: digest }); } } if (hasUncaughtError) { hasUncaughtError = false; var error$1 = firstUncaughtError; firstUncaughtError = null; throw error$1; } // If the passive effects are the result of a discrete render, flush them // synchronously at the end of the current task so that the result is // immediately observable. Otherwise, we assume that they are not // order-dependent and do not need to be observed by external systems, so we // can wait until after paint. // TODO: We can optimize this by not scheduling the callback earlier. Since we // currently schedule the callback in multiple places, will wait until those // are consolidated. if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) { flushPassiveEffects(); } // Read this again, since a passive effect might have updated it remainingLanes = root.pendingLanes; if (includesSomeLane(remainingLanes, SyncLane)) { { markNestedUpdateScheduled(); } // Count the number of times the root synchronously re-renders without // finishing. If there are too many, it indicates an infinite update loop. if (root === rootWithNestedUpdates) { nestedUpdateCount++; } else { nestedUpdateCount = 0; rootWithNestedUpdates = root; } } else { nestedUpdateCount = 0; } // If layout work was scheduled, flush it now. flushSyncCallbacks(); { markCommitStopped(); } return null; } function flushPassiveEffects() { // Returns whether passive effects were flushed. // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should // probably just combine the two functions. I believe they were only separate // in the first place because we used to wrap it with // `Scheduler.runWithPriority`, which accepts a function. But now we track the // priority within React itself, so we can mutate the variable directly. if (rootWithPendingPassiveEffects !== null) { var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); var priority = lowerEventPriority(DefaultEventPriority, renderPriority); var prevTransition = ReactCurrentBatchConfig$3.transition; var previousPriority = getCurrentUpdatePriority(); try { ReactCurrentBatchConfig$3.transition = null; setCurrentUpdatePriority(priority); return flushPassiveEffectsImpl(); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$3.transition = prevTransition; // Once passive effects have run for the tree - giving components a } } return false; } function enqueuePendingPassiveProfilerEffect(fiber) { { pendingPassiveProfilerEffects.push(fiber); if (!rootDoesHavePassiveEffects) { rootDoesHavePassiveEffects = true; scheduleCallback$1(NormalPriority, function () { flushPassiveEffects(); return null; }); } } } function flushPassiveEffectsImpl() { if (rootWithPendingPassiveEffects === null) { return false; } // Cache and clear the transitions flag var transitions = pendingPassiveTransitions; pendingPassiveTransitions = null; var root = rootWithPendingPassiveEffects; var lanes = pendingPassiveEffectsLanes; rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects. // Figure out why and fix it. It's not causing any known issues (probably // because it's only used for profiling), but it's a refactor hazard. pendingPassiveEffectsLanes = NoLanes; if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { throw new Error('Cannot flush passive effects while already rendering.'); } { isFlushingPassiveEffects = true; didScheduleUpdateDuringPassiveEffects = false; } { markPassiveEffectsStarted(lanes); } var prevExecutionContext = executionContext; executionContext |= CommitContext; commitPassiveUnmountEffects(root.current); commitPassiveMountEffects(root, root.current, lanes, transitions); // TODO: Move to commitPassiveMountEffects { var profilerEffects = pendingPassiveProfilerEffects; pendingPassiveProfilerEffects = []; for (var i = 0; i < profilerEffects.length; i++) { var _fiber = profilerEffects[i]; commitPassiveEffectDurations(root, _fiber); } } { markPassiveEffectsStopped(); } { commitDoubleInvokeEffectsInDEV(root.current, true); } executionContext = prevExecutionContext; flushSyncCallbacks(); { // If additional passive effects were scheduled, increment a counter. If this // exceeds the limit, we'll fire a warning. if (didScheduleUpdateDuringPassiveEffects) { if (root === rootWithPassiveNestedUpdates) { nestedPassiveUpdateCount++; } else { nestedPassiveUpdateCount = 0; rootWithPassiveNestedUpdates = root; } } else { nestedPassiveUpdateCount = 0; } isFlushingPassiveEffects = false; didScheduleUpdateDuringPassiveEffects = false; } // TODO: Move to commitPassiveMountEffects onPostCommitRoot(root); { var stateNode = root.current.stateNode; stateNode.effectDuration = 0; stateNode.passiveEffectDuration = 0; } return true; } function isAlreadyFailedLegacyErrorBoundary(instance) { return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); } function markLegacyErrorBoundaryAsFailed(instance) { if (legacyErrorBoundariesThatAlreadyFailed === null) { legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); } else { legacyErrorBoundariesThatAlreadyFailed.add(instance); } } function prepareToThrowUncaughtError(error) { if (!hasUncaughtError) { hasUncaughtError = true; firstUncaughtError = error; } } var onUncaughtError = prepareToThrowUncaughtError; function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) { var errorInfo = createCapturedValueAtFiber(error, sourceFiber); var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane); var root = enqueueUpdate(rootFiber, update, SyncLane); var eventTime = requestEventTime(); if (root !== null) { markRootUpdated(root, SyncLane, eventTime); ensureRootIsScheduled(root, eventTime); } } function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) { { reportUncaughtErrorInDEV(error$1); setIsRunningInsertionEffect(false); } if (sourceFiber.tag === HostRoot) { // Error was thrown at the root. There is no parent, so the root // itself should capture it. captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1); return; } var fiber = null; { fiber = nearestMountedAncestor; } while (fiber !== null) { if (fiber.tag === HostRoot) { captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1); return; } else if (fiber.tag === ClassComponent) { var ctor = fiber.type; var instance = fiber.stateNode; if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) { var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber); var update = createClassErrorUpdate(fiber, errorInfo, SyncLane); var root = enqueueUpdate(fiber, update, SyncLane); var eventTime = requestEventTime(); if (root !== null) { markRootUpdated(root, SyncLane, eventTime); ensureRootIsScheduled(root, eventTime); } return; } } fiber = fiber.return; } { // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning // will fire for errors that are thrown by destroy functions inside deleted // trees. What it should instead do is propagate the error to the parent of // the deleted tree. In the meantime, do not add this warning to the // allowlist; this is only for our internal use. error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1); } } function pingSuspendedRoot(root, wakeable, pingedLanes) { var pingCache = root.pingCache; if (pingCache !== null) { // The wakeable resolved, so we no longer need to memoize, because it will // never be thrown again. pingCache.delete(wakeable); } var eventTime = requestEventTime(); markRootPinged(root, pingedLanes); warnIfSuspenseResolutionNotWrappedWithActDEV(root); if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) { // Received a ping at the same priority level at which we're currently // rendering. We might want to restart this render. This should mirror // the logic of whether or not a root suspends once it completes. // TODO: If we're rendering sync either due to Sync, Batched or expired, // we should probably never restart. // If we're suspended with delay, or if it's a retry, we'll always suspend // so we can always restart. if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) { // Restart from the root. prepareFreshStack(root, NoLanes); } else { // Even though we can't restart right now, we might get an // opportunity later. So we mark this render as having a ping. workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes); } } ensureRootIsScheduled(root, eventTime); } function retryTimedOutBoundary(boundaryFiber, retryLane) { // The boundary fiber (a Suspense component or SuspenseList component) // previously was rendered in its fallback state. One of the promises that // suspended it has resolved, which means at least part of the tree was // likely unblocked. Try rendering again, at a new lanes. if (retryLane === NoLane) { // TODO: Assign this to `suspenseState.retryLane`? to avoid // unnecessary entanglement? retryLane = requestRetryLane(boundaryFiber); } // TODO: Special case idle priority? var eventTime = requestEventTime(); var root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); if (root !== null) { markRootUpdated(root, retryLane, eventTime); ensureRootIsScheduled(root, eventTime); } } function retryDehydratedSuspenseBoundary(boundaryFiber) { var suspenseState = boundaryFiber.memoizedState; var retryLane = NoLane; if (suspenseState !== null) { retryLane = suspenseState.retryLane; } retryTimedOutBoundary(boundaryFiber, retryLane); } function resolveRetryWakeable(boundaryFiber, wakeable) { var retryLane = NoLane; // Default var retryCache; switch (boundaryFiber.tag) { case SuspenseComponent: retryCache = boundaryFiber.stateNode; var suspenseState = boundaryFiber.memoizedState; if (suspenseState !== null) { retryLane = suspenseState.retryLane; } break; case SuspenseListComponent: retryCache = boundaryFiber.stateNode; break; default: throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.'); } if (retryCache !== null) { // The wakeable resolved, so we no longer need to memoize, because it will // never be thrown again. retryCache.delete(wakeable); } retryTimedOutBoundary(boundaryFiber, retryLane); } // Computes the next Just Noticeable Difference (JND) boundary. // The theory is that a person can't tell the difference between small differences in time. // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable // difference in the experience. However, waiting for longer might mean that we can avoid // showing an intermediate loading state. The longer we have already waited, the harder it // is to tell small differences in time. Therefore, the longer we've already waited, // the longer we can wait additionally. At some point we have to give up though. // We pick a train model where the next boundary commits at a consistent schedule. // These particular numbers are vague estimates. We expect to adjust them based on research. function jnd(timeElapsed) { return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960; } function checkForNestedUpdates() { if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { nestedUpdateCount = 0; rootWithNestedUpdates = null; throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.'); } { if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) { nestedPassiveUpdateCount = 0; rootWithPassiveNestedUpdates = null; error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.'); } } } function flushRenderPhaseStrictModeWarningsInDEV() { { ReactStrictModeWarnings.flushLegacyContextWarning(); { ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); } } } function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) { { // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level. // Maybe not a big deal since this is DEV only behavior. setCurrentFiber(fiber); invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV); if (hasPassiveEffects) { invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV); } invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV); if (hasPassiveEffects) { invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV); } resetCurrentFiber(); } } function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) { { // We don't need to re-check StrictEffectsMode here. // This function is only called if that check has already passed. var current = firstChild; var subtreeRoot = null; while (current !== null) { var primarySubtreeFlag = current.subtreeFlags & fiberFlags; if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) { current = current.child; } else { if ((current.flags & fiberFlags) !== NoFlags) { invokeEffectFn(current); } if (current.sibling !== null) { current = current.sibling; } else { current = subtreeRoot = current.return; } } } } } var didWarnStateUpdateForNotYetMountedComponent = null; function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { { if ((executionContext & RenderContext) !== NoContext) { // We let the other warning about render phase updates deal with this one. return; } if (!(fiber.mode & ConcurrentMode)) { return; } var tag = fiber.tag; if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) { // Only warn for user-defined components, not internal ones like Suspense. return; } // We show the whole stack but dedupe on the top component's name because // the problematic code almost always lies inside that component. var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent'; if (didWarnStateUpdateForNotYetMountedComponent !== null) { if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) { return; } didWarnStateUpdateForNotYetMountedComponent.add(componentName); } else { didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]); } var previousFiber = current; try { setCurrentFiber(fiber); error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.'); } finally { if (previousFiber) { setCurrentFiber(fiber); } else { resetCurrentFiber(); } } } } var beginWork$1; { var dummyFiber = null; beginWork$1 = function (current, unitOfWork, lanes) { // If a component throws an error, we replay it again in a synchronously // dispatched event, so that the debugger will treat it as an uncaught // error See ReactErrorUtils for more information. // Before entering the begin phase, copy the work-in-progress onto a dummy // fiber. If beginWork throws, we'll use this to reset the state. var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork); try { return beginWork(current, unitOfWork, lanes); } catch (originalError) { if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') { // Don't replay promises. // Don't replay errors if we are hydrating and have already suspended or handled an error throw originalError; } // Keep this code in sync with handleError; any changes here must have // corresponding changes there. resetContextDependencies(); resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the // same fiber again. // Unwind the failed stack frame unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber. assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); if ( unitOfWork.mode & ProfileMode) { // Reset the profiler timer. startProfilerTimer(unitOfWork); } // Run beginWork again. invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes); if (hasCaughtError()) { var replayError = clearCaughtError(); if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) { // If suppressed, let the flag carry over to the original error which is the one we'll rethrow. originalError._suppressLogging = true; } } // We always throw the original error in case the second render pass is not idempotent. // This can happen if a memoized function or CommonJS module doesn't throw after first invocation. throw originalError; } }; } var didWarnAboutUpdateInRender = false; var didWarnAboutUpdateInRenderForAnotherComponent; { didWarnAboutUpdateInRenderForAnotherComponent = new Set(); } function warnAboutRenderPhaseUpdatesInDEV(fiber) { { if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) { switch (fiber.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed. var dedupeKey = renderingComponentName; if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) { didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey); var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown'; error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName); } break; } case ClassComponent: { if (!didWarnAboutUpdateInRender) { error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.'); didWarnAboutUpdateInRender = true; } break; } } } } } function restorePendingUpdaters(root, lanes) { { if (isDevToolsPresent) { var memoizedUpdaters = root.memoizedUpdaters; memoizedUpdaters.forEach(function (schedulingFiber) { addFiberToLanesMap(root, schedulingFiber, lanes); }); // This function intentionally does not clear memoized updaters. // Those may still be relevant to the current commit // and a future one (e.g. Suspense). } } } var fakeActCallbackNode = {}; function scheduleCallback$1(priorityLevel, callback) { { // If we're currently inside an `act` scope, bypass Scheduler and push to // the `act` queue instead. var actQueue = ReactCurrentActQueue$1.current; if (actQueue !== null) { actQueue.push(callback); return fakeActCallbackNode; } else { return scheduleCallback(priorityLevel, callback); } } } function cancelCallback$1(callbackNode) { if ( callbackNode === fakeActCallbackNode) { return; } // In production, always call Scheduler. This function will be stripped out. return cancelCallback(callbackNode); } function shouldForceFlushFallbacksInDEV() { // Never force flush in production. This function should get stripped out. return ReactCurrentActQueue$1.current !== null; } function warnIfUpdatesNotWrappedWithActDEV(fiber) { { if (fiber.mode & ConcurrentMode) { if (!isConcurrentActEnvironment()) { // Not in an act environment. No need to warn. return; } } else { // Legacy mode has additional cases where we suppress a warning. if (!isLegacyActEnvironment()) { // Not in an act environment. No need to warn. return; } if (executionContext !== NoContext) { // Legacy mode doesn't warn if the update is batched, i.e. // batchedUpdates or flushSync. return; } if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) { // For backwards compatibility with pre-hooks code, legacy mode only // warns for updates that originate from a hook. return; } } if (ReactCurrentActQueue$1.current === null) { var previousFiber = current; try { setCurrentFiber(fiber); error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber)); } finally { if (previousFiber) { setCurrentFiber(fiber); } else { resetCurrentFiber(); } } } } } function warnIfSuspenseResolutionNotWrappedWithActDEV(root) { { if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) { error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + ' /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act'); } } } function setIsRunningInsertionEffect(isRunning) { { isRunningInsertionEffect = isRunning; } } /* eslint-disable react-internal/prod-error-codes */ var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below. var failedBoundaries = null; var setRefreshHandler = function (handler) { { resolveFamily = handler; } }; function resolveFunctionForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } var family = resolveFamily(type); if (family === undefined) { return type; } // Use the latest known implementation. return family.current; } } function resolveClassForHotReloading(type) { // No implementation differences. return resolveFunctionForHotReloading(type); } function resolveForwardRefForHotReloading(type) { { if (resolveFamily === null) { // Hot reloading is disabled. return type; } var family = resolveFamily(type); if (family === undefined) { // Check if we're dealing with a real forwardRef. Don't want to crash early. if (type !== null && type !== undefined && typeof type.render === 'function') { // ForwardRef is special because its resolved .type is an object, // but it's possible that we only have its inner render function in the map. // If that inner render function is different, we'll build a new forwardRef type. var currentRender = resolveFunctionForHotReloading(type.render); if (type.render !== currentRender) { var syntheticType = { $$typeof: REACT_FORWARD_REF_TYPE, render: currentRender }; if (type.displayName !== undefined) { syntheticType.displayName = type.displayName; } return syntheticType; } } return type; } // Use the latest known implementation. return family.current; } } function isCompatibleFamilyForHotReloading(fiber, element) { { if (resolveFamily === null) { // Hot reloading is disabled. return false; } var prevType = fiber.elementType; var nextType = element.type; // If we got here, we know types aren't === equal. var needsCompareFamilies = false; var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null; switch (fiber.tag) { case ClassComponent: { if (typeof nextType === 'function') { needsCompareFamilies = true; } break; } case FunctionComponent: { if (typeof nextType === 'function') { needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { // We don't know the inner type yet. // We're going to assume that the lazy inner type is stable, // and so it is sufficient to avoid reconciling it away. // We're not going to unwrap or actually use the new lazy type. needsCompareFamilies = true; } break; } case ForwardRef: { if ($$typeofNextType === REACT_FORWARD_REF_TYPE) { needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } break; } case MemoComponent: case SimpleMemoComponent: { if ($$typeofNextType === REACT_MEMO_TYPE) { // TODO: if it was but can no longer be simple, // we shouldn't set this. needsCompareFamilies = true; } else if ($$typeofNextType === REACT_LAZY_TYPE) { needsCompareFamilies = true; } break; } default: return false; } // Check if both types have a family and it's the same one. if (needsCompareFamilies) { // Note: memo() and forwardRef() we'll compare outer rather than inner type. // This means both of them need to be registered to preserve state. // If we unwrapped and compared the inner types for wrappers instead, // then we would risk falsely saying two separate memo(Foo) // calls are equivalent because they wrap the same Foo function. var prevFamily = resolveFamily(prevType); if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { return true; } } return false; } } function markFailedErrorBoundaryForHotReloading(fiber) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } if (typeof WeakSet !== 'function') { return; } if (failedBoundaries === null) { failedBoundaries = new WeakSet(); } failedBoundaries.add(fiber); } } var scheduleRefresh = function (root, update) { { if (resolveFamily === null) { // Hot reloading is disabled. return; } var staleFamilies = update.staleFamilies, updatedFamilies = update.updatedFamilies; flushPassiveEffects(); flushSync(function () { scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies); }); } }; var scheduleRoot = function (root, element) { { if (root.context !== emptyContextObject) { // Super edge case: root has a legacy _renderSubtree context // but we don't know the parentComponent so we can't pass it. // Just ignore. We'll delete this with _renderSubtree code path later. return; } flushPassiveEffects(); flushSync(function () { updateContainer(element, root, null, null); }); } }; function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) { { var alternate = fiber.alternate, child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; var candidateType = null; switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; case ForwardRef: candidateType = type.render; break; } if (resolveFamily === null) { throw new Error('Expected resolveFamily to be set during hot reload.'); } var needsRender = false; var needsRemount = false; if (candidateType !== null) { var family = resolveFamily(candidateType); if (family !== undefined) { if (staleFamilies.has(family)) { needsRemount = true; } else if (updatedFamilies.has(family)) { if (tag === ClassComponent) { needsRemount = true; } else { needsRender = true; } } } } if (failedBoundaries !== null) { if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) { needsRemount = true; } } if (needsRemount) { fiber._debugNeedsRemount = true; } if (needsRemount || needsRender) { var _root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (_root !== null) { scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp); } } if (child !== null && !needsRemount) { scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies); } if (sibling !== null) { scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies); } } } var findHostInstancesForRefresh = function (root, families) { { var hostInstances = new Set(); var types = new Set(families.map(function (family) { return family.current; })); findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances); return hostInstances; } }; function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) { { var child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type; var candidateType = null; switch (tag) { case FunctionComponent: case SimpleMemoComponent: case ClassComponent: candidateType = type; break; case ForwardRef: candidateType = type.render; break; } var didMatch = false; if (candidateType !== null) { if (types.has(candidateType)) { didMatch = true; } } if (didMatch) { // We have a match. This only drills down to the closest host components. // There's no need to search deeper because for the purpose of giving // visual feedback, "flashing" outermost parent rectangles is sufficient. findHostInstancesForFiberShallowly(fiber, hostInstances); } else { // If there's no match, maybe there will be one further down in the child tree. if (child !== null) { findHostInstancesForMatchingFibersRecursively(child, types, hostInstances); } } if (sibling !== null) { findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances); } } } function findHostInstancesForFiberShallowly(fiber, hostInstances) { { var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances); if (foundHostInstances) { return; } // If we didn't find any host children, fallback to closest host parent. var node = fiber; while (true) { switch (node.tag) { case HostComponent: hostInstances.add(node.stateNode); return; case HostPortal: hostInstances.add(node.stateNode.containerInfo); return; case HostRoot: hostInstances.add(node.stateNode.containerInfo); return; } if (node.return === null) { throw new Error('Expected to reach root first.'); } node = node.return; } } } function findChildHostInstancesForFiberShallowly(fiber, hostInstances) { { var node = fiber; var foundHostInstances = false; while (true) { if (node.tag === HostComponent) { // We got a match. foundHostInstances = true; hostInstances.add(node.stateNode); // There may still be more, so keep searching. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === fiber) { return foundHostInstances; } while (node.sibling === null) { if (node.return === null || node.return === fiber) { return foundHostInstances; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } } return false; } var hasBadMapPolyfill; { hasBadMapPolyfill = false; try { var nonExtensibleObject = Object.preventExtensions({}); /* eslint-disable no-new */ new Map([[nonExtensibleObject, null]]); new Set([nonExtensibleObject]); /* eslint-enable no-new */ } catch (e) { // TODO: Consider warning about bad polyfills hasBadMapPolyfill = true; } } function FiberNode(tag, pendingProps, key, mode) { // Instance this.tag = tag; this.key = key; this.elementType = null; this.type = null; this.stateNode = null; // Fiber this.return = null; this.child = null; this.sibling = null; this.index = 0; this.ref = null; this.pendingProps = pendingProps; this.memoizedProps = null; this.updateQueue = null; this.memoizedState = null; this.dependencies = null; this.mode = mode; // Effects this.flags = NoFlags; this.subtreeFlags = NoFlags; this.deletions = null; this.lanes = NoLanes; this.childLanes = NoLanes; this.alternate = null; { // Note: The following is done to avoid a v8 performance cliff. // // Initializing the fields below to smis and later updating them with // double values will cause Fibers to end up having separate shapes. // This behavior/bug has something to do with Object.preventExtension(). // Fortunately this only impacts DEV builds. // Unfortunately it makes React unusably slow for some applications. // To work around this, initialize the fields below with doubles. // // Learn more about this here: // https://github.com/facebook/react/issues/14365 // https://bugs.chromium.org/p/v8/issues/detail?id=8538 this.actualDuration = Number.NaN; this.actualStartTime = Number.NaN; this.selfBaseDuration = Number.NaN; this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. // This won't trigger the performance cliff mentioned above, // and it simplifies other profiler code (including DevTools). this.actualDuration = 0; this.actualStartTime = -1; this.selfBaseDuration = 0; this.treeBaseDuration = 0; } { // This isn't directly used but is handy for debugging internals: this._debugSource = null; this._debugOwner = null; this._debugNeedsRemount = false; this._debugHookTypes = null; if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { Object.preventExtensions(this); } } } // This is a constructor function, rather than a POJO constructor, still // please ensure we do the following: // 1) Nobody should add any instance methods on this. Instance methods can be // more difficult to predict when they get optimized and they are almost // never inlined properly in static compilers. // 2) Nobody should rely on `instanceof Fiber` for type testing. We should // always know when it is a fiber. // 3) We might want to experiment with using numeric keys since they are easier // to optimize in a non-JIT environment. // 4) We can easily go from a constructor to a createFiber object literal if that // is faster. // 5) It should be easy to port this to a C struct and keep a C implementation // compatible. var createFiber = function (tag, pendingProps, key, mode) { // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors return new FiberNode(tag, pendingProps, key, mode); }; function shouldConstruct$1(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function isSimpleFunctionComponent(type) { return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined; } function resolveLazyComponentTag(Component) { if (typeof Component === 'function') { return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent; } else if (Component !== undefined && Component !== null) { var $$typeof = Component.$$typeof; if ($$typeof === REACT_FORWARD_REF_TYPE) { return ForwardRef; } if ($$typeof === REACT_MEMO_TYPE) { return MemoComponent; } } return IndeterminateComponent; } // This is used to create an alternate fiber to do work on. function createWorkInProgress(current, pendingProps) { var workInProgress = current.alternate; if (workInProgress === null) { // We use a double buffering pooling technique because we know that we'll // only ever need at most two versions of a tree. We pool the "other" unused // node that we're free to reuse. This is lazily created to avoid allocating // extra objects for things that are never updated. It also allow us to // reclaim the extra memory if needed. workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode); workInProgress.elementType = current.elementType; workInProgress.type = current.type; workInProgress.stateNode = current.stateNode; { // DEV-only fields workInProgress._debugSource = current._debugSource; workInProgress._debugOwner = current._debugOwner; workInProgress._debugHookTypes = current._debugHookTypes; } workInProgress.alternate = current; current.alternate = workInProgress; } else { workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type. workInProgress.type = current.type; // We already have an alternate. // Reset the effect tag. workInProgress.flags = NoFlags; // The effects are no longer valid. workInProgress.subtreeFlags = NoFlags; workInProgress.deletions = null; { // We intentionally reset, rather than copy, actualDuration & actualStartTime. // This prevents time from endlessly accumulating in new commits. // This has the downside of resetting values for different priority renders, // But works for yielding (the common case) and should support resuming. workInProgress.actualDuration = 0; workInProgress.actualStartTime = -1; } } // Reset all effects except static ones. // Static effects are not specific to a render. workInProgress.flags = current.flags & StaticMask; workInProgress.childLanes = current.childLanes; workInProgress.lanes = current.lanes; workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null ? null : { lanes: currentDependencies.lanes, firstContext: currentDependencies.firstContext }; // These will be overridden during the parent's reconciliation workInProgress.sibling = current.sibling; workInProgress.index = current.index; workInProgress.ref = current.ref; { workInProgress.selfBaseDuration = current.selfBaseDuration; workInProgress.treeBaseDuration = current.treeBaseDuration; } { workInProgress._debugNeedsRemount = current._debugNeedsRemount; switch (workInProgress.tag) { case IndeterminateComponent: case FunctionComponent: case SimpleMemoComponent: workInProgress.type = resolveFunctionForHotReloading(current.type); break; case ClassComponent: workInProgress.type = resolveClassForHotReloading(current.type); break; case ForwardRef: workInProgress.type = resolveForwardRefForHotReloading(current.type); break; } } return workInProgress; } // Used to reuse a Fiber for a second pass. function resetWorkInProgress(workInProgress, renderLanes) { // This resets the Fiber to what createFiber or createWorkInProgress would // have set the values to before during the first pass. Ideally this wouldn't // be necessary but unfortunately many code paths reads from the workInProgress // when they should be reading from current and writing to workInProgress. // We assume pendingProps, index, key, ref, return are still untouched to // avoid doing another reconciliation. // Reset the effect flags but keep any Placement tags, since that's something // that child fiber is setting, not the reconciliation. workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid. var current = workInProgress.alternate; if (current === null) { // Reset to createFiber's initial values. workInProgress.childLanes = NoLanes; workInProgress.lanes = renderLanes; workInProgress.child = null; workInProgress.subtreeFlags = NoFlags; workInProgress.memoizedProps = null; workInProgress.memoizedState = null; workInProgress.updateQueue = null; workInProgress.dependencies = null; workInProgress.stateNode = null; { // Note: We don't reset the actualTime counts. It's useful to accumulate // actual time across multiple render passes. workInProgress.selfBaseDuration = 0; workInProgress.treeBaseDuration = 0; } } else { // Reset to the cloned values that createWorkInProgress would've. workInProgress.childLanes = current.childLanes; workInProgress.lanes = current.lanes; workInProgress.child = current.child; workInProgress.subtreeFlags = NoFlags; workInProgress.deletions = null; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type. workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so // it cannot be shared with the current fiber. var currentDependencies = current.dependencies; workInProgress.dependencies = currentDependencies === null ? null : { lanes: currentDependencies.lanes, firstContext: currentDependencies.firstContext }; { // Note: We don't reset the actualTime counts. It's useful to accumulate // actual time across multiple render passes. workInProgress.selfBaseDuration = current.selfBaseDuration; workInProgress.treeBaseDuration = current.treeBaseDuration; } } return workInProgress; } function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) { var mode; if (tag === ConcurrentRoot) { mode = ConcurrentMode; if (isStrictMode === true) { mode |= StrictLegacyMode; { mode |= StrictEffectsMode; } } } else { mode = NoMode; } if ( isDevToolsPresent) { // Always collect profile timings when DevTools are present. // This enables DevTools to start capturing timing at any point– // Without some nodes in the tree having empty base times. mode |= ProfileMode; } return createFiber(HostRoot, null, null, mode); } function createFiberFromTypeAndProps(type, // React$ElementType key, pendingProps, owner, mode, lanes) { var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. var resolvedType = type; if (typeof type === 'function') { if (shouldConstruct$1(type)) { fiberTag = ClassComponent; { resolvedType = resolveClassForHotReloading(resolvedType); } } else { { resolvedType = resolveFunctionForHotReloading(resolvedType); } } } else if (typeof type === 'string') { fiberTag = HostComponent; } else { getTag: switch (type) { case REACT_FRAGMENT_TYPE: return createFiberFromFragment(pendingProps.children, mode, lanes, key); case REACT_STRICT_MODE_TYPE: fiberTag = Mode; mode |= StrictLegacyMode; if ( (mode & ConcurrentMode) !== NoMode) { // Strict effects should never run on legacy roots mode |= StrictEffectsMode; } break; case REACT_PROFILER_TYPE: return createFiberFromProfiler(pendingProps, mode, lanes, key); case REACT_SUSPENSE_TYPE: return createFiberFromSuspense(pendingProps, mode, lanes, key); case REACT_SUSPENSE_LIST_TYPE: return createFiberFromSuspenseList(pendingProps, mode, lanes, key); case REACT_OFFSCREEN_TYPE: return createFiberFromOffscreen(pendingProps, mode, lanes, key); case REACT_LEGACY_HIDDEN_TYPE: // eslint-disable-next-line no-fallthrough case REACT_SCOPE_TYPE: // eslint-disable-next-line no-fallthrough case REACT_CACHE_TYPE: // eslint-disable-next-line no-fallthrough case REACT_TRACING_MARKER_TYPE: // eslint-disable-next-line no-fallthrough case REACT_DEBUG_TRACING_MODE_TYPE: // eslint-disable-next-line no-fallthrough default: { if (typeof type === 'object' && type !== null) { switch (type.$$typeof) { case REACT_PROVIDER_TYPE: fiberTag = ContextProvider; break getTag; case REACT_CONTEXT_TYPE: // This is a consumer fiberTag = ContextConsumer; break getTag; case REACT_FORWARD_REF_TYPE: fiberTag = ForwardRef; { resolvedType = resolveForwardRefForHotReloading(resolvedType); } break getTag; case REACT_MEMO_TYPE: fiberTag = MemoComponent; break getTag; case REACT_LAZY_TYPE: fiberTag = LazyComponent; resolvedType = null; break getTag; } } var info = ''; { if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; } var ownerName = owner ? getComponentNameFromFiber(owner) : null; if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } } throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); } } } var fiber = createFiber(fiberTag, pendingProps, key, mode); fiber.elementType = type; fiber.type = resolvedType; fiber.lanes = lanes; { fiber._debugOwner = owner; } return fiber; } function createFiberFromElement(element, mode, lanes) { var owner = null; { owner = element._owner; } var type = element.type; var key = element.key; var pendingProps = element.props; var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes); { fiber._debugSource = element._source; fiber._debugOwner = element._owner; } return fiber; } function createFiberFromFragment(elements, mode, lanes, key) { var fiber = createFiber(Fragment, elements, key, mode); fiber.lanes = lanes; return fiber; } function createFiberFromProfiler(pendingProps, mode, lanes, key) { { if (typeof pendingProps.id !== 'string') { error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id); } } var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); fiber.elementType = REACT_PROFILER_TYPE; fiber.lanes = lanes; { fiber.stateNode = { effectDuration: 0, passiveEffectDuration: 0 }; } return fiber; } function createFiberFromSuspense(pendingProps, mode, lanes, key) { var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); fiber.elementType = REACT_SUSPENSE_TYPE; fiber.lanes = lanes; return fiber; } function createFiberFromSuspenseList(pendingProps, mode, lanes, key) { var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode); fiber.elementType = REACT_SUSPENSE_LIST_TYPE; fiber.lanes = lanes; return fiber; } function createFiberFromOffscreen(pendingProps, mode, lanes, key) { var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); fiber.elementType = REACT_OFFSCREEN_TYPE; fiber.lanes = lanes; var primaryChildInstance = { isHidden: false }; fiber.stateNode = primaryChildInstance; return fiber; } function createFiberFromText(content, mode, lanes) { var fiber = createFiber(HostText, content, null, mode); fiber.lanes = lanes; return fiber; } function createFiberFromHostInstanceForDeletion() { var fiber = createFiber(HostComponent, null, null, NoMode); fiber.elementType = 'DELETED'; return fiber; } function createFiberFromDehydratedFragment(dehydratedNode) { var fiber = createFiber(DehydratedFragment, null, null, NoMode); fiber.stateNode = dehydratedNode; return fiber; } function createFiberFromPortal(portal, mode, lanes) { var pendingProps = portal.children !== null ? portal.children : []; var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); fiber.lanes = lanes; fiber.stateNode = { containerInfo: portal.containerInfo, pendingChildren: null, // Used by persistent updates implementation: portal.implementation }; return fiber; } // Used for stashing WIP properties to replay failed work in DEV. function assignFiberPropertiesInDEV(target, source) { if (target === null) { // This Fiber's initial properties will always be overwritten. // We only use a Fiber to ensure the same hidden class so DEV isn't slow. target = createFiber(IndeterminateComponent, null, null, NoMode); } // This is intentionally written as a list of all properties. // We tried to use Object.assign() instead but this is called in // the hottest path, and Object.assign() was too slow: // https://github.com/facebook/react/issues/12502 // This code is DEV-only so size is not a concern. target.tag = source.tag; target.key = source.key; target.elementType = source.elementType; target.type = source.type; target.stateNode = source.stateNode; target.return = source.return; target.child = source.child; target.sibling = source.sibling; target.index = source.index; target.ref = source.ref; target.pendingProps = source.pendingProps; target.memoizedProps = source.memoizedProps; target.updateQueue = source.updateQueue; target.memoizedState = source.memoizedState; target.dependencies = source.dependencies; target.mode = source.mode; target.flags = source.flags; target.subtreeFlags = source.subtreeFlags; target.deletions = source.deletions; target.lanes = source.lanes; target.childLanes = source.childLanes; target.alternate = source.alternate; { target.actualDuration = source.actualDuration; target.actualStartTime = source.actualStartTime; target.selfBaseDuration = source.selfBaseDuration; target.treeBaseDuration = source.treeBaseDuration; } target._debugSource = source._debugSource; target._debugOwner = source._debugOwner; target._debugNeedsRemount = source._debugNeedsRemount; target._debugHookTypes = source._debugHookTypes; return target; } function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) { this.tag = tag; this.containerInfo = containerInfo; this.pendingChildren = null; this.current = null; this.pingCache = null; this.finishedWork = null; this.timeoutHandle = noTimeout; this.context = null; this.pendingContext = null; this.callbackNode = null; this.callbackPriority = NoLane; this.eventTimes = createLaneMap(NoLanes); this.expirationTimes = createLaneMap(NoTimestamp); this.pendingLanes = NoLanes; this.suspendedLanes = NoLanes; this.pingedLanes = NoLanes; this.expiredLanes = NoLanes; this.mutableReadLanes = NoLanes; this.finishedLanes = NoLanes; this.entangledLanes = NoLanes; this.entanglements = createLaneMap(NoLanes); this.identifierPrefix = identifierPrefix; this.onRecoverableError = onRecoverableError; { this.mutableSourceEagerHydrationData = null; } { this.effectDuration = 0; this.passiveEffectDuration = 0; } { this.memoizedUpdaters = new Set(); var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = []; for (var _i = 0; _i < TotalLanes; _i++) { pendingUpdatersLaneMap.push(new Set()); } } { switch (tag) { case ConcurrentRoot: this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()'; break; case LegacyRoot: this._debugRootType = hydrate ? 'hydrate()' : 'render()'; break; } } } function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the // host config, but because they are passed in at runtime, we have to thread // them through the root constructor. Perhaps we should put them all into a // single type, like a DynamicHostConfig that is defined by the renderer. identifierPrefix, onRecoverableError, transitionCallbacks) { var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError); // stateNode is any. var uninitializedFiber = createHostRootFiber(tag, isStrictMode); root.current = uninitializedFiber; uninitializedFiber.stateNode = root; { var _initialState = { element: initialChildren, isDehydrated: hydrate, cache: null, // not enabled yet transitions: null, pendingSuspenseBoundaries: null }; uninitializedFiber.memoizedState = _initialState; } initializeUpdateQueue(uninitializedFiber); return root; } var ReactVersion = '18.3.1'; function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation. implementation) { var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; { checkKeyStringCoercion(key); } return { // This tag allow us to uniquely identify this as a React Portal $$typeof: REACT_PORTAL_TYPE, key: key == null ? null : '' + key, children: children, containerInfo: containerInfo, implementation: implementation }; } var didWarnAboutNestedUpdates; var didWarnAboutFindNodeInStrictMode; { didWarnAboutNestedUpdates = false; didWarnAboutFindNodeInStrictMode = {}; } function getContextForSubtree(parentComponent) { if (!parentComponent) { return emptyContextObject; } var fiber = get(parentComponent); var parentContext = findCurrentUnmaskedContext(fiber); if (fiber.tag === ClassComponent) { var Component = fiber.type; if (isContextProvider(Component)) { return processChildContext(fiber, Component, parentContext); } } return parentContext; } function findHostInstanceWithWarning(component, methodName) { { var fiber = get(component); if (fiber === undefined) { if (typeof component.render === 'function') { throw new Error('Unable to find node on an unmounted component.'); } else { var keys = Object.keys(component).join(','); throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys); } } var hostFiber = findCurrentHostFiber(fiber); if (hostFiber === null) { return null; } if (hostFiber.mode & StrictLegacyMode) { var componentName = getComponentNameFromFiber(fiber) || 'Component'; if (!didWarnAboutFindNodeInStrictMode[componentName]) { didWarnAboutFindNodeInStrictMode[componentName] = true; var previousFiber = current; try { setCurrentFiber(hostFiber); if (fiber.mode & StrictLegacyMode) { error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); } else { error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName); } } finally { // Ideally this should reset to previous but this shouldn't be called in // render and there's another warning for that anyway. if (previousFiber) { setCurrentFiber(previousFiber); } else { resetCurrentFiber(); } } } } return hostFiber.stateNode; } } function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { var hydrate = false; var initialChildren = null; return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); } function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode. callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { var hydrate = true; var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from // a regular update because the initial render must match was was rendered // on the server. // NOTE: This update intentionally doesn't have a payload. We're only using // the update to schedule work on the root fiber (and, for legacy roots, to // enqueue the callback if one is provided). var current = root.current; var eventTime = requestEventTime(); var lane = requestUpdateLane(current); var update = createUpdate(eventTime, lane); update.callback = callback !== undefined && callback !== null ? callback : null; enqueueUpdate(current, update, lane); scheduleInitialHydrationOnRoot(root, lane, eventTime); return root; } function updateContainer(element, container, parentComponent, callback) { { onScheduleRoot(container, element); } var current$1 = container.current; var eventTime = requestEventTime(); var lane = requestUpdateLane(current$1); { markRenderScheduled(lane); } var context = getContextForSubtree(parentComponent); if (container.context === null) { container.context = context; } else { container.pendingContext = context; } { if (isRendering && current !== null && !didWarnAboutNestedUpdates) { didWarnAboutNestedUpdates = true; error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown'); } } var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property // being called "element". update.payload = { element: element }; callback = callback === undefined ? null : callback; if (callback !== null) { { if (typeof callback !== 'function') { error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback); } } update.callback = callback; } var root = enqueueUpdate(current$1, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, current$1, lane, eventTime); entangleTransitions(root, current$1, lane); } return lane; } function getPublicRootInstance(container) { var containerFiber = container.current; if (!containerFiber.child) { return null; } switch (containerFiber.child.tag) { case HostComponent: return getPublicInstance(containerFiber.child.stateNode); default: return containerFiber.child.stateNode; } } function attemptSynchronousHydration$1(fiber) { switch (fiber.tag) { case HostRoot: { var root = fiber.stateNode; if (isRootDehydrated(root)) { // Flush the first scheduled "update". var lanes = getHighestPriorityPendingLanes(root); flushRoot(root, lanes); } break; } case SuspenseComponent: { flushSync(function () { var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { var eventTime = requestEventTime(); scheduleUpdateOnFiber(root, fiber, SyncLane, eventTime); } }); // If we're still blocked after this, we need to increase // the priority of any promises resolving within this // boundary so that they next attempt also has higher pri. var retryLane = SyncLane; markRetryLaneIfNotHydrated(fiber, retryLane); break; } } } function markRetryLaneImpl(fiber, retryLane) { var suspenseState = fiber.memoizedState; if (suspenseState !== null && suspenseState.dehydrated !== null) { suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane); } } // Increases the priority of thenables when they resolve within this boundary. function markRetryLaneIfNotHydrated(fiber, retryLane) { markRetryLaneImpl(fiber, retryLane); var alternate = fiber.alternate; if (alternate) { markRetryLaneImpl(alternate, retryLane); } } function attemptContinuousHydration$1(fiber) { if (fiber.tag !== SuspenseComponent) { // We ignore HostRoots here because we can't increase // their priority and they should not suspend on I/O, // since you have to wrap anything that might suspend in // Suspense. return; } var lane = SelectiveHydrationLane; var root = enqueueConcurrentRenderForLane(fiber, lane); if (root !== null) { var eventTime = requestEventTime(); scheduleUpdateOnFiber(root, fiber, lane, eventTime); } markRetryLaneIfNotHydrated(fiber, lane); } function attemptHydrationAtCurrentPriority$1(fiber) { if (fiber.tag !== SuspenseComponent) { // We ignore HostRoots here because we can't increase // their priority other than synchronously flush it. return; } var lane = requestUpdateLane(fiber); var root = enqueueConcurrentRenderForLane(fiber, lane); if (root !== null) { var eventTime = requestEventTime(); scheduleUpdateOnFiber(root, fiber, lane, eventTime); } markRetryLaneIfNotHydrated(fiber, lane); } function findHostInstanceWithNoPortals(fiber) { var hostFiber = findCurrentHostFiberWithNoPortals(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; } var shouldErrorImpl = function (fiber) { return null; }; function shouldError(fiber) { return shouldErrorImpl(fiber); } var shouldSuspendImpl = function (fiber) { return false; }; function shouldSuspend(fiber) { return shouldSuspendImpl(fiber); } var overrideHookState = null; var overrideHookStateDeletePath = null; var overrideHookStateRenamePath = null; var overrideProps = null; var overridePropsDeletePath = null; var overridePropsRenamePath = null; var scheduleUpdate = null; var setErrorHandler = null; var setSuspenseHandler = null; { var copyWithDeleteImpl = function (obj, path, index) { var key = path[index]; var updated = isArray(obj) ? obj.slice() : assign({}, obj); if (index + 1 === path.length) { if (isArray(updated)) { updated.splice(key, 1); } else { delete updated[key]; } return updated; } // $FlowFixMe number or string is fine here updated[key] = copyWithDeleteImpl(obj[key], path, index + 1); return updated; }; var copyWithDelete = function (obj, path) { return copyWithDeleteImpl(obj, path, 0); }; var copyWithRenameImpl = function (obj, oldPath, newPath, index) { var oldKey = oldPath[index]; var updated = isArray(obj) ? obj.slice() : assign({}, obj); if (index + 1 === oldPath.length) { var newKey = newPath[index]; // $FlowFixMe number or string is fine here updated[newKey] = updated[oldKey]; if (isArray(updated)) { updated.splice(oldKey, 1); } else { delete updated[oldKey]; } } else { // $FlowFixMe number or string is fine here updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here obj[oldKey], oldPath, newPath, index + 1); } return updated; }; var copyWithRename = function (obj, oldPath, newPath) { if (oldPath.length !== newPath.length) { warn('copyWithRename() expects paths of the same length'); return; } else { for (var i = 0; i < newPath.length - 1; i++) { if (oldPath[i] !== newPath[i]) { warn('copyWithRename() expects paths to be the same except for the deepest key'); return; } } } return copyWithRenameImpl(obj, oldPath, newPath, 0); }; var copyWithSetImpl = function (obj, path, index, value) { if (index >= path.length) { return value; } var key = path[index]; var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here updated[key] = copyWithSetImpl(obj[key], path, index + 1, value); return updated; }; var copyWithSet = function (obj, path, value) { return copyWithSetImpl(obj, path, 0, value); }; var findHook = function (fiber, id) { // For now, the "id" of stateful hooks is just the stateful hook index. // This may change in the future with e.g. nested hooks. var currentHook = fiber.memoizedState; while (currentHook !== null && id > 0) { currentHook = currentHook.next; id--; } return currentHook; }; // Support DevTools editable values for useState and useReducer. overrideHookState = function (fiber, id, path, value) { var hook = findHook(fiber, id); if (hook !== null) { var newState = copyWithSet(hook.memoizedState, path, value); hook.memoizedState = newState; hook.baseState = newState; // We aren't actually adding an update to the queue, // because there is no update we can add for useReducer hooks that won't trigger an error. // (There's no appropriate action type for DevTools overrides.) // As a result though, React will see the scheduled update as a noop and bailout. // Shallow cloning props works as a workaround for now to bypass the bailout check. fiber.memoizedProps = assign({}, fiber.memoizedProps); var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } } }; overrideHookStateDeletePath = function (fiber, id, path) { var hook = findHook(fiber, id); if (hook !== null) { var newState = copyWithDelete(hook.memoizedState, path); hook.memoizedState = newState; hook.baseState = newState; // We aren't actually adding an update to the queue, // because there is no update we can add for useReducer hooks that won't trigger an error. // (There's no appropriate action type for DevTools overrides.) // As a result though, React will see the scheduled update as a noop and bailout. // Shallow cloning props works as a workaround for now to bypass the bailout check. fiber.memoizedProps = assign({}, fiber.memoizedProps); var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } } }; overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) { var hook = findHook(fiber, id); if (hook !== null) { var newState = copyWithRename(hook.memoizedState, oldPath, newPath); hook.memoizedState = newState; hook.baseState = newState; // We aren't actually adding an update to the queue, // because there is no update we can add for useReducer hooks that won't trigger an error. // (There's no appropriate action type for DevTools overrides.) // As a result though, React will see the scheduled update as a noop and bailout. // Shallow cloning props works as a workaround for now to bypass the bailout check. fiber.memoizedProps = assign({}, fiber.memoizedProps); var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } } }; // Support DevTools props for function components, forwardRef, memo, host components, etc. overrideProps = function (fiber, path, value) { fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } }; overridePropsDeletePath = function (fiber, path) { fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } }; overridePropsRenamePath = function (fiber, oldPath, newPath) { fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } }; scheduleUpdate = function (fiber) { var root = enqueueConcurrentRenderForLane(fiber, SyncLane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp); } }; setErrorHandler = function (newShouldErrorImpl) { shouldErrorImpl = newShouldErrorImpl; }; setSuspenseHandler = function (newShouldSuspendImpl) { shouldSuspendImpl = newShouldSuspendImpl; }; } function findHostInstanceByFiber(fiber) { var hostFiber = findCurrentHostFiber(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; } function emptyFindFiberByHostInstance(instance) { return null; } function getCurrentFiberForDevTools() { return current; } function injectIntoDevTools(devToolsConfig) { var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; return injectInternals({ bundleType: devToolsConfig.bundleType, version: devToolsConfig.version, rendererPackageName: devToolsConfig.rendererPackageName, rendererConfig: devToolsConfig.rendererConfig, overrideHookState: overrideHookState, overrideHookStateDeletePath: overrideHookStateDeletePath, overrideHookStateRenamePath: overrideHookStateRenamePath, overrideProps: overrideProps, overridePropsDeletePath: overridePropsDeletePath, overridePropsRenamePath: overridePropsRenamePath, setErrorHandler: setErrorHandler, setSuspenseHandler: setSuspenseHandler, scheduleUpdate: scheduleUpdate, currentDispatcherRef: ReactCurrentDispatcher, findHostInstanceByFiber: findHostInstanceByFiber, findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance, // React Refresh findHostInstancesForRefresh: findHostInstancesForRefresh , scheduleRefresh: scheduleRefresh , scheduleRoot: scheduleRoot , setRefreshHandler: setRefreshHandler , // Enables DevTools to append owner stacks to error messages in DEV mode. getCurrentFiber: getCurrentFiberForDevTools , // Enables DevTools to detect reconciler version rather than renderer version // which may not match for third party renderers. reconcilerVersion: ReactVersion }); } /* global reportError */ var defaultOnRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event, // emulating an uncaught JavaScript error. reportError : function (error) { // In older browsers and test environments, fallback to console.error. // eslint-disable-next-line react-internal/no-production-logging console['error'](error); }; function ReactDOMRoot(internalRoot) { this._internalRoot = internalRoot; } ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function (children) { var root = this._internalRoot; if (root === null) { throw new Error('Cannot update an unmounted root.'); } { if (typeof arguments[1] === 'function') { error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().'); } else if (isValidContainer(arguments[1])) { error('You passed a container to the second argument of root.render(...). ' + "You don't need to pass it again since you already passed it to create the root."); } else if (typeof arguments[1] !== 'undefined') { error('You passed a second argument to root.render(...) but it only accepts ' + 'one argument.'); } var container = root.containerInfo; if (container.nodeType !== COMMENT_NODE) { var hostInstance = findHostInstanceWithNoPortals(root.current); if (hostInstance) { if (hostInstance.parentNode !== container) { error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container."); } } } } updateContainer(children, root, null, null); }; ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function () { { if (typeof arguments[0] === 'function') { error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().'); } } var root = this._internalRoot; if (root !== null) { this._internalRoot = null; var container = root.containerInfo; { if (isAlreadyRendering()) { error('Attempted to synchronously unmount a root while React was already ' + 'rendering. React cannot finish unmounting the root until the ' + 'current render has completed, which may lead to a race condition.'); } } flushSync(function () { updateContainer(null, root, null, null); }); unmarkContainerAsRoot(container); } }; function createRoot(container, options) { if (!isValidContainer(container)) { throw new Error('createRoot(...): Target container is not a DOM element.'); } warnIfReactDOMContainerInDEV(container); var isStrictMode = false; var concurrentUpdatesByDefaultOverride = false; var identifierPrefix = ''; var onRecoverableError = defaultOnRecoverableError; var transitionCallbacks = null; if (options !== null && options !== undefined) { { if (options.hydrate) { warn('hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead.'); } else { if (typeof options === 'object' && options !== null && options.$$typeof === REACT_ELEMENT_TYPE) { error('You passed a JSX element to createRoot. You probably meant to ' + 'call root.render instead. ' + 'Example usage:\n\n' + ' let root = createRoot(domContainer);\n' + ' root.render(<App />);'); } } } if (options.unstable_strictMode === true) { isStrictMode = true; } if (options.identifierPrefix !== undefined) { identifierPrefix = options.identifierPrefix; } if (options.onRecoverableError !== undefined) { onRecoverableError = options.onRecoverableError; } if (options.transitionCallbacks !== undefined) { transitionCallbacks = options.transitionCallbacks; } } var root = createContainer(container, ConcurrentRoot, null, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); markContainerAsRoot(root.current, container); var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; listenToAllSupportedEvents(rootContainerElement); return new ReactDOMRoot(root); } function ReactDOMHydrationRoot(internalRoot) { this._internalRoot = internalRoot; } function scheduleHydration(target) { if (target) { queueExplicitHydrationTarget(target); } } ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = scheduleHydration; function hydrateRoot(container, initialChildren, options) { if (!isValidContainer(container)) { throw new Error('hydrateRoot(...): Target container is not a DOM element.'); } warnIfReactDOMContainerInDEV(container); { if (initialChildren === undefined) { error('Must provide initial children as second argument to hydrateRoot. ' + 'Example usage: hydrateRoot(domContainer, <App />)'); } } // For now we reuse the whole bag of options since they contain // the hydration callbacks. var hydrationCallbacks = options != null ? options : null; // TODO: Delete this option var mutableSources = options != null && options.hydratedSources || null; var isStrictMode = false; var concurrentUpdatesByDefaultOverride = false; var identifierPrefix = ''; var onRecoverableError = defaultOnRecoverableError; if (options !== null && options !== undefined) { if (options.unstable_strictMode === true) { isStrictMode = true; } if (options.identifierPrefix !== undefined) { identifierPrefix = options.identifierPrefix; } if (options.onRecoverableError !== undefined) { onRecoverableError = options.onRecoverableError; } } var root = createHydrationContainer(initialChildren, null, container, ConcurrentRoot, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); markContainerAsRoot(root.current, container); // This can't be a comment node since hydration doesn't work on comment nodes anyway. listenToAllSupportedEvents(container); if (mutableSources) { for (var i = 0; i < mutableSources.length; i++) { var mutableSource = mutableSources[i]; registerMutableSourceForHydration(root, mutableSource); } } return new ReactDOMHydrationRoot(root); } function isValidContainer(node) { return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || !disableCommentsAsDOMContainers )); } // TODO: Remove this function which also includes comment nodes. // We only use it in places that are currently more relaxed. function isValidContainerLegacy(node) { return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable ')); } function warnIfReactDOMContainerInDEV(container) { { if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') { error('createRoot(): Creating roots directly with document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try using a container element created ' + 'for your app.'); } if (isContainerMarkedAsRoot(container)) { if (container._reactRootContainer) { error('You are calling ReactDOMClient.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.'); } else { error('You are calling ReactDOMClient.createRoot() on a container that ' + 'has already been passed to createRoot() before. Instead, call ' + 'root.render() on the existing root instead if you want to update it.'); } } } } var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner; var topLevelUpdateWarnings; { topLevelUpdateWarnings = function (container) { if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) { var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer.current); if (hostInstance) { if (hostInstance.parentNode !== container) { error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.'); } } } var isRootRenderedBySomeReact = !!container._reactRootContainer; var rootEl = getReactRootElementInContainer(container); var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl)); if (hasNonRootReactChild && !isRootRenderedBySomeReact) { error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.'); } if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') { error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.'); } }; } function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOCUMENT_NODE) { return container.documentElement; } else { return container.firstChild; } } function noopOnRecoverableError() {// This isn't reachable because onRecoverableError isn't called in the // legacy API. } function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) { if (isHydrationContainer) { if (typeof callback === 'function') { var originalCallback = callback; callback = function () { var instance = getPublicRootInstance(root); originalCallback.call(instance); }; } var root = createHydrationContainer(initialChildren, callback, container, LegacyRoot, null, // hydrationCallbacks false, // isStrictMode false, // concurrentUpdatesByDefaultOverride, '', // identifierPrefix noopOnRecoverableError); container._reactRootContainer = root; markContainerAsRoot(root.current, container); var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; listenToAllSupportedEvents(rootContainerElement); flushSync(); return root; } else { // First clear any existing content. var rootSibling; while (rootSibling = container.lastChild) { container.removeChild(rootSibling); } if (typeof callback === 'function') { var _originalCallback = callback; callback = function () { var instance = getPublicRootInstance(_root); _originalCallback.call(instance); }; } var _root = createContainer(container, LegacyRoot, null, // hydrationCallbacks false, // isStrictMode false, // concurrentUpdatesByDefaultOverride, '', // identifierPrefix noopOnRecoverableError); container._reactRootContainer = _root; markContainerAsRoot(_root.current, container); var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; listenToAllSupportedEvents(_rootContainerElement); // Initial mount should not be batched. flushSync(function () { updateContainer(initialChildren, _root, parentComponent, callback); }); return _root; } } function warnOnInvalidCallback$1(callback, callerName) { { if (callback !== null && typeof callback !== 'function') { error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); } } } function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) { { topLevelUpdateWarnings(container); warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render'); } var maybeRoot = container._reactRootContainer; var root; if (!maybeRoot) { // Initial mount root = legacyCreateRootFromDOMContainer(container, children, parentComponent, callback, forceHydrate); } else { root = maybeRoot; if (typeof callback === 'function') { var originalCallback = callback; callback = function () { var instance = getPublicRootInstance(root); originalCallback.call(instance); }; } // Update updateContainer(children, root, parentComponent, callback); } return getPublicRootInstance(root); } var didWarnAboutFindDOMNode = false; function findDOMNode(componentOrElement) { { if (!didWarnAboutFindDOMNode) { didWarnAboutFindDOMNode = true; error('findDOMNode is deprecated and will be removed in the next major ' + 'release. Instead, add a ref directly to the element you want ' + 'to reference. Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node'); } var owner = ReactCurrentOwner$3.current; if (owner !== null && owner.stateNode !== null) { var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender; if (!warnedAboutRefsInRender) { error('%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromType(owner.type) || 'A component'); } owner.stateNode._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === ELEMENT_NODE) { return componentOrElement; } { return findHostInstanceWithWarning(componentOrElement, 'findDOMNode'); } } function hydrate(element, container, callback) { { error('ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot'); } if (!isValidContainerLegacy(container)) { throw new Error('Target container is not a DOM element.'); } { var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; if (isModernRoot) { error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call hydrateRoot(container, element)?'); } } // TODO: throw or warn if we couldn't hydrate? return legacyRenderSubtreeIntoContainer(null, element, container, true, callback); } function render(element, container, callback) { { error('ReactDOM.render is no longer supported in React 18. Use createRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot'); } if (!isValidContainerLegacy(container)) { throw new Error('Target container is not a DOM element.'); } { var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; if (isModernRoot) { error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?'); } } return legacyRenderSubtreeIntoContainer(null, element, container, false, callback); } function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) { { error('ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported ' + 'in React 18. Consider using a portal instead. Until you switch to ' + "the createRoot API, your app will behave as if it's running React " + '17. Learn more: https://reactjs.org/link/switch-to-createroot'); } if (!isValidContainerLegacy(containerNode)) { throw new Error('Target container is not a DOM element.'); } if (parentComponent == null || !has(parentComponent)) { throw new Error('parentComponent must be a valid React Component'); } return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback); } var didWarnAboutUnmountComponentAtNode = false; function unmountComponentAtNode(container) { { if (!didWarnAboutUnmountComponentAtNode) { didWarnAboutUnmountComponentAtNode = true; error('unmountComponentAtNode is deprecated and will be removed in the ' + 'next major release. Switch to the createRoot API. Learn ' + 'more: https://reactjs.org/link/switch-to-createroot'); } } if (!isValidContainerLegacy(container)) { throw new Error('unmountComponentAtNode(...): Target container is not a DOM element.'); } { var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; if (isModernRoot) { error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?'); } } if (container._reactRootContainer) { { var rootEl = getReactRootElementInContainer(container); var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl); if (renderedByDifferentReact) { error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.'); } } // Unmount should not be batched. flushSync(function () { legacyRenderSubtreeIntoContainer(null, null, container, false, function () { // $FlowFixMe This should probably use `delete container._reactRootContainer` container._reactRootContainer = null; unmarkContainerAsRoot(container); }); }); // If you call unmountComponentAtNode twice in quick succession, you'll // get `true` twice. That's probably fine? return true; } else { { var _rootEl = getReactRootElementInContainer(container); var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl)); // Check if the container itself is a React root node. var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainerLegacy(container.parentNode) && !!container.parentNode._reactRootContainer; if (hasNonRootReactChild) { error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.'); } } return false; } } setAttemptSynchronousHydration(attemptSynchronousHydration$1); setAttemptContinuousHydration(attemptContinuousHydration$1); setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1); setGetCurrentUpdatePriority(getCurrentUpdatePriority); setAttemptHydrationAtPriority(runWithPriority); { if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') { error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills'); } } setRestoreImplementation(restoreControlledState$3); setBatchingImplementation(batchedUpdates$1, discreteUpdates, flushSync); function createPortal$1(children, container) { var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; if (!isValidContainer(container)) { throw new Error('Target container is not a DOM element.'); } // TODO: pass ReactDOM portal implementation as third argument // $FlowFixMe The Flow type is opaque but there's no way to actually create it. return createPortal(children, container, null, key); } function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) { return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback); } var Internals = { usingClientEntryPoint: false, // Keep in sync with ReactTestUtils.js. // This is an array for better minification. Events: [getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, enqueueStateRestore, restoreStateIfNeeded, batchedUpdates$1] }; function createRoot$1(container, options) { { if (!Internals.usingClientEntryPoint && !true) { error('You are importing createRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".'); } } return createRoot(container, options); } function hydrateRoot$1(container, initialChildren, options) { { if (!Internals.usingClientEntryPoint && !true) { error('You are importing hydrateRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".'); } } return hydrateRoot(container, initialChildren, options); } // Overload the definition to the two valid signatures. // Warning, this opts-out of checking the function body. // eslint-disable-next-line no-redeclare function flushSync$1(fn) { { if (isAlreadyRendering()) { error('flushSync was called from inside a lifecycle method. React cannot ' + 'flush when React is already rendering. Consider moving this call to ' + 'a scheduler task or micro task.'); } } return flushSync(fn); } var foundDevTools = injectIntoDevTools({ findFiberByHostInstance: getClosestInstanceFromNode, bundleType: 1 , version: ReactVersion, rendererPackageName: 'react-dom' }); { if (!foundDevTools && canUseDOM && window.top === window.self) { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://. if (/^(https?|file):$/.test(protocol)) { // eslint-disable-next-line react-internal/no-production-logging console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://reactjs.org/link/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://reactjs.org/link/react-devtools-faq' : ''), 'font-weight:bold'); } } } } exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals; exports.createPortal = createPortal$1; exports.createRoot = createRoot$1; exports.findDOMNode = findDOMNode; exports.flushSync = flushSync$1; exports.hydrate = hydrate; exports.hydrateRoot = hydrateRoot$1; exports.render = render; exports.unmountComponentAtNode = unmountComponentAtNode; exports.unstable_batchedUpdates = batchedUpdates$1; exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer; exports.version = ReactVersion; }))); react-jsx-runtime.min.js.LICENSE.txt 0000644 00000000371 14720015030 0013135 0 ustar 00 /** * @license React * react-jsx-runtime.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. */ wp-polyfill-dom-rect.min.js 0000644 00000001541 14720015030 0011643 0 ustar 00 !function(){function e(e){return void 0===e?0:Number(e)}function n(e,n){return!(e===n||isNaN(e)&&isNaN(n))}self.DOMRect=function(t,i,u,r){var o,f,c,a,m=e(t),b=e(i),d=e(u),g=e(r);Object.defineProperties(this,{x:{get:function(){return m},set:function(e){n(m,e)&&(m=e,o=f=void 0)},enumerable:!0},y:{get:function(){return b},set:function(e){n(b,e)&&(b=e,c=a=void 0)},enumerable:!0},width:{get:function(){return d},set:function(e){n(d,e)&&(d=e,o=f=void 0)},enumerable:!0},height:{get:function(){return g},set:function(e){n(g,e)&&(g=e,c=a=void 0)},enumerable:!0},left:{get:function(){return o=void 0===o?m+Math.min(0,d):o},enumerable:!0},right:{get:function(){return f=void 0===f?m+Math.max(0,d):f},enumerable:!0},top:{get:function(){return c=void 0===c?b+Math.min(0,g):c},enumerable:!0},bottom:{get:function(){return a=void 0===a?b+Math.max(0,g):a},enumerable:!0}})}}(); react.js 0000604 00000326553 14720015030 0006202 0 ustar 00 /** * @license React * react.development.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. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.React = {})); }(this, (function (exports) { 'use strict'; var ReactVersion = '18.3.1'; // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. var REACT_ELEMENT_TYPE = Symbol.for('react.element'); var REACT_PORTAL_TYPE = Symbol.for('react.portal'); var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); var REACT_CONTEXT_TYPE = Symbol.for('react.context'); var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); var REACT_MEMO_TYPE = Symbol.for('react.memo'); var REACT_LAZY_TYPE = Symbol.for('react.lazy'); var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen'); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } /** * Keeps track of the current dispatcher. */ var ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: null }; /** * Keeps track of the current batch's configuration such as how long an update * should suspend for if it needs to. */ var ReactCurrentBatchConfig = { transition: null }; var ReactCurrentActQueue = { current: null, // Used to reproduce behavior of `batchedUpdates` in legacy mode. isBatchingLegacy: false, didScheduleLegacyUpdate: false }; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; var ReactDebugCurrentFrame = {}; var currentExtraStackFrame = null; function setExtraStackFrame(stack) { { currentExtraStackFrame = stack; } } { ReactDebugCurrentFrame.setExtraStackFrame = function (stack) { { currentExtraStackFrame = stack; } }; // Stack implementation injected by the current renderer. ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function () { var stack = ''; // Add an extra top frame while an element is being validated if (currentExtraStackFrame) { stack += currentExtraStackFrame; } // Delegate to the injected renderer-specific implementation var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ''; } return stack; }; } // ----------------------------------------------------------------------------- var enableScopeAPI = false; // Experimental Create Event Handle API. var enableCacheElement = false; var enableTransitionTracing = false; // No known bugs, but needs performance testing var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber // stuff. Intended to enable React core members to more easily debug scheduling // issues in DEV builds. var enableDebugTracing = false; // Track which Fiber(s) schedule render work. var ReactSharedInternals = { ReactCurrentDispatcher: ReactCurrentDispatcher, ReactCurrentBatchConfig: ReactCurrentBatchConfig, ReactCurrentOwner: ReactCurrentOwner }; { ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; } // by calls to these methods by a Babel plugin. // // In PROD (or in packages without access to React internals), // they are left as they are instead. function warn(format) { { { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning('warn', format, args); } } } function error(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } // eslint-disable-next-line react-internal/safe-string-coercion var argsWithFormat = args.map(function (item) { return String(item); }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } } var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; var warningKey = componentName + "." + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function (publicInstance, callback, callerName) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function (publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, 'setState'); } }; var assign = Object.assign; var emptyObject = {}; { Object.freeze(emptyObject); } /** * Base class helpers for the updating state of a component. */ function Component(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ Component.prototype.setState = function (partialState, callback) { if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) { throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.'); } this.updater.enqueueSetState(this, partialState, callback, 'setState'); }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ Component.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function () { warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); return undefined; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() {} ComponentDummy.prototype = Component.prototype; /** * Convenience component with default shallow equality check for sCU. */ function PureComponent(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; // an immutable object with a single mutable value function createRef() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare function isArray(a) { return isArrayImpl(a); } /* * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol * and Temporal.* types. See https://github.com/facebook/react/pull/22064. * * The functions in this module will throw an easier-to-understand, * easier-to-debug exception with a clear errors message message explaining the * problem. (Instead of a confusing exception thrown inside the implementation * of the `value` object). */ // $FlowFixMe only called in DEV, so void return is not possible. function typeName(value) { { // toStringTag is needed for namespaced types like Temporal.Instant var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; return type; } } // $FlowFixMe only called in DEV, so void return is not possible. function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { // If you ended up here by following an exception call stack, here's what's // happened: you supplied an object or symbol value to React (as a prop, key, // DOM attribute, CSS property, string ref, etc.) and when React tried to // coerce it to a string using `'' + value`, an exception was thrown. // // The most common types that will cause this exception are `Symbol` instances // and Temporal objects like `Temporal.Instant`. But any object that has a // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this // exception. (Library authors do this to prevent users from using built-in // numeric operators like `+` or comparison operators like `>=` because custom // methods are needed to perform accurate arithmetic or comparison.) // // To fix the problem, coerce this object or symbol value to a string before // passing it to React. The most reliable way is usually `String(value)`. // // To find which value is throwing, check the browser or debugger console. // Before this exception was thrown, there should be `console.error` output // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the // problem and how that type was used: key, atrribute, input value prop, etc. // In most cases, this console output also shows the component and its // ancestor components where the exception happened. // // eslint-disable-next-line react-internal/safe-string-coercion return '' + value; } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ''; return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; } // Keep in sync with react-reconciler/getComponentNameFromFiber function getContextName(type) { return type.displayName || 'Context'; } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. function getComponentNameFromType(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + '.Consumer'; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + '.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || 'Memo'; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return getComponentNameFromType(init(payload)); } catch (x) { return null; } } // eslint-disable-next-line no-fallthrough } } return null; } var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName); } } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } function warnIfStringRefCannotBeAutoConverted(config) { { if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); didWarnAboutStringRefs[componentName] = true; } } } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://reactjs.org/docs/react-api.html#createelement */ function createElement(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; { warnIfStringRefCannotBeAutoConverted(config); } } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } /** * Clone and return a new ReactElement using element as the starting point. * See https://reactjs.org/docs/react-api.html#cloneelement */ function cloneElement(element, config, children) { if (element === null || element === undefined) { throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); } var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = key.replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return text.replace(userProvidedKeyEscapeRegex, '$&/'); } /** * Generate a key string that identifies a element within a set. * * @param {*} element A element that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getElementKey(element, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (typeof element === 'object' && element !== null && element.key != null) { // Explicit key { checkKeyStringCoercion(element.key); } return escape('' + element.key); } // Implicit key determined by the index in the set return index.toString(36); } function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } var invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type) { case 'string': case 'number': invokeCallback = true; break; case 'object': switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { var _child = children; var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows: var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; if (isArray(mappedChild)) { var escapedChildKey = ''; if (childKey != null) { escapedChildKey = escapeUserProvidedKey(childKey) + '/'; } mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) { return c; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { { // The `if` statement here prevents auto-disabling of the safe // coercion ESLint rule, so we must manually disable it below. // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { checkKeyStringCoercion(mappedChild.key); } } mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number // eslint-disable-next-line react-internal/safe-string-coercion escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey); } array.push(mappedChild); } return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getElementKey(child, i); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === 'function') { var iterableChildren = children; { // Warn about using Maps as children if (iteratorFn === iterableChildren.entries) { if (!didWarnAboutMaps) { warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); } didWarnAboutMaps = true; } } var iterator = iteratorFn.call(iterableChildren); var step; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getElementKey(child, ii++); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else if (type === 'object') { // eslint-disable-next-line react-internal/safe-string-coercion var childrenString = String(children); throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); } } return subtreeCount; } /** * Maps children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenmap * * The provided mapFunction(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; var count = 0; mapIntoArray(children, result, '', '', function (child) { return func.call(context, child, count++); }); return result; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrencount * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children) { var n = 0; mapChildren(children, function () { n++; // Don't return anything }); return n; } /** * Iterates through children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenforeach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { mapChildren(children, function () { forEachFunc.apply(this, arguments); // Don't return anything. }, forEachContext); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://reactjs.org/docs/react-api.html#reactchildrentoarray */ function toArray(children) { return mapChildren(children, function (child) { return child; }) || []; } /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://reactjs.org/docs/react-api.html#reactchildrenonly * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { if (!isValidElement(children)) { throw new Error('React.Children.only expected to receive a single React element child.'); } return children; } function createContext(defaultValue) { // TODO: Second argument used to be an optional `calculateChangedBits` // function. Warn to reserve for future use? var context = { $$typeof: REACT_CONTEXT_TYPE, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null, // Add these to use same hidden class in VM as ServerContext _defaultValue: null, _globalName: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; var hasWarnedAboutDisplayNameOnConsumer = false; { // A separate object, but proxies back to the original context object for // backwards compatibility. It has a different $$typeof, so we can properly // warn for the incorrect usage of Context as a Consumer. var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here Object.defineProperties(Consumer, { Provider: { get: function () { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?'); } return context.Provider; }, set: function (_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function () { return context._currentValue; }, set: function (_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function () { return context._currentValue2; }, set: function (_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function () { return context._threadCount; }, set: function (_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function () { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } return context.Consumer; } }, displayName: { get: function () { return context.displayName; }, set: function (displayName) { if (!hasWarnedAboutDisplayNameOnConsumer) { warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName); hasWarnedAboutDisplayNameOnConsumer = true; } } } }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; function lazyInitializer(payload) { if (payload._status === Uninitialized) { var ctor = payload._result; var thenable = ctor(); // Transition to the next state. // This might throw either because it's missing or throws. If so, we treat it // as still uninitialized and try again next time. Which is the same as what // happens if the ctor or any wrappers processing the ctor throws. This might // end up fixing it if the resolution was a concurrency bug. thenable.then(function (moduleObject) { if (payload._status === Pending || payload._status === Uninitialized) { // Transition to the next state. var resolved = payload; resolved._status = Resolved; resolved._result = moduleObject; } }, function (error) { if (payload._status === Pending || payload._status === Uninitialized) { // Transition to the next state. var rejected = payload; rejected._status = Rejected; rejected._result = error; } }); if (payload._status === Uninitialized) { // In case, we're still uninitialized, then we're waiting for the thenable // to resolve. Set it as pending in the meantime. var pending = payload; pending._status = Pending; pending._result = thenable; } } if (payload._status === Resolved) { var moduleObject = payload._result; { if (moduleObject === undefined) { error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject); } } { if (!('default' in moduleObject)) { error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies. 'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject); } } return moduleObject.default; } else { throw payload._result; } } function lazy(ctor) { var payload = { // We use these fields to store the result. _status: Uninitialized, _result: ctor }; var lazyType = { $$typeof: REACT_LAZY_TYPE, _payload: payload, _init: lazyInitializer }; { // In production, this would just set it on the object. var defaultProps; var propTypes; // $FlowFixMe Object.defineProperties(lazyType, { defaultProps: { configurable: true, get: function () { return defaultProps; }, set: function (newDefaultProps) { error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); defaultProps = newDefaultProps; // Match production behavior more closely: // $FlowFixMe Object.defineProperty(lazyType, 'defaultProps', { enumerable: true }); } }, propTypes: { configurable: true, get: function () { return propTypes; }, set: function (newPropTypes) { error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); propTypes = newPropTypes; // Match production behavior more closely: // $FlowFixMe Object.defineProperty(lazyType, 'propTypes', { enumerable: true }); } } }); } return lazyType; } function forwardRef(render) { { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).'); } else if (typeof render !== 'function') { error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); } else { if (render.length !== 0 && render.length !== 2) { error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.'); } } if (render != null) { if (render.defaultProps != null || render.propTypes != null) { error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?'); } } } var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render: render }; { var ownName; Object.defineProperty(elementType, 'displayName', { enumerable: false, configurable: true, get: function () { return ownName; }, set: function (name) { ownName = name; // The inner component shouldn't inherit this display name in most cases, // because the component may be used elsewhere. // But it's nice for anonymous functions to inherit the name, // so that our component-stack generation logic will display their frames. // An anonymous function generally suggests a pattern like: // React.forwardRef((props, ref) => {...}); // This kind of inner function is not used elsewhere so the side effect is okay. if (!render.name && !render.displayName) { render.displayName = name; } } }); } return elementType; } var REACT_MODULE_REFERENCE; { REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); } function isValidElementType(type) { if (typeof type === 'string' || typeof type === 'function') { return true; } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) { return true; } if (typeof type === 'object' && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { return true; } } return false; } function memo(type, compare) { { if (!isValidElementType(type)) { error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type); } } var elementType = { $$typeof: REACT_MEMO_TYPE, type: type, compare: compare === undefined ? null : compare }; { var ownName; Object.defineProperty(elementType, 'displayName', { enumerable: false, configurable: true, get: function () { return ownName; }, set: function (name) { ownName = name; // The inner component shouldn't inherit this display name in most cases, // because the component may be used elsewhere. // But it's nice for anonymous functions to inherit the name, // so that our component-stack generation logic will display their frames. // An anonymous function generally suggests a pattern like: // React.memo((props) => {...}); // This kind of inner function is not used elsewhere so the side effect is okay. if (!type.name && !type.displayName) { type.displayName = name; } } }); } return elementType; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; { if (dispatcher === null) { error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); } } // Will result in a null access error if accessed outside render phase. We // intentionally don't throw our own error because this is in a hot path. // Also helps ensure this is inlined. return dispatcher; } function useContext(Context) { var dispatcher = resolveDispatcher(); { // TODO: add a more generic warning for invalid values. if (Context._context !== undefined) { var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs // and nobody should be using this in existing code. if (realContext.Consumer === Context) { error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?'); } else if (realContext.Provider === Context) { error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?'); } } } return dispatcher.useContext(Context); } function useState(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer(reducer, initialArg, init) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer, initialArg, init); } function useRef(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create, deps); } function useInsertionEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useInsertionEffect(create, deps); } function useLayoutEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create, deps); } function useCallback(callback, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, deps); } function useMemo(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create, deps); } function useImperativeHandle(ref, create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create, deps); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } function useTransition() { var dispatcher = resolveDispatcher(); return dispatcher.useTransition(); } function useDeferredValue(value) { var dispatcher = resolveDispatcher(); return dispatcher.useDeferredValue(value); } function useId() { var dispatcher = resolveDispatcher(); return dispatcher.useId(); } function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var dispatcher = resolveDispatcher(); return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); } // Helpers to patch console.logs to avoid logging during side-effect free // replaying on render function. This currently only patches the object // lazily which won't cover if the log function was extracted eagerly. // We could also eagerly patch the method. var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() {} disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); /* eslint-enable react-internal/no-production-logging */ } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ var props = { configurable: true, enumerable: true, writable: true }; // $FlowFixMe Flow thinks console is immutable. Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); /* eslint-enable react-internal/no-production-logging */ } if (disabledDepth < 0) { error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); } } } var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === undefined) { // Extract the VM specific prefix used by each line. try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ''; } } // We use the prefix to ensure our stacks line up with native stack frames. return '\n' + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { // If something asked for a stack inside a fake render, it should get ignored. if ( !fn || reentry) { return ''; } { var frame = componentFrameCache.get(fn); if (frame !== undefined) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. Error.prepareStackTrace = undefined; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function // for warnings. ReactCurrentDispatcher$1.current = null; disableLogs(); } try { // This should throw. if (construct) { // Something should be setting the props in the constructor. var Fake = function () { throw Error(); }; // $FlowFixMe Object.defineProperty(Fake.prototype, 'props', { set: function () { // We use a throwing setter instead of frozen or non-writable props // because that won't throw in a non-strict mode function. throw Error(); } }); if (typeof Reflect === 'object' && Reflect.construct) { // We construct a different control for this case to include any extra // frames added by the construct call. try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { // This is inlined manually because closure doesn't do it for us. if (sample && control && typeof sample.stack === 'string') { // This extracts the first frame from the sample that isn't also in the control. // Skipping one frame that we assume is the frame that calls the two. var sampleLines = sample.stack.split('\n'); var controlLines = control.stack.split('\n'); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { // We expect at least one stack frame to be shared. // Typically this will be the root most one. However, stack frames may be // cut off due to maximum stack limits. In this case, one maybe cut off // earlier than the other. We assume that the sample is longer or the same // and there for cut off earlier. So we should find the root most frame in // the sample somewhere in the control. c--; } for (; s >= 1 && c >= 0; s--, c--) { // Next we find the first one that isn't the same which should be the // frame that called our sample function and the control. if (sampleLines[s] !== controlLines[c]) { // In V8, the first line is describing the message but other VMs don't. // If we're about to return the first line, and the control is also on the same // line, that's a pretty good indicator that our sample threw at same line as // the control. I.e. before we entered the sample frame. So we ignore this result. // This can happen if you passed a class to function component, or non-function. if (s !== 1 || c !== 1) { do { s--; c--; // We may still have similar intermediate frames from the construct call. // The next one that isn't the same should be our match though. if (c < 0 || sampleLines[s] !== controlLines[c]) { // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>" // but we have a user-provided "displayName" // splice it in to make the stack more readable. if (fn.displayName && _frame.includes('<anonymous>')) { _frame = _frame.replace('<anonymous>', fn.displayName); } { if (typeof fn === 'function') { componentFrameCache.set(fn, _frame); } } // Return the line we found. return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher$1.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } // Fallback to just using the name if we couldn't make it throw. var name = fn ? fn.displayName || fn.name : ''; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; { if (typeof fn === 'function') { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ''; } if (typeof type === 'function') { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === 'string') { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame('Suspense'); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame('SuspenseList'); } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: // Memo may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { // Lazy may contain any component type so we recursively resolve it. return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); } catch (x) {} } } } return ''; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { // $FlowFixMe This is okay but Flow doesn't know it. var has = Function.call.bind(hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { // eslint-disable-next-line react-internal/prod-error-codes var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); err.name = 'Invariant Violation'; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error('Failed %s type: %s', location, error$1.message); setCurrentlyValidatingElement(null); } } } } } function setCurrentlyValidatingElement$1(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); setExtraStackFrame(stack); } else { setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = getComponentNameFromType(ReactCurrentOwner.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } function getSourceInfoErrorAddendum(source) { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } function getSourceInfoErrorAddendumForProps(elementProps) { if (elementProps !== null && elementProps !== undefined) { return getSourceInfoErrorAddendum(elementProps.__source); } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; } { setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { // Intentionally inside to avoid triggering lazy initializers: var name = getComponentNameFromType(type); checkPropTypes(propTypes, element.props, 'prop', name, element); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers: var _name = getComponentNameFromType(type); error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { setCurrentlyValidatingElement$1(fragment); error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error('Invalid attribute `ref` supplied to `React.Fragment`.'); setCurrentlyValidatingElement$1(null); } } } function createElementWithValidation(type, props, children) { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendumForProps(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } { error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } } var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } if (type === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } var didWarnAboutDeprecatedCreateFactory = false; function createFactoryWithValidation(type) { var validatedFactory = createElementWithValidation.bind(null, type); validatedFactory.type = type; { if (!didWarnAboutDeprecatedCreateFactory) { didWarnAboutDeprecatedCreateFactory = true; warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.'); } // Legacy hook: remove it Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); Object.defineProperty(this, 'type', { value: type }); return type; } }); } return validatedFactory; } function cloneElementWithValidation(element, props, children) { var newElement = cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } var enableSchedulerDebugging = false; var enableProfiling = false; var frameYieldMs = 5; function push(heap, node) { var index = heap.length; heap.push(node); siftUp(heap, node, index); } function peek(heap) { return heap.length === 0 ? null : heap[0]; } function pop(heap) { if (heap.length === 0) { return null; } var first = heap[0]; var last = heap.pop(); if (last !== first) { heap[0] = last; siftDown(heap, last, 0); } return first; } function siftUp(heap, node, i) { var index = i; while (index > 0) { var parentIndex = index - 1 >>> 1; var parent = heap[parentIndex]; if (compare(parent, node) > 0) { // The parent is larger. Swap positions. heap[parentIndex] = node; heap[index] = parent; index = parentIndex; } else { // The parent is smaller. Exit. return; } } } function siftDown(heap, node, i) { var index = i; var length = heap.length; var halfLength = length >>> 1; while (index < halfLength) { var leftIndex = (index + 1) * 2 - 1; var left = heap[leftIndex]; var rightIndex = leftIndex + 1; var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. if (compare(left, node) < 0) { if (rightIndex < length && compare(right, left) < 0) { heap[index] = right; heap[rightIndex] = node; index = rightIndex; } else { heap[index] = left; heap[leftIndex] = node; index = leftIndex; } } else if (rightIndex < length && compare(right, node) < 0) { heap[index] = right; heap[rightIndex] = node; index = rightIndex; } else { // Neither child is smaller. Exit. return; } } } function compare(a, b) { // Compare sort index first, then task id. var diff = a.sortIndex - b.sortIndex; return diff !== 0 ? diff : a.id - b.id; } // TODO: Use symbols? var ImmediatePriority = 1; var UserBlockingPriority = 2; var NormalPriority = 3; var LowPriority = 4; var IdlePriority = 5; function markTaskErrored(task, ms) { } /* eslint-disable no-var */ var getCurrentTime; var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; if (hasPerformanceNow) { var localPerformance = performance; getCurrentTime = function () { return localPerformance.now(); }; } else { var localDate = Date; var initialTime = localDate.now(); getCurrentTime = function () { return localDate.now() - initialTime; }; } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. // Math.pow(2, 30) - 1 // 0b111111111111111111111111111111 var maxSigned31BitInt = 1073741823; // Times out immediately var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out var USER_BLOCKING_PRIORITY_TIMEOUT = 250; var NORMAL_PRIORITY_TIMEOUT = 5000; var LOW_PRIORITY_TIMEOUT = 10000; // Never times out var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap var taskQueue = []; var timerQueue = []; // Incrementing id counter. Used to maintain insertion order. var taskIdCounter = 1; // Pausing the scheduler is useful for debugging. var currentTask = null; var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance. var isPerformingWork = false; var isHostCallbackScheduled = false; var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them. var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null; var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null; var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; function advanceTimers(currentTime) { // Check for tasks that are no longer delayed and add them to the queue. var timer = peek(timerQueue); while (timer !== null) { if (timer.callback === null) { // Timer was cancelled. pop(timerQueue); } else if (timer.startTime <= currentTime) { // Timer fired. Transfer to the task queue. pop(timerQueue); timer.sortIndex = timer.expirationTime; push(taskQueue, timer); } else { // Remaining timers are pending. return; } timer = peek(timerQueue); } } function handleTimeout(currentTime) { isHostTimeoutScheduled = false; advanceTimers(currentTime); if (!isHostCallbackScheduled) { if (peek(taskQueue) !== null) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } } } } function flushWork(hasTimeRemaining, initialTime) { isHostCallbackScheduled = false; if (isHostTimeoutScheduled) { // We scheduled a timeout but it's no longer needed. Cancel it. isHostTimeoutScheduled = false; cancelHostTimeout(); } isPerformingWork = true; var previousPriorityLevel = currentPriorityLevel; try { if (enableProfiling) { try { return workLoop(hasTimeRemaining, initialTime); } catch (error) { if (currentTask !== null) { var currentTime = getCurrentTime(); markTaskErrored(currentTask, currentTime); currentTask.isQueued = false; } throw error; } } else { // No catch in prod code path. return workLoop(hasTimeRemaining, initialTime); } } finally { currentTask = null; currentPriorityLevel = previousPriorityLevel; isPerformingWork = false; } } function workLoop(hasTimeRemaining, initialTime) { var currentTime = initialTime; advanceTimers(currentTime); currentTask = peek(taskQueue); while (currentTask !== null && !(enableSchedulerDebugging )) { if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { // This currentTask hasn't expired, and we've reached the deadline. break; } var callback = currentTask.callback; if (typeof callback === 'function') { currentTask.callback = null; currentPriorityLevel = currentTask.priorityLevel; var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; var continuationCallback = callback(didUserCallbackTimeout); currentTime = getCurrentTime(); if (typeof continuationCallback === 'function') { currentTask.callback = continuationCallback; } else { if (currentTask === peek(taskQueue)) { pop(taskQueue); } } advanceTimers(currentTime); } else { pop(taskQueue); } currentTask = peek(taskQueue); } // Return whether there's additional work if (currentTask !== null) { return true; } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } return false; } } function unstable_runWithPriority(priorityLevel, eventHandler) { switch (priorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: case LowPriority: case IdlePriority: break; default: priorityLevel = NormalPriority; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_next(eventHandler) { var priorityLevel; switch (currentPriorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: // Shift down to normal priority priorityLevel = NormalPriority; break; default: // Anything lower than normal priority should remain at the current level. priorityLevel = currentPriorityLevel; break; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_wrapCallback(callback) { var parentPriorityLevel = currentPriorityLevel; return function () { // This is a fork of runWithPriority, inlined for performance. var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = parentPriorityLevel; try { return callback.apply(this, arguments); } finally { currentPriorityLevel = previousPriorityLevel; } }; } function unstable_scheduleCallback(priorityLevel, callback, options) { var currentTime = getCurrentTime(); var startTime; if (typeof options === 'object' && options !== null) { var delay = options.delay; if (typeof delay === 'number' && delay > 0) { startTime = currentTime + delay; } else { startTime = currentTime; } } else { startTime = currentTime; } var timeout; switch (priorityLevel) { case ImmediatePriority: timeout = IMMEDIATE_PRIORITY_TIMEOUT; break; case UserBlockingPriority: timeout = USER_BLOCKING_PRIORITY_TIMEOUT; break; case IdlePriority: timeout = IDLE_PRIORITY_TIMEOUT; break; case LowPriority: timeout = LOW_PRIORITY_TIMEOUT; break; case NormalPriority: default: timeout = NORMAL_PRIORITY_TIMEOUT; break; } var expirationTime = startTime + timeout; var newTask = { id: taskIdCounter++, callback: callback, priorityLevel: priorityLevel, startTime: startTime, expirationTime: expirationTime, sortIndex: -1 }; if (startTime > currentTime) { // This is a delayed task. newTask.sortIndex = startTime; push(timerQueue, newTask); if (peek(taskQueue) === null && newTask === peek(timerQueue)) { // All tasks are delayed, and this is the task with the earliest delay. if (isHostTimeoutScheduled) { // Cancel an existing timeout. cancelHostTimeout(); } else { isHostTimeoutScheduled = true; } // Schedule a timeout. requestHostTimeout(handleTimeout, startTime - currentTime); } } else { newTask.sortIndex = expirationTime; push(taskQueue, newTask); // wait until the next time we yield. if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } return newTask; } function unstable_pauseExecution() { } function unstable_continueExecution() { if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } function unstable_getFirstCallbackNode() { return peek(taskQueue); } function unstable_cancelCallback(task) { // remove from the queue because you can't remove arbitrary nodes from an // array based heap, only the first one.) task.callback = null; } function unstable_getCurrentPriorityLevel() { return currentPriorityLevel; } var isMessageLoopRunning = false; var scheduledHostCallback = null; var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main // thread, like user events. By default, it yields multiple times per frame. // It does not attempt to align with frame boundaries, since most tasks don't // need to be frame aligned; for those that do, use requestAnimationFrame. var frameInterval = frameYieldMs; var startTime = -1; function shouldYieldToHost() { var timeElapsed = getCurrentTime() - startTime; if (timeElapsed < frameInterval) { // The main thread has only been blocked for a really short amount of time; // smaller than a single frame. Don't yield yet. return false; } // The main thread has been blocked for a non-negligible amount of time. We return true; } function requestPaint() { } function forceFrameRate(fps) { if (fps < 0 || fps > 125) { // Using console['error'] to evade Babel and ESLint console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported'); return; } if (fps > 0) { frameInterval = Math.floor(1000 / fps); } else { // reset the framerate frameInterval = frameYieldMs; } } var performWorkUntilDeadline = function () { if (scheduledHostCallback !== null) { var currentTime = getCurrentTime(); // Keep track of the start time so we can measure how long the main thread // has been blocked. startTime = currentTime; var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the // error can be observed. // // Intentionally not using a try-catch, since that makes some debugging // techniques harder. Instead, if `scheduledHostCallback` errors, then // `hasMoreWork` will remain true, and we'll continue the work loop. var hasMoreWork = true; try { hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); } finally { if (hasMoreWork) { // If there's more work, schedule the next message event at the end // of the preceding one. schedulePerformWorkUntilDeadline(); } else { isMessageLoopRunning = false; scheduledHostCallback = null; } } } else { isMessageLoopRunning = false; } // Yielding to the browser will give it a chance to paint, so we can }; var schedulePerformWorkUntilDeadline; if (typeof localSetImmediate === 'function') { // Node.js and old IE. // There's a few reasons for why we prefer setImmediate. // // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting. // (Even though this is a DOM fork of the Scheduler, you could get here // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.) // https://github.com/facebook/react/issues/20756 // // But also, it runs earlier which is the semantic we want. // If other browsers ever implement it, it's better to use it. // Although both of these would be inferior to native scheduling. schedulePerformWorkUntilDeadline = function () { localSetImmediate(performWorkUntilDeadline); }; } else if (typeof MessageChannel !== 'undefined') { // DOM and Worker environments. // We prefer MessageChannel because of the 4ms setTimeout clamping. var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = performWorkUntilDeadline; schedulePerformWorkUntilDeadline = function () { port.postMessage(null); }; } else { // We should only fallback here in non-browser environments. schedulePerformWorkUntilDeadline = function () { localSetTimeout(performWorkUntilDeadline, 0); }; } function requestHostCallback(callback) { scheduledHostCallback = callback; if (!isMessageLoopRunning) { isMessageLoopRunning = true; schedulePerformWorkUntilDeadline(); } } function requestHostTimeout(callback, ms) { taskTimeoutID = localSetTimeout(function () { callback(getCurrentTime()); }, ms); } function cancelHostTimeout() { localClearTimeout(taskTimeoutID); taskTimeoutID = -1; } var unstable_requestPaint = requestPaint; var unstable_Profiling = null; var Scheduler = /*#__PURE__*/Object.freeze({ __proto__: null, unstable_ImmediatePriority: ImmediatePriority, unstable_UserBlockingPriority: UserBlockingPriority, unstable_NormalPriority: NormalPriority, unstable_IdlePriority: IdlePriority, unstable_LowPriority: LowPriority, unstable_runWithPriority: unstable_runWithPriority, unstable_next: unstable_next, unstable_scheduleCallback: unstable_scheduleCallback, unstable_cancelCallback: unstable_cancelCallback, unstable_wrapCallback: unstable_wrapCallback, unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel, unstable_shouldYield: shouldYieldToHost, unstable_requestPaint: unstable_requestPaint, unstable_continueExecution: unstable_continueExecution, unstable_pauseExecution: unstable_pauseExecution, unstable_getFirstCallbackNode: unstable_getFirstCallbackNode, get unstable_now () { return getCurrentTime; }, unstable_forceFrameRate: forceFrameRate, unstable_Profiling: unstable_Profiling }); var ReactSharedInternals$1 = { ReactCurrentDispatcher: ReactCurrentDispatcher, ReactCurrentOwner: ReactCurrentOwner, ReactCurrentBatchConfig: ReactCurrentBatchConfig, // Re-export the schedule API(s) for UMD bundles. // This avoids introducing a dependency on a new UMD global in a minor update, // Since that would be a breaking change (e.g. for all existing CodeSandboxes). // This re-export is only required for UMD bundles; // CJS bundles use the shared NPM package. Scheduler: Scheduler }; { ReactSharedInternals$1.ReactCurrentActQueue = ReactCurrentActQueue; ReactSharedInternals$1.ReactDebugCurrentFrame = ReactDebugCurrentFrame; } function startTransition(scope, options) { var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = {}; var currentTransition = ReactCurrentBatchConfig.transition; { ReactCurrentBatchConfig.transition._updatedFibers = new Set(); } try { scope(); } finally { ReactCurrentBatchConfig.transition = prevTransition; { if (prevTransition === null && currentTransition._updatedFibers) { var updatedFibersCount = currentTransition._updatedFibers.size; if (updatedFibersCount > 10) { warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.'); } currentTransition._updatedFibers.clear(); } } } } var didWarnAboutMessageChannel = false; var enqueueTaskImpl = null; function enqueueTask(task) { if (enqueueTaskImpl === null) { try { // read require off the module object to get around the bundlers. // we don't want them to detect a require and bundle a Node polyfill. var requireString = ('require' + Math.random()).slice(0, 7); var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's // version of setImmediate, bypassing fake timers if any. enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate; } catch (_err) { // we're in a browser // we can't use regular timers because they may still be faked // so we try MessageChannel+postMessage instead enqueueTaskImpl = function (callback) { { if (didWarnAboutMessageChannel === false) { didWarnAboutMessageChannel = true; if (typeof MessageChannel === 'undefined') { error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.'); } } } var channel = new MessageChannel(); channel.port1.onmessage = callback; channel.port2.postMessage(undefined); }; } } return enqueueTaskImpl(task); } var actScopeDepth = 0; var didWarnNoAwaitAct = false; function act(callback) { { // `act` calls can be nested, so we track the depth. This represents the // number of `act` scopes on the stack. var prevActScopeDepth = actScopeDepth; actScopeDepth++; if (ReactCurrentActQueue.current === null) { // This is the outermost `act` scope. Initialize the queue. The reconciler // will detect the queue and use it instead of Scheduler. ReactCurrentActQueue.current = []; } var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; var result; try { // Used to reproduce behavior of `batchedUpdates` in legacy mode. Only // set to `true` while the given callback is executed, not for updates // triggered during an async event, because this is how the legacy // implementation of `act` behaved. ReactCurrentActQueue.isBatchingLegacy = true; result = callback(); // Replicate behavior of original `act` implementation in legacy mode, // which flushed updates immediately after the scope function exits, even // if it's an async function. if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { var queue = ReactCurrentActQueue.current; if (queue !== null) { ReactCurrentActQueue.didScheduleLegacyUpdate = false; flushActQueue(queue); } } } catch (error) { popActScope(prevActScopeDepth); throw error; } finally { ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; } if (result !== null && typeof result === 'object' && typeof result.then === 'function') { var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait // for it to resolve before exiting the current scope. var wasAwaited = false; var thenable = { then: function (resolve, reject) { wasAwaited = true; thenableResult.then(function (returnValue) { popActScope(prevActScopeDepth); if (actScopeDepth === 0) { // We've exited the outermost act scope. Recursively flush the // queue until there's no remaining work. recursivelyFlushAsyncActWork(returnValue, resolve, reject); } else { resolve(returnValue); } }, function (error) { // The callback threw an error. popActScope(prevActScopeDepth); reject(error); }); } }; { if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') { // eslint-disable-next-line no-undef Promise.resolve().then(function () {}).then(function () { if (!wasAwaited) { didWarnNoAwaitAct = true; error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);'); } }); } } return thenable; } else { var returnValue = result; // The callback is not an async function. Exit the current scope // immediately, without awaiting. popActScope(prevActScopeDepth); if (actScopeDepth === 0) { // Exiting the outermost act scope. Flush the queue. var _queue = ReactCurrentActQueue.current; if (_queue !== null) { flushActQueue(_queue); ReactCurrentActQueue.current = null; } // Return a thenable. If the user awaits it, we'll flush again in // case additional work was scheduled by a microtask. var _thenable = { then: function (resolve, reject) { // Confirm we haven't re-entered another `act` scope, in case // the user does something weird like await the thenable // multiple times. if (ReactCurrentActQueue.current === null) { // Recursively flush the queue until there's no remaining work. ReactCurrentActQueue.current = []; recursivelyFlushAsyncActWork(returnValue, resolve, reject); } else { resolve(returnValue); } } }; return _thenable; } else { // Since we're inside a nested `act` scope, the returned thenable // immediately resolves. The outer scope will flush the queue. var _thenable2 = { then: function (resolve, reject) { resolve(returnValue); } }; return _thenable2; } } } } function popActScope(prevActScopeDepth) { { if (prevActScopeDepth !== actScopeDepth - 1) { error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. '); } actScopeDepth = prevActScopeDepth; } } function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { { var queue = ReactCurrentActQueue.current; if (queue !== null) { try { flushActQueue(queue); enqueueTask(function () { if (queue.length === 0) { // No additional work was scheduled. Finish. ReactCurrentActQueue.current = null; resolve(returnValue); } else { // Keep flushing work until there's none left. recursivelyFlushAsyncActWork(returnValue, resolve, reject); } }); } catch (error) { reject(error); } } else { resolve(returnValue); } } } var isFlushing = false; function flushActQueue(queue) { { if (!isFlushing) { // Prevent re-entrance. isFlushing = true; var i = 0; try { for (; i < queue.length; i++) { var callback = queue[i]; do { callback = callback(true); } while (callback !== null); } queue.length = 0; } catch (error) { // If something throws, leave the remaining callbacks on the queue. queue = queue.slice(i + 1); throw error; } finally { isFlushing = false; } } } } var createElement$1 = createElementWithValidation ; var cloneElement$1 = cloneElementWithValidation ; var createFactory = createFactoryWithValidation ; var Children = { map: mapChildren, forEach: forEachChildren, count: countChildren, toArray: toArray, only: onlyChild }; exports.Children = Children; exports.Component = Component; exports.Fragment = REACT_FRAGMENT_TYPE; exports.Profiler = REACT_PROFILER_TYPE; exports.PureComponent = PureComponent; exports.StrictMode = REACT_STRICT_MODE_TYPE; exports.Suspense = REACT_SUSPENSE_TYPE; exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1; exports.act = act; exports.cloneElement = cloneElement$1; exports.createContext = createContext; exports.createElement = createElement$1; exports.createFactory = createFactory; exports.createRef = createRef; exports.forwardRef = forwardRef; exports.isValidElement = isValidElement; exports.lazy = lazy; exports.memo = memo; exports.startTransition = startTransition; exports.unstable_act = act; exports.useCallback = useCallback; exports.useContext = useContext; exports.useDebugValue = useDebugValue; exports.useDeferredValue = useDeferredValue; exports.useEffect = useEffect; exports.useId = useId; exports.useImperativeHandle = useImperativeHandle; exports.useInsertionEffect = useInsertionEffect; exports.useLayoutEffect = useLayoutEffect; exports.useMemo = useMemo; exports.useReducer = useReducer; exports.useRef = useRef; exports.useState = useState; exports.useSyncExternalStore = useSyncExternalStore; exports.useTransition = useTransition; exports.version = ReactVersion; }))); lodash.js 0000644 00002046542 14720015030 0006361 0 ustar 00 /** * @license * Lodash <https://lodash.com/> * Copyright OpenJS Foundation and other contributors <https://openjsf.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.21'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function', INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading whitespace. */ var reTrimStart = /^\s+/; /** Used to match a single whitespace character. */ var reWhitespace = /\s/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** * Used to validate the `validate` option in `_.template` variable. * * Forbids characters which could potentially change the meaning of the function argument definition: * - "()," (modification of function parameters) * - "=" (default value) * - "[]{}" (destructuring of function parameters) * - "/" (beginning of a comment) * - whitespace */ var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.trim`. * * @private * @param {string} string The string to trim. * @returns {string} Returns the trimmed string. */ function baseTrim(string) { return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the last non-whitespace character. */ function trimmedEndIndex(string) { var index = string.length; while (index-- && reWhitespace.test(string.charAt(index))) {} return index; } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || (!isRight && arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { stack || (stack = new Stack); if (isObject(srcValue)) { baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || isFunction(objValue)) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { if (iteratees.length) { iteratees = arrayMap(iteratees, function(iteratee) { if (isArray(iteratee)) { return function(value) { return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); } } return iteratee; }); } else { iteratees = [identity]; } var index = -1; iteratees = arrayMap(iteratees, baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (key === '__proto__' || key === 'constructor' || key === 'prototype') { return object; } if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { var low = 0, high = array == null ? 0 : array.length; if (high === 0) { return 0; } value = iteratee(value); var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision && nativeIsFinite(number)) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Check that cyclic values are equal. var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Check that cyclic values are equal. var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key === 'constructor' && typeof object[key] === 'function') { return; } if (key == '__proto__') { return; } return object[key]; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] * * // Combining several predicates using `_.overEvery` or `_.overSome`. * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); * // => objects for ['fred', 'barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 30 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, & pebbles</p>' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = baseTrim(value); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { object[key] = source[key]; } } } return object; }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, & pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b><script></b>' * * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the internal `print` function in "evaluate" delimiters. * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // Use the ES template literal delimiter as an "interpolate" delimiter. * // Disable support by replacing the "interpolate" delimiter. * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // Use backslashes to treat delimiters as plain text. * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // Use the `imports` option to import `jQuery` as `jq`. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the `sourceURL` option to specify a custom sourceURL for the template. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. * * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // Use custom template delimiters. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // Use the `source` property to inline compiled templates for meaningful * // line numbers in error messages and stack traces. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined; } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. // The sourceURL gets injected into the source that's eval-ed, so be careful // to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in // and escape the comment, thus injecting code that gets evaled. var sourceURL = '//# sourceURL=' + (hasOwnProperty.call(options, 'sourceURL') ? (options.sourceURL + '').replace(/\s/g, ' ') : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = hasOwnProperty.call(options, 'variable') && options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Throw an error if a forbidden character was found in `variable`, to prevent // potential command injection attacks. else if (reForbiddenIdentifierChars.test(variable)) { throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT); } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Converts `string`, as a whole, to lower case just like * [String#toLowerCase](https://mdn.io/toLowerCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.toLower('--Foo-Bar--'); * // => '--foo-bar--' * * _.toLower('fooBar'); * // => 'foobar' * * _.toLower('__FOO_BAR__'); * // => '__foo_bar__' */ function toLower(value) { return toString(value).toLowerCase(); } /** * Converts `string`, as a whole, to upper case just like * [String#toUpperCase](https://mdn.io/toUpperCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.toUpper('--foo-bar--'); * // => '--FOO-BAR--' * * _.toUpper('fooBar'); * // => 'FOOBAR' * * _.toUpper('__foo_bar__'); * // => '__FOO_BAR__' */ function toUpper(value) { return toString(value).toUpperCase(); } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return baseTrim(string); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimEnd(' abc '); * // => ' abc' * * _.trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.slice(0, trimmedEndIndex(string) + 1); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join(''); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join(''); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&`, `<`, `>`, `"`, and `'` in `string` to * their corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional * HTML entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @since 0.6.0 * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, & pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = toString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Converts `string`, as space separated words, to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.upperCase('--foo-bar'); * // => 'FOO BAR' * * _.upperCase('fooBar'); * // => 'FOO BAR' * * _.upperCase('__foo_bar__'); * // => 'FOO BAR' */ var upperCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toUpperCase(); }); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); } return string.match(pattern) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Function} func The function to attempt. * @param {...*} [args] The arguments to invoke `func` with. * @returns {*} Returns the `func` result or error object. * @example * * // Avoid throwing errors for invalid selectors. * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = baseRest(function(func, args) { try { return apply(func, undefined, args); } catch (e) { return isError(e) ? e : new Error(e); } }); /** * Binds methods of an object to the object itself, overwriting the existing * method. * * **Note:** This method doesn't set the "length" property of bound functions. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} methodNames The object method names to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'click': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view, ['click']); * jQuery(element).on('click', view.click); * // => Logs 'clicked docs' when clicked. */ var bindAll = flatRest(function(object, methodNames) { arrayEach(methodNames, function(key) { key = toKey(key); baseAssignValue(object, key, bind(object[key], object)); }); return object; }); /** * Creates a function that iterates over `pairs` and invokes the corresponding * function of the first predicate to return truthy. The predicate-function * pairs are invoked with the `this` binding and arguments of the created * function. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Array} pairs The predicate-function pairs. * @returns {Function} Returns the new composite function. * @example * * var func = _.cond([ * [_.matches({ 'a': 1 }), _.constant('matches A')], * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], * [_.stubTrue, _.constant('no match')] * ]); * * func({ 'a': 1, 'b': 2 }); * // => 'matches A' * * func({ 'a': 0, 'b': 1 }); * // => 'matches B' * * func({ 'a': '1', 'b': '2' }); * // => 'no match' */ function cond(pairs) { var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function(pair) { if (typeof pair[1] != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return [toIteratee(pair[0]), pair[1]]; }); return baseRest(function(args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this, args)) { return apply(pair[1], this, args); } } }); } /** * Creates a function that invokes the predicate properties of `source` with * the corresponding property values of a given object, returning `true` if * all predicates return truthy, else `false`. * * **Note:** The created function is equivalent to `_.conformsTo` with * `source` partially applied. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 2, 'b': 1 }, * { 'a': 1, 'b': 2 } * ]; * * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); * // => [{ 'a': 1, 'b': 2 }] */ function conforms(source) { return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); } /** * 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; }; } /** * Checks `value` to determine whether a default value should be returned in * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, * or `undefined`. * * @static * @memberOf _ * @since 4.14.0 * @category Util * @param {*} value The value to check. * @param {*} defaultValue The default value. * @returns {*} Returns the resolved value. * @example * * _.defaultTo(1, 10); * // => 1 * * _.defaultTo(undefined, 10); * // => 10 */ function defaultTo(value, defaultValue) { return (value == null || value !== value) ? defaultValue : value; } /** * Creates a function that returns the result of invoking the given functions * with the `this` binding of the created function, where each successive * invocation is supplied the return value of the previous. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flowRight * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow([_.add, square]); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 3.0.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flow * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight([square, _.add]); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * 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; } /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between a given * object and `source`, returning `true` if the given object has equivalent * property values, else `false`. * * **Note:** The created function is equivalent to `_.isMatch` with `source` * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * **Note:** Multiple values can be checked by combining several matchers * using `_.overSome` * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); * // => [{ 'a': 4, 'b': 5, 'c': 6 }] * * // Checking for several possible values * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })])); * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] */ function matches(source) { return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between the * value at `path` of a given object to `srcValue`, returning `true` if the * object value is equivalent, else `false`. * * **Note:** Partial comparisons will match empty array and empty object * `srcValue` values against any array or object value, respectively. See * `_.isEqual` for a list of supported value comparisons. * * **Note:** Multiple values can be checked by combining several matchers * using `_.overSome` * * @static * @memberOf _ * @since 3.2.0 * @category Util * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.find(objects, _.matchesProperty('a', 4)); * // => { 'a': 4, 'b': 5, 'c': 6 } * * // Checking for several possible values * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)])); * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); } /** * Creates a function that invokes the method at `path` of a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var objects = [ * { 'a': { 'b': _.constant(2) } }, * { 'a': { 'b': _.constant(1) } } * ]; * * _.map(objects, _.method('a.b')); * // => [2, 1] * * _.map(objects, _.method(['a', 'b'])); * // => [2, 1] */ var method = baseRest(function(path, args) { return function(object) { return baseInvoke(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path of `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = baseRest(function(object, args) { return function(path) { return baseInvoke(object, path, args); }; }); /** * Adds all own enumerable string keyed function properties of a source * object to the destination object. If `object` is a function, then methods * are added to its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options={}] The options object. * @param {boolean} [options.chain=true] Specify whether mixins are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { if (root._ === this) { root._ = oldDash; } return this; } /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } /** * Creates a function that gets the argument at index `n`. If `n` is negative, * the nth argument from the end is returned. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [n=0] The index of the argument to return. * @returns {Function} Returns the new pass-thru function. * @example * * var func = _.nthArg(1); * func('a', 'b', 'c', 'd'); * // => 'b' * * var func = _.nthArg(-2); * func('a', 'b', 'c', 'd'); * // => 'c' */ function nthArg(n) { n = toInteger(n); return baseRest(function(args) { return baseNth(args, n); }); } /** * Creates a function that invokes `iteratees` with the arguments it receives * and returns their results. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to invoke. * @returns {Function} Returns the new function. * @example * * var func = _.over([Math.max, Math.min]); * * func(1, 2, 3, 4); * // => [4, 1] */ var over = createOver(arrayMap); /** * Creates a function that checks if **all** of the `predicates` return * truthy when invoked with the arguments it receives. * * Following shorthands are possible for providing predicates. * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overEvery([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => false * * func(NaN); * // => false */ var overEvery = createOver(arrayEvery); /** * Creates a function that checks if **any** of the `predicates` return * truthy when invoked with the arguments it receives. * * Following shorthands are possible for providing predicates. * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overSome([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => true * * func(NaN); * // => false * * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }]) * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]]) */ var overSome = createOver(arraySome); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the value at a given path of `object`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return object == null ? undefined : baseGet(object, path); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.range * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ var rangeRight = createRange(true); /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * 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; } /** * This method returns a new empty object. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Object} Returns the new empty object. * @example * * var objects = _.times(2, _.stubObject); * * console.log(objects); * // => [{}, {}] * * console.log(objects[0] === objects[1]); * // => false */ function stubObject() { return {}; } /** * This method returns an empty string. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {string} Returns the empty string. * @example * * _.times(2, _.stubString); * // => ['', ''] */ function stubString() { return ''; } /** * This method returns `true`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `true`. * @example * * _.times(2, _.stubTrue); * // => [true, true] */ function stubTrue() { return true; } /** * Invokes the iteratee `n` times, returning an array of the results of * each invocation. The iteratee is invoked with one argument; (index). * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of results. * @example * * _.times(3, String); * // => ['0', '1', '2'] * * _.times(4, _.constant(0)); * // => [0, 0, 0, 0] */ function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index); } return result; } /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = createMathOperation(function(augend, addend) { return augend + addend; }, 0); /** * Computes `number` rounded up to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round up. * @param {number} [precision=0] The precision to round up to. * @returns {number} Returns the rounded up number. * @example * * _.ceil(4.006); * // => 5 * * _.ceil(6.004, 2); * // => 6.01 * * _.ceil(6040, -2); * // => 6100 */ var ceil = createRound('ceil'); /** * Divide two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} dividend The first number in a division. * @param {number} divisor The second number in a division. * @returns {number} Returns the quotient. * @example * * _.divide(6, 4); * // => 1.5 */ var divide = createMathOperation(function(dividend, divisor) { return dividend / divisor; }, 1); /** * Computes `number` rounded down to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round down. * @param {number} [precision=0] The precision to round down to. * @returns {number} Returns the rounded down number. * @example * * _.floor(4.006); * // => 4 * * _.floor(0.046, 2); * // => 0.04 * * _.floor(4060, -2); * // => 4000 */ var floor = createRound('floor'); /** * Computes the maximum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => undefined */ function max(array) { return (array && array.length) ? baseExtremum(array, identity, baseGt) : undefined; } /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * // The `_.property` iteratee shorthand. * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ function maxBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined; } /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ function mean(array) { return baseMean(array, identity); } /** * This method is like `_.mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.meanBy(objects, function(o) { return o.n; }); * // => 5 * * // The `_.property` iteratee shorthand. * _.meanBy(objects, 'n'); * // => 5 */ function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee, 2)); } /** * Computes the minimum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => undefined */ function min(array) { return (array && array.length) ? baseExtremum(array, identity, baseLt) : undefined; } /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * // The `_.property` iteratee shorthand. * _.minBy(objects, 'n'); * // => { 'n': 1 } */ function minBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined; } /** * Multiply two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} multiplier The first number in a multiplication. * @param {number} multiplicand The second number in a multiplication. * @returns {number} Returns the product. * @example * * _.multiply(6, 4); * // => 24 */ var multiply = createMathOperation(function(multiplier, multiplicand) { return multiplier * multiplicand; }, 1); /** * Computes `number` rounded to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round. * @param {number} [precision=0] The precision to round to. * @returns {number} Returns the rounded number. * @example * * _.round(4.006); * // => 4 * * _.round(4.006, 2); * // => 4.01 * * _.round(4060, -2); * // => 4100 */ var round = createRound('round'); /** * Subtract two numbers. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ var subtract = createMathOperation(function(minuend, subtrahend) { return minuend - subtrahend; }, 0); /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return (array && array.length) ? baseSum(array, identity) : 0; } /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, getIteratee(iteratee, 2)) : 0; } /*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; // Add aliases. lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; // Add methods to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.conformsTo = conformsTo; lodash.deburr = deburr; lodash.defaultTo = defaultTo; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.stubArray = stubArray; lodash.stubFalse = stubFalse; lodash.stubObject = stubObject; lodash.stubString = stubString; lodash.stubTrue = stubTrue; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; // Add aliases. lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } }); return source; }()), { 'chain': false }); /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type {string} */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { LazyWrapper.prototype[methodName] = function(n) { n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = (this.__filtered__ && !index) ? new LazyWrapper(this) : this.clone(); if (result.__filtered__) { result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { result.__views__.push({ 'size': nativeMin(n, MAX_ARRAY_LENGTH), 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), 'type': type }); result.__filtered__ = result.__filtered__ || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.head` and `_.last`. arrayEach(['head', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. arrayEach(['initial', 'tail'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.find = function(predicate) { return this.filter(predicate).head(); }; LazyWrapper.prototype.findLast = function(predicate) { return this.reverse().find(predicate); }; LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { if (typeof path == 'function') { return new LazyWrapper(this); } return this.map(function(value) { return baseInvoke(value, path, args); }); }); LazyWrapper.prototype.reject = function(predicate) { return this.filter(negate(getIteratee(predicate))); }; LazyWrapper.prototype.slice = function(start, end) { start = toInteger(start); var result = this; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result); } if (start < 0) { result = result.takeRight(-start); } else if (start) { result = result.drop(start); } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.takeRightWhile = function(predicate) { return this.reverse().takeWhile(predicate).reverse(); }; LazyWrapper.prototype.toArray = function() { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function(value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return (isTaker && chainAll) ? result[0] : result; }; if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // Avoid lazy use if the iteratee has a "length" value other than `1`. isLazy = useLazy = false; } var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this); var result = func.apply(value, args); result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(result, chainAll); } if (isUnwrapped && onlyLazy) { return func.apply(this, args); } result = this.thru(interceptor); return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; }; }); // Add `Array` methods to `lodash.prototype`. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } return this[chainName](function(value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = lodashFunc.name + ''; if (!hasOwnProperty.call(realNames, key)) { realNames[key] = []; } realNames[key].push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chain sequence methods to the `lodash` wrapper. lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add lazy aliases. lodash.prototype.first = lodash.prototype.head; if (symIterator) { lodash.prototype[symIterator] = wrapperToIterator; } return lodash; }); /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers, like r.js, check for condition patterns like: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose Lodash on the global object to prevent errors when Lodash is // loaded by a script tag in the presence of an AMD loader. // See http://requirejs.org/docs/errors.html#mismatch for more details. // Use `_.noConflict` to remove Lodash from the global object. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. define(function() { return _; }); } // Check for `exports` after `define` in case a build optimizer adds it. else if (freeModule) { // Export for Node.js. (freeModule.exports = _)._ = _; // Export for CommonJS support. freeExports._ = _; } else { // Export to the global object. root._ = _; } }.call(this)); lodash.min.js 0000644 00000212061 14720015030 0007130 0 ustar 00 /** * @license * Lodash <https://lodash.com/> * Copyright OpenJS Foundation and other contributors <https://openjsf.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ (function(){function n(n,t,r){switch(r.length){case 0:return n.call(t);case 1:return n.call(t,r[0]);case 2:return n.call(t,r[0],r[1]);case 3:return n.call(t,r[0],r[1],r[2])}return n.apply(t,r)}function t(n,t,r,e){for(var u=-1,i=null==n?0:n.length;++u<i;){var o=n[u];t(e,o,r(o),n)}return e}function r(n,t){for(var r=-1,e=null==n?0:n.length;++r<e&&!1!==t(n[r],r,n););return n}function e(n,t){for(var r=null==n?0:n.length;r--&&!1!==t(n[r],r,n););return n}function u(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(!t(n[r],r,n))return!1;return!0}function i(n,t){for(var r=-1,e=null==n?0:n.length,u=0,i=[];++r<e;){var o=n[r];t(o,r,n)&&(i[u++]=o)}return i}function o(n,t){return!(null==n||!n.length)&&g(n,t,0)>-1}function f(n,t,r){for(var e=-1,u=null==n?0:n.length;++e<u;)if(r(t,n[e]))return!0;return!1}function c(n,t){for(var r=-1,e=null==n?0:n.length,u=Array(e);++r<e;)u[r]=t(n[r],r,n);return u}function a(n,t){for(var r=-1,e=t.length,u=n.length;++r<e;)n[u+r]=t[r];return n}function l(n,t,r,e){var u=-1,i=null==n?0:n.length;for(e&&i&&(r=n[++u]);++u<i;)r=t(r,n[u],u,n);return r}function s(n,t,r,e){var u=null==n?0:n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);return r}function h(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(t(n[r],r,n))return!0;return!1}function p(n){return n.match(Jn)||[]}function _(n,t,r){var e;return r(n,(function(n,r,u){if(t(n,r,u))return e=r,!1})),e}function v(n,t,r,e){for(var u=n.length,i=r+(e?1:-1);e?i--:++i<u;)if(t(n[i],i,n))return i;return-1}function g(n,t,r){return t==t?function(n,t,r){for(var e=r-1,u=n.length;++e<u;)if(n[e]===t)return e;return-1}(n,t,r):v(n,d,r)}function y(n,t,r,e){for(var u=r-1,i=n.length;++u<i;)if(e(n[u],t))return u;return-1}function d(n){return n!=n}function b(n,t){var r=null==n?0:n.length;return r?j(n,t)/r:X}function w(n){return function(t){return null==t?N:t[n]}}function m(n){return function(t){return null==n?N:n[t]}}function x(n,t,r,e,u){return u(n,(function(n,u,i){r=e?(e=!1,n):t(r,n,u,i)})),r}function j(n,t){for(var r,e=-1,u=n.length;++e<u;){var i=t(n[e]);i!==N&&(r=r===N?i:r+i)}return r}function A(n,t){for(var r=-1,e=Array(n);++r<n;)e[r]=t(r);return e}function k(n){return n?n.slice(0,M(n)+1).replace(Zn,""):n}function O(n){return function(t){return n(t)}}function I(n,t){return c(t,(function(t){return n[t]}))}function R(n,t){return n.has(t)}function z(n,t){for(var r=-1,e=n.length;++r<e&&g(t,n[r],0)>-1;);return r}function E(n,t){for(var r=n.length;r--&&g(t,n[r],0)>-1;);return r}function S(n){return"\\"+Ht[n]}function W(n){return Pt.test(n)}function L(n){return qt.test(n)}function C(n){var t=-1,r=Array(n.size);return n.forEach((function(n,e){r[++t]=[e,n]})),r}function U(n,t){return function(r){return n(t(r))}}function B(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){var o=n[r];o!==t&&o!==Z||(n[r]=Z,i[u++]=r)}return i}function T(n){var t=-1,r=Array(n.size);return n.forEach((function(n){r[++t]=n})),r}function $(n){return W(n)?function(n){for(var t=Ft.lastIndex=0;Ft.test(n);)++t;return t}(n):hr(n)}function D(n){return W(n)?function(n){return n.match(Ft)||[]}(n):function(n){return n.split("")}(n)}function M(n){for(var t=n.length;t--&&Kn.test(n.charAt(t)););return t}function F(n){return n.match(Nt)||[]}var N,P="Expected a function",q="__lodash_hash_undefined__",Z="__lodash_placeholder__",K=16,V=32,G=64,H=128,J=256,Y=1/0,Q=9007199254740991,X=NaN,nn=4294967295,tn=[["ary",H],["bind",1],["bindKey",2],["curry",8],["curryRight",K],["flip",512],["partial",V],["partialRight",G],["rearg",J]],rn="[object Arguments]",en="[object Array]",un="[object Boolean]",on="[object Date]",fn="[object Error]",cn="[object Function]",an="[object GeneratorFunction]",ln="[object Map]",sn="[object Number]",hn="[object Object]",pn="[object Promise]",_n="[object RegExp]",vn="[object Set]",gn="[object String]",yn="[object Symbol]",dn="[object WeakMap]",bn="[object ArrayBuffer]",wn="[object DataView]",mn="[object Float32Array]",xn="[object Float64Array]",jn="[object Int8Array]",An="[object Int16Array]",kn="[object Int32Array]",On="[object Uint8Array]",In="[object Uint8ClampedArray]",Rn="[object Uint16Array]",zn="[object Uint32Array]",En=/\b__p \+= '';/g,Sn=/\b(__p \+=) '' \+/g,Wn=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Ln=/&(?:amp|lt|gt|quot|#39);/g,Cn=/[&<>"']/g,Un=RegExp(Ln.source),Bn=RegExp(Cn.source),Tn=/<%-([\s\S]+?)%>/g,$n=/<%([\s\S]+?)%>/g,Dn=/<%=([\s\S]+?)%>/g,Mn=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Fn=/^\w*$/,Nn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Pn=/[\\^$.*+?()[\]{}|]/g,qn=RegExp(Pn.source),Zn=/^\s+/,Kn=/\s/,Vn=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gn=/\{\n\/\* \[wrapped with (.+)\] \*/,Hn=/,? & /,Jn=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Yn=/[()=,{}\[\]\/\s]/,Qn=/\\(\\)?/g,Xn=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,nt=/\w*$/,tt=/^[-+]0x[0-9a-f]+$/i,rt=/^0b[01]+$/i,et=/^\[object .+?Constructor\]$/,ut=/^0o[0-7]+$/i,it=/^(?:0|[1-9]\d*)$/,ot=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ft=/($^)/,ct=/['\n\r\u2028\u2029\\]/g,at="\\ud800-\\udfff",lt="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",st="\\u2700-\\u27bf",ht="a-z\\xdf-\\xf6\\xf8-\\xff",pt="A-Z\\xc0-\\xd6\\xd8-\\xde",_t="\\ufe0e\\ufe0f",vt="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",gt="['’]",yt="["+at+"]",dt="["+vt+"]",bt="["+lt+"]",wt="\\d+",mt="["+st+"]",xt="["+ht+"]",jt="[^"+at+vt+wt+st+ht+pt+"]",At="\\ud83c[\\udffb-\\udfff]",kt="[^"+at+"]",Ot="(?:\\ud83c[\\udde6-\\uddff]){2}",It="[\\ud800-\\udbff][\\udc00-\\udfff]",Rt="["+pt+"]",zt="\\u200d",Et="(?:"+xt+"|"+jt+")",St="(?:"+Rt+"|"+jt+")",Wt="(?:['’](?:d|ll|m|re|s|t|ve))?",Lt="(?:['’](?:D|LL|M|RE|S|T|VE))?",Ct="(?:"+bt+"|"+At+")"+"?",Ut="["+_t+"]?",Bt=Ut+Ct+("(?:"+zt+"(?:"+[kt,Ot,It].join("|")+")"+Ut+Ct+")*"),Tt="(?:"+[mt,Ot,It].join("|")+")"+Bt,$t="(?:"+[kt+bt+"?",bt,Ot,It,yt].join("|")+")",Dt=RegExp(gt,"g"),Mt=RegExp(bt,"g"),Ft=RegExp(At+"(?="+At+")|"+$t+Bt,"g"),Nt=RegExp([Rt+"?"+xt+"+"+Wt+"(?="+[dt,Rt,"$"].join("|")+")",St+"+"+Lt+"(?="+[dt,Rt+Et,"$"].join("|")+")",Rt+"?"+Et+"+"+Wt,Rt+"+"+Lt,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",wt,Tt].join("|"),"g"),Pt=RegExp("["+zt+at+lt+_t+"]"),qt=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Zt=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Kt=-1,Vt={};Vt[mn]=Vt[xn]=Vt[jn]=Vt[An]=Vt[kn]=Vt[On]=Vt[In]=Vt[Rn]=Vt[zn]=!0,Vt[rn]=Vt[en]=Vt[bn]=Vt[un]=Vt[wn]=Vt[on]=Vt[fn]=Vt[cn]=Vt[ln]=Vt[sn]=Vt[hn]=Vt[_n]=Vt[vn]=Vt[gn]=Vt[dn]=!1;var Gt={};Gt[rn]=Gt[en]=Gt[bn]=Gt[wn]=Gt[un]=Gt[on]=Gt[mn]=Gt[xn]=Gt[jn]=Gt[An]=Gt[kn]=Gt[ln]=Gt[sn]=Gt[hn]=Gt[_n]=Gt[vn]=Gt[gn]=Gt[yn]=Gt[On]=Gt[In]=Gt[Rn]=Gt[zn]=!0,Gt[fn]=Gt[cn]=Gt[dn]=!1;var Ht={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Jt=parseFloat,Yt=parseInt,Qt="object"==typeof global&&global&&global.Object===Object&&global,Xt="object"==typeof self&&self&&self.Object===Object&&self,nr=Qt||Xt||Function("return this")(),tr="object"==typeof exports&&exports&&!exports.nodeType&&exports,rr=tr&&"object"==typeof module&&module&&!module.nodeType&&module,er=rr&&rr.exports===tr,ur=er&&Qt.process,ir=function(){try{var n=rr&&rr.require&&rr.require("util").types;return n||ur&&ur.binding&&ur.binding("util")}catch(n){}}(),or=ir&&ir.isArrayBuffer,fr=ir&&ir.isDate,cr=ir&&ir.isMap,ar=ir&&ir.isRegExp,lr=ir&&ir.isSet,sr=ir&&ir.isTypedArray,hr=w("length"),pr=m({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"}),_r=m({"&":"&","<":"<",">":">",'"':""","'":"'"}),vr=m({"&":"&","<":"<",">":">",""":'"',"'":"'"}),gr=function m(Kn){function Jn(n){if($u(n)&&!zf(n)&&!(n instanceof st)){if(n instanceof lt)return n;if(Ii.call(n,"__wrapped__"))return lu(n)}return new lt(n)}function at(){}function lt(n,t){this.__wrapped__=n,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=N}function st(n){this.__wrapped__=n,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=nn,this.__views__=[]}function ht(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function pt(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function _t(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function vt(n){var t=-1,r=null==n?0:n.length;for(this.__data__=new _t;++t<r;)this.add(n[t])}function gt(n){this.size=(this.__data__=new pt(n)).size}function yt(n,t){var r=zf(n),e=!r&&Rf(n),u=!r&&!e&&Sf(n),i=!r&&!e&&!u&&Bf(n),o=r||e||u||i,f=o?A(n.length,wi):[],c=f.length;for(var a in n)!t&&!Ii.call(n,a)||o&&("length"==a||u&&("offset"==a||"parent"==a)||i&&("buffer"==a||"byteLength"==a||"byteOffset"==a)||Ge(a,c))||f.push(a);return f}function dt(n){var t=n.length;return t?n[Sr(0,t-1)]:N}function bt(n,t){return ou(ce(n),Rt(t,0,n.length))}function wt(n){return ou(ce(n))}function mt(n,t,r){(r===N||Eu(n[t],r))&&(r!==N||t in n)||Ot(n,t,r)}function xt(n,t,r){var e=n[t];Ii.call(n,t)&&Eu(e,r)&&(r!==N||t in n)||Ot(n,t,r)}function jt(n,t){for(var r=n.length;r--;)if(Eu(n[r][0],t))return r;return-1}function At(n,t,r,e){return Oo(n,(function(n,u,i){t(e,n,r(n),i)})),e}function kt(n,t){return n&&ae(t,Qu(t),n)}function Ot(n,t,r){"__proto__"==t&&Zi?Zi(n,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):n[t]=r}function It(n,t){for(var r=-1,e=t.length,u=pi(e),i=null==n;++r<e;)u[r]=i?N:Ju(n,t[r]);return u}function Rt(n,t,r){return n==n&&(r!==N&&(n=n<=r?n:r),t!==N&&(n=n>=t?n:t)),n}function zt(n,t,e,u,i,o){var f,c=1&t,a=2&t,l=4&t;if(e&&(f=i?e(n,u,i,o):e(n)),f!==N)return f;if(!Tu(n))return n;var s=zf(n);if(s){if(f=function(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&Ii.call(n,"index")&&(r.index=n.index,r.input=n.input),r}(n),!c)return ce(n,f)}else{var h=$o(n),p=h==cn||h==an;if(Sf(n))return re(n,c);if(h==hn||h==rn||p&&!i){if(f=a||p?{}:Ke(n),!c)return a?function(n,t){return ae(n,To(n),t)}(n,function(n,t){return n&&ae(t,Xu(t),n)}(f,n)):function(n,t){return ae(n,Bo(n),t)}(n,kt(f,n))}else{if(!Gt[h])return i?n:{};f=function(n,t,r){var e=n.constructor;switch(t){case bn:return ee(n);case un:case on:return new e(+n);case wn:return function(n,t){return new n.constructor(t?ee(n.buffer):n.buffer,n.byteOffset,n.byteLength)}(n,r);case mn:case xn:case jn:case An:case kn:case On:case In:case Rn:case zn:return ue(n,r);case ln:return new e;case sn:case gn:return new e(n);case _n:return function(n){var t=new n.constructor(n.source,nt.exec(n));return t.lastIndex=n.lastIndex,t}(n);case vn:return new e;case yn:return function(n){return jo?di(jo.call(n)):{}}(n)}}(n,h,c)}}o||(o=new gt);var _=o.get(n);if(_)return _;o.set(n,f),Uf(n)?n.forEach((function(r){f.add(zt(r,t,e,r,n,o))})):Lf(n)&&n.forEach((function(r,u){f.set(u,zt(r,t,e,u,n,o))}));var v=s?N:(l?a?$e:Te:a?Xu:Qu)(n);return r(v||n,(function(r,u){v&&(r=n[u=r]),xt(f,u,zt(r,t,e,u,n,o))})),f}function Et(n,t,r){var e=r.length;if(null==n)return!e;for(n=di(n);e--;){var u=r[e],i=t[u],o=n[u];if(o===N&&!(u in n)||!i(o))return!1}return!0}function St(n,t,r){if("function"!=typeof n)throw new mi(P);return Fo((function(){n.apply(N,r)}),t)}function Wt(n,t,r,e){var u=-1,i=o,a=!0,l=n.length,s=[],h=t.length;if(!l)return s;r&&(t=c(t,O(r))),e?(i=f,a=!1):t.length>=200&&(i=R,a=!1,t=new vt(t));n:for(;++u<l;){var p=n[u],_=null==r?p:r(p);if(p=e||0!==p?p:0,a&&_==_){for(var v=h;v--;)if(t[v]===_)continue n;s.push(p)}else i(t,_,e)||s.push(p)}return s}function Lt(n,t){var r=!0;return Oo(n,(function(n,e,u){return r=!!t(n,e,u)})),r}function Ct(n,t,r){for(var e=-1,u=n.length;++e<u;){var i=n[e],o=t(i);if(null!=o&&(f===N?o==o&&!Nu(o):r(o,f)))var f=o,c=i}return c}function Ut(n,t){var r=[];return Oo(n,(function(n,e,u){t(n,e,u)&&r.push(n)})),r}function Bt(n,t,r,e,u){var i=-1,o=n.length;for(r||(r=Ve),u||(u=[]);++i<o;){var f=n[i];t>0&&r(f)?t>1?Bt(f,t-1,r,e,u):a(u,f):e||(u[u.length]=f)}return u}function Tt(n,t){return n&&Ro(n,t,Qu)}function $t(n,t){return n&&zo(n,t,Qu)}function Ft(n,t){return i(t,(function(t){return Cu(n[t])}))}function Nt(n,t){for(var r=0,e=(t=ne(t,n)).length;null!=n&&r<e;)n=n[fu(t[r++])];return r&&r==e?n:N}function Pt(n,t,r){var e=t(n);return zf(n)?e:a(e,r(n))}function qt(n){return null==n?n===N?"[object Undefined]":"[object Null]":qi&&qi in di(n)?function(n){var t=Ii.call(n,qi),r=n[qi];try{n[qi]=N;var e=!0}catch(n){}var u=Ei.call(n);return e&&(t?n[qi]=r:delete n[qi]),u}(n):function(n){return Ei.call(n)}(n)}function Ht(n,t){return n>t}function Qt(n,t){return null!=n&&Ii.call(n,t)}function Xt(n,t){return null!=n&&t in di(n)}function tr(n,t,r){for(var e=r?f:o,u=n[0].length,i=n.length,a=i,l=pi(i),s=1/0,h=[];a--;){var p=n[a];a&&t&&(p=c(p,O(t))),s=eo(p.length,s),l[a]=!r&&(t||u>=120&&p.length>=120)?new vt(a&&p):N}p=n[0];var _=-1,v=l[0];n:for(;++_<u&&h.length<s;){var g=p[_],y=t?t(g):g;if(g=r||0!==g?g:0,!(v?R(v,y):e(h,y,r))){for(a=i;--a;){var d=l[a];if(!(d?R(d,y):e(n[a],y,r)))continue n}v&&v.push(y),h.push(g)}}return h}function rr(t,r,e){var u=null==(t=ru(t,r=ne(r,t)))?t:t[fu(vu(r))];return null==u?N:n(u,t,e)}function ur(n){return $u(n)&&qt(n)==rn}function ir(n,t,r,e,u){return n===t||(null==n||null==t||!$u(n)&&!$u(t)?n!=n&&t!=t:function(n,t,r,e,u,i){var o=zf(n),f=zf(t),c=o?en:$o(n),a=f?en:$o(t);c=c==rn?hn:c,a=a==rn?hn:a;var l=c==hn,s=a==hn,h=c==a;if(h&&Sf(n)){if(!Sf(t))return!1;o=!0,l=!1}if(h&&!l)return i||(i=new gt),o||Bf(n)?Ue(n,t,r,e,u,i):function(n,t,r,e,u,i,o){switch(r){case wn:if(n.byteLength!=t.byteLength||n.byteOffset!=t.byteOffset)return!1;n=n.buffer,t=t.buffer;case bn:return!(n.byteLength!=t.byteLength||!i(new Bi(n),new Bi(t)));case un:case on:case sn:return Eu(+n,+t);case fn:return n.name==t.name&&n.message==t.message;case _n:case gn:return n==t+"";case ln:var f=C;case vn:var c=1&e;if(f||(f=T),n.size!=t.size&&!c)return!1;var a=o.get(n);if(a)return a==t;e|=2,o.set(n,t);var l=Ue(f(n),f(t),e,u,i,o);return o.delete(n),l;case yn:if(jo)return jo.call(n)==jo.call(t)}return!1}(n,t,c,r,e,u,i);if(!(1&r)){var p=l&&Ii.call(n,"__wrapped__"),_=s&&Ii.call(t,"__wrapped__");if(p||_){var v=p?n.value():n,g=_?t.value():t;return i||(i=new gt),u(v,g,r,e,i)}}return!!h&&(i||(i=new gt),function(n,t,r,e,u,i){var o=1&r,f=Te(n),c=f.length;if(c!=Te(t).length&&!o)return!1;for(var a=c;a--;){var l=f[a];if(!(o?l in t:Ii.call(t,l)))return!1}var s=i.get(n),h=i.get(t);if(s&&h)return s==t&&h==n;var p=!0;i.set(n,t),i.set(t,n);for(var _=o;++a<c;){var v=n[l=f[a]],g=t[l];if(e)var y=o?e(g,v,l,t,n,i):e(v,g,l,n,t,i);if(!(y===N?v===g||u(v,g,r,e,i):y)){p=!1;break}_||(_="constructor"==l)}if(p&&!_){var d=n.constructor,b=t.constructor;d!=b&&"constructor"in n&&"constructor"in t&&!("function"==typeof d&&d instanceof d&&"function"==typeof b&&b instanceof b)&&(p=!1)}return i.delete(n),i.delete(t),p}(n,t,r,e,u,i))}(n,t,r,e,ir,u))}function hr(n,t,r,e){var u=r.length,i=u,o=!e;if(null==n)return!i;for(n=di(n);u--;){var f=r[u];if(o&&f[2]?f[1]!==n[f[0]]:!(f[0]in n))return!1}for(;++u<i;){var c=(f=r[u])[0],a=n[c],l=f[1];if(o&&f[2]){if(a===N&&!(c in n))return!1}else{var s=new gt;if(e)var h=e(a,l,c,n,t,s);if(!(h===N?ir(l,a,3,e,s):h))return!1}}return!0}function yr(n){return!(!Tu(n)||function(n){return!!zi&&zi in n}(n))&&(Cu(n)?Li:et).test(cu(n))}function dr(n){return"function"==typeof n?n:null==n?oi:"object"==typeof n?zf(n)?Ar(n[0],n[1]):jr(n):li(n)}function br(n){if(!Qe(n))return to(n);var t=[];for(var r in di(n))Ii.call(n,r)&&"constructor"!=r&&t.push(r);return t}function wr(n){if(!Tu(n))return function(n){var t=[];if(null!=n)for(var r in di(n))t.push(r);return t}(n);var t=Qe(n),r=[];for(var e in n)("constructor"!=e||!t&&Ii.call(n,e))&&r.push(e);return r}function mr(n,t){return n<t}function xr(n,t){var r=-1,e=Su(n)?pi(n.length):[];return Oo(n,(function(n,u,i){e[++r]=t(n,u,i)})),e}function jr(n){var t=Pe(n);return 1==t.length&&t[0][2]?nu(t[0][0],t[0][1]):function(r){return r===n||hr(r,n,t)}}function Ar(n,t){return Je(n)&&Xe(t)?nu(fu(n),t):function(r){var e=Ju(r,n);return e===N&&e===t?Yu(r,n):ir(t,e,3)}}function kr(n,t,r,e,u){n!==t&&Ro(t,(function(i,o){if(u||(u=new gt),Tu(i))!function(n,t,r,e,u,i,o){var f=eu(n,r),c=eu(t,r),a=o.get(c);if(a)return mt(n,r,a),N;var l=i?i(f,c,r+"",n,t,o):N,s=l===N;if(s){var h=zf(c),p=!h&&Sf(c),_=!h&&!p&&Bf(c);l=c,h||p||_?zf(f)?l=f:Wu(f)?l=ce(f):p?(s=!1,l=re(c,!0)):_?(s=!1,l=ue(c,!0)):l=[]:Mu(c)||Rf(c)?(l=f,Rf(f)?l=Gu(f):Tu(f)&&!Cu(f)||(l=Ke(c))):s=!1}s&&(o.set(c,l),u(l,c,e,i,o),o.delete(c)),mt(n,r,l)}(n,t,o,r,kr,e,u);else{var f=e?e(eu(n,o),i,o+"",n,t,u):N;f===N&&(f=i),mt(n,o,f)}}),Xu)}function Or(n,t){var r=n.length;if(r)return Ge(t+=t<0?r:0,r)?n[t]:N}function Ir(n,t,r){t=t.length?c(t,(function(n){return zf(n)?function(t){return Nt(t,1===n.length?n[0]:n)}:n})):[oi];var e=-1;return t=c(t,O(Fe())),function(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].value;return n}(xr(n,(function(n,r,u){return{criteria:c(t,(function(t){return t(n)})),index:++e,value:n}})),(function(n,t){return function(n,t,r){for(var e=-1,u=n.criteria,i=t.criteria,o=u.length,f=r.length;++e<o;){var c=ie(u[e],i[e]);if(c)return e>=f?c:c*("desc"==r[e]?-1:1)}return n.index-t.index}(n,t,r)}))}function Rr(n,t,r){for(var e=-1,u=t.length,i={};++e<u;){var o=t[e],f=Nt(n,o);r(f,o)&&Br(i,ne(o,n),f)}return i}function zr(n,t,r,e){var u=e?y:g,i=-1,o=t.length,f=n;for(n===t&&(t=ce(t)),r&&(f=c(n,O(r)));++i<o;)for(var a=0,l=t[i],s=r?r(l):l;(a=u(f,s,a,e))>-1;)f!==n&&Fi.call(f,a,1),Fi.call(n,a,1);return n}function Er(n,t){for(var r=n?t.length:0,e=r-1;r--;){var u=t[r];if(r==e||u!==i){var i=u;Ge(u)?Fi.call(n,u,1):Kr(n,u)}}return n}function Sr(n,t){return n+Ji(oo()*(t-n+1))}function Wr(n,t){var r="";if(!n||t<1||t>Q)return r;do{t%2&&(r+=n),(t=Ji(t/2))&&(n+=n)}while(t);return r}function Lr(n,t){return No(tu(n,t,oi),n+"")}function Cr(n){return dt(ti(n))}function Ur(n,t){var r=ti(n);return ou(r,Rt(t,0,r.length))}function Br(n,t,r,e){if(!Tu(n))return n;for(var u=-1,i=(t=ne(t,n)).length,o=i-1,f=n;null!=f&&++u<i;){var c=fu(t[u]),a=r;if("__proto__"===c||"constructor"===c||"prototype"===c)return n;if(u!=o){var l=f[c];(a=e?e(l,c,f):N)===N&&(a=Tu(l)?l:Ge(t[u+1])?[]:{})}xt(f,c,a),f=f[c]}return n}function Tr(n){return ou(ti(n))}function $r(n,t,r){var e=-1,u=n.length;t<0&&(t=-t>u?0:u+t),(r=r>u?u:r)<0&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0;for(var i=pi(u);++e<u;)i[e]=n[e+t];return i}function Dr(n,t){var r;return Oo(n,(function(n,e,u){return!(r=t(n,e,u))})),!!r}function Mr(n,t,r){var e=0,u=null==n?e:n.length;if("number"==typeof t&&t==t&&u<=2147483647){for(;e<u;){var i=e+u>>>1,o=n[i];null!==o&&!Nu(o)&&(r?o<=t:o<t)?e=i+1:u=i}return u}return Fr(n,t,oi,r)}function Fr(n,t,r,e){var u=0,i=null==n?0:n.length;if(0===i)return 0;for(var o=(t=r(t))!=t,f=null===t,c=Nu(t),a=t===N;u<i;){var l=Ji((u+i)/2),s=r(n[l]),h=s!==N,p=null===s,_=s==s,v=Nu(s);if(o)var g=e||_;else g=a?_&&(e||h):f?_&&h&&(e||!p):c?_&&h&&!p&&(e||!v):!p&&!v&&(e?s<=t:s<t);g?u=l+1:i=l}return eo(i,4294967294)}function Nr(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){var o=n[r],f=t?t(o):o;if(!r||!Eu(f,c)){var c=f;i[u++]=0===o?0:o}}return i}function Pr(n){return"number"==typeof n?n:Nu(n)?X:+n}function qr(n){if("string"==typeof n)return n;if(zf(n))return c(n,qr)+"";if(Nu(n))return Ao?Ao.call(n):"";var t=n+"";return"0"==t&&1/n==-Y?"-0":t}function Zr(n,t,r){var e=-1,u=o,i=n.length,c=!0,a=[],l=a;if(r)c=!1,u=f;else if(i>=200){var s=t?null:Co(n);if(s)return T(s);c=!1,u=R,l=new vt}else l=t?[]:a;n:for(;++e<i;){var h=n[e],p=t?t(h):h;if(h=r||0!==h?h:0,c&&p==p){for(var _=l.length;_--;)if(l[_]===p)continue n;t&&l.push(p),a.push(h)}else u(l,p,r)||(l!==a&&l.push(p),a.push(h))}return a}function Kr(n,t){return null==(n=ru(n,t=ne(t,n)))||delete n[fu(vu(t))]}function Vr(n,t,r,e){return Br(n,t,r(Nt(n,t)),e)}function Gr(n,t,r,e){for(var u=n.length,i=e?u:-1;(e?i--:++i<u)&&t(n[i],i,n););return r?$r(n,e?0:i,e?i+1:u):$r(n,e?i+1:0,e?u:i)}function Hr(n,t){var r=n;return r instanceof st&&(r=r.value()),l(t,(function(n,t){return t.func.apply(t.thisArg,a([n],t.args))}),r)}function Jr(n,t,r){var e=n.length;if(e<2)return e?Zr(n[0]):[];for(var u=-1,i=pi(e);++u<e;)for(var o=n[u],f=-1;++f<e;)f!=u&&(i[u]=Wt(i[u]||o,n[f],t,r));return Zr(Bt(i,1),t,r)}function Yr(n,t,r){for(var e=-1,u=n.length,i=t.length,o={};++e<u;)r(o,n[e],e<i?t[e]:N);return o}function Qr(n){return Wu(n)?n:[]}function Xr(n){return"function"==typeof n?n:oi}function ne(n,t){return zf(n)?n:Je(n,t)?[n]:Po(Hu(n))}function te(n,t,r){var e=n.length;return r=r===N?e:r,!t&&r>=e?n:$r(n,t,r)}function re(n,t){if(t)return n.slice();var r=n.length,e=Ti?Ti(r):new n.constructor(r);return n.copy(e),e}function ee(n){var t=new n.constructor(n.byteLength);return new Bi(t).set(new Bi(n)),t}function ue(n,t){return new n.constructor(t?ee(n.buffer):n.buffer,n.byteOffset,n.length)}function ie(n,t){if(n!==t){var r=n!==N,e=null===n,u=n==n,i=Nu(n),o=t!==N,f=null===t,c=t==t,a=Nu(t);if(!f&&!a&&!i&&n>t||i&&o&&c&&!f&&!a||e&&o&&c||!r&&c||!u)return 1;if(!e&&!i&&!a&&n<t||a&&r&&u&&!e&&!i||f&&r&&u||!o&&u||!c)return-1}return 0}function oe(n,t,r,e){for(var u=-1,i=n.length,o=r.length,f=-1,c=t.length,a=ro(i-o,0),l=pi(c+a),s=!e;++f<c;)l[f]=t[f];for(;++u<o;)(s||u<i)&&(l[r[u]]=n[u]);for(;a--;)l[f++]=n[u++];return l}function fe(n,t,r,e){for(var u=-1,i=n.length,o=-1,f=r.length,c=-1,a=t.length,l=ro(i-f,0),s=pi(l+a),h=!e;++u<l;)s[u]=n[u];for(var p=u;++c<a;)s[p+c]=t[c];for(;++o<f;)(h||u<i)&&(s[p+r[o]]=n[u++]);return s}function ce(n,t){var r=-1,e=n.length;for(t||(t=pi(e));++r<e;)t[r]=n[r];return t}function ae(n,t,r,e){var u=!r;r||(r={});for(var i=-1,o=t.length;++i<o;){var f=t[i],c=e?e(r[f],n[f],f,r,n):N;c===N&&(c=n[f]),u?Ot(r,f,c):xt(r,f,c)}return r}function le(n,r){return function(e,u){var i=zf(e)?t:At,o=r?r():{};return i(e,n,Fe(u,2),o)}}function se(n){return Lr((function(t,r){var e=-1,u=r.length,i=u>1?r[u-1]:N,o=u>2?r[2]:N;for(i=n.length>3&&"function"==typeof i?(u--,i):N,o&&He(r[0],r[1],o)&&(i=u<3?N:i,u=1),t=di(t);++e<u;){var f=r[e];f&&n(t,f,e,i)}return t}))}function he(n,t){return function(r,e){if(null==r)return r;if(!Su(r))return n(r,e);for(var u=r.length,i=t?u:-1,o=di(r);(t?i--:++i<u)&&!1!==e(o[i],i,o););return r}}function pe(n){return function(t,r,e){for(var u=-1,i=di(t),o=e(t),f=o.length;f--;){var c=o[n?f:++u];if(!1===r(i[c],c,i))break}return t}}function _e(n){return function(t){var r=W(t=Hu(t))?D(t):N,e=r?r[0]:t.charAt(0),u=r?te(r,1).join(""):t.slice(1);return e[n]()+u}}function ve(n){return function(t){return l(ui(ei(t).replace(Dt,"")),n,"")}}function ge(n){return function(){var t=arguments;switch(t.length){case 0:return new n;case 1:return new n(t[0]);case 2:return new n(t[0],t[1]);case 3:return new n(t[0],t[1],t[2]);case 4:return new n(t[0],t[1],t[2],t[3]);case 5:return new n(t[0],t[1],t[2],t[3],t[4]);case 6:return new n(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new n(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=ko(n.prototype),e=n.apply(r,t);return Tu(e)?e:r}}function ye(t,r,e){var u=ge(t);return function i(){for(var o=arguments.length,f=pi(o),c=o,a=Me(i);c--;)f[c]=arguments[c];var l=o<3&&f[0]!==a&&f[o-1]!==a?[]:B(f,a);return(o-=l.length)<e?Re(t,r,we,i.placeholder,N,f,l,N,N,e-o):n(this&&this!==nr&&this instanceof i?u:t,this,f)}}function de(n){return function(t,r,e){var u=di(t);if(!Su(t)){var i=Fe(r,3);t=Qu(t),r=function(n){return i(u[n],n,u)}}var o=n(t,r,e);return o>-1?u[i?t[o]:o]:N}}function be(n){return Be((function(t){var r=t.length,e=r,u=lt.prototype.thru;for(n&&t.reverse();e--;){var i=t[e];if("function"!=typeof i)throw new mi(P);if(u&&!o&&"wrapper"==De(i))var o=new lt([],!0)}for(e=o?e:r;++e<r;){var f=De(i=t[e]),c="wrapper"==f?Uo(i):N;o=c&&Ye(c[0])&&424==c[1]&&!c[4].length&&1==c[9]?o[De(c[0])].apply(o,c[3]):1==i.length&&Ye(i)?o[f]():o.thru(i)}return function(){var n=arguments,e=n[0];if(o&&1==n.length&&zf(e))return o.plant(e).value();for(var u=0,i=r?t[u].apply(this,n):e;++u<r;)i=t[u].call(this,i);return i}}))}function we(n,t,r,e,u,i,o,f,c,a){var l=t&H,s=1&t,h=2&t,p=24&t,_=512&t,v=h?N:ge(n);return function g(){for(var y=arguments.length,d=pi(y),b=y;b--;)d[b]=arguments[b];if(p)var w=Me(g),m=function(n,t){for(var r=n.length,e=0;r--;)n[r]===t&&++e;return e}(d,w);if(e&&(d=oe(d,e,u,p)),i&&(d=fe(d,i,o,p)),y-=m,p&&y<a)return Re(n,t,we,g.placeholder,r,d,B(d,w),f,c,a-y);var x=s?r:this,j=h?x[n]:n;return y=d.length,f?d=function(n,t){for(var r=n.length,e=eo(t.length,r),u=ce(n);e--;){var i=t[e];n[e]=Ge(i,r)?u[i]:N}return n}(d,f):_&&y>1&&d.reverse(),l&&c<y&&(d.length=c),this&&this!==nr&&this instanceof g&&(j=v||ge(j)),j.apply(x,d)}}function me(n,t){return function(r,e){return function(n,t,r,e){return Tt(n,(function(n,u,i){t(e,r(n),u,i)})),e}(r,n,t(e),{})}}function xe(n,t){return function(r,e){var u;if(r===N&&e===N)return t;if(r!==N&&(u=r),e!==N){if(u===N)return e;"string"==typeof r||"string"==typeof e?(r=qr(r),e=qr(e)):(r=Pr(r),e=Pr(e)),u=n(r,e)}return u}}function je(t){return Be((function(r){return r=c(r,O(Fe())),Lr((function(e){var u=this;return t(r,(function(t){return n(t,u,e)}))}))}))}function Ae(n,t){var r=(t=t===N?" ":qr(t)).length;if(r<2)return r?Wr(t,n):t;var e=Wr(t,Hi(n/$(t)));return W(t)?te(D(e),0,n).join(""):e.slice(0,n)}function ke(t,r,e,u){var i=1&r,o=ge(t);return function r(){for(var f=-1,c=arguments.length,a=-1,l=u.length,s=pi(l+c),h=this&&this!==nr&&this instanceof r?o:t;++a<l;)s[a]=u[a];for(;c--;)s[a++]=arguments[++f];return n(h,i?e:this,s)}}function Oe(n){return function(t,r,e){return e&&"number"!=typeof e&&He(t,r,e)&&(r=e=N),t=qu(t),r===N?(r=t,t=0):r=qu(r),function(n,t,r,e){for(var u=-1,i=ro(Hi((t-n)/(r||1)),0),o=pi(i);i--;)o[e?i:++u]=n,n+=r;return o}(t,r,e=e===N?t<r?1:-1:qu(e),n)}}function Ie(n){return function(t,r){return"string"==typeof t&&"string"==typeof r||(t=Vu(t),r=Vu(r)),n(t,r)}}function Re(n,t,r,e,u,i,o,f,c,a){var l=8&t;t|=l?V:G,4&(t&=~(l?G:V))||(t&=-4);var s=[n,t,u,l?i:N,l?o:N,l?N:i,l?N:o,f,c,a],h=r.apply(N,s);return Ye(n)&&Mo(h,s),h.placeholder=e,uu(h,n,t)}function ze(n){var t=yi[n];return function(n,r){if(n=Vu(n),(r=null==r?0:eo(Zu(r),292))&&Xi(n)){var e=(Hu(n)+"e").split("e");return+((e=(Hu(t(e[0]+"e"+(+e[1]+r)))+"e").split("e"))[0]+"e"+(+e[1]-r))}return t(n)}}function Ee(n){return function(t){var r=$o(t);return r==ln?C(t):r==vn?function(n){var t=-1,r=Array(n.size);return n.forEach((function(n){r[++t]=[n,n]})),r}(t):function(n,t){return c(t,(function(t){return[t,n[t]]}))}(t,n(t))}}function Se(n,t,r,e,u,i,o,f){var c=2&t;if(!c&&"function"!=typeof n)throw new mi(P);var a=e?e.length:0;if(a||(t&=-97,e=u=N),o=o===N?o:ro(Zu(o),0),f=f===N?f:Zu(f),a-=u?u.length:0,t&G){var l=e,s=u;e=u=N}var h=c?N:Uo(n),p=[n,t,r,e,u,l,s,i,o,f];if(h&&function(n,t){var r=n[1],e=t[1],u=r|e,i=u<131,o=e==H&&8==r||e==H&&r==J&&n[7].length<=t[8]||384==e&&t[7].length<=t[8]&&8==r;if(!i&&!o)return n;1&e&&(n[2]=t[2],u|=1&r?0:4);var f=t[3];if(f){var c=n[3];n[3]=c?oe(c,f,t[4]):f,n[4]=c?B(n[3],Z):t[4]}f=t[5],f&&(c=n[5],n[5]=c?fe(c,f,t[6]):f,n[6]=c?B(n[5],Z):t[6]),f=t[7],f&&(n[7]=f),e&H&&(n[8]=null==n[8]?t[8]:eo(n[8],t[8])),null==n[9]&&(n[9]=t[9]),n[0]=t[0],n[1]=u}(p,h),n=p[0],t=p[1],r=p[2],e=p[3],u=p[4],!(f=p[9]=p[9]===N?c?0:n.length:ro(p[9]-a,0))&&24&t&&(t&=-25),t&&1!=t)_=8==t||t==K?ye(n,t,f):t!=V&&33!=t||u.length?we.apply(N,p):ke(n,t,r,e);else var _=function(n,t,r){var e=1&t,u=ge(n);return function t(){return(this&&this!==nr&&this instanceof t?u:n).apply(e?r:this,arguments)}}(n,t,r);return uu((h?Eo:Mo)(_,p),n,t)}function We(n,t,r,e){return n===N||Eu(n,Ai[r])&&!Ii.call(e,r)?t:n}function Le(n,t,r,e,u,i){return Tu(n)&&Tu(t)&&(i.set(t,n),kr(n,t,N,Le,i),i.delete(t)),n}function Ce(n){return Mu(n)?N:n}function Ue(n,t,r,e,u,i){var o=1&r,f=n.length,c=t.length;if(f!=c&&!(o&&c>f))return!1;var a=i.get(n),l=i.get(t);if(a&&l)return a==t&&l==n;var s=-1,p=!0,_=2&r?new vt:N;for(i.set(n,t),i.set(t,n);++s<f;){var v=n[s],g=t[s];if(e)var y=o?e(g,v,s,t,n,i):e(v,g,s,n,t,i);if(y!==N){if(y)continue;p=!1;break}if(_){if(!h(t,(function(n,t){if(!R(_,t)&&(v===n||u(v,n,r,e,i)))return _.push(t)}))){p=!1;break}}else if(v!==g&&!u(v,g,r,e,i)){p=!1;break}}return i.delete(n),i.delete(t),p}function Be(n){return No(tu(n,N,pu),n+"")}function Te(n){return Pt(n,Qu,Bo)}function $e(n){return Pt(n,Xu,To)}function De(n){for(var t=n.name+"",r=vo[t],e=Ii.call(vo,t)?r.length:0;e--;){var u=r[e],i=u.func;if(null==i||i==n)return u.name}return t}function Me(n){return(Ii.call(Jn,"placeholder")?Jn:n).placeholder}function Fe(){var n=Jn.iteratee||fi;return n=n===fi?dr:n,arguments.length?n(arguments[0],arguments[1]):n}function Ne(n,t){var r=n.__data__;return function(n){var t=typeof n;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==n:null===n}(t)?r["string"==typeof t?"string":"hash"]:r.map}function Pe(n){for(var t=Qu(n),r=t.length;r--;){var e=t[r],u=n[e];t[r]=[e,u,Xe(u)]}return t}function qe(n,t){var r=function(n,t){return null==n?N:n[t]}(n,t);return yr(r)?r:N}function Ze(n,t,r){for(var e=-1,u=(t=ne(t,n)).length,i=!1;++e<u;){var o=fu(t[e]);if(!(i=null!=n&&r(n,o)))break;n=n[o]}return i||++e!=u?i:!!(u=null==n?0:n.length)&&Bu(u)&&Ge(o,u)&&(zf(n)||Rf(n))}function Ke(n){return"function"!=typeof n.constructor||Qe(n)?{}:ko($i(n))}function Ve(n){return zf(n)||Rf(n)||!!(Ni&&n&&n[Ni])}function Ge(n,t){var r=typeof n;return!!(t=null==t?Q:t)&&("number"==r||"symbol"!=r&&it.test(n))&&n>-1&&n%1==0&&n<t}function He(n,t,r){if(!Tu(r))return!1;var e=typeof t;return!!("number"==e?Su(r)&&Ge(t,r.length):"string"==e&&t in r)&&Eu(r[t],n)}function Je(n,t){if(zf(n))return!1;var r=typeof n;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=n&&!Nu(n))||Fn.test(n)||!Mn.test(n)||null!=t&&n in di(t)}function Ye(n){var t=De(n),r=Jn[t];if("function"!=typeof r||!(t in st.prototype))return!1;if(n===r)return!0;var e=Uo(r);return!!e&&n===e[0]}function Qe(n){var t=n&&n.constructor;return n===("function"==typeof t&&t.prototype||Ai)}function Xe(n){return n==n&&!Tu(n)}function nu(n,t){return function(r){return null!=r&&r[n]===t&&(t!==N||n in di(r))}}function tu(t,r,e){return r=ro(r===N?t.length-1:r,0),function(){for(var u=arguments,i=-1,o=ro(u.length-r,0),f=pi(o);++i<o;)f[i]=u[r+i];i=-1;for(var c=pi(r+1);++i<r;)c[i]=u[i];return c[r]=e(f),n(t,this,c)}}function ru(n,t){return t.length<2?n:Nt(n,$r(t,0,-1))}function eu(n,t){if(("constructor"!==t||"function"!=typeof n[t])&&"__proto__"!=t)return n[t]}function uu(n,t,r){var e=t+"";return No(n,function(n,t){var r=t.length;if(!r)return n;var e=r-1;return t[e]=(r>1?"& ":"")+t[e],t=t.join(r>2?", ":" "),n.replace(Vn,"{\n/* [wrapped with "+t+"] */\n")}(e,au(function(n){var t=n.match(Gn);return t?t[1].split(Hn):[]}(e),r)))}function iu(n){var t=0,r=0;return function(){var e=uo(),u=16-(e-r);if(r=e,u>0){if(++t>=800)return arguments[0]}else t=0;return n.apply(N,arguments)}}function ou(n,t){var r=-1,e=n.length,u=e-1;for(t=t===N?e:t;++r<t;){var i=Sr(r,u),o=n[i];n[i]=n[r],n[r]=o}return n.length=t,n}function fu(n){if("string"==typeof n||Nu(n))return n;var t=n+"";return"0"==t&&1/n==-Y?"-0":t}function cu(n){if(null!=n){try{return Oi.call(n)}catch(n){}try{return n+""}catch(n){}}return""}function au(n,t){return r(tn,(function(r){var e="_."+r[0];t&r[1]&&!o(n,e)&&n.push(e)})),n.sort()}function lu(n){if(n instanceof st)return n.clone();var t=new lt(n.__wrapped__,n.__chain__);return t.__actions__=ce(n.__actions__),t.__index__=n.__index__,t.__values__=n.__values__,t}function su(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=null==r?0:Zu(r);return u<0&&(u=ro(e+u,0)),v(n,Fe(t,3),u)}function hu(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=e-1;return r!==N&&(u=Zu(r),u=r<0?ro(e+u,0):eo(u,e-1)),v(n,Fe(t,3),u,!0)}function pu(n){return null!=n&&n.length?Bt(n,1):[]}function _u(n){return n&&n.length?n[0]:N}function vu(n){var t=null==n?0:n.length;return t?n[t-1]:N}function gu(n,t){return n&&n.length&&t&&t.length?zr(n,t):n}function yu(n){return null==n?n:fo.call(n)}function du(n){if(!n||!n.length)return[];var t=0;return n=i(n,(function(n){if(Wu(n))return t=ro(n.length,t),!0})),A(t,(function(t){return c(n,w(t))}))}function bu(t,r){if(!t||!t.length)return[];var e=du(t);return null==r?e:c(e,(function(t){return n(r,N,t)}))}function wu(n){var t=Jn(n);return t.__chain__=!0,t}function mu(n,t){return t(n)}function xu(n,t){return(zf(n)?r:Oo)(n,Fe(t,3))}function ju(n,t){return(zf(n)?e:Io)(n,Fe(t,3))}function Au(n,t){return(zf(n)?c:xr)(n,Fe(t,3))}function ku(n,t,r){return t=r?N:t,t=n&&null==t?n.length:t,Se(n,H,N,N,N,N,t)}function Ou(n,t){var r;if("function"!=typeof t)throw new mi(P);return n=Zu(n),function(){return--n>0&&(r=t.apply(this,arguments)),n<=1&&(t=N),r}}function Iu(n,t,r){function e(t){var r=c,e=a;return c=a=N,_=t,s=n.apply(e,r)}function u(n){var r=n-p;return p===N||r>=t||r<0||g&&n-_>=l}function i(){var n=yf();return u(n)?o(n):(h=Fo(i,function(n){var r=t-(n-p);return g?eo(r,l-(n-_)):r}(n)),N)}function o(n){return h=N,y&&c?e(n):(c=a=N,s)}function f(){var n=yf(),r=u(n);if(c=arguments,a=this,p=n,r){if(h===N)return function(n){return _=n,h=Fo(i,t),v?e(n):s}(p);if(g)return Lo(h),h=Fo(i,t),e(p)}return h===N&&(h=Fo(i,t)),s}var c,a,l,s,h,p,_=0,v=!1,g=!1,y=!0;if("function"!=typeof n)throw new mi(P);return t=Vu(t)||0,Tu(r)&&(v=!!r.leading,l=(g="maxWait"in r)?ro(Vu(r.maxWait)||0,t):l,y="trailing"in r?!!r.trailing:y),f.cancel=function(){h!==N&&Lo(h),_=0,c=p=a=h=N},f.flush=function(){return h===N?s:o(yf())},f}function Ru(n,t){if("function"!=typeof n||null!=t&&"function"!=typeof t)throw new mi(P);var r=function(){var e=arguments,u=t?t.apply(this,e):e[0],i=r.cache;if(i.has(u))return i.get(u);var o=n.apply(this,e);return r.cache=i.set(u,o)||i,o};return r.cache=new(Ru.Cache||_t),r}function zu(n){if("function"!=typeof n)throw new mi(P);return function(){var t=arguments;switch(t.length){case 0:return!n.call(this);case 1:return!n.call(this,t[0]);case 2:return!n.call(this,t[0],t[1]);case 3:return!n.call(this,t[0],t[1],t[2])}return!n.apply(this,t)}}function Eu(n,t){return n===t||n!=n&&t!=t}function Su(n){return null!=n&&Bu(n.length)&&!Cu(n)}function Wu(n){return $u(n)&&Su(n)}function Lu(n){if(!$u(n))return!1;var t=qt(n);return t==fn||"[object DOMException]"==t||"string"==typeof n.message&&"string"==typeof n.name&&!Mu(n)}function Cu(n){if(!Tu(n))return!1;var t=qt(n);return t==cn||t==an||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Uu(n){return"number"==typeof n&&n==Zu(n)}function Bu(n){return"number"==typeof n&&n>-1&&n%1==0&&n<=Q}function Tu(n){var t=typeof n;return null!=n&&("object"==t||"function"==t)}function $u(n){return null!=n&&"object"==typeof n}function Du(n){return"number"==typeof n||$u(n)&&qt(n)==sn}function Mu(n){if(!$u(n)||qt(n)!=hn)return!1;var t=$i(n);if(null===t)return!0;var r=Ii.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Oi.call(r)==Si}function Fu(n){return"string"==typeof n||!zf(n)&&$u(n)&&qt(n)==gn}function Nu(n){return"symbol"==typeof n||$u(n)&&qt(n)==yn}function Pu(n){if(!n)return[];if(Su(n))return Fu(n)?D(n):ce(n);if(Pi&&n[Pi])return function(n){for(var t,r=[];!(t=n.next()).done;)r.push(t.value);return r}(n[Pi]());var t=$o(n);return(t==ln?C:t==vn?T:ti)(n)}function qu(n){return n?(n=Vu(n))===Y||n===-Y?17976931348623157e292*(n<0?-1:1):n==n?n:0:0===n?n:0}function Zu(n){var t=qu(n),r=t%1;return t==t?r?t-r:t:0}function Ku(n){return n?Rt(Zu(n),0,nn):0}function Vu(n){if("number"==typeof n)return n;if(Nu(n))return X;if(Tu(n)){var t="function"==typeof n.valueOf?n.valueOf():n;n=Tu(t)?t+"":t}if("string"!=typeof n)return 0===n?n:+n;n=k(n);var r=rt.test(n);return r||ut.test(n)?Yt(n.slice(2),r?2:8):tt.test(n)?X:+n}function Gu(n){return ae(n,Xu(n))}function Hu(n){return null==n?"":qr(n)}function Ju(n,t,r){var e=null==n?N:Nt(n,t);return e===N?r:e}function Yu(n,t){return null!=n&&Ze(n,t,Xt)}function Qu(n){return Su(n)?yt(n):br(n)}function Xu(n){return Su(n)?yt(n,!0):wr(n)}function ni(n,t){if(null==n)return{};var r=c($e(n),(function(n){return[n]}));return t=Fe(t),Rr(n,r,(function(n,r){return t(n,r[0])}))}function ti(n){return null==n?[]:I(n,Qu(n))}function ri(n){return cc(Hu(n).toLowerCase())}function ei(n){return(n=Hu(n))&&n.replace(ot,pr).replace(Mt,"")}function ui(n,t,r){return n=Hu(n),(t=r?N:t)===N?L(n)?F(n):p(n):n.match(t)||[]}function ii(n){return function(){return n}}function oi(n){return n}function fi(n){return dr("function"==typeof n?n:zt(n,1))}function ci(n,t,e){var u=Qu(t),i=Ft(t,u);null!=e||Tu(t)&&(i.length||!u.length)||(e=t,t=n,n=this,i=Ft(t,Qu(t)));var o=!(Tu(e)&&"chain"in e&&!e.chain),f=Cu(n);return r(i,(function(r){var e=t[r];n[r]=e,f&&(n.prototype[r]=function(){var t=this.__chain__;if(o||t){var r=n(this.__wrapped__);return(r.__actions__=ce(this.__actions__)).push({func:e,args:arguments,thisArg:n}),r.__chain__=t,r}return e.apply(n,a([this.value()],arguments))})})),n}function ai(){}function li(n){return Je(n)?w(fu(n)):function(n){return function(t){return Nt(t,n)}}(n)}function si(){return[]}function hi(){return!1}var pi=(Kn=null==Kn?nr:gr.defaults(nr.Object(),Kn,gr.pick(nr,Zt))).Array,_i=Kn.Date,vi=Kn.Error,gi=Kn.Function,yi=Kn.Math,di=Kn.Object,bi=Kn.RegExp,wi=Kn.String,mi=Kn.TypeError,xi=pi.prototype,ji=gi.prototype,Ai=di.prototype,ki=Kn["__core-js_shared__"],Oi=ji.toString,Ii=Ai.hasOwnProperty,Ri=0,zi=function(){var n=/[^.]+$/.exec(ki&&ki.keys&&ki.keys.IE_PROTO||"");return n?"Symbol(src)_1."+n:""}(),Ei=Ai.toString,Si=Oi.call(di),Wi=nr._,Li=bi("^"+Oi.call(Ii).replace(Pn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Ci=er?Kn.Buffer:N,Ui=Kn.Symbol,Bi=Kn.Uint8Array,Ti=Ci?Ci.allocUnsafe:N,$i=U(di.getPrototypeOf,di),Di=di.create,Mi=Ai.propertyIsEnumerable,Fi=xi.splice,Ni=Ui?Ui.isConcatSpreadable:N,Pi=Ui?Ui.iterator:N,qi=Ui?Ui.toStringTag:N,Zi=function(){try{var n=qe(di,"defineProperty");return n({},"",{}),n}catch(n){}}(),Ki=Kn.clearTimeout!==nr.clearTimeout&&Kn.clearTimeout,Vi=_i&&_i.now!==nr.Date.now&&_i.now,Gi=Kn.setTimeout!==nr.setTimeout&&Kn.setTimeout,Hi=yi.ceil,Ji=yi.floor,Yi=di.getOwnPropertySymbols,Qi=Ci?Ci.isBuffer:N,Xi=Kn.isFinite,no=xi.join,to=U(di.keys,di),ro=yi.max,eo=yi.min,uo=_i.now,io=Kn.parseInt,oo=yi.random,fo=xi.reverse,co=qe(Kn,"DataView"),ao=qe(Kn,"Map"),lo=qe(Kn,"Promise"),so=qe(Kn,"Set"),ho=qe(Kn,"WeakMap"),po=qe(di,"create"),_o=ho&&new ho,vo={},go=cu(co),yo=cu(ao),bo=cu(lo),wo=cu(so),mo=cu(ho),xo=Ui?Ui.prototype:N,jo=xo?xo.valueOf:N,Ao=xo?xo.toString:N,ko=function(){function n(){}return function(t){if(!Tu(t))return{};if(Di)return Di(t);n.prototype=t;var r=new n;return n.prototype=N,r}}();Jn.templateSettings={escape:Tn,evaluate:$n,interpolate:Dn,variable:"",imports:{_:Jn}},Jn.prototype=at.prototype,Jn.prototype.constructor=Jn,lt.prototype=ko(at.prototype),lt.prototype.constructor=lt,st.prototype=ko(at.prototype),st.prototype.constructor=st,ht.prototype.clear=function(){this.__data__=po?po(null):{},this.size=0},ht.prototype.delete=function(n){var t=this.has(n)&&delete this.__data__[n];return this.size-=t?1:0,t},ht.prototype.get=function(n){var t=this.__data__;if(po){var r=t[n];return r===q?N:r}return Ii.call(t,n)?t[n]:N},ht.prototype.has=function(n){var t=this.__data__;return po?t[n]!==N:Ii.call(t,n)},ht.prototype.set=function(n,t){var r=this.__data__;return this.size+=this.has(n)?0:1,r[n]=po&&t===N?q:t,this},pt.prototype.clear=function(){this.__data__=[],this.size=0},pt.prototype.delete=function(n){var t=this.__data__,r=jt(t,n);return!(r<0||(r==t.length-1?t.pop():Fi.call(t,r,1),--this.size,0))},pt.prototype.get=function(n){var t=this.__data__,r=jt(t,n);return r<0?N:t[r][1]},pt.prototype.has=function(n){return jt(this.__data__,n)>-1},pt.prototype.set=function(n,t){var r=this.__data__,e=jt(r,n);return e<0?(++this.size,r.push([n,t])):r[e][1]=t,this},_t.prototype.clear=function(){this.size=0,this.__data__={hash:new ht,map:new(ao||pt),string:new ht}},_t.prototype.delete=function(n){var t=Ne(this,n).delete(n);return this.size-=t?1:0,t},_t.prototype.get=function(n){return Ne(this,n).get(n)},_t.prototype.has=function(n){return Ne(this,n).has(n)},_t.prototype.set=function(n,t){var r=Ne(this,n),e=r.size;return r.set(n,t),this.size+=r.size==e?0:1,this},vt.prototype.add=vt.prototype.push=function(n){return this.__data__.set(n,q),this},vt.prototype.has=function(n){return this.__data__.has(n)},gt.prototype.clear=function(){this.__data__=new pt,this.size=0},gt.prototype.delete=function(n){var t=this.__data__,r=t.delete(n);return this.size=t.size,r},gt.prototype.get=function(n){return this.__data__.get(n)},gt.prototype.has=function(n){return this.__data__.has(n)},gt.prototype.set=function(n,t){var r=this.__data__;if(r instanceof pt){var e=r.__data__;if(!ao||e.length<199)return e.push([n,t]),this.size=++r.size,this;r=this.__data__=new _t(e)}return r.set(n,t),this.size=r.size,this};var Oo=he(Tt),Io=he($t,!0),Ro=pe(),zo=pe(!0),Eo=_o?function(n,t){return _o.set(n,t),n}:oi,So=Zi?function(n,t){return Zi(n,"toString",{configurable:!0,enumerable:!1,value:ii(t),writable:!0})}:oi,Wo=Lr,Lo=Ki||function(n){return nr.clearTimeout(n)},Co=so&&1/T(new so([,-0]))[1]==Y?function(n){return new so(n)}:ai,Uo=_o?function(n){return _o.get(n)}:ai,Bo=Yi?function(n){return null==n?[]:(n=di(n),i(Yi(n),(function(t){return Mi.call(n,t)})))}:si,To=Yi?function(n){for(var t=[];n;)a(t,Bo(n)),n=$i(n);return t}:si,$o=qt;(co&&$o(new co(new ArrayBuffer(1)))!=wn||ao&&$o(new ao)!=ln||lo&&$o(lo.resolve())!=pn||so&&$o(new so)!=vn||ho&&$o(new ho)!=dn)&&($o=function(n){var t=qt(n),r=t==hn?n.constructor:N,e=r?cu(r):"";if(e)switch(e){case go:return wn;case yo:return ln;case bo:return pn;case wo:return vn;case mo:return dn}return t});var Do=ki?Cu:hi,Mo=iu(Eo),Fo=Gi||function(n,t){return nr.setTimeout(n,t)},No=iu(So),Po=function(n){var t=Ru(n,(function(n){return 500===r.size&&r.clear(),n})),r=t.cache;return t}((function(n){var t=[];return 46===n.charCodeAt(0)&&t.push(""),n.replace(Nn,(function(n,r,e,u){t.push(e?u.replace(Qn,"$1"):r||n)})),t})),qo=Lr((function(n,t){return Wu(n)?Wt(n,Bt(t,1,Wu,!0)):[]})),Zo=Lr((function(n,t){var r=vu(t);return Wu(r)&&(r=N),Wu(n)?Wt(n,Bt(t,1,Wu,!0),Fe(r,2)):[]})),Ko=Lr((function(n,t){var r=vu(t);return Wu(r)&&(r=N),Wu(n)?Wt(n,Bt(t,1,Wu,!0),N,r):[]})),Vo=Lr((function(n){var t=c(n,Qr);return t.length&&t[0]===n[0]?tr(t):[]})),Go=Lr((function(n){var t=vu(n),r=c(n,Qr);return t===vu(r)?t=N:r.pop(),r.length&&r[0]===n[0]?tr(r,Fe(t,2)):[]})),Ho=Lr((function(n){var t=vu(n),r=c(n,Qr);return(t="function"==typeof t?t:N)&&r.pop(),r.length&&r[0]===n[0]?tr(r,N,t):[]})),Jo=Lr(gu),Yo=Be((function(n,t){var r=null==n?0:n.length,e=It(n,t);return Er(n,c(t,(function(n){return Ge(n,r)?+n:n})).sort(ie)),e})),Qo=Lr((function(n){return Zr(Bt(n,1,Wu,!0))})),Xo=Lr((function(n){var t=vu(n);return Wu(t)&&(t=N),Zr(Bt(n,1,Wu,!0),Fe(t,2))})),nf=Lr((function(n){var t=vu(n);return t="function"==typeof t?t:N,Zr(Bt(n,1,Wu,!0),N,t)})),tf=Lr((function(n,t){return Wu(n)?Wt(n,t):[]})),rf=Lr((function(n){return Jr(i(n,Wu))})),ef=Lr((function(n){var t=vu(n);return Wu(t)&&(t=N),Jr(i(n,Wu),Fe(t,2))})),uf=Lr((function(n){var t=vu(n);return t="function"==typeof t?t:N,Jr(i(n,Wu),N,t)})),of=Lr(du),ff=Lr((function(n){var t=n.length,r=t>1?n[t-1]:N;return r="function"==typeof r?(n.pop(),r):N,bu(n,r)})),cf=Be((function(n){var t=n.length,r=t?n[0]:0,e=this.__wrapped__,u=function(t){return It(t,n)};return!(t>1||this.__actions__.length)&&e instanceof st&&Ge(r)?((e=e.slice(r,+r+(t?1:0))).__actions__.push({func:mu,args:[u],thisArg:N}),new lt(e,this.__chain__).thru((function(n){return t&&!n.length&&n.push(N),n}))):this.thru(u)})),af=le((function(n,t,r){Ii.call(n,r)?++n[r]:Ot(n,r,1)})),lf=de(su),sf=de(hu),hf=le((function(n,t,r){Ii.call(n,r)?n[r].push(t):Ot(n,r,[t])})),pf=Lr((function(t,r,e){var u=-1,i="function"==typeof r,o=Su(t)?pi(t.length):[];return Oo(t,(function(t){o[++u]=i?n(r,t,e):rr(t,r,e)})),o})),_f=le((function(n,t,r){Ot(n,r,t)})),vf=le((function(n,t,r){n[r?0:1].push(t)}),(function(){return[[],[]]})),gf=Lr((function(n,t){if(null==n)return[];var r=t.length;return r>1&&He(n,t[0],t[1])?t=[]:r>2&&He(t[0],t[1],t[2])&&(t=[t[0]]),Ir(n,Bt(t,1),[])})),yf=Vi||function(){return nr.Date.now()},df=Lr((function(n,t,r){var e=1;if(r.length){var u=B(r,Me(df));e|=V}return Se(n,e,t,r,u)})),bf=Lr((function(n,t,r){var e=3;if(r.length){var u=B(r,Me(bf));e|=V}return Se(t,e,n,r,u)})),wf=Lr((function(n,t){return St(n,1,t)})),mf=Lr((function(n,t,r){return St(n,Vu(t)||0,r)}));Ru.Cache=_t;var xf=Wo((function(t,r){var e=(r=1==r.length&&zf(r[0])?c(r[0],O(Fe())):c(Bt(r,1),O(Fe()))).length;return Lr((function(u){for(var i=-1,o=eo(u.length,e);++i<o;)u[i]=r[i].call(this,u[i]);return n(t,this,u)}))})),jf=Lr((function(n,t){return Se(n,V,N,t,B(t,Me(jf)))})),Af=Lr((function(n,t){return Se(n,G,N,t,B(t,Me(Af)))})),kf=Be((function(n,t){return Se(n,J,N,N,N,t)})),Of=Ie(Ht),If=Ie((function(n,t){return n>=t})),Rf=ur(function(){return arguments}())?ur:function(n){return $u(n)&&Ii.call(n,"callee")&&!Mi.call(n,"callee")},zf=pi.isArray,Ef=or?O(or):function(n){return $u(n)&&qt(n)==bn},Sf=Qi||hi,Wf=fr?O(fr):function(n){return $u(n)&&qt(n)==on},Lf=cr?O(cr):function(n){return $u(n)&&$o(n)==ln},Cf=ar?O(ar):function(n){return $u(n)&&qt(n)==_n},Uf=lr?O(lr):function(n){return $u(n)&&$o(n)==vn},Bf=sr?O(sr):function(n){return $u(n)&&Bu(n.length)&&!!Vt[qt(n)]},Tf=Ie(mr),$f=Ie((function(n,t){return n<=t})),Df=se((function(n,t){if(Qe(t)||Su(t))return ae(t,Qu(t),n),N;for(var r in t)Ii.call(t,r)&&xt(n,r,t[r])})),Mf=se((function(n,t){ae(t,Xu(t),n)})),Ff=se((function(n,t,r,e){ae(t,Xu(t),n,e)})),Nf=se((function(n,t,r,e){ae(t,Qu(t),n,e)})),Pf=Be(It),qf=Lr((function(n,t){n=di(n);var r=-1,e=t.length,u=e>2?t[2]:N;for(u&&He(t[0],t[1],u)&&(e=1);++r<e;)for(var i=t[r],o=Xu(i),f=-1,c=o.length;++f<c;){var a=o[f],l=n[a];(l===N||Eu(l,Ai[a])&&!Ii.call(n,a))&&(n[a]=i[a])}return n})),Zf=Lr((function(t){return t.push(N,Le),n(Jf,N,t)})),Kf=me((function(n,t,r){null!=t&&"function"!=typeof t.toString&&(t=Ei.call(t)),n[t]=r}),ii(oi)),Vf=me((function(n,t,r){null!=t&&"function"!=typeof t.toString&&(t=Ei.call(t)),Ii.call(n,t)?n[t].push(r):n[t]=[r]}),Fe),Gf=Lr(rr),Hf=se((function(n,t,r){kr(n,t,r)})),Jf=se((function(n,t,r,e){kr(n,t,r,e)})),Yf=Be((function(n,t){var r={};if(null==n)return r;var e=!1;t=c(t,(function(t){return t=ne(t,n),e||(e=t.length>1),t})),ae(n,$e(n),r),e&&(r=zt(r,7,Ce));for(var u=t.length;u--;)Kr(r,t[u]);return r})),Qf=Be((function(n,t){return null==n?{}:function(n,t){return Rr(n,t,(function(t,r){return Yu(n,r)}))}(n,t)})),Xf=Ee(Qu),nc=Ee(Xu),tc=ve((function(n,t,r){return t=t.toLowerCase(),n+(r?ri(t):t)})),rc=ve((function(n,t,r){return n+(r?"-":"")+t.toLowerCase()})),ec=ve((function(n,t,r){return n+(r?" ":"")+t.toLowerCase()})),uc=_e("toLowerCase"),ic=ve((function(n,t,r){return n+(r?"_":"")+t.toLowerCase()})),oc=ve((function(n,t,r){return n+(r?" ":"")+cc(t)})),fc=ve((function(n,t,r){return n+(r?" ":"")+t.toUpperCase()})),cc=_e("toUpperCase"),ac=Lr((function(t,r){try{return n(t,N,r)}catch(n){return Lu(n)?n:new vi(n)}})),lc=Be((function(n,t){return r(t,(function(t){t=fu(t),Ot(n,t,df(n[t],n))})),n})),sc=be(),hc=be(!0),pc=Lr((function(n,t){return function(r){return rr(r,n,t)}})),_c=Lr((function(n,t){return function(r){return rr(n,r,t)}})),vc=je(c),gc=je(u),yc=je(h),dc=Oe(),bc=Oe(!0),wc=xe((function(n,t){return n+t}),0),mc=ze("ceil"),xc=xe((function(n,t){return n/t}),1),jc=ze("floor"),Ac=xe((function(n,t){return n*t}),1),kc=ze("round"),Oc=xe((function(n,t){return n-t}),0);return Jn.after=function(n,t){if("function"!=typeof t)throw new mi(P);return n=Zu(n),function(){if(--n<1)return t.apply(this,arguments)}},Jn.ary=ku,Jn.assign=Df,Jn.assignIn=Mf,Jn.assignInWith=Ff,Jn.assignWith=Nf,Jn.at=Pf,Jn.before=Ou,Jn.bind=df,Jn.bindAll=lc,Jn.bindKey=bf,Jn.castArray=function(){if(!arguments.length)return[];var n=arguments[0];return zf(n)?n:[n]},Jn.chain=wu,Jn.chunk=function(n,t,r){t=(r?He(n,t,r):t===N)?1:ro(Zu(t),0);var e=null==n?0:n.length;if(!e||t<1)return[];for(var u=0,i=0,o=pi(Hi(e/t));u<e;)o[i++]=$r(n,u,u+=t);return o},Jn.compact=function(n){for(var t=-1,r=null==n?0:n.length,e=0,u=[];++t<r;){var i=n[t];i&&(u[e++]=i)}return u},Jn.concat=function(){var n=arguments.length;if(!n)return[];for(var t=pi(n-1),r=arguments[0],e=n;e--;)t[e-1]=arguments[e];return a(zf(r)?ce(r):[r],Bt(t,1))},Jn.cond=function(t){var r=null==t?0:t.length,e=Fe();return t=r?c(t,(function(n){if("function"!=typeof n[1])throw new mi(P);return[e(n[0]),n[1]]})):[],Lr((function(e){for(var u=-1;++u<r;){var i=t[u];if(n(i[0],this,e))return n(i[1],this,e)}}))},Jn.conforms=function(n){return function(n){var t=Qu(n);return function(r){return Et(r,n,t)}}(zt(n,1))},Jn.constant=ii,Jn.countBy=af,Jn.create=function(n,t){var r=ko(n);return null==t?r:kt(r,t)},Jn.curry=function n(t,r,e){var u=Se(t,8,N,N,N,N,N,r=e?N:r);return u.placeholder=n.placeholder,u},Jn.curryRight=function n(t,r,e){var u=Se(t,K,N,N,N,N,N,r=e?N:r);return u.placeholder=n.placeholder,u},Jn.debounce=Iu,Jn.defaults=qf,Jn.defaultsDeep=Zf,Jn.defer=wf,Jn.delay=mf,Jn.difference=qo,Jn.differenceBy=Zo,Jn.differenceWith=Ko,Jn.drop=function(n,t,r){var e=null==n?0:n.length;return e?$r(n,(t=r||t===N?1:Zu(t))<0?0:t,e):[]},Jn.dropRight=function(n,t,r){var e=null==n?0:n.length;return e?$r(n,0,(t=e-(t=r||t===N?1:Zu(t)))<0?0:t):[]},Jn.dropRightWhile=function(n,t){return n&&n.length?Gr(n,Fe(t,3),!0,!0):[]},Jn.dropWhile=function(n,t){return n&&n.length?Gr(n,Fe(t,3),!0):[]},Jn.fill=function(n,t,r,e){var u=null==n?0:n.length;return u?(r&&"number"!=typeof r&&He(n,t,r)&&(r=0,e=u),function(n,t,r,e){var u=n.length;for((r=Zu(r))<0&&(r=-r>u?0:u+r),(e=e===N||e>u?u:Zu(e))<0&&(e+=u),e=r>e?0:Ku(e);r<e;)n[r++]=t;return n}(n,t,r,e)):[]},Jn.filter=function(n,t){return(zf(n)?i:Ut)(n,Fe(t,3))},Jn.flatMap=function(n,t){return Bt(Au(n,t),1)},Jn.flatMapDeep=function(n,t){return Bt(Au(n,t),Y)},Jn.flatMapDepth=function(n,t,r){return r=r===N?1:Zu(r),Bt(Au(n,t),r)},Jn.flatten=pu,Jn.flattenDeep=function(n){return null!=n&&n.length?Bt(n,Y):[]},Jn.flattenDepth=function(n,t){return null!=n&&n.length?Bt(n,t=t===N?1:Zu(t)):[]},Jn.flip=function(n){return Se(n,512)},Jn.flow=sc,Jn.flowRight=hc,Jn.fromPairs=function(n){for(var t=-1,r=null==n?0:n.length,e={};++t<r;){var u=n[t];e[u[0]]=u[1]}return e},Jn.functions=function(n){return null==n?[]:Ft(n,Qu(n))},Jn.functionsIn=function(n){return null==n?[]:Ft(n,Xu(n))},Jn.groupBy=hf,Jn.initial=function(n){return null!=n&&n.length?$r(n,0,-1):[]},Jn.intersection=Vo,Jn.intersectionBy=Go,Jn.intersectionWith=Ho,Jn.invert=Kf,Jn.invertBy=Vf,Jn.invokeMap=pf,Jn.iteratee=fi,Jn.keyBy=_f,Jn.keys=Qu,Jn.keysIn=Xu,Jn.map=Au,Jn.mapKeys=function(n,t){var r={};return t=Fe(t,3),Tt(n,(function(n,e,u){Ot(r,t(n,e,u),n)})),r},Jn.mapValues=function(n,t){var r={};return t=Fe(t,3),Tt(n,(function(n,e,u){Ot(r,e,t(n,e,u))})),r},Jn.matches=function(n){return jr(zt(n,1))},Jn.matchesProperty=function(n,t){return Ar(n,zt(t,1))},Jn.memoize=Ru,Jn.merge=Hf,Jn.mergeWith=Jf,Jn.method=pc,Jn.methodOf=_c,Jn.mixin=ci,Jn.negate=zu,Jn.nthArg=function(n){return n=Zu(n),Lr((function(t){return Or(t,n)}))},Jn.omit=Yf,Jn.omitBy=function(n,t){return ni(n,zu(Fe(t)))},Jn.once=function(n){return Ou(2,n)},Jn.orderBy=function(n,t,r,e){return null==n?[]:(zf(t)||(t=null==t?[]:[t]),zf(r=e?N:r)||(r=null==r?[]:[r]),Ir(n,t,r))},Jn.over=vc,Jn.overArgs=xf,Jn.overEvery=gc,Jn.overSome=yc,Jn.partial=jf,Jn.partialRight=Af,Jn.partition=vf,Jn.pick=Qf,Jn.pickBy=ni,Jn.property=li,Jn.propertyOf=function(n){return function(t){return null==n?N:Nt(n,t)}},Jn.pull=Jo,Jn.pullAll=gu,Jn.pullAllBy=function(n,t,r){return n&&n.length&&t&&t.length?zr(n,t,Fe(r,2)):n},Jn.pullAllWith=function(n,t,r){return n&&n.length&&t&&t.length?zr(n,t,N,r):n},Jn.pullAt=Yo,Jn.range=dc,Jn.rangeRight=bc,Jn.rearg=kf,Jn.reject=function(n,t){return(zf(n)?i:Ut)(n,zu(Fe(t,3)))},Jn.remove=function(n,t){var r=[];if(!n||!n.length)return r;var e=-1,u=[],i=n.length;for(t=Fe(t,3);++e<i;){var o=n[e];t(o,e,n)&&(r.push(o),u.push(e))}return Er(n,u),r},Jn.rest=function(n,t){if("function"!=typeof n)throw new mi(P);return Lr(n,t=t===N?t:Zu(t))},Jn.reverse=yu,Jn.sampleSize=function(n,t,r){return t=(r?He(n,t,r):t===N)?1:Zu(t),(zf(n)?bt:Ur)(n,t)},Jn.set=function(n,t,r){return null==n?n:Br(n,t,r)},Jn.setWith=function(n,t,r,e){return e="function"==typeof e?e:N,null==n?n:Br(n,t,r,e)},Jn.shuffle=function(n){return(zf(n)?wt:Tr)(n)},Jn.slice=function(n,t,r){var e=null==n?0:n.length;return e?(r&&"number"!=typeof r&&He(n,t,r)?(t=0,r=e):(t=null==t?0:Zu(t),r=r===N?e:Zu(r)),$r(n,t,r)):[]},Jn.sortBy=gf,Jn.sortedUniq=function(n){return n&&n.length?Nr(n):[]},Jn.sortedUniqBy=function(n,t){return n&&n.length?Nr(n,Fe(t,2)):[]},Jn.split=function(n,t,r){return r&&"number"!=typeof r&&He(n,t,r)&&(t=r=N),(r=r===N?nn:r>>>0)?(n=Hu(n))&&("string"==typeof t||null!=t&&!Cf(t))&&(!(t=qr(t))&&W(n))?te(D(n),0,r):n.split(t,r):[]},Jn.spread=function(t,r){if("function"!=typeof t)throw new mi(P);return r=null==r?0:ro(Zu(r),0),Lr((function(e){var u=e[r],i=te(e,0,r);return u&&a(i,u),n(t,this,i)}))},Jn.tail=function(n){var t=null==n?0:n.length;return t?$r(n,1,t):[]},Jn.take=function(n,t,r){return n&&n.length?$r(n,0,(t=r||t===N?1:Zu(t))<0?0:t):[]},Jn.takeRight=function(n,t,r){var e=null==n?0:n.length;return e?$r(n,(t=e-(t=r||t===N?1:Zu(t)))<0?0:t,e):[]},Jn.takeRightWhile=function(n,t){return n&&n.length?Gr(n,Fe(t,3),!1,!0):[]},Jn.takeWhile=function(n,t){return n&&n.length?Gr(n,Fe(t,3)):[]},Jn.tap=function(n,t){return t(n),n},Jn.throttle=function(n,t,r){var e=!0,u=!0;if("function"!=typeof n)throw new mi(P);return Tu(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),Iu(n,t,{leading:e,maxWait:t,trailing:u})},Jn.thru=mu,Jn.toArray=Pu,Jn.toPairs=Xf,Jn.toPairsIn=nc,Jn.toPath=function(n){return zf(n)?c(n,fu):Nu(n)?[n]:ce(Po(Hu(n)))},Jn.toPlainObject=Gu,Jn.transform=function(n,t,e){var u=zf(n),i=u||Sf(n)||Bf(n);if(t=Fe(t,4),null==e){var o=n&&n.constructor;e=i?u?new o:[]:Tu(n)&&Cu(o)?ko($i(n)):{}}return(i?r:Tt)(n,(function(n,r,u){return t(e,n,r,u)})),e},Jn.unary=function(n){return ku(n,1)},Jn.union=Qo,Jn.unionBy=Xo,Jn.unionWith=nf,Jn.uniq=function(n){return n&&n.length?Zr(n):[]},Jn.uniqBy=function(n,t){return n&&n.length?Zr(n,Fe(t,2)):[]},Jn.uniqWith=function(n,t){return t="function"==typeof t?t:N,n&&n.length?Zr(n,N,t):[]},Jn.unset=function(n,t){return null==n||Kr(n,t)},Jn.unzip=du,Jn.unzipWith=bu,Jn.update=function(n,t,r){return null==n?n:Vr(n,t,Xr(r))},Jn.updateWith=function(n,t,r,e){return e="function"==typeof e?e:N,null==n?n:Vr(n,t,Xr(r),e)},Jn.values=ti,Jn.valuesIn=function(n){return null==n?[]:I(n,Xu(n))},Jn.without=tf,Jn.words=ui,Jn.wrap=function(n,t){return jf(Xr(t),n)},Jn.xor=rf,Jn.xorBy=ef,Jn.xorWith=uf,Jn.zip=of,Jn.zipObject=function(n,t){return Yr(n||[],t||[],xt)},Jn.zipObjectDeep=function(n,t){return Yr(n||[],t||[],Br)},Jn.zipWith=ff,Jn.entries=Xf,Jn.entriesIn=nc,Jn.extend=Mf,Jn.extendWith=Ff,ci(Jn,Jn),Jn.add=wc,Jn.attempt=ac,Jn.camelCase=tc,Jn.capitalize=ri,Jn.ceil=mc,Jn.clamp=function(n,t,r){return r===N&&(r=t,t=N),r!==N&&(r=(r=Vu(r))==r?r:0),t!==N&&(t=(t=Vu(t))==t?t:0),Rt(Vu(n),t,r)},Jn.clone=function(n){return zt(n,4)},Jn.cloneDeep=function(n){return zt(n,5)},Jn.cloneDeepWith=function(n,t){return zt(n,5,t="function"==typeof t?t:N)},Jn.cloneWith=function(n,t){return zt(n,4,t="function"==typeof t?t:N)},Jn.conformsTo=function(n,t){return null==t||Et(n,t,Qu(t))},Jn.deburr=ei,Jn.defaultTo=function(n,t){return null==n||n!=n?t:n},Jn.divide=xc,Jn.endsWith=function(n,t,r){n=Hu(n),t=qr(t);var e=n.length,u=r=r===N?e:Rt(Zu(r),0,e);return(r-=t.length)>=0&&n.slice(r,u)==t},Jn.eq=Eu,Jn.escape=function(n){return(n=Hu(n))&&Bn.test(n)?n.replace(Cn,_r):n},Jn.escapeRegExp=function(n){return(n=Hu(n))&&qn.test(n)?n.replace(Pn,"\\$&"):n},Jn.every=function(n,t,r){var e=zf(n)?u:Lt;return r&&He(n,t,r)&&(t=N),e(n,Fe(t,3))},Jn.find=lf,Jn.findIndex=su,Jn.findKey=function(n,t){return _(n,Fe(t,3),Tt)},Jn.findLast=sf,Jn.findLastIndex=hu,Jn.findLastKey=function(n,t){return _(n,Fe(t,3),$t)},Jn.floor=jc,Jn.forEach=xu,Jn.forEachRight=ju,Jn.forIn=function(n,t){return null==n?n:Ro(n,Fe(t,3),Xu)},Jn.forInRight=function(n,t){return null==n?n:zo(n,Fe(t,3),Xu)},Jn.forOwn=function(n,t){return n&&Tt(n,Fe(t,3))},Jn.forOwnRight=function(n,t){return n&&$t(n,Fe(t,3))},Jn.get=Ju,Jn.gt=Of,Jn.gte=If,Jn.has=function(n,t){return null!=n&&Ze(n,t,Qt)},Jn.hasIn=Yu,Jn.head=_u,Jn.identity=oi,Jn.includes=function(n,t,r,e){n=Su(n)?n:ti(n),r=r&&!e?Zu(r):0;var u=n.length;return r<0&&(r=ro(u+r,0)),Fu(n)?r<=u&&n.indexOf(t,r)>-1:!!u&&g(n,t,r)>-1},Jn.indexOf=function(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=null==r?0:Zu(r);return u<0&&(u=ro(e+u,0)),g(n,t,u)},Jn.inRange=function(n,t,r){return t=qu(t),r===N?(r=t,t=0):r=qu(r),function(n,t,r){return n>=eo(t,r)&&n<ro(t,r)}(n=Vu(n),t,r)},Jn.invoke=Gf,Jn.isArguments=Rf,Jn.isArray=zf,Jn.isArrayBuffer=Ef,Jn.isArrayLike=Su,Jn.isArrayLikeObject=Wu,Jn.isBoolean=function(n){return!0===n||!1===n||$u(n)&&qt(n)==un},Jn.isBuffer=Sf,Jn.isDate=Wf,Jn.isElement=function(n){return $u(n)&&1===n.nodeType&&!Mu(n)},Jn.isEmpty=function(n){if(null==n)return!0;if(Su(n)&&(zf(n)||"string"==typeof n||"function"==typeof n.splice||Sf(n)||Bf(n)||Rf(n)))return!n.length;var t=$o(n);if(t==ln||t==vn)return!n.size;if(Qe(n))return!br(n).length;for(var r in n)if(Ii.call(n,r))return!1;return!0},Jn.isEqual=function(n,t){return ir(n,t)},Jn.isEqualWith=function(n,t,r){var e=(r="function"==typeof r?r:N)?r(n,t):N;return e===N?ir(n,t,N,r):!!e},Jn.isError=Lu,Jn.isFinite=function(n){return"number"==typeof n&&Xi(n)},Jn.isFunction=Cu,Jn.isInteger=Uu,Jn.isLength=Bu,Jn.isMap=Lf,Jn.isMatch=function(n,t){return n===t||hr(n,t,Pe(t))},Jn.isMatchWith=function(n,t,r){return r="function"==typeof r?r:N,hr(n,t,Pe(t),r)},Jn.isNaN=function(n){return Du(n)&&n!=+n},Jn.isNative=function(n){if(Do(n))throw new vi("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return yr(n)},Jn.isNil=function(n){return null==n},Jn.isNull=function(n){return null===n},Jn.isNumber=Du,Jn.isObject=Tu,Jn.isObjectLike=$u,Jn.isPlainObject=Mu,Jn.isRegExp=Cf,Jn.isSafeInteger=function(n){return Uu(n)&&n>=-Q&&n<=Q},Jn.isSet=Uf,Jn.isString=Fu,Jn.isSymbol=Nu,Jn.isTypedArray=Bf,Jn.isUndefined=function(n){return n===N},Jn.isWeakMap=function(n){return $u(n)&&$o(n)==dn},Jn.isWeakSet=function(n){return $u(n)&&"[object WeakSet]"==qt(n)},Jn.join=function(n,t){return null==n?"":no.call(n,t)},Jn.kebabCase=rc,Jn.last=vu,Jn.lastIndexOf=function(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=e;return r!==N&&(u=(u=Zu(r))<0?ro(e+u,0):eo(u,e-1)),t==t?function(n,t,r){for(var e=r+1;e--;)if(n[e]===t)return e;return e}(n,t,u):v(n,d,u,!0)},Jn.lowerCase=ec,Jn.lowerFirst=uc,Jn.lt=Tf,Jn.lte=$f,Jn.max=function(n){return n&&n.length?Ct(n,oi,Ht):N},Jn.maxBy=function(n,t){return n&&n.length?Ct(n,Fe(t,2),Ht):N},Jn.mean=function(n){return b(n,oi)},Jn.meanBy=function(n,t){return b(n,Fe(t,2))},Jn.min=function(n){return n&&n.length?Ct(n,oi,mr):N},Jn.minBy=function(n,t){return n&&n.length?Ct(n,Fe(t,2),mr):N},Jn.stubArray=si,Jn.stubFalse=hi,Jn.stubObject=function(){return{}},Jn.stubString=function(){return""},Jn.stubTrue=function(){return!0},Jn.multiply=Ac,Jn.nth=function(n,t){return n&&n.length?Or(n,Zu(t)):N},Jn.noConflict=function(){return nr._===this&&(nr._=Wi),this},Jn.noop=ai,Jn.now=yf,Jn.pad=function(n,t,r){n=Hu(n);var e=(t=Zu(t))?$(n):0;if(!t||e>=t)return n;var u=(t-e)/2;return Ae(Ji(u),r)+n+Ae(Hi(u),r)},Jn.padEnd=function(n,t,r){n=Hu(n);var e=(t=Zu(t))?$(n):0;return t&&e<t?n+Ae(t-e,r):n},Jn.padStart=function(n,t,r){n=Hu(n);var e=(t=Zu(t))?$(n):0;return t&&e<t?Ae(t-e,r)+n:n},Jn.parseInt=function(n,t,r){return r||null==t?t=0:t&&(t=+t),io(Hu(n).replace(Zn,""),t||0)},Jn.random=function(n,t,r){if(r&&"boolean"!=typeof r&&He(n,t,r)&&(t=r=N),r===N&&("boolean"==typeof t?(r=t,t=N):"boolean"==typeof n&&(r=n,n=N)),n===N&&t===N?(n=0,t=1):(n=qu(n),t===N?(t=n,n=0):t=qu(t)),n>t){var e=n;n=t,t=e}if(r||n%1||t%1){var u=oo();return eo(n+u*(t-n+Jt("1e-"+((u+"").length-1))),t)}return Sr(n,t)},Jn.reduce=function(n,t,r){var e=zf(n)?l:x,u=arguments.length<3;return e(n,Fe(t,4),r,u,Oo)},Jn.reduceRight=function(n,t,r){var e=zf(n)?s:x,u=arguments.length<3;return e(n,Fe(t,4),r,u,Io)},Jn.repeat=function(n,t,r){return t=(r?He(n,t,r):t===N)?1:Zu(t),Wr(Hu(n),t)},Jn.replace=function(){var n=arguments,t=Hu(n[0]);return n.length<3?t:t.replace(n[1],n[2])},Jn.result=function(n,t,r){var e=-1,u=(t=ne(t,n)).length;for(u||(u=1,n=N);++e<u;){var i=null==n?N:n[fu(t[e])];i===N&&(e=u,i=r),n=Cu(i)?i.call(n):i}return n},Jn.round=kc,Jn.runInContext=m,Jn.sample=function(n){return(zf(n)?dt:Cr)(n)},Jn.size=function(n){if(null==n)return 0;if(Su(n))return Fu(n)?$(n):n.length;var t=$o(n);return t==ln||t==vn?n.size:br(n).length},Jn.snakeCase=ic,Jn.some=function(n,t,r){var e=zf(n)?h:Dr;return r&&He(n,t,r)&&(t=N),e(n,Fe(t,3))},Jn.sortedIndex=function(n,t){return Mr(n,t)},Jn.sortedIndexBy=function(n,t,r){return Fr(n,t,Fe(r,2))},Jn.sortedIndexOf=function(n,t){var r=null==n?0:n.length;if(r){var e=Mr(n,t);if(e<r&&Eu(n[e],t))return e}return-1},Jn.sortedLastIndex=function(n,t){return Mr(n,t,!0)},Jn.sortedLastIndexBy=function(n,t,r){return Fr(n,t,Fe(r,2),!0)},Jn.sortedLastIndexOf=function(n,t){if(null!=n&&n.length){var r=Mr(n,t,!0)-1;if(Eu(n[r],t))return r}return-1},Jn.startCase=oc,Jn.startsWith=function(n,t,r){return n=Hu(n),r=null==r?0:Rt(Zu(r),0,n.length),t=qr(t),n.slice(r,r+t.length)==t},Jn.subtract=Oc,Jn.sum=function(n){return n&&n.length?j(n,oi):0},Jn.sumBy=function(n,t){return n&&n.length?j(n,Fe(t,2)):0},Jn.template=function(n,t,r){var e=Jn.templateSettings;r&&He(n,t,r)&&(t=N),n=Hu(n),t=Ff({},t,e,We);var u,i,o=Ff({},t.imports,e.imports,We),f=Qu(o),c=I(o,f),a=0,l=t.interpolate||ft,s="__p += '",h=bi((t.escape||ft).source+"|"+l.source+"|"+(l===Dn?Xn:ft).source+"|"+(t.evaluate||ft).source+"|$","g"),p="//# sourceURL="+(Ii.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Kt+"]")+"\n";n.replace(h,(function(t,r,e,o,f,c){return e||(e=o),s+=n.slice(a,c).replace(ct,S),r&&(u=!0,s+="' +\n__e("+r+") +\n'"),f&&(i=!0,s+="';\n"+f+";\n__p += '"),e&&(s+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"),a=c+t.length,t})),s+="';\n";var _=Ii.call(t,"variable")&&t.variable;if(_){if(Yn.test(_))throw new vi("Invalid `variable` option passed into `_.template`")}else s="with (obj) {\n"+s+"\n}\n";s=(i?s.replace(En,""):s).replace(Sn,"$1").replace(Wn,"$1;"),s="function("+(_||"obj")+") {\n"+(_?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(u?", __e = _.escape":"")+(i?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+s+"return __p\n}";var v=ac((function(){return gi(f,p+"return "+s).apply(N,c)}));if(v.source=s,Lu(v))throw v;return v},Jn.times=function(n,t){if((n=Zu(n))<1||n>Q)return[];var r=nn,e=eo(n,nn);t=Fe(t),n-=nn;for(var u=A(e,t);++r<n;)t(r);return u},Jn.toFinite=qu,Jn.toInteger=Zu,Jn.toLength=Ku,Jn.toLower=function(n){return Hu(n).toLowerCase()},Jn.toNumber=Vu,Jn.toSafeInteger=function(n){return n?Rt(Zu(n),-Q,Q):0===n?n:0},Jn.toString=Hu,Jn.toUpper=function(n){return Hu(n).toUpperCase()},Jn.trim=function(n,t,r){if((n=Hu(n))&&(r||t===N))return k(n);if(!n||!(t=qr(t)))return n;var e=D(n),u=D(t);return te(e,z(e,u),E(e,u)+1).join("")},Jn.trimEnd=function(n,t,r){if((n=Hu(n))&&(r||t===N))return n.slice(0,M(n)+1);if(!n||!(t=qr(t)))return n;var e=D(n);return te(e,0,E(e,D(t))+1).join("")},Jn.trimStart=function(n,t,r){if((n=Hu(n))&&(r||t===N))return n.replace(Zn,"");if(!n||!(t=qr(t)))return n;var e=D(n);return te(e,z(e,D(t))).join("")},Jn.truncate=function(n,t){var r=30,e="...";if(Tu(t)){var u="separator"in t?t.separator:u;r="length"in t?Zu(t.length):r,e="omission"in t?qr(t.omission):e}var i=(n=Hu(n)).length;if(W(n)){var o=D(n);i=o.length}if(r>=i)return n;var f=r-$(e);if(f<1)return e;var c=o?te(o,0,f).join(""):n.slice(0,f);if(u===N)return c+e;if(o&&(f+=c.length-f),Cf(u)){if(n.slice(f).search(u)){var a,l=c;for(u.global||(u=bi(u.source,Hu(nt.exec(u))+"g")),u.lastIndex=0;a=u.exec(l);)var s=a.index;c=c.slice(0,s===N?f:s)}}else if(n.indexOf(qr(u),f)!=f){var h=c.lastIndexOf(u);h>-1&&(c=c.slice(0,h))}return c+e},Jn.unescape=function(n){return(n=Hu(n))&&Un.test(n)?n.replace(Ln,vr):n},Jn.uniqueId=function(n){var t=++Ri;return Hu(n)+t},Jn.upperCase=fc,Jn.upperFirst=cc,Jn.each=xu,Jn.eachRight=ju,Jn.first=_u,ci(Jn,function(){var n={};return Tt(Jn,(function(t,r){Ii.call(Jn.prototype,r)||(n[r]=t)})),n}(),{chain:!1}),Jn.VERSION="4.17.21",r(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(n){Jn[n].placeholder=Jn})),r(["drop","take"],(function(n,t){st.prototype[n]=function(r){r=r===N?1:ro(Zu(r),0);var e=this.__filtered__&&!t?new st(this):this.clone();return e.__filtered__?e.__takeCount__=eo(r,e.__takeCount__):e.__views__.push({size:eo(r,nn),type:n+(e.__dir__<0?"Right":"")}),e},st.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()}})),r(["filter","map","takeWhile"],(function(n,t){var r=t+1,e=1==r||3==r;st.prototype[n]=function(n){var t=this.clone();return t.__iteratees__.push({iteratee:Fe(n,3),type:r}),t.__filtered__=t.__filtered__||e,t}})),r(["head","last"],(function(n,t){var r="take"+(t?"Right":"");st.prototype[n]=function(){return this[r](1).value()[0]}})),r(["initial","tail"],(function(n,t){var r="drop"+(t?"":"Right");st.prototype[n]=function(){return this.__filtered__?new st(this):this[r](1)}})),st.prototype.compact=function(){return this.filter(oi)},st.prototype.find=function(n){return this.filter(n).head()},st.prototype.findLast=function(n){return this.reverse().find(n)},st.prototype.invokeMap=Lr((function(n,t){return"function"==typeof n?new st(this):this.map((function(r){return rr(r,n,t)}))})),st.prototype.reject=function(n){return this.filter(zu(Fe(n)))},st.prototype.slice=function(n,t){n=Zu(n);var r=this;return r.__filtered__&&(n>0||t<0)?new st(r):(n<0?r=r.takeRight(-n):n&&(r=r.drop(n)),t!==N&&(r=(t=Zu(t))<0?r.dropRight(-t):r.take(t-n)),r)},st.prototype.takeRightWhile=function(n){return this.reverse().takeWhile(n).reverse()},st.prototype.toArray=function(){return this.take(nn)},Tt(st.prototype,(function(n,t){var r=/^(?:filter|find|map|reject)|While$/.test(t),e=/^(?:head|last)$/.test(t),u=Jn[e?"take"+("last"==t?"Right":""):t],i=e||/^find/.test(t);u&&(Jn.prototype[t]=function(){var t=this.__wrapped__,o=e?[1]:arguments,f=t instanceof st,c=o[0],l=f||zf(t),s=function(n){var t=u.apply(Jn,a([n],o));return e&&h?t[0]:t};l&&r&&"function"==typeof c&&1!=c.length&&(f=l=!1);var h=this.__chain__,p=!!this.__actions__.length,_=i&&!h,v=f&&!p;if(!i&&l){t=v?t:new st(this);var g=n.apply(t,o);return g.__actions__.push({func:mu,args:[s],thisArg:N}),new lt(g,h)}return _&&v?n.apply(this,o):(g=this.thru(s),_?e?g.value()[0]:g.value():g)})})),r(["pop","push","shift","sort","splice","unshift"],(function(n){var t=xi[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:pop|shift)$/.test(n);Jn.prototype[n]=function(){var n=arguments;if(e&&!this.__chain__){var u=this.value();return t.apply(zf(u)?u:[],n)}return this[r]((function(r){return t.apply(zf(r)?r:[],n)}))}})),Tt(st.prototype,(function(n,t){var r=Jn[t];if(r){var e=r.name+"";Ii.call(vo,e)||(vo[e]=[]),vo[e].push({name:t,func:r})}})),vo[we(N,2).name]=[{name:"wrapper",func:N}],st.prototype.clone=function(){var n=new st(this.__wrapped__);return n.__actions__=ce(this.__actions__),n.__dir__=this.__dir__,n.__filtered__=this.__filtered__,n.__iteratees__=ce(this.__iteratees__),n.__takeCount__=this.__takeCount__,n.__views__=ce(this.__views__),n},st.prototype.reverse=function(){if(this.__filtered__){var n=new st(this);n.__dir__=-1,n.__filtered__=!0}else(n=this.clone()).__dir__*=-1;return n},st.prototype.value=function(){var n=this.__wrapped__.value(),t=this.__dir__,r=zf(n),e=t<0,u=r?n.length:0,i=function(n,t,r){for(var e=-1,u=r.length;++e<u;){var i=r[e],o=i.size;switch(i.type){case"drop":n+=o;break;case"dropRight":t-=o;break;case"take":t=eo(t,n+o);break;case"takeRight":n=ro(n,t-o)}}return{start:n,end:t}}(0,u,this.__views__),o=i.start,f=i.end,c=f-o,a=e?f:o-1,l=this.__iteratees__,s=l.length,h=0,p=eo(c,this.__takeCount__);if(!r||!e&&u==c&&p==c)return Hr(n,this.__actions__);var _=[];n:for(;c--&&h<p;){for(var v=-1,g=n[a+=t];++v<s;){var y=l[v],d=y.iteratee,b=y.type,w=d(g);if(2==b)g=w;else if(!w){if(1==b)continue n;break n}}_[h++]=g}return _},Jn.prototype.at=cf,Jn.prototype.chain=function(){return wu(this)},Jn.prototype.commit=function(){return new lt(this.value(),this.__chain__)},Jn.prototype.next=function(){this.__values__===N&&(this.__values__=Pu(this.value()));var n=this.__index__>=this.__values__.length;return{done:n,value:n?N:this.__values__[this.__index__++]}},Jn.prototype.plant=function(n){for(var t,r=this;r instanceof at;){var e=lu(r);e.__index__=0,e.__values__=N,t?u.__wrapped__=e:t=e;var u=e;r=r.__wrapped__}return u.__wrapped__=n,t},Jn.prototype.reverse=function(){var n=this.__wrapped__;if(n instanceof st){var t=n;return this.__actions__.length&&(t=new st(this)),(t=t.reverse()).__actions__.push({func:mu,args:[yu],thisArg:N}),new lt(t,this.__chain__)}return this.thru(yu)},Jn.prototype.toJSON=Jn.prototype.valueOf=Jn.prototype.value=function(){return Hr(this.__wrapped__,this.__actions__)},Jn.prototype.first=Jn.prototype.head,Pi&&(Jn.prototype[Pi]=function(){return this}),Jn}();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(nr._=gr,define((function(){return gr}))):rr?((rr.exports=gr)._=gr,tr._=gr):nr._=gr}).call(this); wp-polyfill-node-contains.js 0000644 00000001203 14720015030 0012103 0 ustar 00 // Node.prototype.contains (function() { function contains(node) { if (!(0 in arguments)) { throw new TypeError('1 argument is required'); } do { if (this === node) { return true; } // eslint-disable-next-line no-cond-assign } while (node = node && node.parentNode); return false; } // IE if ('HTMLElement' in self && 'contains' in HTMLElement.prototype) { try { delete HTMLElement.prototype.contains; // eslint-disable-next-line no-empty } catch (e) {} } if ('Node' in self) { Node.prototype.contains = contains; } else { document.contains = Element.prototype.contains = contains; } }()); wp-polyfill-element-closest.min.js 0000644 00000000652 14720015030 0013236 0 ustar 00 !function(e){var t=window.Element.prototype;"function"!=typeof t.matches&&(t.matches=t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||function(e){for(var t=(this.document||this.ownerDocument).querySelectorAll(e),o=0;t[o]&&t[o]!==this;)++o;return Boolean(t[o])}),"function"!=typeof t.closest&&(t.closest=function(e){for(var t=this;t&&1===t.nodeType;){if(t.matches(e))return t;t=t.parentNode}return null})}(); wp-polyfill-formdata.min.js 0000644 00000021106 14720015030 0011725 0 ustar 00 /*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */ !function(){var t;function e(t){var e=0;return function(){return e<t.length?{done:!1,value:t[e++]}:{done:!0}}}var n="function"==typeof Object.defineProperties?Object.defineProperty:function(t,e,n){return t==Array.prototype||t==Object.prototype||(t[e]=n.value),t};var r,o=function(t){t=["object"==typeof globalThis&&globalThis,t,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var e=0;e<t.length;++e){var n=t[e];if(n&&n.Math==Math)return n}throw Error("Cannot find global object")}(this);function i(t,e){if(e)t:{var r=o;t=t.split(".");for(var i=0;i<t.length-1;i++){var a=t[i];if(!(a in r))break t;r=r[a]}(e=e(i=r[t=t[t.length-1]]))!=i&&null!=e&&n(r,t,{configurable:!0,writable:!0,value:e})}}function a(t){return(t={next:t})[Symbol.iterator]=function(){return this},t}function u(t){var n="undefined"!=typeof Symbol&&Symbol.iterator&&t[Symbol.iterator];return n?n.call(t):{next:e(t)}}if(i("Symbol",(function(t){function e(t,e){this.A=t,n(this,"description",{configurable:!0,writable:!0,value:e})}if(t)return t;e.prototype.toString=function(){return this.A};var r="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",o=0;return function t(n){if(this instanceof t)throw new TypeError("Symbol is not a constructor");return new e(r+(n||"")+"_"+o++,n)}})),i("Symbol.iterator",(function(t){if(t)return t;t=Symbol("Symbol.iterator");for(var r="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),i=0;i<r.length;i++){var u=o[r[i]];"function"==typeof u&&"function"!=typeof u.prototype[t]&&n(u.prototype,t,{configurable:!0,writable:!0,value:function(){return a(e(this))}})}return t})),"function"==typeof Object.setPrototypeOf)r=Object.setPrototypeOf;else{var l;t:{var s={};try{s.__proto__={a:!0},l=s.a;break t}catch(t){}l=!1}r=l?function(t,e){if(t.__proto__=e,t.__proto__!==e)throw new TypeError(t+" is not extensible");return t}:null}var f=r;function c(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function h(t){if(t.m)throw new TypeError("Generator is already running");t.m=!0}function p(t,e){return t.h=3,{value:e}}function y(t){this.g=new c,this.G=t}function v(t,e,n,r){try{var o=e.call(t.g.j,n);if(!(o instanceof Object))throw new TypeError("Iterator result "+o+" is not an object");if(!o.done)return t.g.m=!1,o;var i=o.value}catch(e){return t.g.j=null,t.g.s(e),g(t)}return t.g.j=null,r.call(t.g,i),g(t)}function g(t){for(;t.g.h;)try{var e=t.G(t.g);if(e)return t.g.m=!1,{value:e.value,done:!1}}catch(e){t.g.v=void 0,t.g.s(e)}if(t.g.m=!1,t.g.l){if(e=t.g.l,t.g.l=null,e.F)throw e.D;return{value:e.return,done:!0}}return{value:void 0,done:!0}}function d(t){this.next=function(e){return t.o(e)},this.throw=function(e){return t.s(e)},this.return=function(e){return function(t,e){h(t.g);var n=t.g.j;return n?v(t,"return"in n?n.return:function(t){return{value:t,done:!0}},e,t.g.return):(t.g.return(e),g(t))}(t,e)},this[Symbol.iterator]=function(){return this}}function b(t,e){return e=new d(new y(e)),f&&t.prototype&&f(e,t.prototype),e}if(c.prototype.o=function(t){this.v=t},c.prototype.s=function(t){this.l={D:t,F:!0},this.h=this.C||this.u},c.prototype.return=function(t){this.l={return:t},this.h=this.u},y.prototype.o=function(t){return h(this.g),this.g.j?v(this,this.g.j.next,t,this.g.o):(this.g.o(t),g(this))},y.prototype.s=function(t){return h(this.g),this.g.j?v(this,this.g.j.throw,t,this.g.o):(this.g.s(t),g(this))},i("Array.prototype.entries",(function(t){return t||function(){return function(t,e){t instanceof String&&(t+="");var n=0,r=!1,o={next:function(){if(!r&&n<t.length){var o=n++;return{value:e(o,t[o]),done:!1}}return r=!0,{done:!0,value:void 0}}};return o[Symbol.iterator]=function(){return o},o}(this,(function(t,e){return[t,e]}))}})),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var m=function(t,e){for(var n=0;n<t.length;n++)e(t[n])},w=function(t){return t.replace(/\r?\n|\r/g,"\r\n")},S=function(t,e,n){return e instanceof Blob?(n=void 0!==n?String(n+""):"string"==typeof e.name?e.name:"blob",e.name===n&&"[object Blob]"!==Object.prototype.toString.call(e)||(e=new File([e],n)),[String(t),e]):[String(t),String(e)]},j=function(t,e){if(t.length<e)throw new TypeError(e+" argument required, but only "+t.length+" present.")},x="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,_=x.FormData,F=x.XMLHttpRequest&&x.XMLHttpRequest.prototype.send,A=x.Request&&x.fetch,M=x.navigator&&x.navigator.sendBeacon,D=x.Element&&x.Element.prototype,B=x.Symbol&&Symbol.toStringTag;B&&(Blob.prototype[B]||(Blob.prototype[B]="Blob"),"File"in x&&!File.prototype[B]&&(File.prototype[B]="File"));try{new File([],"")}catch(t){x.File=function(t,e,n){return t=new Blob(t,n||{}),Object.defineProperties(t,{name:{value:e},lastModified:{value:+(n&&void 0!==n.lastModified?new Date(n.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),B&&Object.defineProperty(t,B,{value:"File"}),t}}var T=function(t){return t.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},q=function(t){this.i=[];var e=this;t&&m(t.elements,(function(t){if(t.name&&!t.disabled&&"submit"!==t.type&&"button"!==t.type&&!t.matches("form fieldset[disabled] *"))if("file"===t.type){var n=t.files&&t.files.length?t.files:[new File([],"",{type:"application/octet-stream"})];m(n,(function(n){e.append(t.name,n)}))}else"select-multiple"===t.type||"select-one"===t.type?m(t.options,(function(n){!n.disabled&&n.selected&&e.append(t.name,n.value)})):"checkbox"===t.type||"radio"===t.type?t.checked&&e.append(t.name,t.value):(n="textarea"===t.type?w(t.value):t.value,e.append(t.name,n))}))};if((t=q.prototype).append=function(t,e,n){j(arguments,2),this.i.push(S(t,e,n))},t.delete=function(t){j(arguments,1);var e=[];t=String(t),m(this.i,(function(n){n[0]!==t&&e.push(n)})),this.i=e},t.entries=function t(){var e,n=this;return b(t,(function(t){if(1==t.h&&(e=0),3!=t.h)return e<n.i.length?t=p(t,n.i[e]):(t.h=0,t=void 0),t;e++,t.h=2}))},t.forEach=function(t,e){j(arguments,1);for(var n=u(this),r=n.next();!r.done;r=n.next()){var o=u(r.value);r=o.next().value,o=o.next().value,t.call(e,o,r,this)}},t.get=function(t){j(arguments,1);var e=this.i;t=String(t);for(var n=0;n<e.length;n++)if(e[n][0]===t)return e[n][1];return null},t.getAll=function(t){j(arguments,1);var e=[];return t=String(t),m(this.i,(function(n){n[0]===t&&e.push(n[1])})),e},t.has=function(t){j(arguments,1),t=String(t);for(var e=0;e<this.i.length;e++)if(this.i[e][0]===t)return!0;return!1},t.keys=function t(){var e,n,r,o,i=this;return b(t,(function(t){if(1==t.h&&(e=u(i),n=e.next()),3!=t.h)return n.done?void(t.h=0):(r=n.value,o=u(r),p(t,o.next().value));n=e.next(),t.h=2}))},t.set=function(t,e,n){j(arguments,2),t=String(t);var r=[],o=S(t,e,n),i=!0;m(this.i,(function(e){e[0]===t?i&&(i=!r.push(o)):r.push(e)})),i&&r.push(o),this.i=r},t.values=function t(){var e,n,r,o,i=this;return b(t,(function(t){if(1==t.h&&(e=u(i),n=e.next()),3!=t.h)return n.done?void(t.h=0):(r=n.value,(o=u(r)).next(),p(t,o.next().value));n=e.next(),t.h=2}))},q.prototype._asNative=function(){for(var t=new _,e=u(this),n=e.next();!n.done;n=e.next()){var r=u(n.value);n=r.next().value,r=r.next().value,t.append(n,r)}return t},q.prototype._blob=function(){var t="----formdata-polyfill-"+Math.random(),e=[],n="--"+t+'\r\nContent-Disposition: form-data; name="';return this.forEach((function(t,r){return"string"==typeof t?e.push(n+T(w(r))+'"\r\n\r\n'+w(t)+"\r\n"):e.push(n+T(w(r))+'"; filename="'+T(t.name)+'"\r\nContent-Type: '+(t.type||"application/octet-stream")+"\r\n\r\n",t,"\r\n")})),e.push("--"+t+"--"),new Blob(e,{type:"multipart/form-data; boundary="+t})},q.prototype[Symbol.iterator]=function(){return this.entries()},q.prototype.toString=function(){return"[object FormData]"},D&&!D.matches&&(D.matches=D.matchesSelector||D.mozMatchesSelector||D.msMatchesSelector||D.oMatchesSelector||D.webkitMatchesSelector||function(t){for(var e=(t=(this.document||this.ownerDocument).querySelectorAll(t)).length;0<=--e&&t.item(e)!==this;);return-1<e}),B&&(q.prototype[B]="FormData"),F){var O=x.XMLHttpRequest.prototype.setRequestHeader;x.XMLHttpRequest.prototype.setRequestHeader=function(t,e){O.call(this,t,e),"content-type"===t.toLowerCase()&&(this.B=!0)},x.XMLHttpRequest.prototype.send=function(t){t instanceof q?(t=t._blob(),this.B||this.setRequestHeader("Content-Type",t.type),F.call(this,t)):F.call(this,t)}}A&&(x.fetch=function(t,e){return e&&e.body&&e.body instanceof q&&(e.body=e.body._blob()),A.call(this,t,e)}),M&&(x.navigator.sendBeacon=function(t,e){return e instanceof q&&(e=e._asNative()),M.call(this,t,e)}),x.FormData=q}}(); wp-polyfill-fetch.min.js 0000604 00000023476 14720015030 0011231 0 ustar 00 !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.WHATWGFetch={})}(this,(function(t){"use strict";var e,r,o="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||"undefined"!=typeof global&&global||{},n="URLSearchParams"in o,s="Symbol"in o&&"iterator"in Symbol,i="FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch(t){return!1}}(),a="FormData"in o,h="ArrayBuffer"in o;function u(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||""===t)throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}function f(t){return"string"!=typeof t?String(t):t}function d(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return s&&(e[Symbol.iterator]=function(){return e}),e}function c(t){this.map={},t instanceof c?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){if(2!=t.length)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+t.length);this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function y(t){if(!t._noBody)return t.bodyUsed?Promise.reject(new TypeError("Already read")):void(t.bodyUsed=!0)}function l(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function p(t){var e=new FileReader,r=l(e);return e.readAsArrayBuffer(t),r}function b(t){var e;return t.slice?t.slice(0):((e=new Uint8Array(t.byteLength)).set(new Uint8Array(t)),e.buffer)}function m(){return this.bodyUsed=!1,this._initBody=function(t){var e;this.bodyUsed=this.bodyUsed,(this._bodyInit=t)?"string"==typeof t?this._bodyText=t:i&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:a&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:n&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():h&&i&&(e=t)&&DataView.prototype.isPrototypeOf(e)?(this._bodyArrayBuffer=b(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):h&&(ArrayBuffer.prototype.isPrototypeOf(t)||r(t))?this._bodyArrayBuffer=b(t):this._bodyText=t=Object.prototype.toString.call(t):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):n&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var t=y(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer)return y(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer));if(i)return this.blob().then(p);throw new Error("could not read as ArrayBuffer")},this.text=function(){var t,e,r,o=y(this);if(o)return o;if(this._bodyBlob)return o=this._bodyBlob,e=l(t=new FileReader),r=(r=/charset=([A-Za-z0-9_-]+)/.exec(o.type))?r[1]:"utf-8",t.readAsText(o,r),e;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),o=0;o<e.length;o++)r[o]=String.fromCharCode(e[o]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a&&(this.formData=function(){return this.text().then(A)}),this.json=function(){return this.text().then(JSON.parse)},this}h&&(e=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],r=ArrayBuffer.isView||function(t){return t&&-1<e.indexOf(Object.prototype.toString.call(t))}),c.prototype.append=function(t,e){t=u(t),e=f(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},c.prototype.delete=function(t){delete this.map[u(t)]},c.prototype.get=function(t){return t=u(t),this.has(t)?this.map[t]:null},c.prototype.has=function(t){return this.map.hasOwnProperty(u(t))},c.prototype.set=function(t,e){this.map[u(t)]=f(e)},c.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},c.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),d(t)},c.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),d(t)},c.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),d(t)},s&&(c.prototype[Symbol.iterator]=c.prototype.entries);var w=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function E(t,e){if(!(this instanceof E))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r,n=(e=e||{}).body;if(t instanceof E){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new c(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,n||null==t._bodyInit||(n=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",!e.headers&&this.headers||(this.headers=new c(e.headers)),this.method=(r=(t=e.method||this.method||"GET").toUpperCase(),-1<w.indexOf(r)?r:t),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||function(){if("AbortController"in o)return(new AbortController).signal}(),this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(n),"GET"!==this.method&&"HEAD"!==this.method||"no-store"!==e.cache&&"no-cache"!==e.cache||((r=/([?&])_=[^&]*/).test(this.url)?this.url=this.url.replace(r,"$1_="+(new Date).getTime()):this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime())}function A(t){var e=new FormData;return t.trim().split("&").forEach((function(t){var r;t&&(r=(t=t.split("=")).shift().replace(/\+/g," "),t=t.join("=").replace(/\+/g," "),e.append(decodeURIComponent(r),decodeURIComponent(t)))})),e}function g(t,e){if(!(this instanceof g))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e=e||{},this.type="default",this.status=void 0===e.status?200:e.status,this.status<200||599<this.status)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=200<=this.status&&this.status<300,this.statusText=void 0===e.statusText?"":""+e.statusText,this.headers=new c(e.headers),this.url=e.url||"",this._initBody(t)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})},m.call(E.prototype),m.call(g.prototype),g.prototype.clone=function(){return new g(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new c(this.headers),url:this.url})},g.error=function(){var t=new g(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};var T=[301,302,303,307,308];g.redirect=function(t,e){if(-1===T.indexOf(e))throw new RangeError("Invalid status code");return new g(null,{status:e,headers:{location:t}})},t.DOMException=o.DOMException;try{new t.DOMException}catch(d){t.DOMException=function(t,e){this.message=t,this.name=e,e=Error(t),this.stack=e.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function _(e,r){return new Promise((function(n,s){var a=new E(e,r);if(a.signal&&a.signal.aborted)return s(new t.DOMException("Aborted","AbortError"));var d,y=new XMLHttpRequest;function l(){y.abort()}y.onload=function(){var t,e,r={statusText:y.statusText,headers:(t=y.getAllResponseHeaders()||"",e=new c,t.replace(/\r?\n[\t ]+/g," ").split("\r").map((function(t){return 0===t.indexOf("\n")?t.substr(1,t.length):t})).forEach((function(t){var r=(t=t.split(":")).shift().trim();if(r){t=t.join(":").trim();try{e.append(r,t)}catch(t){console.warn("Response "+t.message)}}})),e)},o=(0===a.url.indexOf("file://")&&(y.status<200||599<y.status)?r.status=200:r.status=y.status,r.url="responseURL"in y?y.responseURL:r.headers.get("X-Request-URL"),"response"in y?y.response:y.responseText);setTimeout((function(){n(new g(o,r))}),0)},y.onerror=function(){setTimeout((function(){s(new TypeError("Network request failed"))}),0)},y.ontimeout=function(){setTimeout((function(){s(new TypeError("Network request timed out"))}),0)},y.onabort=function(){setTimeout((function(){s(new t.DOMException("Aborted","AbortError"))}),0)},y.open(a.method,function(t){try{return""===t&&o.location.href?o.location.href:t}catch(e){return t}}(a.url),!0),"include"===a.credentials?y.withCredentials=!0:"omit"===a.credentials&&(y.withCredentials=!1),"responseType"in y&&(i?y.responseType="blob":h&&(y.responseType="arraybuffer")),r&&"object"==typeof r.headers&&!(r.headers instanceof c||o.Headers&&r.headers instanceof o.Headers)?(d=[],Object.getOwnPropertyNames(r.headers).forEach((function(t){d.push(u(t)),y.setRequestHeader(t,f(r.headers[t]))})),a.headers.forEach((function(t,e){-1===d.indexOf(e)&&y.setRequestHeader(e,t)}))):a.headers.forEach((function(t,e){y.setRequestHeader(e,t)})),a.signal&&(a.signal.addEventListener("abort",l),y.onreadystatechange=function(){4===y.readyState&&a.signal.removeEventListener("abort",l)}),y.send(void 0===a._bodyInit?null:a._bodyInit)}))}_.polyfill=!0,o.fetch||(o.fetch=_,o.Headers=c,o.Request=E,o.Response=g),t.Headers=c,t.Request=E,t.Response=g,t.fetch=_,Object.defineProperty(t,"__esModule",{value:!0})})); moment.min.js 0000604 00000162673 14720015030 0007166 0 ustar 00 !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";var H;function _(){return H.apply(null,arguments)}function y(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function F(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function c(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function L(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;for(var t in e)if(c(e,t))return;return 1}function g(e){return void 0===e}function w(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function V(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function G(e,t){for(var n=[],s=e.length,i=0;i<s;++i)n.push(t(e[i],i));return n}function E(e,t){for(var n in t)c(t,n)&&(e[n]=t[n]);return c(t,"toString")&&(e.toString=t.toString),c(t,"valueOf")&&(e.valueOf=t.valueOf),e}function l(e,t,n,s){return Wt(e,t,n,s,!0).utc()}function p(e){return null==e._pf&&(e._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}),e._pf}function A(e){var t,n,s=e._d&&!isNaN(e._d.getTime());return s&&(t=p(e),n=j.call(t.parsedDateParts,function(e){return null!=e}),s=t.overflow<0&&!t.empty&&!t.invalidEra&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n),e._strict)&&(s=s&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e)?s:(e._isValid=s,e._isValid)}function I(e){var t=l(NaN);return null!=e?E(p(t),e):p(t).userInvalidated=!0,t}var j=Array.prototype.some||function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1},Z=_.momentProperties=[],z=!1;function q(e,t){var n,s,i,r=Z.length;if(g(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),g(t._i)||(e._i=t._i),g(t._f)||(e._f=t._f),g(t._l)||(e._l=t._l),g(t._strict)||(e._strict=t._strict),g(t._tzm)||(e._tzm=t._tzm),g(t._isUTC)||(e._isUTC=t._isUTC),g(t._offset)||(e._offset=t._offset),g(t._pf)||(e._pf=p(t)),g(t._locale)||(e._locale=t._locale),0<r)for(n=0;n<r;n++)g(i=t[s=Z[n]])||(e[s]=i);return e}function $(e){q(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===z&&(z=!0,_.updateOffset(this),z=!1)}function k(e){return e instanceof $||null!=e&&null!=e._isAMomentObject}function B(e){!1===_.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function e(r,a){var o=!0;return E(function(){if(null!=_.deprecationHandler&&_.deprecationHandler(null,r),o){for(var e,t,n=[],s=arguments.length,i=0;i<s;i++){if(e="","object"==typeof arguments[i]){for(t in e+="\n["+i+"] ",arguments[0])c(arguments[0],t)&&(e+=t+": "+arguments[0][t]+", ");e=e.slice(0,-2)}else e=arguments[i];n.push(e)}B(r+"\nArguments: "+Array.prototype.slice.call(n).join("")+"\n"+(new Error).stack),o=!1}return a.apply(this,arguments)},a)}var J={};function Q(e,t){null!=_.deprecationHandler&&_.deprecationHandler(e,t),J[e]||(B(t),J[e]=!0)}function a(e){return"undefined"!=typeof Function&&e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function X(e,t){var n,s=E({},e);for(n in t)c(t,n)&&(F(e[n])&&F(t[n])?(s[n]={},E(s[n],e[n]),E(s[n],t[n])):null!=t[n]?s[n]=t[n]:delete s[n]);for(n in e)c(e,n)&&!c(t,n)&&F(e[n])&&(s[n]=E({},s[n]));return s}function K(e){null!=e&&this.set(e)}_.suppressDeprecationWarnings=!1,_.deprecationHandler=null;var ee=Object.keys||function(e){var t,n=[];for(t in e)c(e,t)&&n.push(t);return n};function r(e,t,n){var s=""+Math.abs(e);return(0<=e?n?"+":"":"-")+Math.pow(10,Math.max(0,t-s.length)).toString().substr(1)+s}var te=/(\[[^\[]*\])|(\\)?([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,ne=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,se={},ie={};function s(e,t,n,s){var i="string"==typeof s?function(){return this[s]()}:s;e&&(ie[e]=i),t&&(ie[t[0]]=function(){return r(i.apply(this,arguments),t[1],t[2])}),n&&(ie[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function re(e,t){return e.isValid()?(t=ae(t,e.localeData()),se[t]=se[t]||function(s){for(var e,i=s.match(te),t=0,r=i.length;t<r;t++)ie[i[t]]?i[t]=ie[i[t]]:i[t]=(e=i[t]).match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"");return function(e){for(var t="",n=0;n<r;n++)t+=a(i[n])?i[n].call(e,s):i[n];return t}}(t),se[t](e)):e.localeData().invalidDate()}function ae(e,t){var n=5;function s(e){return t.longDateFormat(e)||e}for(ne.lastIndex=0;0<=n&&ne.test(e);)e=e.replace(ne,s),ne.lastIndex=0,--n;return e}var oe={D:"date",dates:"date",date:"date",d:"day",days:"day",day:"day",e:"weekday",weekdays:"weekday",weekday:"weekday",E:"isoWeekday",isoweekdays:"isoWeekday",isoweekday:"isoWeekday",DDD:"dayOfYear",dayofyears:"dayOfYear",dayofyear:"dayOfYear",h:"hour",hours:"hour",hour:"hour",ms:"millisecond",milliseconds:"millisecond",millisecond:"millisecond",m:"minute",minutes:"minute",minute:"minute",M:"month",months:"month",month:"month",Q:"quarter",quarters:"quarter",quarter:"quarter",s:"second",seconds:"second",second:"second",gg:"weekYear",weekyears:"weekYear",weekyear:"weekYear",GG:"isoWeekYear",isoweekyears:"isoWeekYear",isoweekyear:"isoWeekYear",w:"week",weeks:"week",week:"week",W:"isoWeek",isoweeks:"isoWeek",isoweek:"isoWeek",y:"year",years:"year",year:"year"};function o(e){return"string"==typeof e?oe[e]||oe[e.toLowerCase()]:void 0}function ue(e){var t,n,s={};for(n in e)c(e,n)&&(t=o(n))&&(s[t]=e[n]);return s}var le={date:9,day:11,weekday:11,isoWeekday:11,dayOfYear:4,hour:13,millisecond:16,minute:14,month:8,quarter:7,second:15,weekYear:1,isoWeekYear:1,week:5,isoWeek:5,year:1};var de=/\d/,t=/\d\d/,he=/\d{3}/,ce=/\d{4}/,fe=/[+-]?\d{6}/,n=/\d\d?/,me=/\d\d\d\d?/,_e=/\d\d\d\d\d\d?/,ye=/\d{1,3}/,ge=/\d{1,4}/,we=/[+-]?\d{1,6}/,pe=/\d+/,ke=/[+-]?\d+/,Me=/Z|[+-]\d\d:?\d\d/gi,ve=/Z|[+-]\d\d(?::?\d\d)?/gi,i=/[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,u=/^[1-9]\d?/,d=/^([1-9]\d|\d)/;function h(e,n,s){Ye[e]=a(n)?n:function(e,t){return e&&s?s:n}}function De(e,t){return c(Ye,e)?Ye[e](t._strict,t._locale):new RegExp(f(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i})))}function f(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function m(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function M(e){var e=+e,t=0;return t=0!=e&&isFinite(e)?m(e):t}var Ye={},Se={};function v(e,n){var t,s,i=n;for("string"==typeof e&&(e=[e]),w(n)&&(i=function(e,t){t[n]=M(e)}),s=e.length,t=0;t<s;t++)Se[e[t]]=i}function Oe(e,i){v(e,function(e,t,n,s){n._w=n._w||{},i(e,n._w,n,s)})}function be(e){return e%4==0&&e%100!=0||e%400==0}var D=0,Y=1,S=2,O=3,b=4,T=5,Te=6,xe=7,Ne=8;function We(e){return be(e)?366:365}s("Y",0,0,function(){var e=this.year();return e<=9999?r(e,4):"+"+e}),s(0,["YY",2],0,function(){return this.year()%100}),s(0,["YYYY",4],0,"year"),s(0,["YYYYY",5],0,"year"),s(0,["YYYYYY",6,!0],0,"year"),h("Y",ke),h("YY",n,t),h("YYYY",ge,ce),h("YYYYY",we,fe),h("YYYYYY",we,fe),v(["YYYYY","YYYYYY"],D),v("YYYY",function(e,t){t[D]=2===e.length?_.parseTwoDigitYear(e):M(e)}),v("YY",function(e,t){t[D]=_.parseTwoDigitYear(e)}),v("Y",function(e,t){t[D]=parseInt(e,10)}),_.parseTwoDigitYear=function(e){return M(e)+(68<M(e)?1900:2e3)};var x,Pe=Re("FullYear",!0);function Re(t,n){return function(e){return null!=e?(Ue(this,t,e),_.updateOffset(this,n),this):Ce(this,t)}}function Ce(e,t){if(!e.isValid())return NaN;var n=e._d,s=e._isUTC;switch(t){case"Milliseconds":return s?n.getUTCMilliseconds():n.getMilliseconds();case"Seconds":return s?n.getUTCSeconds():n.getSeconds();case"Minutes":return s?n.getUTCMinutes():n.getMinutes();case"Hours":return s?n.getUTCHours():n.getHours();case"Date":return s?n.getUTCDate():n.getDate();case"Day":return s?n.getUTCDay():n.getDay();case"Month":return s?n.getUTCMonth():n.getMonth();case"FullYear":return s?n.getUTCFullYear():n.getFullYear();default:return NaN}}function Ue(e,t,n){var s,i,r;if(e.isValid()&&!isNaN(n)){switch(s=e._d,i=e._isUTC,t){case"Milliseconds":return i?s.setUTCMilliseconds(n):s.setMilliseconds(n);case"Seconds":return i?s.setUTCSeconds(n):s.setSeconds(n);case"Minutes":return i?s.setUTCMinutes(n):s.setMinutes(n);case"Hours":return i?s.setUTCHours(n):s.setHours(n);case"Date":return i?s.setUTCDate(n):s.setDate(n);case"FullYear":break;default:return}t=n,r=e.month(),e=29!==(e=e.date())||1!==r||be(t)?e:28,i?s.setUTCFullYear(t,r,e):s.setFullYear(t,r,e)}}function He(e,t){var n;return isNaN(e)||isNaN(t)?NaN:(n=(t%(n=12)+n)%n,e+=(t-n)/12,1==n?be(e)?29:28:31-n%7%2)}x=Array.prototype.indexOf||function(e){for(var t=0;t<this.length;++t)if(this[t]===e)return t;return-1},s("M",["MM",2],"Mo",function(){return this.month()+1}),s("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),s("MMMM",0,0,function(e){return this.localeData().months(this,e)}),h("M",n,u),h("MM",n,t),h("MMM",function(e,t){return t.monthsShortRegex(e)}),h("MMMM",function(e,t){return t.monthsRegex(e)}),v(["M","MM"],function(e,t){t[Y]=M(e)-1}),v(["MMM","MMMM"],function(e,t,n,s){s=n._locale.monthsParse(e,s,n._strict);null!=s?t[Y]=s:p(n).invalidMonth=e});var Fe="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Le="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),Ve=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Ge=i,Ee=i;function Ae(e,t){if(e.isValid()){if("string"==typeof t)if(/^\d+$/.test(t))t=M(t);else if(!w(t=e.localeData().monthsParse(t)))return;var n=(n=e.date())<29?n:Math.min(n,He(e.year(),t));e._isUTC?e._d.setUTCMonth(t,n):e._d.setMonth(t,n)}}function Ie(e){return null!=e?(Ae(this,e),_.updateOffset(this,!0),this):Ce(this,"Month")}function je(){function e(e,t){return t.length-e.length}for(var t,n,s=[],i=[],r=[],a=0;a<12;a++)n=l([2e3,a]),t=f(this.monthsShort(n,"")),n=f(this.months(n,"")),s.push(t),i.push(n),r.push(n),r.push(t);s.sort(e),i.sort(e),r.sort(e),this._monthsRegex=new RegExp("^("+r.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function Ze(e,t,n,s,i,r,a){var o;return e<100&&0<=e?(o=new Date(e+400,t,n,s,i,r,a),isFinite(o.getFullYear())&&o.setFullYear(e)):o=new Date(e,t,n,s,i,r,a),o}function ze(e){var t;return e<100&&0<=e?((t=Array.prototype.slice.call(arguments))[0]=e+400,t=new Date(Date.UTC.apply(null,t)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function qe(e,t,n){n=7+t-n;return n-(7+ze(e,0,n).getUTCDay()-t)%7-1}function $e(e,t,n,s,i){var r,t=1+7*(t-1)+(7+n-s)%7+qe(e,s,i),n=t<=0?We(r=e-1)+t:t>We(e)?(r=e+1,t-We(e)):(r=e,t);return{year:r,dayOfYear:n}}function Be(e,t,n){var s,i,r=qe(e.year(),t,n),r=Math.floor((e.dayOfYear()-r-1)/7)+1;return r<1?s=r+N(i=e.year()-1,t,n):r>N(e.year(),t,n)?(s=r-N(e.year(),t,n),i=e.year()+1):(i=e.year(),s=r),{week:s,year:i}}function N(e,t,n){var s=qe(e,t,n),t=qe(e+1,t,n);return(We(e)-s+t)/7}s("w",["ww",2],"wo","week"),s("W",["WW",2],"Wo","isoWeek"),h("w",n,u),h("ww",n,t),h("W",n,u),h("WW",n,t),Oe(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=M(e)});function Je(e,t){return e.slice(t,7).concat(e.slice(0,t))}s("d",0,"do","day"),s("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),s("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),s("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),s("e",0,0,"weekday"),s("E",0,0,"isoWeekday"),h("d",n),h("e",n),h("E",n),h("dd",function(e,t){return t.weekdaysMinRegex(e)}),h("ddd",function(e,t){return t.weekdaysShortRegex(e)}),h("dddd",function(e,t){return t.weekdaysRegex(e)}),Oe(["dd","ddd","dddd"],function(e,t,n,s){s=n._locale.weekdaysParse(e,s,n._strict);null!=s?t.d=s:p(n).invalidWeekday=e}),Oe(["d","e","E"],function(e,t,n,s){t[s]=M(e)});var Qe="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Xe="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Ke="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),et=i,tt=i,nt=i;function st(){function e(e,t){return t.length-e.length}for(var t,n,s,i=[],r=[],a=[],o=[],u=0;u<7;u++)s=l([2e3,1]).day(u),t=f(this.weekdaysMin(s,"")),n=f(this.weekdaysShort(s,"")),s=f(this.weekdays(s,"")),i.push(t),r.push(n),a.push(s),o.push(t),o.push(n),o.push(s);i.sort(e),r.sort(e),a.sort(e),o.sort(e),this._weekdaysRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+r.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+i.join("|")+")","i")}function it(){return this.hours()%12||12}function rt(e,t){s(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function at(e,t){return t._meridiemParse}s("H",["HH",2],0,"hour"),s("h",["hh",2],0,it),s("k",["kk",2],0,function(){return this.hours()||24}),s("hmm",0,0,function(){return""+it.apply(this)+r(this.minutes(),2)}),s("hmmss",0,0,function(){return""+it.apply(this)+r(this.minutes(),2)+r(this.seconds(),2)}),s("Hmm",0,0,function(){return""+this.hours()+r(this.minutes(),2)}),s("Hmmss",0,0,function(){return""+this.hours()+r(this.minutes(),2)+r(this.seconds(),2)}),rt("a",!0),rt("A",!1),h("a",at),h("A",at),h("H",n,d),h("h",n,u),h("k",n,u),h("HH",n,t),h("hh",n,t),h("kk",n,t),h("hmm",me),h("hmmss",_e),h("Hmm",me),h("Hmmss",_e),v(["H","HH"],O),v(["k","kk"],function(e,t,n){e=M(e);t[O]=24===e?0:e}),v(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),v(["h","hh"],function(e,t,n){t[O]=M(e),p(n).bigHour=!0}),v("hmm",function(e,t,n){var s=e.length-2;t[O]=M(e.substr(0,s)),t[b]=M(e.substr(s)),p(n).bigHour=!0}),v("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[O]=M(e.substr(0,s)),t[b]=M(e.substr(s,2)),t[T]=M(e.substr(i)),p(n).bigHour=!0}),v("Hmm",function(e,t,n){var s=e.length-2;t[O]=M(e.substr(0,s)),t[b]=M(e.substr(s))}),v("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[O]=M(e.substr(0,s)),t[b]=M(e.substr(s,2)),t[T]=M(e.substr(i))});i=Re("Hours",!0);var ot,ut={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:Fe,monthsShort:Le,week:{dow:0,doy:6},weekdays:Qe,weekdaysMin:Ke,weekdaysShort:Xe,meridiemParse:/[ap]\.?m?\.?/i},W={},lt={};function dt(e){return e&&e.toLowerCase().replace("_","-")}function ht(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=dt(e[r]).split("-")).length,n=(n=dt(e[r+1]))?n.split("-"):null;0<t;){if(s=ct(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&function(e,t){for(var n=Math.min(e.length,t.length),s=0;s<n;s+=1)if(e[s]!==t[s])return s;return n}(i,n)>=t-1)break;t--}r++}return ot}function ct(t){var e,n;if(void 0===W[t]&&"undefined"!=typeof module&&module&&module.exports&&(n=t)&&n.match("^[^/\\\\]*$"))try{e=ot._abbr,require("./locale/"+t),ft(e)}catch(e){W[t]=null}return W[t]}function ft(e,t){return e&&((t=g(t)?P(e):mt(e,t))?ot=t:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),ot._abbr}function mt(e,t){if(null===t)return delete W[e],null;var n,s=ut;if(t.abbr=e,null!=W[e])Q("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."),s=W[e]._config;else if(null!=t.parentLocale)if(null!=W[t.parentLocale])s=W[t.parentLocale]._config;else{if(null==(n=ct(t.parentLocale)))return lt[t.parentLocale]||(lt[t.parentLocale]=[]),lt[t.parentLocale].push({name:e,config:t}),null;s=n._config}return W[e]=new K(X(s,t)),lt[e]&<[e].forEach(function(e){mt(e.name,e.config)}),ft(e),W[e]}function P(e){var t;if(!(e=e&&e._locale&&e._locale._abbr?e._locale._abbr:e))return ot;if(!y(e)){if(t=ct(e))return t;e=[e]}return ht(e)}function _t(e){var t=e._a;return t&&-2===p(e).overflow&&(t=t[Y]<0||11<t[Y]?Y:t[S]<1||t[S]>He(t[D],t[Y])?S:t[O]<0||24<t[O]||24===t[O]&&(0!==t[b]||0!==t[T]||0!==t[Te])?O:t[b]<0||59<t[b]?b:t[T]<0||59<t[T]?T:t[Te]<0||999<t[Te]?Te:-1,p(e)._overflowDayOfYear&&(t<D||S<t)&&(t=S),p(e)._overflowWeeks&&-1===t&&(t=xe),p(e)._overflowWeekday&&-1===t&&(t=Ne),p(e).overflow=t),e}var yt=/^\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)?)?$/,gt=/^\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)?)?$/,wt=/Z|[+-]\d\d(?::?\d\d)?/,pt=[["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]],kt=[["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/]],Mt=/^\/?Date\((-?\d+)/i,vt=/^(?:(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}))$/,Dt={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Yt(e){var t,n,s,i,r,a,o=e._i,u=yt.exec(o)||gt.exec(o),o=pt.length,l=kt.length;if(u){for(p(e).iso=!0,t=0,n=o;t<n;t++)if(pt[t][1].exec(u[1])){i=pt[t][0],s=!1!==pt[t][2];break}if(null==i)e._isValid=!1;else{if(u[3]){for(t=0,n=l;t<n;t++)if(kt[t][1].exec(u[3])){r=(u[2]||" ")+kt[t][0];break}if(null==r)return void(e._isValid=!1)}if(s||null==r){if(u[4]){if(!wt.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),xt(e)}else e._isValid=!1}}else e._isValid=!1}function St(e,t,n,s,i,r){e=[function(e){e=parseInt(e,10);{if(e<=49)return 2e3+e;if(e<=999)return 1900+e}return e}(e),Le.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&e.push(parseInt(r,10)),e}function Ot(e){var t,n,s=vt.exec(e._i.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,""));s?(t=St(s[4],s[3],s[2],s[5],s[6],s[7]),function(e,t,n){if(!e||Xe.indexOf(e)===new Date(t[0],t[1],t[2]).getDay())return 1;p(n).weekdayMismatch=!0,n._isValid=!1}(s[1],t,e)&&(e._a=t,e._tzm=(t=s[8],n=s[9],s=s[10],t?Dt[t]:n?0:60*(((t=parseInt(s,10))-(n=t%100))/100)+n),e._d=ze.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),p(e).rfc2822=!0)):e._isValid=!1}function bt(e,t,n){return null!=e?e:null!=t?t:n}function Tt(e){var t,n,s,i,r,a,o,u,l,d,h,c=[];if(!e._d){for(s=e,i=new Date(_.now()),n=s._useUTC?[i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate()]:[i.getFullYear(),i.getMonth(),i.getDate()],e._w&&null==e._a[S]&&null==e._a[Y]&&(null!=(i=(s=e)._w).GG||null!=i.W||null!=i.E?(u=1,l=4,r=bt(i.GG,s._a[D],Be(R(),1,4).year),a=bt(i.W,1),((o=bt(i.E,1))<1||7<o)&&(d=!0)):(u=s._locale._week.dow,l=s._locale._week.doy,h=Be(R(),u,l),r=bt(i.gg,s._a[D],h.year),a=bt(i.w,h.week),null!=i.d?((o=i.d)<0||6<o)&&(d=!0):null!=i.e?(o=i.e+u,(i.e<0||6<i.e)&&(d=!0)):o=u),a<1||a>N(r,u,l)?p(s)._overflowWeeks=!0:null!=d?p(s)._overflowWeekday=!0:(h=$e(r,a,o,u,l),s._a[D]=h.year,s._dayOfYear=h.dayOfYear)),null!=e._dayOfYear&&(i=bt(e._a[D],n[D]),(e._dayOfYear>We(i)||0===e._dayOfYear)&&(p(e)._overflowDayOfYear=!0),d=ze(i,0,e._dayOfYear),e._a[Y]=d.getUTCMonth(),e._a[S]=d.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=c[t]=n[t];for(;t<7;t++)e._a[t]=c[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[O]&&0===e._a[b]&&0===e._a[T]&&0===e._a[Te]&&(e._nextDay=!0,e._a[O]=0),e._d=(e._useUTC?ze:Ze).apply(null,c),r=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[O]=24),e._w&&void 0!==e._w.d&&e._w.d!==r&&(p(e).weekdayMismatch=!0)}}function xt(e){if(e._f===_.ISO_8601)Yt(e);else if(e._f===_.RFC_2822)Ot(e);else{e._a=[],p(e).empty=!0;for(var t,n,s,i,r,a=""+e._i,o=a.length,u=0,l=ae(e._f,e._locale).match(te)||[],d=l.length,h=0;h<d;h++)n=l[h],(t=(a.match(De(n,e))||[])[0])&&(0<(s=a.substr(0,a.indexOf(t))).length&&p(e).unusedInput.push(s),a=a.slice(a.indexOf(t)+t.length),u+=t.length),ie[n]?(t?p(e).empty=!1:p(e).unusedTokens.push(n),s=n,r=e,null!=(i=t)&&c(Se,s)&&Se[s](i,r._a,r,s)):e._strict&&!t&&p(e).unusedTokens.push(n);p(e).charsLeftOver=o-u,0<a.length&&p(e).unusedInput.push(a),e._a[O]<=12&&!0===p(e).bigHour&&0<e._a[O]&&(p(e).bigHour=void 0),p(e).parsedDateParts=e._a.slice(0),p(e).meridiem=e._meridiem,e._a[O]=function(e,t,n){if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((e=e.isPM(n))&&t<12&&(t+=12),t=e||12!==t?t:0):t}(e._locale,e._a[O],e._meridiem),null!==(o=p(e).era)&&(e._a[D]=e._locale.erasConvertYear(o,e._a[D])),Tt(e),_t(e)}}function Nt(e){var t,n,s,i=e._i,r=e._f;if(e._locale=e._locale||P(e._l),null===i||void 0===r&&""===i)return I({nullInput:!0});if("string"==typeof i&&(e._i=i=e._locale.preparse(i)),k(i))return new $(_t(i));if(V(i))e._d=i;else if(y(r)){var a,o,u,l,d,h,c=e,f=!1,m=c._f.length;if(0===m)p(c).invalidFormat=!0,c._d=new Date(NaN);else{for(l=0;l<m;l++)d=0,h=!1,a=q({},c),null!=c._useUTC&&(a._useUTC=c._useUTC),a._f=c._f[l],xt(a),A(a)&&(h=!0),d=(d+=p(a).charsLeftOver)+10*p(a).unusedTokens.length,p(a).score=d,f?d<u&&(u=d,o=a):(null==u||d<u||h)&&(u=d,o=a,h)&&(f=!0);E(c,o||a)}}else if(r)xt(e);else if(g(r=(i=e)._i))i._d=new Date(_.now());else V(r)?i._d=new Date(r.valueOf()):"string"==typeof r?(n=i,null!==(t=Mt.exec(n._i))?n._d=new Date(+t[1]):(Yt(n),!1===n._isValid&&(delete n._isValid,Ot(n),!1===n._isValid)&&(delete n._isValid,n._strict?n._isValid=!1:_.createFromInputFallback(n)))):y(r)?(i._a=G(r.slice(0),function(e){return parseInt(e,10)}),Tt(i)):F(r)?(t=i)._d||(s=void 0===(n=ue(t._i)).day?n.date:n.day,t._a=G([n.year,n.month,s,n.hour,n.minute,n.second,n.millisecond],function(e){return e&&parseInt(e,10)}),Tt(t)):w(r)?i._d=new Date(r):_.createFromInputFallback(i);return A(e)||(e._d=null),e}function Wt(e,t,n,s,i){var r={};return!0!==t&&!1!==t||(s=t,t=void 0),!0!==n&&!1!==n||(s=n,n=void 0),(F(e)&&L(e)||y(e)&&0===e.length)&&(e=void 0),r._isAMomentObject=!0,r._useUTC=r._isUTC=i,r._l=n,r._i=e,r._f=t,r._strict=s,(i=new $(_t(Nt(i=r))))._nextDay&&(i.add(1,"d"),i._nextDay=void 0),i}function R(e,t,n,s){return Wt(e,t,n,s,!1)}_.createFromInputFallback=e("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(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),_.ISO_8601=function(){},_.RFC_2822=function(){};me=e("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=R.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:I()}),_e=e("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=R.apply(null,arguments);return this.isValid()&&e.isValid()?this<e?this:e:I()});function Pt(e,t){var n,s;if(!(t=1===t.length&&y(t[0])?t[0]:t).length)return R();for(n=t[0],s=1;s<t.length;++s)t[s].isValid()&&!t[s][e](n)||(n=t[s]);return n}var Rt=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Ct(e){var e=ue(e),t=e.year||0,n=e.quarter||0,s=e.month||0,i=e.week||e.isoWeek||0,r=e.day||0,a=e.hour||0,o=e.minute||0,u=e.second||0,l=e.millisecond||0;this._isValid=function(e){var t,n,s=!1,i=Rt.length;for(t in e)if(c(e,t)&&(-1===x.call(Rt,t)||null!=e[t]&&isNaN(e[t])))return!1;for(n=0;n<i;++n)if(e[Rt[n]]){if(s)return!1;parseFloat(e[Rt[n]])!==M(e[Rt[n]])&&(s=!0)}return!0}(e),this._milliseconds=+l+1e3*u+6e4*o+1e3*a*60*60,this._days=+r+7*i,this._months=+s+3*n+12*t,this._data={},this._locale=P(),this._bubble()}function Ut(e){return e instanceof Ct}function Ht(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ft(e,n){s(e,0,0,function(){var e=this.utcOffset(),t="+";return e<0&&(e=-e,t="-"),t+r(~~(e/60),2)+n+r(~~e%60,2)})}Ft("Z",":"),Ft("ZZ",""),h("Z",ve),h("ZZ",ve),v(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Vt(ve,e)});var Lt=/([\+\-]|\d\d)/gi;function Vt(e,t){var t=(t||"").match(e);return null===t?null:0===(t=60*(e=((t[t.length-1]||[])+"").match(Lt)||["-",0,0])[1]+M(e[2]))?0:"+"===e[0]?t:-t}function Gt(e,t){var n;return t._isUTC?(t=t.clone(),n=(k(e)||V(e)?e:R(e)).valueOf()-t.valueOf(),t._d.setTime(t._d.valueOf()+n),_.updateOffset(t,!1),t):R(e).local()}function Et(e){return-Math.round(e._d.getTimezoneOffset())}function At(){return!!this.isValid()&&this._isUTC&&0===this._offset}_.updateOffset=function(){};var It=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,jt=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function C(e,t){var n,s=e;return Ut(e)?s={ms:e._milliseconds,d:e._days,M:e._months}:w(e)||!isNaN(+e)?(s={},t?s[t]=+e:s.milliseconds=+e):(t=It.exec(e))?(n="-"===t[1]?-1:1,s={y:0,d:M(t[S])*n,h:M(t[O])*n,m:M(t[b])*n,s:M(t[T])*n,ms:M(Ht(1e3*t[Te]))*n}):(t=jt.exec(e))?(n="-"===t[1]?-1:1,s={y:Zt(t[2],n),M:Zt(t[3],n),w:Zt(t[4],n),d:Zt(t[5],n),h:Zt(t[6],n),m:Zt(t[7],n),s:Zt(t[8],n)}):null==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(t=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Gt(t,e),e.isBefore(t)?n=zt(e,t):((n=zt(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(R(s.from),R(s.to)),(s={}).ms=t.milliseconds,s.M=t.months),n=new Ct(s),Ut(e)&&c(e,"_locale")&&(n._locale=e._locale),Ut(e)&&c(e,"_isValid")&&(n._isValid=e._isValid),n}function Zt(e,t){e=e&&parseFloat(e.replace(",","."));return(isNaN(e)?0:e)*t}function zt(e,t){var n={};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function qt(s,i){return function(e,t){var n;return null===t||isNaN(+t)||(Q(i,"moment()."+i+"(period, number) is deprecated. Please use moment()."+i+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),n=e,e=t,t=n),$t(this,C(e,t),s),this}}function $t(e,t,n,s){var i=t._milliseconds,r=Ht(t._days),t=Ht(t._months);e.isValid()&&(s=null==s||s,t&&Ae(e,Ce(e,"Month")+t*n),r&&Ue(e,"Date",Ce(e,"Date")+r*n),i&&e._d.setTime(e._d.valueOf()+i*n),s)&&_.updateOffset(e,r||t)}C.fn=Ct.prototype,C.invalid=function(){return C(NaN)};Fe=qt(1,"add"),Qe=qt(-1,"subtract");function Bt(e){return"string"==typeof e||e instanceof String}function Jt(e){return k(e)||V(e)||Bt(e)||w(e)||function(t){var e=y(t),n=!1;e&&(n=0===t.filter(function(e){return!w(e)&&Bt(t)}).length);return e&&n}(e)||function(e){var t,n,s=F(e)&&!L(e),i=!1,r=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],a=r.length;for(t=0;t<a;t+=1)n=r[t],i=i||c(e,n);return s&&i}(e)||null==e}function Qt(e,t){var n,s;return e.date()<t.date()?-Qt(t,e):-((n=12*(t.year()-e.year())+(t.month()-e.month()))+(t-(s=e.clone().add(n,"months"))<0?(t-s)/(s-e.clone().add(n-1,"months")):(t-s)/(e.clone().add(1+n,"months")-s)))||0}function Xt(e){return void 0===e?this._locale._abbr:(null!=(e=P(e))&&(this._locale=e),this)}_.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",_.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";Ke=e("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});function Kt(){return this._locale}var en=126227808e5;function tn(e,t){return(e%t+t)%t}function nn(e,t,n){return e<100&&0<=e?new Date(e+400,t,n)-en:new Date(e,t,n).valueOf()}function sn(e,t,n){return e<100&&0<=e?Date.UTC(e+400,t,n)-en:Date.UTC(e,t,n)}function rn(e,t){return t.erasAbbrRegex(e)}function an(){for(var e,t,n,s=[],i=[],r=[],a=[],o=this.eras(),u=0,l=o.length;u<l;++u)e=f(o[u].name),t=f(o[u].abbr),n=f(o[u].narrow),i.push(e),s.push(t),r.push(n),a.push(e),a.push(t),a.push(n);this._erasRegex=new RegExp("^("+a.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+i.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+s.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+r.join("|")+")","i")}function on(e,t){s(0,[e,e.length],0,t)}function un(e,t,n,s,i){var r;return null==e?Be(this,s,i).year:(r=N(e,s,i),function(e,t,n,s,i){e=$e(e,t,n,s,i),t=ze(e.year,0,e.dayOfYear);return this.year(t.getUTCFullYear()),this.month(t.getUTCMonth()),this.date(t.getUTCDate()),this}.call(this,e,t=r<t?r:t,n,s,i))}s("N",0,0,"eraAbbr"),s("NN",0,0,"eraAbbr"),s("NNN",0,0,"eraAbbr"),s("NNNN",0,0,"eraName"),s("NNNNN",0,0,"eraNarrow"),s("y",["y",1],"yo","eraYear"),s("y",["yy",2],0,"eraYear"),s("y",["yyy",3],0,"eraYear"),s("y",["yyyy",4],0,"eraYear"),h("N",rn),h("NN",rn),h("NNN",rn),h("NNNN",function(e,t){return t.erasNameRegex(e)}),h("NNNNN",function(e,t){return t.erasNarrowRegex(e)}),v(["N","NN","NNN","NNNN","NNNNN"],function(e,t,n,s){s=n._locale.erasParse(e,s,n._strict);s?p(n).era=s:p(n).invalidEra=e}),h("y",pe),h("yy",pe),h("yyy",pe),h("yyyy",pe),h("yo",function(e,t){return t._eraYearOrdinalRegex||pe}),v(["y","yy","yyy","yyyy"],D),v(["yo"],function(e,t,n,s){var i;n._locale._eraYearOrdinalRegex&&(i=e.match(n._locale._eraYearOrdinalRegex)),n._locale.eraYearOrdinalParse?t[D]=n._locale.eraYearOrdinalParse(e,i):t[D]=parseInt(e,10)}),s(0,["gg",2],0,function(){return this.weekYear()%100}),s(0,["GG",2],0,function(){return this.isoWeekYear()%100}),on("gggg","weekYear"),on("ggggg","weekYear"),on("GGGG","isoWeekYear"),on("GGGGG","isoWeekYear"),h("G",ke),h("g",ke),h("GG",n,t),h("gg",n,t),h("GGGG",ge,ce),h("gggg",ge,ce),h("GGGGG",we,fe),h("ggggg",we,fe),Oe(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=M(e)}),Oe(["gg","GG"],function(e,t,n,s){t[s]=_.parseTwoDigitYear(e)}),s("Q",0,"Qo","quarter"),h("Q",de),v("Q",function(e,t){t[Y]=3*(M(e)-1)}),s("D",["DD",2],"Do","date"),h("D",n,u),h("DD",n,t),h("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),v(["D","DD"],S),v("Do",function(e,t){t[S]=M(e.match(n)[0])});ge=Re("Date",!0);s("DDD",["DDDD",3],"DDDo","dayOfYear"),h("DDD",ye),h("DDDD",he),v(["DDD","DDDD"],function(e,t,n){n._dayOfYear=M(e)}),s("m",["mm",2],0,"minute"),h("m",n,d),h("mm",n,t),v(["m","mm"],b);var ln,ce=Re("Minutes",!1),we=(s("s",["ss",2],0,"second"),h("s",n,d),h("ss",n,t),v(["s","ss"],T),Re("Seconds",!1));for(s("S",0,0,function(){return~~(this.millisecond()/100)}),s(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),s(0,["SSS",3],0,"millisecond"),s(0,["SSSS",4],0,function(){return 10*this.millisecond()}),s(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),s(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),s(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),s(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),s(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),h("S",ye,de),h("SS",ye,t),h("SSS",ye,he),ln="SSSS";ln.length<=9;ln+="S")h(ln,pe);function dn(e,t){t[Te]=M(1e3*("0."+e))}for(ln="S";ln.length<=9;ln+="S")v(ln,dn);fe=Re("Milliseconds",!1),s("z",0,0,"zoneAbbr"),s("zz",0,0,"zoneName");u=$.prototype;function hn(e){return e}u.add=Fe,u.calendar=function(e,t){1===arguments.length&&(arguments[0]?Jt(arguments[0])?(e=arguments[0],t=void 0):function(e){for(var t=F(e)&&!L(e),n=!1,s=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"],i=0;i<s.length;i+=1)n=n||c(e,s[i]);return t&&n}(arguments[0])&&(t=arguments[0],e=void 0):t=e=void 0);var e=e||R(),n=Gt(e,this).startOf("day"),n=_.calendarFormat(this,n)||"sameElse",t=t&&(a(t[n])?t[n].call(this,e):t[n]);return this.format(t||this.localeData().calendar(n,this,R(e)))},u.clone=function(){return new $(this)},u.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Gt(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=o(t)){case"year":r=Qt(this,s)/12;break;case"month":r=Qt(this,s);break;case"quarter":r=Qt(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:m(r)},u.endOf=function(e){var t,n;if(void 0!==(e=o(e))&&"millisecond"!==e&&this.isValid()){switch(n=this._isUTC?sn:nn,e){case"year":t=n(this.year()+1,0,1)-1;break;case"quarter":t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=n(this.year(),this.month()+1,1)-1;break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=36e5-tn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5)-1;break;case"minute":t=this._d.valueOf(),t+=6e4-tn(t,6e4)-1;break;case"second":t=this._d.valueOf(),t+=1e3-tn(t,1e3)-1}this._d.setTime(t),_.updateOffset(this,!0)}return this},u.format=function(e){return e=e||(this.isUtc()?_.defaultFormatUtc:_.defaultFormat),e=re(this,e),this.localeData().postformat(e)},u.from=function(e,t){return this.isValid()&&(k(e)&&e.isValid()||R(e).isValid())?C({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},u.fromNow=function(e){return this.from(R(),e)},u.to=function(e,t){return this.isValid()&&(k(e)&&e.isValid()||R(e).isValid())?C({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},u.toNow=function(e){return this.to(R(),e)},u.get=function(e){return a(this[e=o(e)])?this[e]():this},u.invalidAt=function(){return p(this).overflow},u.isAfter=function(e,t){return e=k(e)?e:R(e),!(!this.isValid()||!e.isValid())&&("millisecond"===(t=o(t)||"millisecond")?this.valueOf()>e.valueOf():e.valueOf()<this.clone().startOf(t).valueOf())},u.isBefore=function(e,t){return e=k(e)?e:R(e),!(!this.isValid()||!e.isValid())&&("millisecond"===(t=o(t)||"millisecond")?this.valueOf()<e.valueOf():this.clone().endOf(t).valueOf()<e.valueOf())},u.isBetween=function(e,t,n,s){return e=k(e)?e:R(e),t=k(t)?t:R(t),!!(this.isValid()&&e.isValid()&&t.isValid())&&("("===(s=s||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===s[1]?this.isBefore(t,n):!this.isAfter(t,n))},u.isSame=function(e,t){var e=k(e)?e:R(e);return!(!this.isValid()||!e.isValid())&&("millisecond"===(t=o(t)||"millisecond")?this.valueOf()===e.valueOf():(e=e.valueOf(),this.clone().startOf(t).valueOf()<=e&&e<=this.clone().endOf(t).valueOf()))},u.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},u.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},u.isValid=function(){return A(this)},u.lang=Ke,u.locale=Xt,u.localeData=Kt,u.max=_e,u.min=me,u.parsingFlags=function(){return E({},p(this))},u.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t,n=[];for(t in e)c(e,t)&&n.push({unit:t,priority:le[t]});return n.sort(function(e,t){return e.priority-t.priority}),n}(e=ue(e)),s=n.length,i=0;i<s;i++)this[n[i].unit](e[n[i].unit]);else if(a(this[e=o(e)]))return this[e](t);return this},u.startOf=function(e){var t,n;if(void 0!==(e=o(e))&&"millisecond"!==e&&this.isValid()){switch(n=this._isUTC?sn:nn,e){case"year":t=n(this.year(),0,1);break;case"quarter":t=n(this.year(),this.month()-this.month()%3,1);break;case"month":t=n(this.year(),this.month(),1);break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=n(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=tn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5);break;case"minute":t=this._d.valueOf(),t-=tn(t,6e4);break;case"second":t=this._d.valueOf(),t-=tn(t,1e3)}this._d.setTime(t),_.updateOffset(this,!0)}return this},u.subtract=Qe,u.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},u.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},u.toDate=function(){return new Date(this.valueOf())},u.toISOString=function(e){var t;return this.isValid()?(t=(e=!0!==e)?this.clone().utc():this).year()<0||9999<t.year()?re(t,e?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):a(Date.prototype.toISOString)?e?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",re(t,"Z")):re(t,e?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ"):null},u.inspect=function(){var e,t,n;return this.isValid()?(t="moment",e="",this.isLocal()||(t=0===this.utcOffset()?"moment.utc":"moment.parseZone",e="Z"),t="["+t+'("]',n=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",this.format(t+n+"-MM-DD[T]HH:mm:ss.SSS"+(e+'[")]'))):"moment.invalid(/* "+this._i+" */)"},"undefined"!=typeof Symbol&&null!=Symbol.for&&(u[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),u.toJSON=function(){return this.isValid()?this.toISOString():null},u.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},u.unix=function(){return Math.floor(this.valueOf()/1e3)},u.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},u.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},u.eraName=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].name;if(t[n].until<=e&&e<=t[n].since)return t[n].name}return""},u.eraNarrow=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].narrow;if(t[n].until<=e&&e<=t[n].since)return t[n].narrow}return""},u.eraAbbr=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].abbr;if(t[n].until<=e&&e<=t[n].since)return t[n].abbr}return""},u.eraYear=function(){for(var e,t,n=this.localeData().eras(),s=0,i=n.length;s<i;++s)if(e=n[s].since<=n[s].until?1:-1,t=this.clone().startOf("day").valueOf(),n[s].since<=t&&t<=n[s].until||n[s].until<=t&&t<=n[s].since)return(this.year()-_(n[s].since).year())*e+n[s].offset;return this.year()},u.year=Pe,u.isLeapYear=function(){return be(this.year())},u.weekYear=function(e){return un.call(this,e,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)},u.isoWeekYear=function(e){return un.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},u.quarter=u.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},u.month=Ie,u.daysInMonth=function(){return He(this.year(),this.month())},u.week=u.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},u.isoWeek=u.isoWeeks=function(e){var t=Be(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},u.weeksInYear=function(){var e=this.localeData()._week;return N(this.year(),e.dow,e.doy)},u.weeksInWeekYear=function(){var e=this.localeData()._week;return N(this.weekYear(),e.dow,e.doy)},u.isoWeeksInYear=function(){return N(this.year(),1,4)},u.isoWeeksInISOWeekYear=function(){return N(this.isoWeekYear(),1,4)},u.date=ge,u.day=u.days=function(e){var t,n,s;return this.isValid()?(t=Ce(this,"Day"),null!=e?(n=e,s=this.localeData(),e="string"!=typeof n?n:isNaN(n)?"number"==typeof(n=s.weekdaysParse(n))?n:null:parseInt(n,10),this.add(e-t,"d")):t):null!=e?this:NaN},u.weekday=function(e){var t;return this.isValid()?(t=(this.day()+7-this.localeData()._week.dow)%7,null==e?t:this.add(e-t,"d")):null!=e?this:NaN},u.isoWeekday=function(e){var t,n;return this.isValid()?null!=e?(t=e,n=this.localeData(),n="string"==typeof t?n.weekdaysParse(t)%7||7:isNaN(t)?null:t,this.day(this.day()%7?n:n-7)):this.day()||7:null!=e?this:NaN},u.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},u.hour=u.hours=i,u.minute=u.minutes=ce,u.second=u.seconds=we,u.millisecond=u.milliseconds=fe,u.utcOffset=function(e,t,n){var s,i=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null==e)return this._isUTC?i:Et(this);if("string"==typeof e){if(null===(e=Vt(ve,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(s=Et(this)),this._offset=e,this._isUTC=!0,null!=s&&this.add(s,"m"),i!==e&&(!t||this._changeInProgress?$t(this,C(e-i,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,_.updateOffset(this,!0),this._changeInProgress=null)),this},u.utc=function(e){return this.utcOffset(0,e)},u.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e)&&this.subtract(Et(this),"m"),this},u.parseZone=function(){var e;return null!=this._tzm?this.utcOffset(this._tzm,!1,!0):"string"==typeof this._i&&(null!=(e=Vt(Me,this._i))?this.utcOffset(e):this.utcOffset(0,!0)),this},u.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?R(e).utcOffset():0,(this.utcOffset()-e)%60==0)},u.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},u.isLocal=function(){return!!this.isValid()&&!this._isUTC},u.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},u.isUtc=At,u.isUTC=At,u.zoneAbbr=function(){return this._isUTC?"UTC":""},u.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},u.dates=e("dates accessor is deprecated. Use date instead.",ge),u.months=e("months accessor is deprecated. Use month instead",Ie),u.years=e("years accessor is deprecated. Use year instead",Pe),u.zone=e("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?(this.utcOffset(e="string"!=typeof e?-e:e,t),this):-this.utcOffset()}),u.isDSTShifted=e("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){var e,t;return g(this._isDSTShifted)&&(q(e={},this),(e=Nt(e))._a?(t=(e._isUTC?l:R)(e._a),this._isDSTShifted=this.isValid()&&0<function(e,t,n){for(var s=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),r=0,a=0;a<s;a++)(n&&e[a]!==t[a]||!n&&M(e[a])!==M(t[a]))&&r++;return r+i}(e._a,t.toArray())):this._isDSTShifted=!1),this._isDSTShifted});d=K.prototype;function cn(e,t,n,s){var i=P(),s=l().set(s,t);return i[n](s,e)}function fn(e,t,n){if(w(e)&&(t=e,e=void 0),e=e||"",null!=t)return cn(e,t,n,"month");for(var s=[],i=0;i<12;i++)s[i]=cn(e,i,n,"month");return s}function mn(e,t,n,s){t=("boolean"==typeof e?w(t)&&(n=t,t=void 0):(t=e,e=!1,w(n=t)&&(n=t,t=void 0)),t||"");var i,r=P(),a=e?r._week.dow:0,o=[];if(null!=n)return cn(t,(n+a)%7,s,"day");for(i=0;i<7;i++)o[i]=cn(t,(i+a)%7,s,"day");return o}d.calendar=function(e,t,n){return a(e=this._calendar[e]||this._calendar.sameElse)?e.call(t,n):e},d.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(te).map(function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e}).join(""),this._longDateFormat[e])},d.invalidDate=function(){return this._invalidDate},d.ordinal=function(e){return this._ordinal.replace("%d",e)},d.preparse=hn,d.postformat=hn,d.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return a(i)?i(e,t,n,s):i.replace(/%d/i,e)},d.pastFuture=function(e,t){return a(e=this._relativeTime[0<e?"future":"past"])?e(t):e.replace(/%s/i,t)},d.set=function(e){var t,n;for(n in e)c(e,n)&&(a(t=e[n])?this[n]=t:this["_"+n]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},d.eras=function(e,t){for(var n,s=this._eras||P("en")._eras,i=0,r=s.length;i<r;++i)switch("string"==typeof s[i].since&&(n=_(s[i].since).startOf("day"),s[i].since=n.valueOf()),typeof s[i].until){case"undefined":s[i].until=1/0;break;case"string":n=_(s[i].until).startOf("day").valueOf(),s[i].until=n.valueOf()}return s},d.erasParse=function(e,t,n){var s,i,r,a,o,u=this.eras();for(e=e.toUpperCase(),s=0,i=u.length;s<i;++s)if(r=u[s].name.toUpperCase(),a=u[s].abbr.toUpperCase(),o=u[s].narrow.toUpperCase(),n)switch(t){case"N":case"NN":case"NNN":if(a===e)return u[s];break;case"NNNN":if(r===e)return u[s];break;case"NNNNN":if(o===e)return u[s]}else if(0<=[r,a,o].indexOf(e))return u[s]},d.erasConvertYear=function(e,t){var n=e.since<=e.until?1:-1;return void 0===t?_(e.since).year():_(e.since).year()+(t-e.offset)*n},d.erasAbbrRegex=function(e){return c(this,"_erasAbbrRegex")||an.call(this),e?this._erasAbbrRegex:this._erasRegex},d.erasNameRegex=function(e){return c(this,"_erasNameRegex")||an.call(this),e?this._erasNameRegex:this._erasRegex},d.erasNarrowRegex=function(e){return c(this,"_erasNarrowRegex")||an.call(this),e?this._erasNarrowRegex:this._erasRegex},d.months=function(e,t){return e?(y(this._months)?this._months:this._months[(this._months.isFormat||Ve).test(t)?"format":"standalone"])[e.month()]:y(this._months)?this._months:this._months.standalone},d.monthsShort=function(e,t){return e?(y(this._monthsShort)?this._monthsShort:this._monthsShort[Ve.test(t)?"format":"standalone"])[e.month()]:y(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},d.monthsParse=function(e,t,n){var s,i;if(this._monthsParseExact)return function(e,t,n){var s,i,r,e=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=l([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=x.call(this._shortMonthsParse,e))?i:null:-1!==(i=x.call(this._longMonthsParse,e))?i:null:"MMM"===t?-1!==(i=x.call(this._shortMonthsParse,e))||-1!==(i=x.call(this._longMonthsParse,e))?i:null:-1!==(i=x.call(this._longMonthsParse,e))||-1!==(i=x.call(this._shortMonthsParse,e))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=l([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(i="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(i.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},d.monthsRegex=function(e){return this._monthsParseExact?(c(this,"_monthsRegex")||je.call(this),e?this._monthsStrictRegex:this._monthsRegex):(c(this,"_monthsRegex")||(this._monthsRegex=Ee),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},d.monthsShortRegex=function(e){return this._monthsParseExact?(c(this,"_monthsRegex")||je.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(c(this,"_monthsShortRegex")||(this._monthsShortRegex=Ge),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},d.week=function(e){return Be(e,this._week.dow,this._week.doy).week},d.firstDayOfYear=function(){return this._week.doy},d.firstDayOfWeek=function(){return this._week.dow},d.weekdays=function(e,t){return t=y(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"],!0===e?Je(t,this._week.dow):e?t[e.day()]:t},d.weekdaysMin=function(e){return!0===e?Je(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin},d.weekdaysShort=function(e){return!0===e?Je(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort},d.weekdaysParse=function(e,t,n){var s,i;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,e=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=l([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=x.call(this._weekdaysParse,e))?i:null:"ddd"===t?-1!==(i=x.call(this._shortWeekdaysParse,e))?i:null:-1!==(i=x.call(this._minWeekdaysParse,e))?i:null:"dddd"===t?-1!==(i=x.call(this._weekdaysParse,e))||-1!==(i=x.call(this._shortWeekdaysParse,e))||-1!==(i=x.call(this._minWeekdaysParse,e))?i:null:"ddd"===t?-1!==(i=x.call(this._shortWeekdaysParse,e))||-1!==(i=x.call(this._weekdaysParse,e))||-1!==(i=x.call(this._minWeekdaysParse,e))?i:null:-1!==(i=x.call(this._minWeekdaysParse,e))||-1!==(i=x.call(this._weekdaysParse,e))||-1!==(i=x.call(this._shortWeekdaysParse,e))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=l([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[s]||(i="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(i.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},d.weekdaysRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||st.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(c(this,"_weekdaysRegex")||(this._weekdaysRegex=et),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},d.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||st.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(c(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=tt),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},d.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||st.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(c(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=nt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},d.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},d.meridiem=function(e,t,n){return 11<e?n?"pm":"PM":n?"am":"AM"},ft("en",{eras:[{since:"0001-01-01",until:1/0,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(e){var t=e%10;return e+(1===M(e%100/10)?"th":1==t?"st":2==t?"nd":3==t?"rd":"th")}}),_.lang=e("moment.lang is deprecated. Use moment.locale instead.",ft),_.langData=e("moment.langData is deprecated. Use moment.localeData instead.",P);var _n=Math.abs;function yn(e,t,n,s){t=C(t,n);return e._milliseconds+=s*t._milliseconds,e._days+=s*t._days,e._months+=s*t._months,e._bubble()}function gn(e){return e<0?Math.floor(e):Math.ceil(e)}function wn(e){return 4800*e/146097}function pn(e){return 146097*e/4800}function kn(e){return function(){return this.as(e)}}de=kn("ms"),t=kn("s"),ye=kn("m"),he=kn("h"),Fe=kn("d"),_e=kn("w"),me=kn("M"),Qe=kn("Q"),i=kn("y"),ce=de;function Mn(e){return function(){return this.isValid()?this._data[e]:NaN}}var we=Mn("milliseconds"),fe=Mn("seconds"),ge=Mn("minutes"),Pe=Mn("hours"),d=Mn("days"),vn=Mn("months"),Dn=Mn("years");var Yn=Math.round,Sn={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function On(e,t,n,s){var i=C(e).abs(),r=Yn(i.as("s")),a=Yn(i.as("m")),o=Yn(i.as("h")),u=Yn(i.as("d")),l=Yn(i.as("M")),d=Yn(i.as("w")),i=Yn(i.as("y")),r=(r<=n.ss?["s",r]:r<n.s&&["ss",r])||(a<=1?["m"]:a<n.m&&["mm",a])||(o<=1?["h"]:o<n.h&&["hh",o])||(u<=1?["d"]:u<n.d&&["dd",u]);return(r=(r=null!=n.w?r||(d<=1?["w"]:d<n.w&&["ww",d]):r)||(l<=1?["M"]:l<n.M&&["MM",l])||(i<=1?["y"]:["yy",i]))[2]=t,r[3]=0<+e,r[4]=s,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,r)}var bn=Math.abs;function Tn(e){return(0<e)-(e<0)||+e}function xn(){var e,t,n,s,i,r,a,o,u,l,d;return this.isValid()?(e=bn(this._milliseconds)/1e3,t=bn(this._days),n=bn(this._months),(o=this.asSeconds())?(s=m(e/60),i=m(s/60),e%=60,s%=60,r=m(n/12),n%=12,a=e?e.toFixed(3).replace(/\.?0+$/,""):"",u=Tn(this._months)!==Tn(o)?"-":"",l=Tn(this._days)!==Tn(o)?"-":"",d=Tn(this._milliseconds)!==Tn(o)?"-":"",(o<0?"-":"")+"P"+(r?u+r+"Y":"")+(n?u+n+"M":"")+(t?l+t+"D":"")+(i||s||e?"T":"")+(i?d+i+"H":"")+(s?d+s+"M":"")+(e?d+a+"S":"")):"P0D"):this.localeData().invalidDate()}var U=Ct.prototype;return U.isValid=function(){return this._isValid},U.abs=function(){var e=this._data;return this._milliseconds=_n(this._milliseconds),this._days=_n(this._days),this._months=_n(this._months),e.milliseconds=_n(e.milliseconds),e.seconds=_n(e.seconds),e.minutes=_n(e.minutes),e.hours=_n(e.hours),e.months=_n(e.months),e.years=_n(e.years),this},U.add=function(e,t){return yn(this,e,t,1)},U.subtract=function(e,t){return yn(this,e,t,-1)},U.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=o(e))||"quarter"===e||"year"===e)switch(t=this._days+s/864e5,n=this._months+wn(t),e){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(t=this._days+Math.round(pn(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},U.asMilliseconds=de,U.asSeconds=t,U.asMinutes=ye,U.asHours=he,U.asDays=Fe,U.asWeeks=_e,U.asMonths=me,U.asQuarters=Qe,U.asYears=i,U.valueOf=ce,U._bubble=function(){var e=this._milliseconds,t=this._days,n=this._months,s=this._data;return 0<=e&&0<=t&&0<=n||e<=0&&t<=0&&n<=0||(e+=864e5*gn(pn(n)+t),n=t=0),s.milliseconds=e%1e3,e=m(e/1e3),s.seconds=e%60,e=m(e/60),s.minutes=e%60,e=m(e/60),s.hours=e%24,t+=m(e/24),n+=e=m(wn(t)),t-=gn(pn(e)),e=m(n/12),n%=12,s.days=t,s.months=n,s.years=e,this},U.clone=function(){return C(this)},U.get=function(e){return e=o(e),this.isValid()?this[e+"s"]():NaN},U.milliseconds=we,U.seconds=fe,U.minutes=ge,U.hours=Pe,U.days=d,U.weeks=function(){return m(this.days()/7)},U.months=vn,U.years=Dn,U.humanize=function(e,t){var n,s;return this.isValid()?(n=!1,s=Sn,"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(n=e),"object"==typeof t&&(s=Object.assign({},Sn,t),null!=t.s)&&null==t.ss&&(s.ss=t.s-1),e=this.localeData(),t=On(this,!n,s,e),n&&(t=e.pastFuture(+this,t)),e.postformat(t)):this.localeData().invalidDate()},U.toISOString=xn,U.toString=xn,U.toJSON=xn,U.locale=Xt,U.localeData=Kt,U.toIsoString=e("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",xn),U.lang=Ke,s("X",0,0,"unix"),s("x",0,0,"valueOf"),h("x",ke),h("X",/[+-]?\d+(\.\d{1,3})?/),v("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e))}),v("x",function(e,t,n){n._d=new Date(M(e))}),_.version="2.30.1",H=R,_.fn=u,_.min=function(){return Pt("isBefore",[].slice.call(arguments,0))},_.max=function(){return Pt("isAfter",[].slice.call(arguments,0))},_.now=function(){return Date.now?Date.now():+new Date},_.utc=l,_.unix=function(e){return R(1e3*e)},_.months=function(e,t){return fn(e,t,"months")},_.isDate=V,_.locale=ft,_.invalid=I,_.duration=C,_.isMoment=k,_.weekdays=function(e,t,n){return mn(e,t,n,"weekdays")},_.parseZone=function(){return R.apply(null,arguments).parseZone()},_.localeData=P,_.isDuration=Ut,_.monthsShort=function(e,t){return fn(e,t,"monthsShort")},_.weekdaysMin=function(e,t,n){return mn(e,t,n,"weekdaysMin")},_.defineLocale=mt,_.updateLocale=function(e,t){var n,s;return null!=t?(s=ut,null!=W[e]&&null!=W[e].parentLocale?W[e].set(X(W[e]._config,t)):(t=X(s=null!=(n=ct(e))?n._config:s,t),null==n&&(t.abbr=e),(s=new K(t)).parentLocale=W[e],W[e]=s),ft(e)):null!=W[e]&&(null!=W[e].parentLocale?(W[e]=W[e].parentLocale,e===ft()&&ft(e)):null!=W[e]&&delete W[e]),W[e]},_.locales=function(){return ee(W)},_.weekdaysShort=function(e,t,n){return mn(e,t,n,"weekdaysShort")},_.normalizeUnits=o,_.relativeTimeRounding=function(e){return void 0===e?Yn:"function"==typeof e&&(Yn=e,!0)},_.relativeTimeThreshold=function(e,t){return void 0!==Sn[e]&&(void 0===t?Sn[e]:(Sn[e]=t,"s"===e&&(Sn.ss=t-1),!0))},_.calendarFormat=function(e,t){return(e=e.diff(t,"days",!0))<-6?"sameElse":e<-1?"lastWeek":e<0?"lastDay":e<1?"sameDay":e<2?"nextDay":e<7?"nextWeek":"sameElse"},_.prototype=u,_.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"},_}); moment.js 0000604 00000530463 14720015030 0006400 0 ustar 00 //! moment.js //! version : 2.30.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, arrLen = arr.length; for (i = 0; i < arrLen; ++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) { var flags = null, parsedParts = false, isNowValid = m._d && !isNaN(m._d.getTime()); if (isNowValid) { flags = getParsingFlags(m); parsedParts = some.call(flags.parsedDateParts, function (i) { return i != null; }); isNowValid = 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, momentPropertiesLen = momentProperties.length; 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 (momentPropertiesLen > 0) { for (i = 0; i < momentPropertiesLen; 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, argLen = arguments.length; for (i = 0; i < argLen; 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 = { D: 'date', dates: 'date', date: 'date', d: 'day', days: 'day', day: 'day', e: 'weekday', weekdays: 'weekday', weekday: 'weekday', E: 'isoWeekday', isoweekdays: 'isoWeekday', isoweekday: 'isoWeekday', DDD: 'dayOfYear', dayofyears: 'dayOfYear', dayofyear: 'dayOfYear', h: 'hour', hours: 'hour', hour: 'hour', ms: 'millisecond', milliseconds: 'millisecond', millisecond: 'millisecond', m: 'minute', minutes: 'minute', minute: 'minute', M: 'month', months: 'month', month: 'month', Q: 'quarter', quarters: 'quarter', quarter: 'quarter', s: 'second', seconds: 'second', second: 'second', gg: 'weekYear', weekyears: 'weekYear', weekyear: 'weekYear', GG: 'isoWeekYear', isoweekyears: 'isoWeekYear', isoweekyear: 'isoWeekYear', w: 'week', weeks: 'week', week: 'week', W: 'isoWeek', isoweeks: 'isoWeek', isoweek: 'isoWeek', y: 'year', years: 'year', year: 'year', }; 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 = { date: 9, day: 11, weekday: 11, isoWeekday: 11, dayOfYear: 4, hour: 13, millisecond: 16, minute: 14, month: 8, quarter: 7, second: 15, weekYear: 1, isoWeekYear: 1, week: 5, isoWeek: 5, year: 1, }; 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; } 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, match1to2NoLeadingZero = /^[1-9]\d?/, // 1-99 match1to2HasZero = /^([1-9]\d|\d)/, // 0-99 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, '\\$&'); } 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; } var tokens = {}; function addParseToken(token, callback) { var i, func = callback, tokenLen; if (typeof token === 'string') { token = [token]; } if (isNumber(callback)) { func = function (input, array) { array[callback] = toInt(input); }; } tokenLen = token.length; for (i = 0; i < tokenLen; 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); } } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } var YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, WEEK = 7, WEEKDAY = 8; // 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'); // 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 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) { if (!mom.isValid()) { return NaN; } var d = mom._d, isUTC = mom._isUTC; switch (unit) { case 'Milliseconds': return isUTC ? d.getUTCMilliseconds() : d.getMilliseconds(); case 'Seconds': return isUTC ? d.getUTCSeconds() : d.getSeconds(); case 'Minutes': return isUTC ? d.getUTCMinutes() : d.getMinutes(); case 'Hours': return isUTC ? d.getUTCHours() : d.getHours(); case 'Date': return isUTC ? d.getUTCDate() : d.getDate(); case 'Day': return isUTC ? d.getUTCDay() : d.getDay(); case 'Month': return isUTC ? d.getUTCMonth() : d.getMonth(); case 'FullYear': return isUTC ? d.getUTCFullYear() : d.getFullYear(); default: return NaN; // Just in case } } function set$1(mom, unit, value) { var d, isUTC, year, month, date; if (!mom.isValid() || isNaN(value)) { return; } d = mom._d; isUTC = mom._isUTC; switch (unit) { case 'Milliseconds': return void (isUTC ? d.setUTCMilliseconds(value) : d.setMilliseconds(value)); case 'Seconds': return void (isUTC ? d.setUTCSeconds(value) : d.setSeconds(value)); case 'Minutes': return void (isUTC ? d.setUTCMinutes(value) : d.setMinutes(value)); case 'Hours': return void (isUTC ? d.setUTCHours(value) : d.setHours(value)); case 'Date': return void (isUTC ? d.setUTCDate(value) : d.setDate(value)); // case 'Day': // Not real // return void (isUTC ? d.setUTCDay(value) : d.setDay(value)); // case 'Month': // Not used because we need to pass two variables // return void (isUTC ? d.setUTCMonth(value) : d.setMonth(value)); case 'FullYear': break; // See below ... default: return; // Just in case } year = value; month = mom.month(); date = mom.date(); date = date === 29 && month === 1 && !isLeapYear(year) ? 28 : date; void (isUTC ? d.setUTCFullYear(year, month, date) : d.setFullYear(year, month, date)); } // 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, prioritizedLen = prioritized.length; for (i = 0; i < prioritizedLen; i++) { this[prioritized[i].unit](units[prioritized[i].unit]); } } else { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](value); } } return this; } 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); }); // PARSING addRegexToken('M', match1to2, match1to2NoLeadingZero); 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) { 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; } } } var month = value, date = mom.date(); date = date < 29 ? date : Math.min(date, daysInMonth(mom.year(), month)); void (mom._isUTC ? mom._d.setUTCMonth(month, date) : mom._d.setMonth(month, date)); 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, shortP, longP; for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = createUTC([2000, i]); shortP = regexEscape(this.monthsShort(mom, '')); longP = regexEscape(this.months(mom, '')); shortPieces.push(shortP); longPieces.push(longP); mixedPieces.push(longP); mixedPieces.push(shortP); } // 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); 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' ); } 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'); // PARSING addRegexToken('w', match1to2, match1to2NoLeadingZero); addRegexToken('ww', match1to2, match2); addRegexToken('W', match1to2, match1to2NoLeadingZero); 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'); // 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 = get(this, 'Day'); 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); // PARSING function matchMeridiem(isStrict, locale) { return locale._meridiemParse; } addRegexToken('a', matchMeridiem); addRegexToken('A', matchMeridiem); addRegexToken('H', match1to2, match1to2HasZero); addRegexToken('h', match1to2, match1to2NoLeadingZero); addRegexToken('k', match1to2, match1to2NoLeadingZero); 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 isLocaleNameSane(name) { // Prevent names that look like filesystem paths, i.e contain '/' or '\' // Ensure name is available and function returns boolean return !!(name && name.match('^[^/\\\\]*$')); } 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 && isLocaleNameSane(name) ) { 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, isoDatesLen = isoDates.length, isoTimesLen = isoTimes.length; if (match) { getParsingFlags(config).iso = true; for (i = 0, l = isoDatesLen; 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 = isoTimesLen; 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, tokenLen; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; tokenLen = tokens.length; for (i = 0; i < tokenLen; 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, configfLen = config._f.length; if (configfLen === 0) { getParsingFlags(config).invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < configfLen; 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, orderLen = ordering.length; 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 < orderLen; ++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, propertyLen = properties.length; for (i = 0; i < propertyLen; 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, erasName, erasAbbr, erasNarrow, eras = this.eras(); for (i = 0, l = eras.length; i < l; ++i) { erasName = regexEscape(eras[i].name); erasAbbr = regexEscape(eras[i].abbr); erasNarrow = regexEscape(eras[i].narrow); namePieces.push(erasName); abbrPieces.push(erasAbbr); narrowPieces.push(erasNarrow); mixedPieces.push(erasName); mixedPieces.push(erasAbbr); mixedPieces.push(erasNarrow); } 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 // 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.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'); // 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'); // PARSING addRegexToken('D', match1to2, match1to2NoLeadingZero); 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'); // 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'); // PARSING addRegexToken('m', match1to2, match1to2HasZero); addRegexToken('mm', match1to2, match2); addParseToken(['m', 'mm'], MINUTE); // MOMENTS var getSetMinute = makeGetSet('Minutes', false); // FORMATTING addFormatToken('s', ['ss', 2], 0, 'second'); // PARSING addRegexToken('s', match1to2, match1to2HasZero); 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; }); // 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); } } } 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'), valueOf$1 = asMilliseconds; 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.30.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; }))); react-dom.min.js 0000604 00000374507 14720015030 0007543 0 ustar 00 /** * @license React * react-dom.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. */ !function(){"use strict";var e,n;e=this,n=function(e,n){function t(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t<arguments.length;t++)n+="&args[]="+encodeURIComponent(arguments[t]);return"Minified React error #"+e+"; visit "+n+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(e,n){l(e,n),l(e+"Capture",n)}function l(e,n){for(ra[e]=n,e=0;e<n.length;e++)ta.add(n[e])}function a(e,n,t,r,l,a,u){this.acceptsBooleans=2===n||3===n||4===n,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=t,this.propertyName=e,this.type=n,this.sanitizeURL=a,this.removeEmptyString=u}function u(e,n,t,r){var l=sa.hasOwnProperty(n)?sa[n]:null;(null!==l?0!==l.type:r||!(2<n.length)||"o"!==n[0]&&"O"!==n[0]||"n"!==n[1]&&"N"!==n[1])&&(function(e,n,t,r){if(null==n||function(e,n,t,r){if(null!==t&&0===t.type)return!1;switch(typeof n){case"function":case"symbol":return!0;case"boolean":return!r&&(null!==t?!t.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,n,t,r))return!0;if(r)return!1;if(null!==t)switch(t.type){case 3:return!n;case 4:return!1===n;case 5:return isNaN(n);case 6:return isNaN(n)||1>n}return!1}(n,t,l,r)&&(t=null),r||null===l?function(e){return!!aa.call(ia,e)||!aa.call(oa,e)&&(ua.test(e)?ia[e]=!0:(oa[e]=!0,!1))}(n)&&(null===t?e.removeAttribute(n):e.setAttribute(n,""+t)):l.mustUseProperty?e[l.propertyName]=null===t?3!==l.type&&"":t:(n=l.attributeName,r=l.attributeNamespace,null===t?e.removeAttribute(n):(t=3===(l=l.type)||4===l&&!0===t?"":""+t,r?e.setAttributeNS(r,n,t):e.setAttribute(n,t))))}function o(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=_a&&e[_a]||e["@@iterator"])?e:null}function i(e,n,t){if(void 0===za)try{throw Error()}catch(e){za=(n=e.stack.trim().match(/\n( *(at )?)/))&&n[1]||""}return"\n"+za+e}function s(e,n){if(!e||Ta)return"";Ta=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(n)if(n=function(){throw Error()},Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}else{try{throw Error()}catch(e){r=e}e()}}catch(n){if(n&&r&&"string"==typeof n.stack){for(var l=n.stack.split("\n"),a=r.stack.split("\n"),u=l.length-1,o=a.length-1;1<=u&&0<=o&&l[u]!==a[o];)o--;for(;1<=u&&0<=o;u--,o--)if(l[u]!==a[o]){if(1!==u||1!==o)do{if(u--,0>--o||l[u]!==a[o]){var s="\n"+l[u].replace(" at new "," at ");return e.displayName&&s.includes("<anonymous>")&&(s=s.replace("<anonymous>",e.displayName)),s}}while(1<=u&&0<=o);break}}}finally{Ta=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?i(e):""}function c(e){switch(e.tag){case 5:return i(e.type);case 16:return i("Lazy");case 13:return i("Suspense");case 19:return i("SuspenseList");case 0:case 2:case 15:return e=s(e.type,!1);case 11:return e=s(e.type.render,!1);case 1:return e=s(e.type,!0);default:return""}}function f(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case ha:return"Fragment";case ma:return"Portal";case va:return"Profiler";case ga:return"StrictMode";case wa:return"Suspense";case Sa:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case ba:return(e.displayName||"Context")+".Consumer";case ya:return(e._context.displayName||"Context")+".Provider";case ka:var n=e.render;return(e=e.displayName)||(e=""!==(e=n.displayName||n.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case xa:return null!==(n=e.displayName||null)?n:f(e.type)||"Memo";case Ea:n=e._payload,e=e._init;try{return f(e(n))}catch(e){}}return null}function d(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=(e=n.render).displayName||e.name||"",n.displayName||(""!==e?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return f(n);case 8:return n===ga?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof n)return n.displayName||n.name||null;if("string"==typeof n)return n}return null}function p(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function m(e){var n=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===n||"radio"===n)}function h(e){e._valueTracker||(e._valueTracker=function(e){var n=m(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&void 0!==t&&"function"==typeof t.get&&"function"==typeof t.set){var l=t.get,a=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return l.call(this)},set:function(e){r=""+e,a.call(this,e)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}(e))}function g(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=m(e)?e.checked?"true":"false":e.value),(e=r)!==t&&(n.setValue(e),!0)}function v(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(n){return e.body}}function y(e,n){var t=n.checked;return La({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=t?t:e._wrapperState.initialChecked})}function b(e,n){var t=null==n.defaultValue?"":n.defaultValue,r=null!=n.checked?n.checked:n.defaultChecked;t=p(null!=n.value?n.value:t),e._wrapperState={initialChecked:r,initialValue:t,controlled:"checkbox"===n.type||"radio"===n.type?null!=n.checked:null!=n.value}}function k(e,n){null!=(n=n.checked)&&u(e,"checked",n,!1)}function w(e,n){k(e,n);var t=p(n.value),r=n.type;if(null!=t)"number"===r?(0===t&&""===e.value||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if("submit"===r||"reset"===r)return void e.removeAttribute("value");n.hasOwnProperty("value")?x(e,n.type,t):n.hasOwnProperty("defaultValue")&&x(e,n.type,p(n.defaultValue)),null==n.checked&&null!=n.defaultChecked&&(e.defaultChecked=!!n.defaultChecked)}function S(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(!("submit"!==r&&"reset"!==r||void 0!==n.value&&null!==n.value))return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}""!==(t=e.name)&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,""!==t&&(e.name=t)}function x(e,n,t){"number"===n&&v(e.ownerDocument)===e||(null==t?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}function E(e,n,t,r){if(e=e.options,n){n={};for(var l=0;l<t.length;l++)n["$"+t[l]]=!0;for(t=0;t<e.length;t++)l=n.hasOwnProperty("$"+e[t].value),e[t].selected!==l&&(e[t].selected=l),l&&r&&(e[t].defaultSelected=!0)}else{for(t=""+p(t),n=null,l=0;l<e.length;l++){if(e[l].value===t)return e[l].selected=!0,void(r&&(e[l].defaultSelected=!0));null!==n||e[l].disabled||(n=e[l])}null!==n&&(n.selected=!0)}}function C(e,n){if(null!=n.dangerouslySetInnerHTML)throw Error(t(91));return La({},n,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function z(e,n){var r=n.value;if(null==r){if(r=n.children,n=n.defaultValue,null!=r){if(null!=n)throw Error(t(92));if(Ma(r)){if(1<r.length)throw Error(t(93));r=r[0]}n=r}null==n&&(n=""),r=n}e._wrapperState={initialValue:p(r)}}function N(e,n){var t=p(n.value),r=p(n.defaultValue);null!=t&&((t=""+t)!==e.value&&(e.value=t),null==n.defaultValue&&e.defaultValue!==t&&(e.defaultValue=t)),null!=r&&(e.defaultValue=""+r)}function P(e,n){(n=e.textContent)===e._wrapperState.initialValue&&""!==n&&null!==n&&(e.value=n)}function _(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function L(e,n){return null==e||"http://www.w3.org/1999/xhtml"===e?_(n):"http://www.w3.org/2000/svg"===e&&"foreignObject"===n?"http://www.w3.org/1999/xhtml":e}function T(e,n,t){return null==n||"boolean"==typeof n||""===n?"":t||"number"!=typeof n||0===n||Da.hasOwnProperty(e)&&Da[e]?(""+n).trim():n+"px"}function M(e,n){for(var t in e=e.style,n)if(n.hasOwnProperty(t)){var r=0===t.indexOf("--"),l=T(t,n[t],r);"float"===t&&(t="cssFloat"),r?e.setProperty(t,l):e[t]=l}}function F(e,n){if(n){if(Ia[e]&&(null!=n.children||null!=n.dangerouslySetInnerHTML))throw Error(t(137,e));if(null!=n.dangerouslySetInnerHTML){if(null!=n.children)throw Error(t(60));if("object"!=typeof n.dangerouslySetInnerHTML||!("__html"in n.dangerouslySetInnerHTML))throw Error(t(61))}if(null!=n.style&&"object"!=typeof n.style)throw Error(t(62))}}function R(e,n){if(-1===e.indexOf("-"))return"string"==typeof n.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}function D(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}function O(e){if(e=mn(e)){if("function"!=typeof Va)throw Error(t(280));var n=e.stateNode;n&&(n=gn(n),Va(e.stateNode,e.type,n))}}function I(e){Aa?Ba?Ba.push(e):Ba=[e]:Aa=e}function U(){if(Aa){var e=Aa,n=Ba;if(Ba=Aa=null,O(e),n)for(e=0;e<n.length;e++)O(n[e])}}function V(e,n,t){if(Qa)return e(n,t);Qa=!0;try{return Wa(e,n,t)}finally{Qa=!1,(null!==Aa||null!==Ba)&&(Ha(),U())}}function A(e,n){var r=e.stateNode;if(null===r)return null;var l=gn(r);if(null===l)return null;r=l[n];e:switch(n){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(l=!l.disabled)||(l=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!l;break e;default:e=!1}if(e)return null;if(r&&"function"!=typeof r)throw Error(t(231,n,typeof r));return r}function B(e,n,t,r,l,a,u,o,i){Ga=!1,Za=null,Xa.apply(nu,arguments)}function W(e,n,r,l,a,u,o,i,s){if(B.apply(this,arguments),Ga){if(!Ga)throw Error(t(198));var c=Za;Ga=!1,Za=null,Ja||(Ja=!0,eu=c)}}function H(e){var n=e,t=e;if(e.alternate)for(;n.return;)n=n.return;else{e=n;do{0!=(4098&(n=e).flags)&&(t=n.return),e=n.return}while(e)}return 3===n.tag?t:null}function Q(e){if(13===e.tag){var n=e.memoizedState;if(null===n&&null!==(e=e.alternate)&&(n=e.memoizedState),null!==n)return n.dehydrated}return null}function j(e){if(H(e)!==e)throw Error(t(188))}function $(e){return null!==(e=function(e){var n=e.alternate;if(!n){if(null===(n=H(e)))throw Error(t(188));return n!==e?null:e}for(var r=e,l=n;;){var a=r.return;if(null===a)break;var u=a.alternate;if(null===u){if(null!==(l=a.return)){r=l;continue}break}if(a.child===u.child){for(u=a.child;u;){if(u===r)return j(a),e;if(u===l)return j(a),n;u=u.sibling}throw Error(t(188))}if(r.return!==l.return)r=a,l=u;else{for(var o=!1,i=a.child;i;){if(i===r){o=!0,r=a,l=u;break}if(i===l){o=!0,l=a,r=u;break}i=i.sibling}if(!o){for(i=u.child;i;){if(i===r){o=!0,r=u,l=a;break}if(i===l){o=!0,l=u,r=a;break}i=i.sibling}if(!o)throw Error(t(189))}}if(r.alternate!==l)throw Error(t(190))}if(3!==r.tag)throw Error(t(188));return r.stateNode.current===r?e:n}(e))?q(e):null}function q(e){if(5===e.tag||6===e.tag)return e;for(e=e.child;null!==e;){var n=q(e);if(null!==n)return n;e=e.sibling}return null}function K(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194240&e;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return 130023424&e;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Y(e,n){var t=e.pendingLanes;if(0===t)return 0;var r=0,l=e.suspendedLanes,a=e.pingedLanes,u=268435455&t;if(0!==u){var o=u&~l;0!==o?r=K(o):0!=(a&=u)&&(r=K(a))}else 0!=(u=t&~l)?r=K(u):0!==a&&(r=K(a));if(0===r)return 0;if(0!==n&&n!==r&&0==(n&l)&&((l=r&-r)>=(a=n&-n)||16===l&&0!=(4194240&a)))return n;if(0!=(4&r)&&(r|=16&t),0!==(n=e.entangledLanes))for(e=e.entanglements,n&=r;0<n;)l=1<<(t=31-yu(n)),r|=e[t],n&=~l;return r}function X(e,n){switch(e){case 1:case 2:case 4:return n+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return n+5e3;default:return-1}}function G(e){return 0!=(e=-1073741825&e.pendingLanes)?e:1073741824&e?1073741824:0}function Z(){var e=wu;return 0==(4194240&(wu<<=1))&&(wu=64),e}function J(e){for(var n=[],t=0;31>t;t++)n.push(e);return n}function ee(e,n,t){e.pendingLanes|=n,536870912!==n&&(e.suspendedLanes=0,e.pingedLanes=0),(e=e.eventTimes)[n=31-yu(n)]=t}function ne(e,n){var t=e.entangledLanes|=n;for(e=e.entanglements;t;){var r=31-yu(t),l=1<<r;l&n|e[r]&n&&(e[r]|=n),t&=~l}}function te(e){return 1<(e&=-e)?4<e?0!=(268435455&e)?16:536870912:4:1}function re(e,n){switch(e){case"focusin":case"focusout":zu=null;break;case"dragenter":case"dragleave":Nu=null;break;case"mouseover":case"mouseout":Pu=null;break;case"pointerover":case"pointerout":_u.delete(n.pointerId);break;case"gotpointercapture":case"lostpointercapture":Lu.delete(n.pointerId)}}function le(e,n,t,r,l,a){return null===e||e.nativeEvent!==a?(e={blockedOn:n,domEventName:t,eventSystemFlags:r,nativeEvent:a,targetContainers:[l]},null!==n&&null!==(n=mn(n))&&Ks(n),e):(e.eventSystemFlags|=r,n=e.targetContainers,null!==l&&-1===n.indexOf(l)&&n.push(l),e)}function ae(e){var n=pn(e.target);if(null!==n){var t=H(n);if(null!==t)if(13===(n=t.tag)){if(null!==(n=Q(t)))return e.blockedOn=n,void Gs(e.priority,(function(){Ys(t)}))}else if(3===n&&t.stateNode.current.memoizedState.isDehydrated)return void(e.blockedOn=3===t.tag?t.stateNode.containerInfo:null)}e.blockedOn=null}function ue(e){if(null!==e.blockedOn)return!1;for(var n=e.targetContainers;0<n.length;){var t=me(e.domEventName,e.eventSystemFlags,n[0],e.nativeEvent);if(null!==t)return null!==(n=mn(t))&&Ks(n),e.blockedOn=t,!1;var r=new(t=e.nativeEvent).constructor(t.type,t);Ua=r,t.target.dispatchEvent(r),Ua=null,n.shift()}return!0}function oe(e,n,t){ue(e)&&t.delete(n)}function ie(){Eu=!1,null!==zu&&ue(zu)&&(zu=null),null!==Nu&&ue(Nu)&&(Nu=null),null!==Pu&&ue(Pu)&&(Pu=null),_u.forEach(oe),Lu.forEach(oe)}function se(e,n){e.blockedOn===n&&(e.blockedOn=null,Eu||(Eu=!0,ru(lu,ie)))}function ce(e){if(0<Cu.length){se(Cu[0],e);for(var n=1;n<Cu.length;n++){var t=Cu[n];t.blockedOn===e&&(t.blockedOn=null)}}for(null!==zu&&se(zu,e),null!==Nu&&se(Nu,e),null!==Pu&&se(Pu,e),n=function(n){return se(n,e)},_u.forEach(n),Lu.forEach(n),n=0;n<Tu.length;n++)(t=Tu[n]).blockedOn===e&&(t.blockedOn=null);for(;0<Tu.length&&null===(n=Tu[0]).blockedOn;)ae(n),null===n.blockedOn&&Tu.shift()}function fe(e,n,t,r){var l=xu,a=Fu.transition;Fu.transition=null;try{xu=1,pe(e,n,t,r)}finally{xu=l,Fu.transition=a}}function de(e,n,t,r){var l=xu,a=Fu.transition;Fu.transition=null;try{xu=4,pe(e,n,t,r)}finally{xu=l,Fu.transition=a}}function pe(e,n,t,r){if(Ru){var l=me(e,n,t,r);if(null===l)Je(e,n,r,Du,t),re(e,r);else if(function(e,n,t,r,l){switch(n){case"focusin":return zu=le(zu,e,n,t,r,l),!0;case"dragenter":return Nu=le(Nu,e,n,t,r,l),!0;case"mouseover":return Pu=le(Pu,e,n,t,r,l),!0;case"pointerover":var a=l.pointerId;return _u.set(a,le(_u.get(a)||null,e,n,t,r,l)),!0;case"gotpointercapture":return a=l.pointerId,Lu.set(a,le(Lu.get(a)||null,e,n,t,r,l)),!0}return!1}(l,e,n,t,r))r.stopPropagation();else if(re(e,r),4&n&&-1<Mu.indexOf(e)){for(;null!==l;){var a=mn(l);if(null!==a&&qs(a),null===(a=me(e,n,t,r))&&Je(e,n,r,Du,t),a===l)break;l=a}null!==l&&r.stopPropagation()}else Je(e,n,r,null,t)}}function me(e,n,t,r){if(Du=null,null!==(e=pn(e=D(r))))if(null===(n=H(e)))e=null;else if(13===(t=n.tag)){if(null!==(e=Q(n)))return e;e=null}else if(3===t){if(n.stateNode.current.memoizedState.isDehydrated)return 3===n.tag?n.stateNode.containerInfo:null;e=null}else n!==e&&(e=null);return Du=e,null}function he(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(cu()){case fu:return 1;case du:return 4;case pu:case mu:return 16;case hu:return 536870912;default:return 16}default:return 16}}function ge(){if(Uu)return Uu;var e,n,t=Iu,r=t.length,l="value"in Ou?Ou.value:Ou.textContent,a=l.length;for(e=0;e<r&&t[e]===l[e];e++);var u=r-e;for(n=1;n<=u&&t[r-n]===l[a-n];n++);return Uu=l.slice(e,1<n?1-n:void 0)}function ve(e){var n=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===n&&(e=13):e=n,10===e&&(e=13),32<=e||13===e?e:0}function ye(){return!0}function be(){return!1}function ke(e){function n(n,t,r,l,a){for(var u in this._reactName=n,this._targetInst=r,this.type=t,this.nativeEvent=l,this.target=a,this.currentTarget=null,e)e.hasOwnProperty(u)&&(n=e[u],this[u]=n?n(l):l[u]);return this.isDefaultPrevented=(null!=l.defaultPrevented?l.defaultPrevented:!1===l.returnValue)?ye:be,this.isPropagationStopped=be,this}return La(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=ye)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=ye)},persist:function(){},isPersistent:ye}),n}function we(e){var n=this.nativeEvent;return n.getModifierState?n.getModifierState(e):!!(e=eo[e])&&!!n[e]}function Se(e){return we}function xe(e,n){switch(e){case"keyup":return-1!==io.indexOf(n.keyCode);case"keydown":return 229!==n.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ee(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}function Ce(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===n?!!vo[e.type]:"textarea"===n}function ze(e,n,t,r){I(r),0<(n=nn(n,"onChange")).length&&(t=new Au("onChange","change",null,t,r),e.push({event:t,listeners:n}))}function Ne(e){Ke(e,0)}function Pe(e){if(g(hn(e)))return e}function _e(e,n){if("change"===e)return n}function Le(){yo&&(yo.detachEvent("onpropertychange",Te),bo=yo=null)}function Te(e){if("value"===e.propertyName&&Pe(bo)){var n=[];ze(n,bo,e,D(e)),V(Ne,n)}}function Me(e,n,t){"focusin"===e?(Le(),bo=t,(yo=n).attachEvent("onpropertychange",Te)):"focusout"===e&&Le()}function Fe(e,n){if("selectionchange"===e||"keyup"===e||"keydown"===e)return Pe(bo)}function Re(e,n){if("click"===e)return Pe(n)}function De(e,n){if("input"===e||"change"===e)return Pe(n)}function Oe(e,n){if(wo(e,n))return!0;if("object"!=typeof e||null===e||"object"!=typeof n||null===n)return!1;var t=Object.keys(e),r=Object.keys(n);if(t.length!==r.length)return!1;for(r=0;r<t.length;r++){var l=t[r];if(!aa.call(n,l)||!wo(e[l],n[l]))return!1}return!0}function Ie(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Ue(e,n){var t,r=Ie(e);for(e=0;r;){if(3===r.nodeType){if(t=e+r.textContent.length,e<=n&&t>=n)return{node:r,offset:n-e};e=t}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Ie(r)}}function Ve(e,n){return!(!e||!n)&&(e===n||(!e||3!==e.nodeType)&&(n&&3===n.nodeType?Ve(e,n.parentNode):"contains"in e?e.contains(n):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(n))))}function Ae(){for(var e=window,n=v();n instanceof e.HTMLIFrameElement;){try{var t="string"==typeof n.contentWindow.location.href}catch(e){t=!1}if(!t)break;n=v((e=n.contentWindow).document)}return n}function Be(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&("input"===n&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===n||"true"===e.contentEditable)}function We(e){var n=Ae(),t=e.focusedElem,r=e.selectionRange;if(n!==t&&t&&t.ownerDocument&&Ve(t.ownerDocument.documentElement,t)){if(null!==r&&Be(t))if(n=r.start,void 0===(e=r.end)&&(e=n),"selectionStart"in t)t.selectionStart=n,t.selectionEnd=Math.min(e,t.value.length);else if((e=(n=t.ownerDocument||document)&&n.defaultView||window).getSelection){e=e.getSelection();var l=t.textContent.length,a=Math.min(r.start,l);r=void 0===r.end?a:Math.min(r.end,l),!e.extend&&a>r&&(l=r,r=a,a=l),l=Ue(t,a);var u=Ue(t,r);l&&u&&(1!==e.rangeCount||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==u.node||e.focusOffset!==u.offset)&&((n=n.createRange()).setStart(l.node,l.offset),e.removeAllRanges(),a>r?(e.addRange(n),e.extend(u.node,u.offset)):(n.setEnd(u.node,u.offset),e.addRange(n)))}for(n=[],e=t;e=e.parentNode;)1===e.nodeType&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"==typeof t.focus&&t.focus(),t=0;t<n.length;t++)(e=n[t]).element.scrollLeft=e.left,e.element.scrollTop=e.top}}function He(e,n,t){var r=t.window===t?t.document:9===t.nodeType?t:t.ownerDocument;zo||null==xo||xo!==v(r)||(r="selectionStart"in(r=xo)&&Be(r)?{start:r.selectionStart,end:r.selectionEnd}:{anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},Co&&Oe(Co,r)||(Co=r,0<(r=nn(Eo,"onSelect")).length&&(n=new Au("onSelect","select",null,n,t),e.push({event:n,listeners:r}),n.target=xo)))}function Qe(e,n){var t={};return t[e.toLowerCase()]=n.toLowerCase(),t["Webkit"+e]="webkit"+n,t["Moz"+e]="moz"+n,t}function je(e){if(Po[e])return Po[e];if(!No[e])return e;var n,t=No[e];for(n in t)if(t.hasOwnProperty(n)&&n in _o)return Po[e]=t[n];return e}function $e(e,n){Ro.set(e,n),r(n,[e])}function qe(e,n,t){var r=e.type||"unknown-event";e.currentTarget=t,W(r,n,void 0,e),e.currentTarget=null}function Ke(e,n){n=0!=(4&n);for(var t=0;t<e.length;t++){var r=e[t],l=r.event;r=r.listeners;e:{var a=void 0;if(n)for(var u=r.length-1;0<=u;u--){var o=r[u],i=o.instance,s=o.currentTarget;if(o=o.listener,i!==a&&l.isPropagationStopped())break e;qe(l,o,s),a=i}else for(u=0;u<r.length;u++){if(i=(o=r[u]).instance,s=o.currentTarget,o=o.listener,i!==a&&l.isPropagationStopped())break e;qe(l,o,s),a=i}}}if(Ja)throw e=eu,Ja=!1,eu=null,e}function Ye(e,n){var t=n[Go];void 0===t&&(t=n[Go]=new Set);var r=e+"__bubble";t.has(r)||(Ze(n,e,2,!1),t.add(r))}function Xe(e,n,t){var r=0;n&&(r|=4),Ze(t,e,r,n)}function Ge(e){if(!e[Uo]){e[Uo]=!0,ta.forEach((function(n){"selectionchange"!==n&&(Io.has(n)||Xe(n,!1,e),Xe(n,!0,e))}));var n=9===e.nodeType?e:e.ownerDocument;null===n||n[Uo]||(n[Uo]=!0,Xe("selectionchange",!1,n))}}function Ze(e,n,t,r,l){switch(he(n)){case 1:l=fe;break;case 4:l=de;break;default:l=pe}t=l.bind(null,n,t,e),l=void 0,!ja||"touchstart"!==n&&"touchmove"!==n&&"wheel"!==n||(l=!0),r?void 0!==l?e.addEventListener(n,t,{capture:!0,passive:l}):e.addEventListener(n,t,!0):void 0!==l?e.addEventListener(n,t,{passive:l}):e.addEventListener(n,t,!1)}function Je(e,n,t,r,l){var a=r;if(0==(1&n)&&0==(2&n)&&null!==r)e:for(;;){if(null===r)return;var u=r.tag;if(3===u||4===u){var o=r.stateNode.containerInfo;if(o===l||8===o.nodeType&&o.parentNode===l)break;if(4===u)for(u=r.return;null!==u;){var i=u.tag;if((3===i||4===i)&&((i=u.stateNode.containerInfo)===l||8===i.nodeType&&i.parentNode===l))return;u=u.return}for(;null!==o;){if(null===(u=pn(o)))return;if(5===(i=u.tag)||6===i){r=a=u;continue e}o=o.parentNode}}r=r.return}V((function(){var r=a,l=D(t),u=[];e:{var o=Ro.get(e);if(void 0!==o){var i=Au,s=e;switch(e){case"keypress":if(0===ve(t))break e;case"keydown":case"keyup":i=to;break;case"focusin":s="focus",i=$u;break;case"focusout":s="blur",i=$u;break;case"beforeblur":case"afterblur":i=$u;break;case"click":if(2===t.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":i=Qu;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":i=ju;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":i=lo;break;case Lo:case To:case Mo:i=qu;break;case Fo:i=ao;break;case"scroll":i=Wu;break;case"wheel":i=oo;break;case"copy":case"cut":case"paste":i=Yu;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":i=ro}var c=0!=(4&n),f=!c&&"scroll"===e,d=c?null!==o?o+"Capture":null:o;c=[];for(var p,m=r;null!==m;){var h=(p=m).stateNode;if(5===p.tag&&null!==h&&(p=h,null!==d&&null!=(h=A(m,d))&&c.push(en(m,h,p))),f)break;m=m.return}0<c.length&&(o=new i(o,s,null,t,l),u.push({event:o,listeners:c}))}}if(0==(7&n)){if(i="mouseout"===e||"pointerout"===e,(!(o="mouseover"===e||"pointerover"===e)||t===Ua||!(s=t.relatedTarget||t.fromElement)||!pn(s)&&!s[Xo])&&(i||o)&&(o=l.window===l?l:(o=l.ownerDocument)?o.defaultView||o.parentWindow:window,i?(i=r,null!==(s=(s=t.relatedTarget||t.toElement)?pn(s):null)&&(s!==(f=H(s))||5!==s.tag&&6!==s.tag)&&(s=null)):(i=null,s=r),i!==s)){if(c=Qu,h="onMouseLeave",d="onMouseEnter",m="mouse","pointerout"!==e&&"pointerover"!==e||(c=ro,h="onPointerLeave",d="onPointerEnter",m="pointer"),f=null==i?o:hn(i),p=null==s?o:hn(s),(o=new c(h,m+"leave",i,t,l)).target=f,o.relatedTarget=p,h=null,pn(l)===r&&((c=new c(d,m+"enter",s,t,l)).target=p,c.relatedTarget=f,h=c),f=h,i&&s)e:{for(d=s,m=0,p=c=i;p;p=tn(p))m++;for(p=0,h=d;h;h=tn(h))p++;for(;0<m-p;)c=tn(c),m--;for(;0<p-m;)d=tn(d),p--;for(;m--;){if(c===d||null!==d&&c===d.alternate)break e;c=tn(c),d=tn(d)}c=null}else c=null;null!==i&&rn(u,o,i,c,!1),null!==s&&null!==f&&rn(u,f,s,c,!0)}if("select"===(i=(o=r?hn(r):window).nodeName&&o.nodeName.toLowerCase())||"input"===i&&"file"===o.type)var g=_e;else if(Ce(o))if(ko)g=De;else{g=Fe;var v=Me}else(i=o.nodeName)&&"input"===i.toLowerCase()&&("checkbox"===o.type||"radio"===o.type)&&(g=Re);switch(g&&(g=g(e,r))?ze(u,g,t,l):(v&&v(e,o,r),"focusout"===e&&(v=o._wrapperState)&&v.controlled&&"number"===o.type&&x(o,"number",o.value)),v=r?hn(r):window,e){case"focusin":(Ce(v)||"true"===v.contentEditable)&&(xo=v,Eo=r,Co=null);break;case"focusout":Co=Eo=xo=null;break;case"mousedown":zo=!0;break;case"contextmenu":case"mouseup":case"dragend":zo=!1,He(u,t,l);break;case"selectionchange":if(So)break;case"keydown":case"keyup":He(u,t,l)}var y;if(so)e:{switch(e){case"compositionstart":var b="onCompositionStart";break e;case"compositionend":b="onCompositionEnd";break e;case"compositionupdate":b="onCompositionUpdate";break e}b=void 0}else go?xe(e,t)&&(b="onCompositionEnd"):"keydown"===e&&229===t.keyCode&&(b="onCompositionStart");b&&(po&&"ko"!==t.locale&&(go||"onCompositionStart"!==b?"onCompositionEnd"===b&&go&&(y=ge()):(Iu="value"in(Ou=l)?Ou.value:Ou.textContent,go=!0)),0<(v=nn(r,b)).length&&(b=new Xu(b,e,null,t,l),u.push({event:b,listeners:v}),(y||null!==(y=Ee(t)))&&(b.data=y))),(y=fo?function(e,n){switch(e){case"compositionend":return Ee(n);case"keypress":return 32!==n.which?null:(ho=!0,mo);case"textInput":return(e=n.data)===mo&&ho?null:e;default:return null}}(e,t):function(e,n){if(go)return"compositionend"===e||!so&&xe(e,n)?(e=ge(),Uu=Iu=Ou=null,go=!1,e):null;switch(e){case"paste":default:return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1<n.char.length)return n.char;if(n.which)return String.fromCharCode(n.which)}return null;case"compositionend":return po&&"ko"!==n.locale?null:n.data}}(e,t))&&0<(r=nn(r,"onBeforeInput")).length&&(l=new Gu("onBeforeInput","beforeinput",null,t,l),u.push({event:l,listeners:r}),l.data=y)}Ke(u,n)}))}function en(e,n,t){return{instance:e,listener:n,currentTarget:t}}function nn(e,n){for(var t=n+"Capture",r=[];null!==e;){var l=e,a=l.stateNode;5===l.tag&&null!==a&&(l=a,null!=(a=A(e,t))&&r.unshift(en(e,a,l)),null!=(a=A(e,n))&&r.push(en(e,a,l))),e=e.return}return r}function tn(e){if(null===e)return null;do{e=e.return}while(e&&5!==e.tag);return e||null}function rn(e,n,t,r,l){for(var a=n._reactName,u=[];null!==t&&t!==r;){var o=t,i=o.alternate,s=o.stateNode;if(null!==i&&i===r)break;5===o.tag&&null!==s&&(o=s,l?null!=(i=A(t,a))&&u.unshift(en(t,i,o)):l||null!=(i=A(t,a))&&u.push(en(t,i,o))),t=t.return}0!==u.length&&e.push({event:n,listeners:u})}function ln(e){return("string"==typeof e?e:""+e).replace(Vo,"\n").replace(Ao,"")}function an(e,n,r,l){if(n=ln(n),ln(e)!==n&&r)throw Error(t(425))}function un(){}function on(e,n){return"textarea"===e||"noscript"===e||"string"==typeof n.children||"number"==typeof n.children||"object"==typeof n.dangerouslySetInnerHTML&&null!==n.dangerouslySetInnerHTML&&null!=n.dangerouslySetInnerHTML.__html}function sn(e){setTimeout((function(){throw e}))}function cn(e,n){var t=n,r=0;do{var l=t.nextSibling;if(e.removeChild(t),l&&8===l.nodeType)if("/$"===(t=l.data)){if(0===r)return e.removeChild(l),void ce(n);r--}else"$"!==t&&"$?"!==t&&"$!"!==t||r++;t=l}while(t);ce(n)}function fn(e){for(;null!=e;e=e.nextSibling){var n=e.nodeType;if(1===n||3===n)break;if(8===n){if("$"===(n=e.data)||"$!"===n||"$?"===n)break;if("/$"===n)return null}}return e}function dn(e){e=e.previousSibling;for(var n=0;e;){if(8===e.nodeType){var t=e.data;if("$"===t||"$!"===t||"$?"===t){if(0===n)return e;n--}else"/$"===t&&n++}e=e.previousSibling}return null}function pn(e){var n=e[Ko];if(n)return n;for(var t=e.parentNode;t;){if(n=t[Xo]||t[Ko]){if(t=n.alternate,null!==n.child||null!==t&&null!==t.child)for(e=dn(e);null!==e;){if(t=e[Ko])return t;e=dn(e)}return n}t=(e=t).parentNode}return null}function mn(e){return!(e=e[Ko]||e[Xo])||5!==e.tag&&6!==e.tag&&13!==e.tag&&3!==e.tag?null:e}function hn(e){if(5===e.tag||6===e.tag)return e.stateNode;throw Error(t(33))}function gn(e){return e[Yo]||null}function vn(e){return{current:e}}function yn(e,n){0>ni||(e.current=ei[ni],ei[ni]=null,ni--)}function bn(e,n,t){ni++,ei[ni]=e.current,e.current=n}function kn(e,n){var t=e.type.contextTypes;if(!t)return ti;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l,a={};for(l in t)a[l]=n[l];return r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=a),a}function wn(e){return null!=(e=e.childContextTypes)}function Sn(e,n,r){if(ri.current!==ti)throw Error(t(168));bn(ri,n),bn(li,r)}function xn(e,n,r){var l=e.stateNode;if(n=n.childContextTypes,"function"!=typeof l.getChildContext)return r;for(var a in l=l.getChildContext())if(!(a in n))throw Error(t(108,d(e)||"Unknown",a));return La({},r,l)}function En(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ti,ai=ri.current,bn(ri,e),bn(li,li.current),!0}function Cn(e,n,r){var l=e.stateNode;if(!l)throw Error(t(169));r?(e=xn(e,n,ai),l.__reactInternalMemoizedMergedChildContext=e,yn(li),yn(ri),bn(ri,e)):yn(li),bn(li,r)}function zn(e){null===ui?ui=[e]:ui.push(e)}function Nn(){if(!ii&&null!==ui){ii=!0;var e=0,n=xu;try{var t=ui;for(xu=1;e<t.length;e++){var r=t[e];do{r=r(!0)}while(null!==r)}ui=null,oi=!1}catch(n){throw null!==ui&&(ui=ui.slice(e+1)),au(fu,Nn),n}finally{xu=n,ii=!1}}return null}function Pn(e,n){si[ci++]=di,si[ci++]=fi,fi=e,di=n}function _n(e,n,t){pi[mi++]=gi,pi[mi++]=vi,pi[mi++]=hi,hi=e;var r=gi;e=vi;var l=32-yu(r)-1;r&=~(1<<l),t+=1;var a=32-yu(n)+l;if(30<a){var u=l-l%5;a=(r&(1<<u)-1).toString(32),r>>=u,l-=u,gi=1<<32-yu(n)+l|t<<l|r,vi=a+e}else gi=1<<a|t<<l|r,vi=e}function Ln(e){null!==e.return&&(Pn(e,1),_n(e,1,0))}function Tn(e){for(;e===fi;)fi=si[--ci],si[ci]=null,di=si[--ci],si[ci]=null;for(;e===hi;)hi=pi[--mi],pi[mi]=null,vi=pi[--mi],pi[mi]=null,gi=pi[--mi],pi[mi]=null}function Mn(e,n){var t=js(5,null,null,0);t.elementType="DELETED",t.stateNode=n,t.return=e,null===(n=e.deletions)?(e.deletions=[t],e.flags|=16):n.push(t)}function Fn(e,n){switch(e.tag){case 5:var t=e.type;return null!==(n=1!==n.nodeType||t.toLowerCase()!==n.nodeName.toLowerCase()?null:n)&&(e.stateNode=n,yi=e,bi=fn(n.firstChild),!0);case 6:return null!==(n=""===e.pendingProps||3!==n.nodeType?null:n)&&(e.stateNode=n,yi=e,bi=null,!0);case 13:return null!==(n=8!==n.nodeType?null:n)&&(t=null!==hi?{id:gi,overflow:vi}:null,e.memoizedState={dehydrated:n,treeContext:t,retryLane:1073741824},(t=js(18,null,null,0)).stateNode=n,t.return=e,e.child=t,yi=e,bi=null,!0);default:return!1}}function Rn(e){return 0!=(1&e.mode)&&0==(128&e.flags)}function Dn(e){if(ki){var n=bi;if(n){var r=n;if(!Fn(e,n)){if(Rn(e))throw Error(t(418));n=fn(r.nextSibling);var l=yi;n&&Fn(e,n)?Mn(l,r):(e.flags=-4097&e.flags|2,ki=!1,yi=e)}}else{if(Rn(e))throw Error(t(418));e.flags=-4097&e.flags|2,ki=!1,yi=e}}}function On(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&13!==e.tag;)e=e.return;yi=e}function In(e){if(e!==yi)return!1;if(!ki)return On(e),ki=!0,!1;var n;if((n=3!==e.tag)&&!(n=5!==e.tag)&&(n="head"!==(n=e.type)&&"body"!==n&&!on(e.type,e.memoizedProps)),n&&(n=bi)){if(Rn(e)){for(e=bi;e;)e=fn(e.nextSibling);throw Error(t(418))}for(;n;)Mn(e,n),n=fn(n.nextSibling)}if(On(e),13===e.tag){if(!(e=null!==(e=e.memoizedState)?e.dehydrated:null))throw Error(t(317));e:{for(e=e.nextSibling,n=0;e;){if(8===e.nodeType){var r=e.data;if("/$"===r){if(0===n){bi=fn(e.nextSibling);break e}n--}else"$"!==r&&"$!"!==r&&"$?"!==r||n++}e=e.nextSibling}bi=null}}else bi=yi?fn(e.stateNode.nextSibling):null;return!0}function Un(){bi=yi=null,ki=!1}function Vn(e){null===wi?wi=[e]:wi.push(e)}function An(e,n,r){if(null!==(e=r.ref)&&"function"!=typeof e&&"object"!=typeof e){if(r._owner){if(r=r._owner){if(1!==r.tag)throw Error(t(309));var l=r.stateNode}if(!l)throw Error(t(147,e));var a=l,u=""+e;return null!==n&&null!==n.ref&&"function"==typeof n.ref&&n.ref._stringRef===u?n.ref:(n=function(e){var n=a.refs;null===e?delete n[u]:n[u]=e},n._stringRef=u,n)}if("string"!=typeof e)throw Error(t(284));if(!r._owner)throw Error(t(290,e))}return e}function Bn(e,n){throw e=Object.prototype.toString.call(n),Error(t(31,"[object Object]"===e?"object with keys {"+Object.keys(n).join(", ")+"}":e))}function Wn(e){return(0,e._init)(e._payload)}function Hn(e){function n(n,t){if(e){var r=n.deletions;null===r?(n.deletions=[t],n.flags|=16):r.push(t)}}function r(t,r){if(!e)return null;for(;null!==r;)n(t,r),r=r.sibling;return null}function l(e,n){for(e=new Map;null!==n;)null!==n.key?e.set(n.key,n):e.set(n.index,n),n=n.sibling;return e}function a(e,n){return(e=Rl(e,n)).index=0,e.sibling=null,e}function u(n,t,r){return n.index=r,e?null!==(r=n.alternate)?(r=r.index)<t?(n.flags|=2,t):r:(n.flags|=2,t):(n.flags|=1048576,t)}function i(n){return e&&null===n.alternate&&(n.flags|=2),n}function s(e,n,t,r){return null===n||6!==n.tag?((n=Ul(t,e.mode,r)).return=e,n):((n=a(n,t)).return=e,n)}function c(e,n,t,r){var l=t.type;return l===ha?d(e,n,t.props.children,r,t.key):null!==n&&(n.elementType===l||"object"==typeof l&&null!==l&&l.$$typeof===Ea&&Wn(l)===n.type)?((r=a(n,t.props)).ref=An(e,n,t),r.return=e,r):((r=Dl(t.type,t.key,t.props,null,e.mode,r)).ref=An(e,n,t),r.return=e,r)}function f(e,n,t,r){return null===n||4!==n.tag||n.stateNode.containerInfo!==t.containerInfo||n.stateNode.implementation!==t.implementation?((n=Vl(t,e.mode,r)).return=e,n):((n=a(n,t.children||[])).return=e,n)}function d(e,n,t,r,l){return null===n||7!==n.tag?((n=Ol(t,e.mode,r,l)).return=e,n):((n=a(n,t)).return=e,n)}function p(e,n,t){if("string"==typeof n&&""!==n||"number"==typeof n)return(n=Ul(""+n,e.mode,t)).return=e,n;if("object"==typeof n&&null!==n){switch(n.$$typeof){case pa:return(t=Dl(n.type,n.key,n.props,null,e.mode,t)).ref=An(e,null,n),t.return=e,t;case ma:return(n=Vl(n,e.mode,t)).return=e,n;case Ea:return p(e,(0,n._init)(n._payload),t)}if(Ma(n)||o(n))return(n=Ol(n,e.mode,t,null)).return=e,n;Bn(e,n)}return null}function m(e,n,t,r){var l=null!==n?n.key:null;if("string"==typeof t&&""!==t||"number"==typeof t)return null!==l?null:s(e,n,""+t,r);if("object"==typeof t&&null!==t){switch(t.$$typeof){case pa:return t.key===l?c(e,n,t,r):null;case ma:return t.key===l?f(e,n,t,r):null;case Ea:return m(e,n,(l=t._init)(t._payload),r)}if(Ma(t)||o(t))return null!==l?null:d(e,n,t,r,null);Bn(e,t)}return null}function h(e,n,t,r,l){if("string"==typeof r&&""!==r||"number"==typeof r)return s(n,e=e.get(t)||null,""+r,l);if("object"==typeof r&&null!==r){switch(r.$$typeof){case pa:return c(n,e=e.get(null===r.key?t:r.key)||null,r,l);case ma:return f(n,e=e.get(null===r.key?t:r.key)||null,r,l);case Ea:return h(e,n,t,(0,r._init)(r._payload),l)}if(Ma(r)||o(r))return d(n,e=e.get(t)||null,r,l,null);Bn(n,r)}return null}function g(t,a,o,i){for(var s=null,c=null,f=a,d=a=0,g=null;null!==f&&d<o.length;d++){f.index>d?(g=f,f=null):g=f.sibling;var v=m(t,f,o[d],i);if(null===v){null===f&&(f=g);break}e&&f&&null===v.alternate&&n(t,f),a=u(v,a,d),null===c?s=v:c.sibling=v,c=v,f=g}if(d===o.length)return r(t,f),ki&&Pn(t,d),s;if(null===f){for(;d<o.length;d++)null!==(f=p(t,o[d],i))&&(a=u(f,a,d),null===c?s=f:c.sibling=f,c=f);return ki&&Pn(t,d),s}for(f=l(t,f);d<o.length;d++)null!==(g=h(f,t,d,o[d],i))&&(e&&null!==g.alternate&&f.delete(null===g.key?d:g.key),a=u(g,a,d),null===c?s=g:c.sibling=g,c=g);return e&&f.forEach((function(e){return n(t,e)})),ki&&Pn(t,d),s}function v(a,i,s,c){var f=o(s);if("function"!=typeof f)throw Error(t(150));if(null==(s=f.call(s)))throw Error(t(151));for(var d=f=null,g=i,v=i=0,y=null,b=s.next();null!==g&&!b.done;v++,b=s.next()){g.index>v?(y=g,g=null):y=g.sibling;var k=m(a,g,b.value,c);if(null===k){null===g&&(g=y);break}e&&g&&null===k.alternate&&n(a,g),i=u(k,i,v),null===d?f=k:d.sibling=k,d=k,g=y}if(b.done)return r(a,g),ki&&Pn(a,v),f;if(null===g){for(;!b.done;v++,b=s.next())null!==(b=p(a,b.value,c))&&(i=u(b,i,v),null===d?f=b:d.sibling=b,d=b);return ki&&Pn(a,v),f}for(g=l(a,g);!b.done;v++,b=s.next())null!==(b=h(g,a,v,b.value,c))&&(e&&null!==b.alternate&&g.delete(null===b.key?v:b.key),i=u(b,i,v),null===d?f=b:d.sibling=b,d=b);return e&&g.forEach((function(e){return n(a,e)})),ki&&Pn(a,v),f}return function e(t,l,u,s){if("object"==typeof u&&null!==u&&u.type===ha&&null===u.key&&(u=u.props.children),"object"==typeof u&&null!==u){switch(u.$$typeof){case pa:e:{for(var c=u.key,f=l;null!==f;){if(f.key===c){if((c=u.type)===ha){if(7===f.tag){r(t,f.sibling),(l=a(f,u.props.children)).return=t,t=l;break e}}else if(f.elementType===c||"object"==typeof c&&null!==c&&c.$$typeof===Ea&&Wn(c)===f.type){r(t,f.sibling),(l=a(f,u.props)).ref=An(t,f,u),l.return=t,t=l;break e}r(t,f);break}n(t,f),f=f.sibling}u.type===ha?((l=Ol(u.props.children,t.mode,s,u.key)).return=t,t=l):((s=Dl(u.type,u.key,u.props,null,t.mode,s)).ref=An(t,l,u),s.return=t,t=s)}return i(t);case ma:e:{for(f=u.key;null!==l;){if(l.key===f){if(4===l.tag&&l.stateNode.containerInfo===u.containerInfo&&l.stateNode.implementation===u.implementation){r(t,l.sibling),(l=a(l,u.children||[])).return=t,t=l;break e}r(t,l);break}n(t,l),l=l.sibling}(l=Vl(u,t.mode,s)).return=t,t=l}return i(t);case Ea:return e(t,l,(f=u._init)(u._payload),s)}if(Ma(u))return g(t,l,u,s);if(o(u))return v(t,l,u,s);Bn(t,u)}return"string"==typeof u&&""!==u||"number"==typeof u?(u=""+u,null!==l&&6===l.tag?(r(t,l.sibling),(l=a(l,u)).return=t,t=l):(r(t,l),(l=Ul(u,t.mode,s)).return=t,t=l),i(t)):r(t,l)}}function Qn(){Pi=Ni=zi=null}function jn(e,n){n=Ci.current,yn(Ci),e._currentValue=n}function $n(e,n,t){for(;null!==e;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,null!==r&&(r.childLanes|=n)):null!==r&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function qn(e,n){zi=e,Pi=Ni=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(0!=(e.lanes&n)&&(ns=!0),e.firstContext=null)}function Kn(e){var n=e._currentValue;if(Pi!==e)if(e={context:e,memoizedValue:n,next:null},null===Ni){if(null===zi)throw Error(t(308));Ni=e,zi.dependencies={lanes:0,firstContext:e}}else Ni=Ni.next=e;return n}function Yn(e){null===_i?_i=[e]:_i.push(e)}function Xn(e,n,t,r){var l=n.interleaved;return null===l?(t.next=t,Yn(n)):(t.next=l.next,l.next=t),n.interleaved=t,Gn(e,r)}function Gn(e,n){e.lanes|=n;var t=e.alternate;for(null!==t&&(t.lanes|=n),t=e,e=e.return;null!==e;)e.childLanes|=n,null!==(t=e.alternate)&&(t.childLanes|=n),t=e,e=e.return;return 3===t.tag?t.stateNode:null}function Zn(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Jn(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function et(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function nt(e,n,t){var r=e.updateQueue;if(null===r)return null;if(r=r.shared,0!=(2&ys)){var l=r.pending;return null===l?n.next=n:(n.next=l.next,l.next=n),r.pending=n,Li(e,t)}return null===(l=r.interleaved)?(n.next=n,Yn(r)):(n.next=l.next,l.next=n),r.interleaved=n,Gn(e,t)}function tt(e,n,t){if(null!==(n=n.updateQueue)&&(n=n.shared,0!=(4194240&t))){var r=n.lanes;t|=r&=e.pendingLanes,n.lanes=t,ne(e,t)}}function rt(e,n){var t=e.updateQueue,r=e.alternate;if(null!==r&&t===(r=r.updateQueue)){var l=null,a=null;if(null!==(t=t.firstBaseUpdate)){do{var u={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};null===a?l=a=u:a=a.next=u,t=t.next}while(null!==t);null===a?l=a=n:a=a.next=n}else l=a=n;return t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:a,shared:r.shared,effects:r.effects},void(e.updateQueue=t)}null===(e=t.lastBaseUpdate)?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function lt(e,n,t,r){var l=e.updateQueue;Ti=!1;var a=l.firstBaseUpdate,u=l.lastBaseUpdate,o=l.shared.pending;if(null!==o){l.shared.pending=null;var i=o,s=i.next;i.next=null,null===u?a=s:u.next=s,u=i;var c=e.alternate;null!==c&&(o=(c=c.updateQueue).lastBaseUpdate)!==u&&(null===o?c.firstBaseUpdate=s:o.next=s,c.lastBaseUpdate=i)}if(null!==a){var f=l.baseState;for(u=0,c=s=i=null,o=a;;){var d=o.lane,p=o.eventTime;if((r&d)===d){null!==c&&(c=c.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var m=e,h=o;switch(d=n,p=t,h.tag){case 1:if("function"==typeof(m=h.payload)){f=m.call(p,f,d);break e}f=m;break e;case 3:m.flags=-65537&m.flags|128;case 0:if(null==(d="function"==typeof(m=h.payload)?m.call(p,f,d):m))break e;f=La({},f,d);break e;case 2:Ti=!0}}null!==o.callback&&0!==o.lane&&(e.flags|=64,null===(d=l.effects)?l.effects=[o]:d.push(o))}else p={eventTime:p,lane:d,tag:o.tag,payload:o.payload,callback:o.callback,next:null},null===c?(s=c=p,i=f):c=c.next=p,u|=d;if(null===(o=o.next)){if(null===(o=l.shared.pending))break;o=(d=o).next,d.next=null,l.lastBaseUpdate=d,l.shared.pending=null}}if(null===c&&(i=f),l.baseState=i,l.firstBaseUpdate=s,l.lastBaseUpdate=c,null!==(n=l.shared.interleaved)){l=n;do{u|=l.lane,l=l.next}while(l!==n)}else null===a&&(l.shared.lanes=0);zs|=u,e.lanes=u,e.memoizedState=f}}function at(e,n,r){if(e=n.effects,n.effects=null,null!==e)for(n=0;n<e.length;n++){var l=e[n],a=l.callback;if(null!==a){if(l.callback=null,l=r,"function"!=typeof a)throw Error(t(191,a));a.call(l)}}}function ut(e){if(e===Mi)throw Error(t(174));return e}function ot(e,n){switch(bn(Di,n),bn(Ri,e),bn(Fi,Mi),e=n.nodeType){case 9:case 11:n=(n=n.documentElement)?n.namespaceURI:L(null,"");break;default:n=L(n=(e=8===e?n.parentNode:n).namespaceURI||null,e=e.tagName)}yn(Fi),bn(Fi,n)}function it(e){yn(Fi),yn(Ri),yn(Di)}function st(e){ut(Di.current);var n=ut(Fi.current),t=L(n,e.type);n!==t&&(bn(Ri,e),bn(Fi,t))}function ct(e){Ri.current===e&&(yn(Fi),yn(Ri))}function ft(e){for(var n=e;null!==n;){if(13===n.tag){var t=n.memoizedState;if(null!==t&&(null===(t=t.dehydrated)||"$?"===t.data||"$!"===t.data))return n}else if(19===n.tag&&void 0!==n.memoizedProps.revealOrder){if(0!=(128&n.flags))return n}else if(null!==n.child){n.child.return=n,n=n.child;continue}if(n===e)break;for(;null===n.sibling;){if(null===n.return||n.return===e)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}return null}function dt(){for(var e=0;e<Ii.length;e++)Ii[e]._workInProgressVersionPrimary=null;Ii.length=0}function pt(){throw Error(t(321))}function mt(e,n){if(null===n)return!1;for(var t=0;t<n.length&&t<e.length;t++)if(!wo(e[t],n[t]))return!1;return!0}function ht(e,n,r,l,a,u){if(Ai=u,Bi=n,n.memoizedState=null,n.updateQueue=null,n.lanes=0,Ui.current=null===e||null===e.memoizedState?Yi:Xi,e=r(l,a),ji){u=0;do{if(ji=!1,$i=0,25<=u)throw Error(t(301));u+=1,Hi=Wi=null,n.updateQueue=null,Ui.current=Gi,e=r(l,a)}while(ji)}if(Ui.current=Ki,n=null!==Wi&&null!==Wi.next,Ai=0,Hi=Wi=Bi=null,Qi=!1,n)throw Error(t(300));return e}function gt(){var e=0!==$i;return $i=0,e}function vt(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===Hi?Bi.memoizedState=Hi=e:Hi=Hi.next=e,Hi}function yt(){if(null===Wi){var e=Bi.alternate;e=null!==e?e.memoizedState:null}else e=Wi.next;var n=null===Hi?Bi.memoizedState:Hi.next;if(null!==n)Hi=n,Wi=e;else{if(null===e)throw Error(t(310));e={memoizedState:(Wi=e).memoizedState,baseState:Wi.baseState,baseQueue:Wi.baseQueue,queue:Wi.queue,next:null},null===Hi?Bi.memoizedState=Hi=e:Hi=Hi.next=e}return Hi}function bt(e,n){return"function"==typeof n?n(e):n}function kt(e,n,r){if(null===(r=(n=yt()).queue))throw Error(t(311));r.lastRenderedReducer=e;var l=Wi,a=l.baseQueue,u=r.pending;if(null!==u){if(null!==a){var o=a.next;a.next=u.next,u.next=o}l.baseQueue=a=u,r.pending=null}if(null!==a){u=a.next,l=l.baseState;var i=o=null,s=null,c=u;do{var f=c.lane;if((Ai&f)===f)null!==s&&(s=s.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),l=c.hasEagerState?c.eagerState:e(l,c.action);else{var d={lane:f,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};null===s?(i=s=d,o=l):s=s.next=d,Bi.lanes|=f,zs|=f}c=c.next}while(null!==c&&c!==u);null===s?o=l:s.next=i,wo(l,n.memoizedState)||(ns=!0),n.memoizedState=l,n.baseState=o,n.baseQueue=s,r.lastRenderedState=l}if(null!==(e=r.interleaved)){a=e;do{u=a.lane,Bi.lanes|=u,zs|=u,a=a.next}while(a!==e)}else null===a&&(r.lanes=0);return[n.memoizedState,r.dispatch]}function wt(e,n,r){if(null===(r=(n=yt()).queue))throw Error(t(311));r.lastRenderedReducer=e;var l=r.dispatch,a=r.pending,u=n.memoizedState;if(null!==a){r.pending=null;var o=a=a.next;do{u=e(u,o.action),o=o.next}while(o!==a);wo(u,n.memoizedState)||(ns=!0),n.memoizedState=u,null===n.baseQueue&&(n.baseState=u),r.lastRenderedState=u}return[u,l]}function St(e,n,t){}function xt(e,n,r){r=Bi;var l=yt(),a=n(),u=!wo(l.memoizedState,a);if(u&&(l.memoizedState=a,ns=!0),l=l.queue,Dt(zt.bind(null,r,l,e),[e]),l.getSnapshot!==n||u||null!==Hi&&1&Hi.memoizedState.tag){if(r.flags|=2048,Lt(9,Ct.bind(null,r,l,a,n),void 0,null),null===bs)throw Error(t(349));0!=(30&Ai)||Et(r,n,a)}return a}function Et(e,n,t){e.flags|=16384,e={getSnapshot:n,value:t},null===(n=Bi.updateQueue)?(n={lastEffect:null,stores:null},Bi.updateQueue=n,n.stores=[e]):null===(t=n.stores)?n.stores=[e]:t.push(e)}function Ct(e,n,t,r){n.value=t,n.getSnapshot=r,Nt(n)&&Pt(e)}function zt(e,n,t){return t((function(){Nt(n)&&Pt(e)}))}function Nt(e){var n=e.getSnapshot;e=e.value;try{var t=n();return!wo(e,t)}catch(e){return!0}}function Pt(e){var n=Gn(e,1);null!==n&&al(n,e,1,-1)}function _t(e){var n=vt();return"function"==typeof e&&(e=e()),n.memoizedState=n.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:bt,lastRenderedState:e},n.queue=e,e=e.dispatch=qt.bind(null,Bi,e),[n.memoizedState,e]}function Lt(e,n,t,r){return e={tag:e,create:n,destroy:t,deps:r,next:null},null===(n=Bi.updateQueue)?(n={lastEffect:null,stores:null},Bi.updateQueue=n,n.lastEffect=e.next=e):null===(t=n.lastEffect)?n.lastEffect=e.next=e:(r=t.next,t.next=e,e.next=r,n.lastEffect=e),e}function Tt(e){return yt().memoizedState}function Mt(e,n,t,r){var l=vt();Bi.flags|=e,l.memoizedState=Lt(1|n,t,void 0,void 0===r?null:r)}function Ft(e,n,t,r){var l=yt();r=void 0===r?null:r;var a=void 0;if(null!==Wi){var u=Wi.memoizedState;if(a=u.destroy,null!==r&&mt(r,u.deps))return void(l.memoizedState=Lt(n,t,a,r))}Bi.flags|=e,l.memoizedState=Lt(1|n,t,a,r)}function Rt(e,n){return Mt(8390656,8,e,n)}function Dt(e,n){return Ft(2048,8,e,n)}function Ot(e,n){return Ft(4,2,e,n)}function It(e,n){return Ft(4,4,e,n)}function Ut(e,n){return"function"==typeof n?(e=e(),n(e),function(){n(null)}):null!=n?(e=e(),n.current=e,function(){n.current=null}):void 0}function Vt(e,n,t){return t=null!=t?t.concat([e]):null,Ft(4,4,Ut.bind(null,n,e),t)}function At(e,n){}function Bt(e,n){var t=yt();n=void 0===n?null:n;var r=t.memoizedState;return null!==r&&null!==n&&mt(n,r[1])?r[0]:(t.memoizedState=[e,n],e)}function Wt(e,n){var t=yt();n=void 0===n?null:n;var r=t.memoizedState;return null!==r&&null!==n&&mt(n,r[1])?r[0]:(e=e(),t.memoizedState=[e,n],e)}function Ht(e,n,t){return 0==(21&Ai)?(e.baseState&&(e.baseState=!1,ns=!0),e.memoizedState=t):(wo(t,n)||(t=Z(),Bi.lanes|=t,zs|=t,e.baseState=!0),n)}function Qt(e,n,t){xu=0!==(t=xu)&&4>t?t:4,e(!0);var r=Vi.transition;Vi.transition={};try{e(!1),n()}finally{xu=t,Vi.transition=r}}function jt(){return yt().memoizedState}function $t(e,n,t){var r=ll(e);t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},Kt(e)?Yt(n,t):null!==(t=Xn(e,n,t,r))&&(al(t,e,r,rl()),Xt(t,n,r))}function qt(e,n,t){var r=ll(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(Kt(e))Yt(n,l);else{var a=e.alternate;if(0===e.lanes&&(null===a||0===a.lanes)&&null!==(a=n.lastRenderedReducer))try{var u=n.lastRenderedState,o=a(u,t);if(l.hasEagerState=!0,l.eagerState=o,wo(o,u)){var i=n.interleaved;return null===i?(l.next=l,Yn(n)):(l.next=i.next,i.next=l),void(n.interleaved=l)}}catch(e){}null!==(t=Xn(e,n,l,r))&&(al(t,e,r,l=rl()),Xt(t,n,r))}}function Kt(e){var n=e.alternate;return e===Bi||null!==n&&n===Bi}function Yt(e,n){ji=Qi=!0;var t=e.pending;null===t?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function Xt(e,n,t){if(0!=(4194240&t)){var r=n.lanes;t|=r&=e.pendingLanes,n.lanes=t,ne(e,t)}}function Gt(e,n){if(e&&e.defaultProps){for(var t in n=La({},n),e=e.defaultProps)void 0===n[t]&&(n[t]=e[t]);return n}return n}function Zt(e,n,t,r){t=null==(t=t(r,n=e.memoizedState))?n:La({},n,t),e.memoizedState=t,0===e.lanes&&(e.updateQueue.baseState=t)}function Jt(e,n,t,r,l,a,u){return"function"==typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,a,u):!(n.prototype&&n.prototype.isPureReactComponent&&Oe(t,r)&&Oe(l,a))}function er(e,n,t){var r=!1,l=ti,a=n.contextType;return"object"==typeof a&&null!==a?a=Kn(a):(l=wn(n)?ai:ri.current,a=(r=null!=(r=n.contextTypes))?kn(e,l):ti),n=new n(t,a),e.memoizedState=null!==n.state&&void 0!==n.state?n.state:null,n.updater=Zi,e.stateNode=n,n._reactInternals=e,r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=a),n}function nr(e,n,t,r){e=n.state,"function"==typeof n.componentWillReceiveProps&&n.componentWillReceiveProps(t,r),"function"==typeof n.UNSAFE_componentWillReceiveProps&&n.UNSAFE_componentWillReceiveProps(t,r),n.state!==e&&Zi.enqueueReplaceState(n,n.state,null)}function tr(e,n,t,r){var l=e.stateNode;l.props=t,l.state=e.memoizedState,l.refs={},Zn(e);var a=n.contextType;"object"==typeof a&&null!==a?l.context=Kn(a):(a=wn(n)?ai:ri.current,l.context=kn(e,a)),l.state=e.memoizedState,"function"==typeof(a=n.getDerivedStateFromProps)&&(Zt(e,n,a,t),l.state=e.memoizedState),"function"==typeof n.getDerivedStateFromProps||"function"==typeof l.getSnapshotBeforeUpdate||"function"!=typeof l.UNSAFE_componentWillMount&&"function"!=typeof l.componentWillMount||(n=l.state,"function"==typeof l.componentWillMount&&l.componentWillMount(),"function"==typeof l.UNSAFE_componentWillMount&&l.UNSAFE_componentWillMount(),n!==l.state&&Zi.enqueueReplaceState(l,l.state,null),lt(e,t,l,r),l.state=e.memoizedState),"function"==typeof l.componentDidMount&&(e.flags|=4194308)}function rr(e,n){try{var t="",r=n;do{t+=c(r),r=r.return}while(r);var l=t}catch(e){l="\nError generating stack: "+e.message+"\n"+e.stack}return{value:e,source:n,stack:l,digest:null}}function lr(e,n,t){return{value:e,source:null,stack:null!=t?t:null,digest:null!=n?n:null}}function ar(e,n){try{console.error(n.value)}catch(e){setTimeout((function(){throw e}))}}function ur(e,n,t){(t=et(-1,t)).tag=3,t.payload={element:null};var r=n.value;return t.callback=function(){Rs||(Rs=!0,Ds=r),ar(0,n)},t}function or(e,n,t){(t=et(-1,t)).tag=3;var r=e.type.getDerivedStateFromError;if("function"==typeof r){var l=n.value;t.payload=function(){return r(l)},t.callback=function(){ar(0,n)}}var a=e.stateNode;return null!==a&&"function"==typeof a.componentDidCatch&&(t.callback=function(){ar(0,n),"function"!=typeof r&&(null===Os?Os=new Set([this]):Os.add(this));var e=n.stack;this.componentDidCatch(n.value,{componentStack:null!==e?e:""})}),t}function ir(e,n,t){var r=e.pingCache;if(null===r){r=e.pingCache=new Ji;var l=new Set;r.set(n,l)}else void 0===(l=r.get(n))&&(l=new Set,r.set(n,l));l.has(t)||(l.add(t),e=Nl.bind(null,e,n,t),n.then(e,e))}function sr(e){do{var n;if((n=13===e.tag)&&(n=null===(n=e.memoizedState)||null!==n.dehydrated),n)return e;e=e.return}while(null!==e);return null}function cr(e,n,t,r,l){return 0==(1&e.mode)?(e===n?e.flags|=65536:(e.flags|=128,t.flags|=131072,t.flags&=-52805,1===t.tag&&(null===t.alternate?t.tag=17:((n=et(-1,1)).tag=2,nt(t,n,1))),t.lanes|=1),e):(e.flags|=65536,e.lanes=l,e)}function fr(e,n,t,r){n.child=null===e?Ei(n,null,t,r):xi(n,e.child,t,r)}function dr(e,n,t,r,l){t=t.render;var a=n.ref;return qn(n,l),r=ht(e,n,t,r,a,l),t=gt(),null===e||ns?(ki&&t&&Ln(n),n.flags|=1,fr(e,n,r,l),n.child):(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~l,Lr(e,n,l))}function pr(e,n,t,r,l){if(null===e){var a=t.type;return"function"!=typeof a||Fl(a)||void 0!==a.defaultProps||null!==t.compare||void 0!==t.defaultProps?((e=Dl(t.type,null,r,n,n.mode,l)).ref=n.ref,e.return=n,n.child=e):(n.tag=15,n.type=a,mr(e,n,a,r,l))}if(a=e.child,0==(e.lanes&l)){var u=a.memoizedProps;if((t=null!==(t=t.compare)?t:Oe)(u,r)&&e.ref===n.ref)return Lr(e,n,l)}return n.flags|=1,(e=Rl(a,r)).ref=n.ref,e.return=n,n.child=e}function mr(e,n,t,r,l){if(null!==e){var a=e.memoizedProps;if(Oe(a,r)&&e.ref===n.ref){if(ns=!1,n.pendingProps=r=a,0==(e.lanes&l))return n.lanes=e.lanes,Lr(e,n,l);0!=(131072&e.flags)&&(ns=!0)}}return vr(e,n,t,r,l)}function hr(e,n,t){var r=n.pendingProps,l=r.children,a=null!==e?e.memoizedState:null;if("hidden"===r.mode)if(0==(1&n.mode))n.memoizedState={baseLanes:0,cachePool:null,transitions:null},bn(xs,Ss),Ss|=t;else{if(0==(1073741824&t))return e=null!==a?a.baseLanes|t:t,n.lanes=n.childLanes=1073741824,n.memoizedState={baseLanes:e,cachePool:null,transitions:null},n.updateQueue=null,bn(xs,Ss),Ss|=e,null;n.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=null!==a?a.baseLanes:t,bn(xs,Ss),Ss|=r}else null!==a?(r=a.baseLanes|t,n.memoizedState=null):r=t,bn(xs,Ss),Ss|=r;return fr(e,n,l,t),n.child}function gr(e,n){var t=n.ref;(null===e&&null!==t||null!==e&&e.ref!==t)&&(n.flags|=512,n.flags|=2097152)}function vr(e,n,t,r,l){var a=wn(t)?ai:ri.current;return a=kn(n,a),qn(n,l),t=ht(e,n,t,r,a,l),r=gt(),null===e||ns?(ki&&r&&Ln(n),n.flags|=1,fr(e,n,t,l),n.child):(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~l,Lr(e,n,l))}function yr(e,n,t,r,l){if(wn(t)){var a=!0;En(n)}else a=!1;if(qn(n,l),null===n.stateNode)_r(e,n),er(n,t,r),tr(n,t,r,l),r=!0;else if(null===e){var u=n.stateNode,o=n.memoizedProps;u.props=o;var i=u.context,s=t.contextType;s="object"==typeof s&&null!==s?Kn(s):kn(n,s=wn(t)?ai:ri.current);var c=t.getDerivedStateFromProps,f="function"==typeof c||"function"==typeof u.getSnapshotBeforeUpdate;f||"function"!=typeof u.UNSAFE_componentWillReceiveProps&&"function"!=typeof u.componentWillReceiveProps||(o!==r||i!==s)&&nr(n,u,r,s),Ti=!1;var d=n.memoizedState;u.state=d,lt(n,r,u,l),i=n.memoizedState,o!==r||d!==i||li.current||Ti?("function"==typeof c&&(Zt(n,t,c,r),i=n.memoizedState),(o=Ti||Jt(n,t,o,r,d,i,s))?(f||"function"!=typeof u.UNSAFE_componentWillMount&&"function"!=typeof u.componentWillMount||("function"==typeof u.componentWillMount&&u.componentWillMount(),"function"==typeof u.UNSAFE_componentWillMount&&u.UNSAFE_componentWillMount()),"function"==typeof u.componentDidMount&&(n.flags|=4194308)):("function"==typeof u.componentDidMount&&(n.flags|=4194308),n.memoizedProps=r,n.memoizedState=i),u.props=r,u.state=i,u.context=s,r=o):("function"==typeof u.componentDidMount&&(n.flags|=4194308),r=!1)}else{u=n.stateNode,Jn(e,n),o=n.memoizedProps,s=n.type===n.elementType?o:Gt(n.type,o),u.props=s,f=n.pendingProps,d=u.context,i="object"==typeof(i=t.contextType)&&null!==i?Kn(i):kn(n,i=wn(t)?ai:ri.current);var p=t.getDerivedStateFromProps;(c="function"==typeof p||"function"==typeof u.getSnapshotBeforeUpdate)||"function"!=typeof u.UNSAFE_componentWillReceiveProps&&"function"!=typeof u.componentWillReceiveProps||(o!==f||d!==i)&&nr(n,u,r,i),Ti=!1,d=n.memoizedState,u.state=d,lt(n,r,u,l);var m=n.memoizedState;o!==f||d!==m||li.current||Ti?("function"==typeof p&&(Zt(n,t,p,r),m=n.memoizedState),(s=Ti||Jt(n,t,s,r,d,m,i)||!1)?(c||"function"!=typeof u.UNSAFE_componentWillUpdate&&"function"!=typeof u.componentWillUpdate||("function"==typeof u.componentWillUpdate&&u.componentWillUpdate(r,m,i),"function"==typeof u.UNSAFE_componentWillUpdate&&u.UNSAFE_componentWillUpdate(r,m,i)),"function"==typeof u.componentDidUpdate&&(n.flags|=4),"function"==typeof u.getSnapshotBeforeUpdate&&(n.flags|=1024)):("function"!=typeof u.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=4),"function"!=typeof u.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=1024),n.memoizedProps=r,n.memoizedState=m),u.props=r,u.state=m,u.context=i,r=s):("function"!=typeof u.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=4),"function"!=typeof u.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=1024),r=!1)}return br(e,n,t,r,a,l)}function br(e,n,t,r,l,a){gr(e,n);var u=0!=(128&n.flags);if(!r&&!u)return l&&Cn(n,t,!1),Lr(e,n,a);r=n.stateNode,es.current=n;var o=u&&"function"!=typeof t.getDerivedStateFromError?null:r.render();return n.flags|=1,null!==e&&u?(n.child=xi(n,e.child,null,a),n.child=xi(n,null,o,a)):fr(e,n,o,a),n.memoizedState=r.state,l&&Cn(n,t,!0),n.child}function kr(e){var n=e.stateNode;n.pendingContext?Sn(0,n.pendingContext,n.pendingContext!==n.context):n.context&&Sn(0,n.context,!1),ot(e,n.containerInfo)}function wr(e,n,t,r,l){return Un(),Vn(l),n.flags|=256,fr(e,n,t,r),n.child}function Sr(e){return{baseLanes:e,cachePool:null,transitions:null}}function xr(e,n,r){var l,a=n.pendingProps,u=Oi.current,o=!1,i=0!=(128&n.flags);if((l=i)||(l=(null===e||null!==e.memoizedState)&&0!=(2&u)),l?(o=!0,n.flags&=-129):null!==e&&null===e.memoizedState||(u|=1),bn(Oi,1&u),null===e)return Dn(n),null!==(e=n.memoizedState)&&null!==(e=e.dehydrated)?(0==(1&n.mode)?n.lanes=1:"$!"===e.data?n.lanes=8:n.lanes=1073741824,null):(i=a.children,e=a.fallback,o?(a=n.mode,o=n.child,i={mode:"hidden",children:i},0==(1&a)&&null!==o?(o.childLanes=0,o.pendingProps=i):o=Il(i,a,0,null),e=Ol(e,a,r,null),o.return=n,e.return=n,o.sibling=e,n.child=o,n.child.memoizedState=Sr(r),n.memoizedState=ts,e):Er(n,i));if(null!==(u=e.memoizedState)&&null!==(l=u.dehydrated))return function(e,n,r,l,a,u,o){if(r)return 256&n.flags?(n.flags&=-257,Cr(e,n,o,l=lr(Error(t(422))))):null!==n.memoizedState?(n.child=e.child,n.flags|=128,null):(u=l.fallback,a=n.mode,l=Il({mode:"visible",children:l.children},a,0,null),(u=Ol(u,a,o,null)).flags|=2,l.return=n,u.return=n,l.sibling=u,n.child=l,0!=(1&n.mode)&&xi(n,e.child,null,o),n.child.memoizedState=Sr(o),n.memoizedState=ts,u);if(0==(1&n.mode))return Cr(e,n,o,null);if("$!"===a.data){if(l=a.nextSibling&&a.nextSibling.dataset)var i=l.dgst;return l=i,Cr(e,n,o,l=lr(u=Error(t(419)),l,void 0))}if(i=0!=(o&e.childLanes),ns||i){if(null!==(l=bs)){switch(o&-o){case 4:a=2;break;case 16:a=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:a=32;break;case 536870912:a=268435456;break;default:a=0}0!==(a=0!=(a&(l.suspendedLanes|o))?0:a)&&a!==u.retryLane&&(u.retryLane=a,Gn(e,a),al(l,e,a,-1))}return vl(),Cr(e,n,o,l=lr(Error(t(421))))}return"$?"===a.data?(n.flags|=128,n.child=e.child,n=_l.bind(null,e),a._reactRetry=n,null):(e=u.treeContext,bi=fn(a.nextSibling),yi=n,ki=!0,wi=null,null!==e&&(pi[mi++]=gi,pi[mi++]=vi,pi[mi++]=hi,gi=e.id,vi=e.overflow,hi=n),(n=Er(n,l.children)).flags|=4096,n)}(e,n,i,a,l,u,r);if(o){o=a.fallback,i=n.mode,l=(u=e.child).sibling;var s={mode:"hidden",children:a.children};return 0==(1&i)&&n.child!==u?((a=n.child).childLanes=0,a.pendingProps=s,n.deletions=null):(a=Rl(u,s)).subtreeFlags=14680064&u.subtreeFlags,null!==l?o=Rl(l,o):(o=Ol(o,i,r,null)).flags|=2,o.return=n,a.return=n,a.sibling=o,n.child=a,a=o,o=n.child,i=null===(i=e.child.memoizedState)?Sr(r):{baseLanes:i.baseLanes|r,cachePool:null,transitions:i.transitions},o.memoizedState=i,o.childLanes=e.childLanes&~r,n.memoizedState=ts,a}return e=(o=e.child).sibling,a=Rl(o,{mode:"visible",children:a.children}),0==(1&n.mode)&&(a.lanes=r),a.return=n,a.sibling=null,null!==e&&(null===(r=n.deletions)?(n.deletions=[e],n.flags|=16):r.push(e)),n.child=a,n.memoizedState=null,a}function Er(e,n,t){return(n=Il({mode:"visible",children:n},e.mode,0,null)).return=e,e.child=n}function Cr(e,n,t,r){return null!==r&&Vn(r),xi(n,e.child,null,t),(e=Er(n,n.pendingProps.children)).flags|=2,n.memoizedState=null,e}function zr(e,n,t){e.lanes|=n;var r=e.alternate;null!==r&&(r.lanes|=n),$n(e.return,n,t)}function Nr(e,n,t,r,l){var a=e.memoizedState;null===a?e.memoizedState={isBackwards:n,rendering:null,renderingStartTime:0,last:r,tail:t,tailMode:l}:(a.isBackwards=n,a.rendering=null,a.renderingStartTime=0,a.last=r,a.tail=t,a.tailMode=l)}function Pr(e,n,t){var r=n.pendingProps,l=r.revealOrder,a=r.tail;if(fr(e,n,r.children,t),0!=(2&(r=Oi.current)))r=1&r|2,n.flags|=128;else{if(null!==e&&0!=(128&e.flags))e:for(e=n.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&zr(e,t,n);else if(19===e.tag)zr(e,t,n);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===n)break e;for(;null===e.sibling;){if(null===e.return||e.return===n)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(bn(Oi,r),0==(1&n.mode))n.memoizedState=null;else switch(l){case"forwards":for(t=n.child,l=null;null!==t;)null!==(e=t.alternate)&&null===ft(e)&&(l=t),t=t.sibling;null===(t=l)?(l=n.child,n.child=null):(l=t.sibling,t.sibling=null),Nr(n,!1,l,t,a);break;case"backwards":for(t=null,l=n.child,n.child=null;null!==l;){if(null!==(e=l.alternate)&&null===ft(e)){n.child=l;break}e=l.sibling,l.sibling=t,t=l,l=e}Nr(n,!0,t,null,a);break;case"together":Nr(n,!1,null,null,void 0);break;default:n.memoizedState=null}return n.child}function _r(e,n){0==(1&n.mode)&&null!==e&&(e.alternate=null,n.alternate=null,n.flags|=2)}function Lr(e,n,r){if(null!==e&&(n.dependencies=e.dependencies),zs|=n.lanes,0==(r&n.childLanes))return null;if(null!==e&&n.child!==e.child)throw Error(t(153));if(null!==n.child){for(r=Rl(e=n.child,e.pendingProps),n.child=r,r.return=n;null!==e.sibling;)e=e.sibling,(r=r.sibling=Rl(e,e.pendingProps)).return=n;r.sibling=null}return n.child}function Tr(e,n){if(!ki)switch(e.tailMode){case"hidden":n=e.tail;for(var t=null;null!==n;)null!==n.alternate&&(t=n),n=n.sibling;null===t?e.tail=null:t.sibling=null;break;case"collapsed":t=e.tail;for(var r=null;null!==t;)null!==t.alternate&&(r=t),t=t.sibling;null===r?n||null===e.tail?e.tail=null:e.tail.sibling=null:r.sibling=null}}function Mr(e){var n=null!==e.alternate&&e.alternate.child===e.child,t=0,r=0;if(n)for(var l=e.child;null!==l;)t|=l.lanes|l.childLanes,r|=14680064&l.subtreeFlags,r|=14680064&l.flags,l.return=e,l=l.sibling;else for(l=e.child;null!==l;)t|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=t,n}function Fr(e,n,r){var l=n.pendingProps;switch(Tn(n),n.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Mr(n),null;case 1:case 17:return wn(n.type)&&(yn(li),yn(ri)),Mr(n),null;case 3:return l=n.stateNode,it(),yn(li),yn(ri),dt(),l.pendingContext&&(l.context=l.pendingContext,l.pendingContext=null),null!==e&&null!==e.child||(In(n)?n.flags|=4:null===e||e.memoizedState.isDehydrated&&0==(256&n.flags)||(n.flags|=1024,null!==wi&&(sl(wi),wi=null))),ls(e,n),Mr(n),null;case 5:ct(n);var a=ut(Di.current);if(r=n.type,null!==e&&null!=n.stateNode)as(e,n,r,l,a),e.ref!==n.ref&&(n.flags|=512,n.flags|=2097152);else{if(!l){if(null===n.stateNode)throw Error(t(166));return Mr(n),null}if(e=ut(Fi.current),In(n)){l=n.stateNode,r=n.type;var o=n.memoizedProps;switch(l[Ko]=n,l[Yo]=o,e=0!=(1&n.mode),r){case"dialog":Ye("cancel",l),Ye("close",l);break;case"iframe":case"object":case"embed":Ye("load",l);break;case"video":case"audio":for(a=0;a<Oo.length;a++)Ye(Oo[a],l);break;case"source":Ye("error",l);break;case"img":case"image":case"link":Ye("error",l),Ye("load",l);break;case"details":Ye("toggle",l);break;case"input":b(l,o),Ye("invalid",l);break;case"select":l._wrapperState={wasMultiple:!!o.multiple},Ye("invalid",l);break;case"textarea":z(l,o),Ye("invalid",l)}for(var i in F(r,o),a=null,o)if(o.hasOwnProperty(i)){var s=o[i];"children"===i?"string"==typeof s?l.textContent!==s&&(!0!==o.suppressHydrationWarning&&an(l.textContent,s,e),a=["children",s]):"number"==typeof s&&l.textContent!==""+s&&(!0!==o.suppressHydrationWarning&&an(l.textContent,s,e),a=["children",""+s]):ra.hasOwnProperty(i)&&null!=s&&"onScroll"===i&&Ye("scroll",l)}switch(r){case"input":h(l),S(l,o,!0);break;case"textarea":h(l),P(l);break;case"select":case"option":break;default:"function"==typeof o.onClick&&(l.onclick=un)}l=a,n.updateQueue=l,null!==l&&(n.flags|=4)}else{i=9===a.nodeType?a:a.ownerDocument,"http://www.w3.org/1999/xhtml"===e&&(e=_(r)),"http://www.w3.org/1999/xhtml"===e?"script"===r?((e=i.createElement("div")).innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):"string"==typeof l.is?e=i.createElement(r,{is:l.is}):(e=i.createElement(r),"select"===r&&(i=e,l.multiple?i.multiple=!0:l.size&&(i.size=l.size))):e=i.createElementNS(e,r),e[Ko]=n,e[Yo]=l,rs(e,n,!1,!1),n.stateNode=e;e:{switch(i=R(r,l),r){case"dialog":Ye("cancel",e),Ye("close",e),a=l;break;case"iframe":case"object":case"embed":Ye("load",e),a=l;break;case"video":case"audio":for(a=0;a<Oo.length;a++)Ye(Oo[a],e);a=l;break;case"source":Ye("error",e),a=l;break;case"img":case"image":case"link":Ye("error",e),Ye("load",e),a=l;break;case"details":Ye("toggle",e),a=l;break;case"input":b(e,l),a=y(e,l),Ye("invalid",e);break;case"option":default:a=l;break;case"select":e._wrapperState={wasMultiple:!!l.multiple},a=La({},l,{value:void 0}),Ye("invalid",e);break;case"textarea":z(e,l),a=C(e,l),Ye("invalid",e)}for(o in F(r,a),s=a)if(s.hasOwnProperty(o)){var c=s[o];"style"===o?M(e,c):"dangerouslySetInnerHTML"===o?null!=(c=c?c.__html:void 0)&&Fa(e,c):"children"===o?"string"==typeof c?("textarea"!==r||""!==c)&&Ra(e,c):"number"==typeof c&&Ra(e,""+c):"suppressContentEditableWarning"!==o&&"suppressHydrationWarning"!==o&&"autoFocus"!==o&&(ra.hasOwnProperty(o)?null!=c&&"onScroll"===o&&Ye("scroll",e):null!=c&&u(e,o,c,i))}switch(r){case"input":h(e),S(e,l,!1);break;case"textarea":h(e),P(e);break;case"option":null!=l.value&&e.setAttribute("value",""+p(l.value));break;case"select":e.multiple=!!l.multiple,null!=(o=l.value)?E(e,!!l.multiple,o,!1):null!=l.defaultValue&&E(e,!!l.multiple,l.defaultValue,!0);break;default:"function"==typeof a.onClick&&(e.onclick=un)}switch(r){case"button":case"input":case"select":case"textarea":l=!!l.autoFocus;break e;case"img":l=!0;break e;default:l=!1}}l&&(n.flags|=4)}null!==n.ref&&(n.flags|=512,n.flags|=2097152)}return Mr(n),null;case 6:if(e&&null!=n.stateNode)us(e,n,e.memoizedProps,l);else{if("string"!=typeof l&&null===n.stateNode)throw Error(t(166));if(r=ut(Di.current),ut(Fi.current),In(n)){if(l=n.stateNode,r=n.memoizedProps,l[Ko]=n,(o=l.nodeValue!==r)&&null!==(e=yi))switch(e.tag){case 3:an(l.nodeValue,r,0!=(1&e.mode));break;case 5:!0!==e.memoizedProps.suppressHydrationWarning&&an(l.nodeValue,r,0!=(1&e.mode))}o&&(n.flags|=4)}else(l=(9===r.nodeType?r:r.ownerDocument).createTextNode(l))[Ko]=n,n.stateNode=l}return Mr(n),null;case 13:if(yn(Oi),l=n.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(ki&&null!==bi&&0!=(1&n.mode)&&0==(128&n.flags)){for(o=bi;o;)o=fn(o.nextSibling);Un(),n.flags|=98560,o=!1}else if(o=In(n),null!==l&&null!==l.dehydrated){if(null===e){if(!o)throw Error(t(318));if(!(o=null!==(o=n.memoizedState)?o.dehydrated:null))throw Error(t(317));o[Ko]=n}else Un(),0==(128&n.flags)&&(n.memoizedState=null),n.flags|=4;Mr(n),o=!1}else null!==wi&&(sl(wi),wi=null),o=!0;if(!o)return 65536&n.flags?n:null}return 0!=(128&n.flags)?(n.lanes=r,n):((l=null!==l)!=(null!==e&&null!==e.memoizedState)&&l&&(n.child.flags|=8192,0!=(1&n.mode)&&(null===e||0!=(1&Oi.current)?0===Es&&(Es=3):vl())),null!==n.updateQueue&&(n.flags|=4),Mr(n),null);case 4:return it(),ls(e,n),null===e&&Ge(n.stateNode.containerInfo),Mr(n),null;case 10:return jn(n.type._context),Mr(n),null;case 19:if(yn(Oi),null===(o=n.memoizedState))return Mr(n),null;if(l=0!=(128&n.flags),null===(i=o.rendering))if(l)Tr(o,!1);else{if(0!==Es||null!==e&&0!=(128&e.flags))for(e=n.child;null!==e;){if(null!==(i=ft(e))){for(n.flags|=128,Tr(o,!1),null!==(l=i.updateQueue)&&(n.updateQueue=l,n.flags|=4),n.subtreeFlags=0,l=r,r=n.child;null!==r;)e=l,(o=r).flags&=14680066,null===(i=o.alternate)?(o.childLanes=0,o.lanes=e,o.child=null,o.subtreeFlags=0,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null,o.stateNode=null):(o.childLanes=i.childLanes,o.lanes=i.lanes,o.child=i.child,o.subtreeFlags=0,o.deletions=null,o.memoizedProps=i.memoizedProps,o.memoizedState=i.memoizedState,o.updateQueue=i.updateQueue,o.type=i.type,e=i.dependencies,o.dependencies=null===e?null:{lanes:e.lanes,firstContext:e.firstContext}),r=r.sibling;return bn(Oi,1&Oi.current|2),n.child}e=e.sibling}null!==o.tail&&su()>Ms&&(n.flags|=128,l=!0,Tr(o,!1),n.lanes=4194304)}else{if(!l)if(null!==(e=ft(i))){if(n.flags|=128,l=!0,null!==(r=e.updateQueue)&&(n.updateQueue=r,n.flags|=4),Tr(o,!0),null===o.tail&&"hidden"===o.tailMode&&!i.alternate&&!ki)return Mr(n),null}else 2*su()-o.renderingStartTime>Ms&&1073741824!==r&&(n.flags|=128,l=!0,Tr(o,!1),n.lanes=4194304);o.isBackwards?(i.sibling=n.child,n.child=i):(null!==(r=o.last)?r.sibling=i:n.child=i,o.last=i)}return null!==o.tail?(n=o.tail,o.rendering=n,o.tail=n.sibling,o.renderingStartTime=su(),n.sibling=null,r=Oi.current,bn(Oi,l?1&r|2:1&r),n):(Mr(n),null);case 22:case 23:return Ss=xs.current,yn(xs),l=null!==n.memoizedState,null!==e&&null!==e.memoizedState!==l&&(n.flags|=8192),l&&0!=(1&n.mode)?0!=(1073741824&Ss)&&(Mr(n),6&n.subtreeFlags&&(n.flags|=8192)):Mr(n),null;case 24:case 25:return null}throw Error(t(156,n.tag))}function Rr(e,n,r){switch(Tn(n),n.tag){case 1:return wn(n.type)&&(yn(li),yn(ri)),65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 3:return it(),yn(li),yn(ri),dt(),0!=(65536&(e=n.flags))&&0==(128&e)?(n.flags=-65537&e|128,n):null;case 5:return ct(n),null;case 13:if(yn(Oi),null!==(e=n.memoizedState)&&null!==e.dehydrated){if(null===n.alternate)throw Error(t(340));Un()}return 65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 19:return yn(Oi),null;case 4:return it(),null;case 10:return jn(n.type._context),null;case 22:case 23:return Ss=xs.current,yn(xs),null;default:return null}}function Dr(e,n){var t=e.ref;if(null!==t)if("function"==typeof t)try{t(null)}catch(t){zl(e,n,t)}else t.current=null}function Or(e,n,t){try{t()}catch(t){zl(e,n,t)}}function Ir(e,n,t){var r=n.updateQueue;if(null!==(r=null!==r?r.lastEffect:null)){var l=r=r.next;do{if((l.tag&e)===e){var a=l.destroy;l.destroy=void 0,void 0!==a&&Or(n,t,a)}l=l.next}while(l!==r)}}function Ur(e,n){if(null!==(n=null!==(n=n.updateQueue)?n.lastEffect:null)){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Vr(e){var n=e.ref;if(null!==n){var t=e.stateNode;e.tag,e=t,"function"==typeof n?n(e):n.current=e}}function Ar(e){var n=e.alternate;null!==n&&(e.alternate=null,Ar(n)),e.child=null,e.deletions=null,e.sibling=null,5===e.tag&&null!==(n=e.stateNode)&&(delete n[Ko],delete n[Yo],delete n[Go],delete n[Zo],delete n[Jo]),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Br(e){return 5===e.tag||3===e.tag||4===e.tag}function Wr(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||Br(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(2&e.flags)continue e;if(null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function Hr(e,n,t){var r=e.tag;if(5===r||6===r)e=e.stateNode,n?8===t.nodeType?t.parentNode.insertBefore(e,n):t.insertBefore(e,n):(8===t.nodeType?(n=t.parentNode).insertBefore(e,t):(n=t).appendChild(e),null!=(t=t._reactRootContainer)||null!==n.onclick||(n.onclick=un));else if(4!==r&&null!==(e=e.child))for(Hr(e,n,t),e=e.sibling;null!==e;)Hr(e,n,t),e=e.sibling}function Qr(e,n,t){var r=e.tag;if(5===r||6===r)e=e.stateNode,n?t.insertBefore(e,n):t.appendChild(e);else if(4!==r&&null!==(e=e.child))for(Qr(e,n,t),e=e.sibling;null!==e;)Qr(e,n,t),e=e.sibling}function jr(e,n,t){for(t=t.child;null!==t;)$r(e,n,t),t=t.sibling}function $r(e,n,t){if(vu&&"function"==typeof vu.onCommitFiberUnmount)try{vu.onCommitFiberUnmount(gu,t)}catch(e){}switch(t.tag){case 5:is||Dr(t,n);case 6:var r=ds,l=ps;ds=null,jr(e,n,t),ps=l,null!==(ds=r)&&(ps?(e=ds,t=t.stateNode,8===e.nodeType?e.parentNode.removeChild(t):e.removeChild(t)):ds.removeChild(t.stateNode));break;case 18:null!==ds&&(ps?(e=ds,t=t.stateNode,8===e.nodeType?cn(e.parentNode,t):1===e.nodeType&&cn(e,t),ce(e)):cn(ds,t.stateNode));break;case 4:r=ds,l=ps,ds=t.stateNode.containerInfo,ps=!0,jr(e,n,t),ds=r,ps=l;break;case 0:case 11:case 14:case 15:if(!is&&null!==(r=t.updateQueue)&&null!==(r=r.lastEffect)){l=r=r.next;do{var a=l,u=a.destroy;a=a.tag,void 0!==u&&(0!=(2&a)||0!=(4&a))&&Or(t,n,u),l=l.next}while(l!==r)}jr(e,n,t);break;case 1:if(!is&&(Dr(t,n),"function"==typeof(r=t.stateNode).componentWillUnmount))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(e){zl(t,n,e)}jr(e,n,t);break;case 21:jr(e,n,t);break;case 22:1&t.mode?(is=(r=is)||null!==t.memoizedState,jr(e,n,t),is=r):jr(e,n,t);break;default:jr(e,n,t)}}function qr(e){var n=e.updateQueue;if(null!==n){e.updateQueue=null;var t=e.stateNode;null===t&&(t=e.stateNode=new ss),n.forEach((function(n){var r=Ll.bind(null,e,n);t.has(n)||(t.add(n),n.then(r,r))}))}}function Kr(e,n,r){if(null!==(r=n.deletions))for(var l=0;l<r.length;l++){var a=r[l];try{var u=e,o=n,i=o;e:for(;null!==i;){switch(i.tag){case 5:ds=i.stateNode,ps=!1;break e;case 3:case 4:ds=i.stateNode.containerInfo,ps=!0;break e}i=i.return}if(null===ds)throw Error(t(160));$r(u,o,a),ds=null,ps=!1;var s=a.alternate;null!==s&&(s.return=null),a.return=null}catch(e){zl(a,n,e)}}if(12854&n.subtreeFlags)for(n=n.child;null!==n;)Yr(n,e),n=n.sibling}function Yr(e,n,r){var l=e.alternate;switch(r=e.flags,e.tag){case 0:case 11:case 14:case 15:if(Kr(n,e),Xr(e),4&r){try{Ir(3,e,e.return),Ur(3,e)}catch(n){zl(e,e.return,n)}try{Ir(5,e,e.return)}catch(n){zl(e,e.return,n)}}break;case 1:Kr(n,e),Xr(e),512&r&&null!==l&&Dr(l,l.return);break;case 5:if(Kr(n,e),Xr(e),512&r&&null!==l&&Dr(l,l.return),32&e.flags){var a=e.stateNode;try{Ra(a,"")}catch(n){zl(e,e.return,n)}}if(4&r&&null!=(a=e.stateNode)){var o=e.memoizedProps,i=null!==l?l.memoizedProps:o,s=e.type,c=e.updateQueue;if(e.updateQueue=null,null!==c)try{"input"===s&&"radio"===o.type&&null!=o.name&&k(a,o),R(s,i);var f=R(s,o);for(i=0;i<c.length;i+=2){var d=c[i],p=c[i+1];"style"===d?M(a,p):"dangerouslySetInnerHTML"===d?Fa(a,p):"children"===d?Ra(a,p):u(a,d,p,f)}switch(s){case"input":w(a,o);break;case"textarea":N(a,o);break;case"select":var m=a._wrapperState.wasMultiple;a._wrapperState.wasMultiple=!!o.multiple;var h=o.value;null!=h?E(a,!!o.multiple,h,!1):m!==!!o.multiple&&(null!=o.defaultValue?E(a,!!o.multiple,o.defaultValue,!0):E(a,!!o.multiple,o.multiple?[]:"",!1))}a[Yo]=o}catch(n){zl(e,e.return,n)}}break;case 6:if(Kr(n,e),Xr(e),4&r){if(null===e.stateNode)throw Error(t(162));a=e.stateNode,o=e.memoizedProps;try{a.nodeValue=o}catch(n){zl(e,e.return,n)}}break;case 3:if(Kr(n,e),Xr(e),4&r&&null!==l&&l.memoizedState.isDehydrated)try{ce(n.containerInfo)}catch(n){zl(e,e.return,n)}break;case 4:default:Kr(n,e),Xr(e);break;case 13:Kr(n,e),Xr(e),8192&(a=e.child).flags&&(o=null!==a.memoizedState,a.stateNode.isHidden=o,!o||null!==a.alternate&&null!==a.alternate.memoizedState||(Ts=su())),4&r&&qr(e);break;case 22:if(d=null!==l&&null!==l.memoizedState,1&e.mode?(is=(f=is)||d,Kr(n,e),is=f):Kr(n,e),Xr(e),8192&r){if(f=null!==e.memoizedState,(e.stateNode.isHidden=f)&&!d&&0!=(1&e.mode))for(cs=e,d=e.child;null!==d;){for(p=cs=d;null!==cs;){switch(h=(m=cs).child,m.tag){case 0:case 11:case 14:case 15:Ir(4,m,m.return);break;case 1:Dr(m,m.return);var g=m.stateNode;if("function"==typeof g.componentWillUnmount){r=m,n=m.return;try{l=r,g.props=l.memoizedProps,g.state=l.memoizedState,g.componentWillUnmount()}catch(e){zl(r,n,e)}}break;case 5:Dr(m,m.return);break;case 22:if(null!==m.memoizedState){el(p);continue}}null!==h?(h.return=m,cs=h):el(p)}d=d.sibling}e:for(d=null,p=e;;){if(5===p.tag){if(null===d){d=p;try{a=p.stateNode,f?"function"==typeof(o=a.style).setProperty?o.setProperty("display","none","important"):o.display="none":(s=p.stateNode,i=null!=(c=p.memoizedProps.style)&&c.hasOwnProperty("display")?c.display:null,s.style.display=T("display",i))}catch(n){zl(e,e.return,n)}}}else if(6===p.tag){if(null===d)try{p.stateNode.nodeValue=f?"":p.memoizedProps}catch(n){zl(e,e.return,n)}}else if((22!==p.tag&&23!==p.tag||null===p.memoizedState||p===e)&&null!==p.child){p.child.return=p,p=p.child;continue}if(p===e)break e;for(;null===p.sibling;){if(null===p.return||p.return===e)break e;d===p&&(d=null),p=p.return}d===p&&(d=null),p.sibling.return=p.return,p=p.sibling}}break;case 19:Kr(n,e),Xr(e),4&r&&qr(e);case 21:}}function Xr(e){var n=e.flags;if(2&n){try{e:{for(var r=e.return;null!==r;){if(Br(r)){var l=r;break e}r=r.return}throw Error(t(160))}switch(l.tag){case 5:var a=l.stateNode;32&l.flags&&(Ra(a,""),l.flags&=-33),Qr(e,Wr(e),a);break;case 3:case 4:var u=l.stateNode.containerInfo;Hr(e,Wr(e),u);break;default:throw Error(t(161))}}catch(n){zl(e,e.return,n)}e.flags&=-3}4096&n&&(e.flags&=-4097)}function Gr(e,n,t){cs=e,Zr(e,n,t)}function Zr(e,n,t){for(var r=0!=(1&e.mode);null!==cs;){var l=cs,a=l.child;if(22===l.tag&&r){var u=null!==l.memoizedState||os;if(!u){var o=l.alternate,i=null!==o&&null!==o.memoizedState||is;o=os;var s=is;if(os=u,(is=i)&&!s)for(cs=l;null!==cs;)i=(u=cs).child,22===u.tag&&null!==u.memoizedState?nl(l):null!==i?(i.return=u,cs=i):nl(l);for(;null!==a;)cs=a,Zr(a,n,t),a=a.sibling;cs=l,os=o,is=s}Jr(e,n,t)}else 0!=(8772&l.subtreeFlags)&&null!==a?(a.return=l,cs=a):Jr(e,n,t)}}function Jr(e,n,r){for(;null!==cs;){if(0!=(8772&(n=cs).flags)){r=n.alternate;try{if(0!=(8772&n.flags))switch(n.tag){case 0:case 11:case 15:is||Ur(5,n);break;case 1:var l=n.stateNode;if(4&n.flags&&!is)if(null===r)l.componentDidMount();else{var a=n.elementType===n.type?r.memoizedProps:Gt(n.type,r.memoizedProps);l.componentDidUpdate(a,r.memoizedState,l.__reactInternalSnapshotBeforeUpdate)}var u=n.updateQueue;null!==u&&at(n,u,l);break;case 3:var o=n.updateQueue;if(null!==o){if(r=null,null!==n.child)switch(n.child.tag){case 5:case 1:r=n.child.stateNode}at(n,o,r)}break;case 5:var i=n.stateNode;if(null===r&&4&n.flags){r=i;var s=n.memoizedProps;switch(n.type){case"button":case"input":case"select":case"textarea":s.autoFocus&&r.focus();break;case"img":s.src&&(r.src=s.src)}}break;case 6:case 4:case 12:case 19:case 17:case 21:case 22:case 23:case 25:break;case 13:if(null===n.memoizedState){var c=n.alternate;if(null!==c){var f=c.memoizedState;if(null!==f){var d=f.dehydrated;null!==d&&ce(d)}}}break;default:throw Error(t(163))}is||512&n.flags&&Vr(n)}catch(e){zl(n,n.return,e)}}if(n===e){cs=null;break}if(null!==(r=n.sibling)){r.return=n.return,cs=r;break}cs=n.return}}function el(e){for(;null!==cs;){var n=cs;if(n===e){cs=null;break}var t=n.sibling;if(null!==t){t.return=n.return,cs=t;break}cs=n.return}}function nl(e){for(;null!==cs;){var n=cs;try{switch(n.tag){case 0:case 11:case 15:var t=n.return;try{Ur(4,n)}catch(e){zl(n,t,e)}break;case 1:var r=n.stateNode;if("function"==typeof r.componentDidMount){var l=n.return;try{r.componentDidMount()}catch(e){zl(n,l,e)}}var a=n.return;try{Vr(n)}catch(e){zl(n,a,e)}break;case 5:var u=n.return;try{Vr(n)}catch(e){zl(n,u,e)}}}catch(e){zl(n,n.return,e)}if(n===e){cs=null;break}var o=n.sibling;if(null!==o){o.return=n.return,cs=o;break}cs=n.return}}function tl(){Ms=su()+500}function rl(){return 0!=(6&ys)?su():-1!==Ws?Ws:Ws=su()}function ll(e){return 0==(1&e.mode)?1:0!=(2&ys)&&0!==ws?ws&-ws:null!==Si.transition?(0===Hs&&(Hs=Z()),Hs):0!==(e=xu)?e:e=void 0===(e=window.event)?16:he(e.type)}function al(e,n,r,l){if(50<As)throw As=0,Bs=null,Error(t(185));ee(e,r,l),0!=(2&ys)&&e===bs||(e===bs&&(0==(2&ys)&&(Ns|=r),4===Es&&cl(e,ws)),ul(e,l),1===r&&0===ys&&0==(1&n.mode)&&(tl(),oi&&Nn()))}function ul(e,n){var t=e.callbackNode;!function(e,n){for(var t=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,a=e.pendingLanes;0<a;){var u=31-yu(a),o=1<<u,i=l[u];-1===i?0!=(o&t)&&0==(o&r)||(l[u]=X(o,n)):i<=n&&(e.expiredLanes|=o),a&=~o}}(e,n);var r=Y(e,e===bs?ws:0);if(0===r)null!==t&&uu(t),e.callbackNode=null,e.callbackPriority=0;else if(n=r&-r,e.callbackPriority!==n){if(null!=t&&uu(t),1===n)0===e.tag?function(e){oi=!0,zn(e)}(fl.bind(null,e)):zn(fl.bind(null,e)),$o((function(){0==(6&ys)&&Nn()})),t=null;else{switch(te(r)){case 1:t=fu;break;case 4:t=du;break;case 16:default:t=pu;break;case 536870912:t=hu}t=Tl(t,ol.bind(null,e))}e.callbackPriority=n,e.callbackNode=t}}function ol(e,n){if(Ws=-1,Hs=0,0!=(6&ys))throw Error(t(327));var r=e.callbackNode;if(El()&&e.callbackNode!==r)return null;var l=Y(e,e===bs?ws:0);if(0===l)return null;if(0!=(30&l)||0!=(l&e.expiredLanes)||n)n=yl(e,l);else{n=l;var a=ys;ys|=2;var u=gl();for(bs===e&&ws===n||(Fs=null,tl(),ml(e,n));;)try{kl();break}catch(n){hl(e,n)}Qn(),hs.current=u,ys=a,null!==ks?n=0:(bs=null,ws=0,n=Es)}if(0!==n){if(2===n&&0!==(a=G(e))&&(l=a,n=il(e,a)),1===n)throw r=Cs,ml(e,0),cl(e,l),ul(e,su()),r;if(6===n)cl(e,l);else{if(a=e.current.alternate,0==(30&l)&&!function(e){for(var n=e;;){if(16384&n.flags){var t=n.updateQueue;if(null!==t&&null!==(t=t.stores))for(var r=0;r<t.length;r++){var l=t[r],a=l.getSnapshot;l=l.value;try{if(!wo(a(),l))return!1}catch(e){return!1}}}if(t=n.child,16384&n.subtreeFlags&&null!==t)t.return=n,n=t;else{if(n===e)break;for(;null===n.sibling;){if(null===n.return||n.return===e)return!0;n=n.return}n.sibling.return=n.return,n=n.sibling}}return!0}(a)&&(2===(n=yl(e,l))&&0!==(u=G(e))&&(l=u,n=il(e,u)),1===n))throw r=Cs,ml(e,0),cl(e,l),ul(e,su()),r;switch(e.finishedWork=a,e.finishedLanes=l,n){case 0:case 1:throw Error(t(345));case 2:case 5:xl(e,Ls,Fs);break;case 3:if(cl(e,l),(130023424&l)===l&&10<(n=Ts+500-su())){if(0!==Y(e,0))break;if(((a=e.suspendedLanes)&l)!==l){rl(),e.pingedLanes|=e.suspendedLanes&a;break}e.timeoutHandle=Ho(xl.bind(null,e,Ls,Fs),n);break}xl(e,Ls,Fs);break;case 4:if(cl(e,l),(4194240&l)===l)break;for(n=e.eventTimes,a=-1;0<l;){var o=31-yu(l);u=1<<o,(o=n[o])>a&&(a=o),l&=~u}if(l=a,10<(l=(120>(l=su()-l)?120:480>l?480:1080>l?1080:1920>l?1920:3e3>l?3e3:4320>l?4320:1960*ms(l/1960))-l)){e.timeoutHandle=Ho(xl.bind(null,e,Ls,Fs),l);break}xl(e,Ls,Fs);break;default:throw Error(t(329))}}}return ul(e,su()),e.callbackNode===r?ol.bind(null,e):null}function il(e,n){var t=_s;return e.current.memoizedState.isDehydrated&&(ml(e,n).flags|=256),2!==(e=yl(e,n))&&(n=Ls,Ls=t,null!==n&&sl(n)),e}function sl(e){null===Ls?Ls=e:Ls.push.apply(Ls,e)}function cl(e,n){for(n&=~Ps,n&=~Ns,e.suspendedLanes|=n,e.pingedLanes&=~n,e=e.expirationTimes;0<n;){var t=31-yu(n),r=1<<t;e[t]=-1,n&=~r}}function fl(e){if(0!=(6&ys))throw Error(t(327));El();var n=Y(e,0);if(0==(1&n))return ul(e,su()),null;var r=yl(e,n);if(0!==e.tag&&2===r){var l=G(e);0!==l&&(n=l,r=il(e,l))}if(1===r)throw r=Cs,ml(e,0),cl(e,n),ul(e,su()),r;if(6===r)throw Error(t(345));return e.finishedWork=e.current.alternate,e.finishedLanes=n,xl(e,Ls,Fs),ul(e,su()),null}function dl(e,n){var t=ys;ys|=1;try{return e(n)}finally{0===(ys=t)&&(tl(),oi&&Nn())}}function pl(e){null!==Us&&0===Us.tag&&0==(6&ys)&&El();var n=ys;ys|=1;var t=vs.transition,r=xu;try{if(vs.transition=null,xu=1,e)return e()}finally{xu=r,vs.transition=t,0==(6&(ys=n))&&Nn()}}function ml(e,n){e.finishedWork=null,e.finishedLanes=0;var t=e.timeoutHandle;if(-1!==t&&(e.timeoutHandle=-1,Qo(t)),null!==ks)for(t=ks.return;null!==t;){var r=t;switch(Tn(r),r.tag){case 1:null!=(r=r.type.childContextTypes)&&(yn(li),yn(ri));break;case 3:it(),yn(li),yn(ri),dt();break;case 5:ct(r);break;case 4:it();break;case 13:case 19:yn(Oi);break;case 10:jn(r.type._context);break;case 22:case 23:Ss=xs.current,yn(xs)}t=t.return}if(bs=e,ks=e=Rl(e.current,null),ws=Ss=n,Es=0,Cs=null,Ps=Ns=zs=0,Ls=_s=null,null!==_i){for(n=0;n<_i.length;n++)if(null!==(r=(t=_i[n]).interleaved)){t.interleaved=null;var l=r.next,a=t.pending;if(null!==a){var u=a.next;a.next=l,r.next=u}t.pending=r}_i=null}return e}function hl(e,n){for(;;){var r=ks;try{if(Qn(),Ui.current=Ki,Qi){for(var l=Bi.memoizedState;null!==l;){var a=l.queue;null!==a&&(a.pending=null),l=l.next}Qi=!1}if(Ai=0,Hi=Wi=Bi=null,ji=!1,$i=0,gs.current=null,null===r||null===r.return){Es=1,Cs=n,ks=null;break}e:{var u=e,o=r.return,i=r,s=n;if(n=ws,i.flags|=32768,null!==s&&"object"==typeof s&&"function"==typeof s.then){var c=s,f=i,d=f.tag;if(0==(1&f.mode)&&(0===d||11===d||15===d)){var p=f.alternate;p?(f.updateQueue=p.updateQueue,f.memoizedState=p.memoizedState,f.lanes=p.lanes):(f.updateQueue=null,f.memoizedState=null)}var m=sr(o);if(null!==m){m.flags&=-257,cr(m,o,i,0,n),1&m.mode&&ir(u,c,n),s=c;var h=(n=m).updateQueue;if(null===h){var g=new Set;g.add(s),n.updateQueue=g}else h.add(s);break e}if(0==(1&n)){ir(u,c,n),vl();break e}s=Error(t(426))}else if(ki&&1&i.mode){var v=sr(o);if(null!==v){0==(65536&v.flags)&&(v.flags|=256),cr(v,o,i,0,n),Vn(rr(s,i));break e}}u=s=rr(s,i),4!==Es&&(Es=2),null===_s?_s=[u]:_s.push(u),u=o;do{switch(u.tag){case 3:u.flags|=65536,n&=-n,u.lanes|=n,rt(u,ur(0,s,n));break e;case 1:i=s;var y=u.type,b=u.stateNode;if(0==(128&u.flags)&&("function"==typeof y.getDerivedStateFromError||null!==b&&"function"==typeof b.componentDidCatch&&(null===Os||!Os.has(b)))){u.flags|=65536,n&=-n,u.lanes|=n,rt(u,or(u,i,n));break e}}u=u.return}while(null!==u)}Sl(r)}catch(e){n=e,ks===r&&null!==r&&(ks=r=r.return);continue}break}}function gl(){var e=hs.current;return hs.current=Ki,null===e?Ki:e}function vl(){0!==Es&&3!==Es&&2!==Es||(Es=4),null===bs||0==(268435455&zs)&&0==(268435455&Ns)||cl(bs,ws)}function yl(e,n){var r=ys;ys|=2;var l=gl();for(bs===e&&ws===n||(Fs=null,ml(e,n));;)try{bl();break}catch(n){hl(e,n)}if(Qn(),ys=r,hs.current=l,null!==ks)throw Error(t(261));return bs=null,ws=0,Es}function bl(){for(;null!==ks;)wl(ks)}function kl(){for(;null!==ks&&!ou();)wl(ks)}function wl(e){var n=Qs(e.alternate,e,Ss);e.memoizedProps=e.pendingProps,null===n?Sl(e):ks=n,gs.current=null}function Sl(e){var n=e;do{var t=n.alternate;if(e=n.return,0==(32768&n.flags)){if(null!==(t=Fr(t,n,Ss)))return void(ks=t)}else{if(null!==(t=Rr(t,n)))return t.flags&=32767,void(ks=t);if(null===e)return Es=6,void(ks=null);e.flags|=32768,e.subtreeFlags=0,e.deletions=null}if(null!==(n=n.sibling))return void(ks=n);ks=n=e}while(null!==n);0===Es&&(Es=5)}function xl(e,n,r){var l=xu,a=vs.transition;try{vs.transition=null,xu=1,function(e,n,r,l){do{El()}while(null!==Us);if(0!=(6&ys))throw Error(t(327));r=e.finishedWork;var a=e.finishedLanes;if(null===r)return null;if(e.finishedWork=null,e.finishedLanes=0,r===e.current)throw Error(t(177));e.callbackNode=null,e.callbackPriority=0;var u=r.lanes|r.childLanes;if(function(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<t;){var l=31-yu(t),a=1<<l;n[l]=0,r[l]=-1,e[l]=-1,t&=~a}}(e,u),e===bs&&(ks=bs=null,ws=0),0==(2064&r.subtreeFlags)&&0==(2064&r.flags)||Is||(Is=!0,Tl(pu,(function(){return El(),null}))),u=0!=(15990&r.flags),0!=(15990&r.subtreeFlags)||u){u=vs.transition,vs.transition=null;var o=xu;xu=1;var i=ys;ys|=4,gs.current=null,function(e,n){if(Bo=Ru,Be(e=Ae())){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{var l=(r=(r=e.ownerDocument)&&r.defaultView||window).getSelection&&r.getSelection();if(l&&0!==l.rangeCount){r=l.anchorNode;var a=l.anchorOffset,u=l.focusNode;l=l.focusOffset;try{r.nodeType,u.nodeType}catch(e){r=null;break e}var o=0,i=-1,s=-1,c=0,f=0,d=e,p=null;n:for(;;){for(var m;d!==r||0!==a&&3!==d.nodeType||(i=o+a),d!==u||0!==l&&3!==d.nodeType||(s=o+l),3===d.nodeType&&(o+=d.nodeValue.length),null!==(m=d.firstChild);)p=d,d=m;for(;;){if(d===e)break n;if(p===r&&++c===a&&(i=o),p===u&&++f===l&&(s=o),null!==(m=d.nextSibling))break;p=(d=p).parentNode}d=m}r=-1===i||-1===s?null:{start:i,end:s}}else r=null}r=r||{start:0,end:0}}else r=null;for(Wo={focusedElem:e,selectionRange:r},Ru=!1,cs=n;null!==cs;)if(e=(n=cs).child,0!=(1028&n.subtreeFlags)&&null!==e)e.return=n,cs=e;else for(;null!==cs;){n=cs;try{var h=n.alternate;if(0!=(1024&n.flags))switch(n.tag){case 0:case 11:case 15:case 5:case 6:case 4:case 17:break;case 1:if(null!==h){var g=h.memoizedProps,v=h.memoizedState,y=n.stateNode,b=y.getSnapshotBeforeUpdate(n.elementType===n.type?g:Gt(n.type,g),v);y.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var k=n.stateNode.containerInfo;1===k.nodeType?k.textContent="":9===k.nodeType&&k.documentElement&&k.removeChild(k.documentElement);break;default:throw Error(t(163))}}catch(e){zl(n,n.return,e)}if(null!==(e=n.sibling)){e.return=n.return,cs=e;break}cs=n.return}h=fs,fs=!1}(e,r),Yr(r,e),We(Wo),Ru=!!Bo,Wo=Bo=null,e.current=r,Gr(r,e,a),iu(),ys=i,xu=o,vs.transition=u}else e.current=r;if(Is&&(Is=!1,Us=e,Vs=a),0===(u=e.pendingLanes)&&(Os=null),function(e,n){if(vu&&"function"==typeof vu.onCommitFiberRoot)try{vu.onCommitFiberRoot(gu,e,void 0,128==(128&e.current.flags))}catch(e){}}(r.stateNode),ul(e,su()),null!==n)for(l=e.onRecoverableError,r=0;r<n.length;r++)a=n[r],l(a.value,{componentStack:a.stack,digest:a.digest});if(Rs)throw Rs=!1,e=Ds,Ds=null,e;0!=(1&Vs)&&0!==e.tag&&El(),0!=(1&(u=e.pendingLanes))?e===Bs?As++:(As=0,Bs=e):As=0,Nn()}(e,n,r,l)}finally{vs.transition=a,xu=l}return null}function El(){if(null!==Us){var e=te(Vs),n=vs.transition,r=xu;try{if(vs.transition=null,xu=16>e?16:e,null===Us)var l=!1;else{if(e=Us,Us=null,Vs=0,0!=(6&ys))throw Error(t(331));var a=ys;for(ys|=4,cs=e.current;null!==cs;){var u=cs,o=u.child;if(0!=(16&cs.flags)){var i=u.deletions;if(null!==i){for(var s=0;s<i.length;s++){var c=i[s];for(cs=c;null!==cs;){var f=cs;switch(f.tag){case 0:case 11:case 15:Ir(8,f,u)}var d=f.child;if(null!==d)d.return=f,cs=d;else for(;null!==cs;){var p=(f=cs).sibling,m=f.return;if(Ar(f),f===c){cs=null;break}if(null!==p){p.return=m,cs=p;break}cs=m}}}var h=u.alternate;if(null!==h){var g=h.child;if(null!==g){h.child=null;do{var v=g.sibling;g.sibling=null,g=v}while(null!==g)}}cs=u}}if(0!=(2064&u.subtreeFlags)&&null!==o)o.return=u,cs=o;else e:for(;null!==cs;){if(0!=(2048&(u=cs).flags))switch(u.tag){case 0:case 11:case 15:Ir(9,u,u.return)}var y=u.sibling;if(null!==y){y.return=u.return,cs=y;break e}cs=u.return}}var b=e.current;for(cs=b;null!==cs;){var k=(o=cs).child;if(0!=(2064&o.subtreeFlags)&&null!==k)k.return=o,cs=k;else e:for(o=b;null!==cs;){if(0!=(2048&(i=cs).flags))try{switch(i.tag){case 0:case 11:case 15:Ur(9,i)}}catch(e){zl(i,i.return,e)}if(i===o){cs=null;break e}var w=i.sibling;if(null!==w){w.return=i.return,cs=w;break e}cs=i.return}}if(ys=a,Nn(),vu&&"function"==typeof vu.onPostCommitFiberRoot)try{vu.onPostCommitFiberRoot(gu,e)}catch(e){}l=!0}return l}finally{xu=r,vs.transition=n}}return!1}function Cl(e,n,t){e=nt(e,n=ur(0,n=rr(t,n),1),1),n=rl(),null!==e&&(ee(e,1,n),ul(e,n))}function zl(e,n,t){if(3===e.tag)Cl(e,e,t);else for(;null!==n;){if(3===n.tag){Cl(n,e,t);break}if(1===n.tag){var r=n.stateNode;if("function"==typeof n.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===Os||!Os.has(r))){n=nt(n,e=or(n,e=rr(t,e),1),1),e=rl(),null!==n&&(ee(n,1,e),ul(n,e));break}}n=n.return}}function Nl(e,n,t){var r=e.pingCache;null!==r&&r.delete(n),n=rl(),e.pingedLanes|=e.suspendedLanes&t,bs===e&&(ws&t)===t&&(4===Es||3===Es&&(130023424&ws)===ws&&500>su()-Ts?ml(e,0):Ps|=t),ul(e,n)}function Pl(e,n){0===n&&(0==(1&e.mode)?n=1:(n=Su,0==(130023424&(Su<<=1))&&(Su=4194304)));var t=rl();null!==(e=Gn(e,n))&&(ee(e,n,t),ul(e,t))}function _l(e){var n=e.memoizedState,t=0;null!==n&&(t=n.retryLane),Pl(e,t)}function Ll(e,n){var r=0;switch(e.tag){case 13:var l=e.stateNode,a=e.memoizedState;null!==a&&(r=a.retryLane);break;case 19:l=e.stateNode;break;default:throw Error(t(314))}null!==l&&l.delete(n),Pl(e,r)}function Tl(e,n){return au(e,n)}function Ml(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Fl(e){return!(!(e=e.prototype)||!e.isReactComponent)}function Rl(e,n){var t=e.alternate;return null===t?((t=js(e.tag,n,e.key,e.mode)).elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=14680064&e.flags,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=null===n?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Dl(e,n,r,l,a,u){var o=2;if(l=e,"function"==typeof e)Fl(e)&&(o=1);else if("string"==typeof e)o=5;else e:switch(e){case ha:return Ol(r.children,a,u,n);case ga:o=8,a|=8;break;case va:return(e=js(12,r,n,2|a)).elementType=va,e.lanes=u,e;case wa:return(e=js(13,r,n,a)).elementType=wa,e.lanes=u,e;case Sa:return(e=js(19,r,n,a)).elementType=Sa,e.lanes=u,e;case Ca:return Il(r,a,u,n);default:if("object"==typeof e&&null!==e)switch(e.$$typeof){case ya:o=10;break e;case ba:o=9;break e;case ka:o=11;break e;case xa:o=14;break e;case Ea:o=16,l=null;break e}throw Error(t(130,null==e?e:typeof e,""))}return(n=js(o,r,n,a)).elementType=e,n.type=l,n.lanes=u,n}function Ol(e,n,t,r){return(e=js(7,e,r,n)).lanes=t,e}function Il(e,n,t,r){return(e=js(22,e,r,n)).elementType=Ca,e.lanes=t,e.stateNode={isHidden:!1},e}function Ul(e,n,t){return(e=js(6,e,null,n)).lanes=t,e}function Vl(e,n,t){return(n=js(4,null!==e.children?e.children:[],e.key,n)).lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Al(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=J(0),this.expirationTimes=J(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=J(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Bl(e,n,t,r,l,a,u,o,i,s){return e=new Al(e,n,t,o,i),1===n?(n=1,!0===a&&(n|=8)):n=0,a=js(3,null,null,n),e.current=a,a.stateNode=e,a.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},Zn(a),e}function Wl(e){if(!e)return ti;e:{if(H(e=e._reactInternals)!==e||1!==e.tag)throw Error(t(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(wn(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(null!==n);throw Error(t(171))}if(1===e.tag){var r=e.type;if(wn(r))return xn(e,r,n)}return n}function Hl(e,n,t,r,l,a,u,o,i,s){return(e=Bl(t,r,!0,e,0,a,0,o,i)).context=Wl(null),t=e.current,(a=et(r=rl(),l=ll(t))).callback=null!=n?n:null,nt(t,a,l),e.current.lanes=l,ee(e,l,r),ul(e,r),e}function Ql(e,n,t,r){var l=n.current,a=rl(),u=ll(l);return t=Wl(t),null===n.context?n.context=t:n.pendingContext=t,(n=et(a,u)).payload={element:e},null!==(r=void 0===r?null:r)&&(n.callback=r),null!==(e=nt(l,n,u))&&(al(e,l,u,a),tt(e,l,u)),u}function jl(e){return(e=e.current).child?(e.child.tag,e.child.stateNode):null}function $l(e,n){if(null!==(e=e.memoizedState)&&null!==e.dehydrated){var t=e.retryLane;e.retryLane=0!==t&&t<n?t:n}}function ql(e,n){$l(e,n),(e=e.alternate)&&$l(e,n)}function Kl(e){return null===(e=$(e))?null:e.stateNode}function Yl(e){return null}function Xl(e){this._internalRoot=e}function Gl(e){this._internalRoot=e}function Zl(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType)}function Jl(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function ea(){}function na(e,n,t,r,l){var a=t._reactRootContainer;if(a){var u=a;if("function"==typeof l){var o=l;l=function(){var e=jl(u);o.call(e)}}Ql(n,u,e,l)}else u=function(e,n,t,r,l){if(l){if("function"==typeof r){var a=r;r=function(){var e=jl(u);a.call(e)}}var u=Hl(n,r,e,0,null,!1,0,"",ea);return e._reactRootContainer=u,e[Xo]=u.current,Ge(8===e.nodeType?e.parentNode:e),pl(),u}for(;l=e.lastChild;)e.removeChild(l);if("function"==typeof r){var o=r;r=function(){var e=jl(i);o.call(e)}}var i=Bl(e,0,!1,null,0,!1,0,"",ea);return e._reactRootContainer=i,e[Xo]=i.current,Ge(8===e.nodeType?e.parentNode:e),pl((function(){Ql(n,i,t,r)})),i}(t,n,e,l,r);return jl(u)}var ta=new Set,ra={},la=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),aa=Object.prototype.hasOwnProperty,ua=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,oa={},ia={},sa={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){sa[e]=new a(e,0,!1,e,null,!1,!1)})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){var n=e[0];sa[n]=new a(n,1,!1,e[1],null,!1,!1)})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){sa[e]=new a(e,2,!1,e.toLowerCase(),null,!1,!1)})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){sa[e]=new a(e,2,!1,e,null,!1,!1)})),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){sa[e]=new a(e,3,!1,e.toLowerCase(),null,!1,!1)})),["checked","multiple","muted","selected"].forEach((function(e){sa[e]=new a(e,3,!0,e,null,!1,!1)})),["capture","download"].forEach((function(e){sa[e]=new a(e,4,!1,e,null,!1,!1)})),["cols","rows","size","span"].forEach((function(e){sa[e]=new a(e,6,!1,e,null,!1,!1)})),["rowSpan","start"].forEach((function(e){sa[e]=new a(e,5,!1,e.toLowerCase(),null,!1,!1)}));var ca=/[\-:]([a-z])/g,fa=function(e){return e[1].toUpperCase()};"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){var n=e.replace(ca,fa);sa[n]=new a(n,1,!1,e,null,!1,!1)})),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){var n=e.replace(ca,fa);sa[n]=new a(n,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)})),["xml:base","xml:lang","xml:space"].forEach((function(e){var n=e.replace(ca,fa);sa[n]=new a(n,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)})),["tabIndex","crossOrigin"].forEach((function(e){sa[e]=new a(e,1,!1,e.toLowerCase(),null,!1,!1)})),sa.xlinkHref=new a("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach((function(e){sa[e]=new a(e,1,!1,e.toLowerCase(),null,!0,!0)}));var da=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,pa=Symbol.for("react.element"),ma=Symbol.for("react.portal"),ha=Symbol.for("react.fragment"),ga=Symbol.for("react.strict_mode"),va=Symbol.for("react.profiler"),ya=Symbol.for("react.provider"),ba=Symbol.for("react.context"),ka=Symbol.for("react.forward_ref"),wa=Symbol.for("react.suspense"),Sa=Symbol.for("react.suspense_list"),xa=Symbol.for("react.memo"),Ea=Symbol.for("react.lazy");Symbol.for("react.scope"),Symbol.for("react.debug_trace_mode");var Ca=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden"),Symbol.for("react.cache"),Symbol.for("react.tracing_marker");var za,Na,Pa,_a=Symbol.iterator,La=Object.assign,Ta=!1,Ma=Array.isArray,Fa=(Pa=function(e,n){if("http://www.w3.org/2000/svg"!==e.namespaceURI||"innerHTML"in e)e.innerHTML=n;else{for((Na=Na||document.createElement("div")).innerHTML="<svg>"+n.valueOf().toString()+"</svg>",n=Na.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}},"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(e,n,t,r){MSApp.execUnsafeLocalFunction((function(){return Pa(e,n)}))}:Pa),Ra=function(e,n){if(n){var t=e.firstChild;if(t&&t===e.lastChild&&3===t.nodeType)return void(t.nodeValue=n)}e.textContent=n},Da={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Oa=["Webkit","ms","Moz","O"];Object.keys(Da).forEach((function(e){Oa.forEach((function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),Da[n]=Da[e]}))}));var Ia=La({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}),Ua=null,Va=null,Aa=null,Ba=null,Wa=function(e,n){return e(n)},Ha=function(){},Qa=!1,ja=!1;if(la)try{var $a={};Object.defineProperty($a,"passive",{get:function(){ja=!0}}),window.addEventListener("test",$a,$a),window.removeEventListener("test",$a,$a)}catch(Pa){ja=!1}var qa,Ka,Ya,Xa=function(e,n,t,r,l,a,u,o,i){var s=Array.prototype.slice.call(arguments,3);try{n.apply(t,s)}catch(e){this.onError(e)}},Ga=!1,Za=null,Ja=!1,eu=null,nu={onError:function(e){Ga=!0,Za=e}},tu=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler,ru=tu.unstable_scheduleCallback,lu=tu.unstable_NormalPriority,au=ru,uu=tu.unstable_cancelCallback,ou=tu.unstable_shouldYield,iu=tu.unstable_requestPaint,su=tu.unstable_now,cu=tu.unstable_getCurrentPriorityLevel,fu=tu.unstable_ImmediatePriority,du=tu.unstable_UserBlockingPriority,pu=lu,mu=tu.unstable_LowPriority,hu=tu.unstable_IdlePriority,gu=null,vu=null,yu=Math.clz32?Math.clz32:function(e){return 0==(e>>>=0)?32:31-(bu(e)/ku|0)|0},bu=Math.log,ku=Math.LN2,wu=64,Su=4194304,xu=0,Eu=!1,Cu=[],zu=null,Nu=null,Pu=null,_u=new Map,Lu=new Map,Tu=[],Mu="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" "),Fu=da.ReactCurrentBatchConfig,Ru=!0,Du=null,Ou=null,Iu=null,Uu=null,Vu={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Au=ke(Vu),Bu=La({},Vu,{view:0,detail:0}),Wu=ke(Bu),Hu=La({},Bu,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Se,button:0,buttons:0,relatedTarget:function(e){return void 0===e.relatedTarget?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==Ya&&(Ya&&"mousemove"===e.type?(qa=e.screenX-Ya.screenX,Ka=e.screenY-Ya.screenY):Ka=qa=0,Ya=e),qa)},movementY:function(e){return"movementY"in e?e.movementY:Ka}}),Qu=ke(Hu),ju=ke(La({},Hu,{dataTransfer:0})),$u=ke(La({},Bu,{relatedTarget:0})),qu=ke(La({},Vu,{animationName:0,elapsedTime:0,pseudoElement:0})),Ku=La({},Vu,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),Yu=ke(Ku),Xu=ke(La({},Vu,{data:0})),Gu=Xu,Zu={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Ju={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},eo={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"},no=La({},Bu,{key:function(e){if(e.key){var n=Zu[e.key]||e.key;if("Unidentified"!==n)return n}return"keypress"===e.type?13===(e=ve(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?Ju[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Se,charCode:function(e){return"keypress"===e.type?ve(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?ve(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),to=ke(no),ro=ke(La({},Hu,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),lo=ke(La({},Bu,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Se})),ao=ke(La({},Vu,{propertyName:0,elapsedTime:0,pseudoElement:0})),uo=La({},Hu,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),oo=ke(uo),io=[9,13,27,32],so=la&&"CompositionEvent"in window,co=null;la&&"documentMode"in document&&(co=document.documentMode);var fo=la&&"TextEvent"in window&&!co,po=la&&(!so||co&&8<co&&11>=co),mo=String.fromCharCode(32),ho=!1,go=!1,vo={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0},yo=null,bo=null,ko=!1;la&&(ko=function(e){if(!la)return!1;var n=(e="on"+e)in document;return n||((n=document.createElement("div")).setAttribute(e,"return;"),n="function"==typeof n[e]),n}("input")&&(!document.documentMode||9<document.documentMode));var wo="function"==typeof Object.is?Object.is:function(e,n){return e===n&&(0!==e||1/e==1/n)||e!=e&&n!=n},So=la&&"documentMode"in document&&11>=document.documentMode,xo=null,Eo=null,Co=null,zo=!1,No={animationend:Qe("Animation","AnimationEnd"),animationiteration:Qe("Animation","AnimationIteration"),animationstart:Qe("Animation","AnimationStart"),transitionend:Qe("Transition","TransitionEnd")},Po={},_o={};la&&(_o=document.createElement("div").style,"AnimationEvent"in window||(delete No.animationend.animation,delete No.animationiteration.animation,delete No.animationstart.animation),"TransitionEvent"in window||delete No.transitionend.transition);var Lo=je("animationend"),To=je("animationiteration"),Mo=je("animationstart"),Fo=je("transitionend"),Ro=new Map,Do="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");!function(){for(var e=0;e<Do.length;e++){var n=Do[e];$e(n.toLowerCase(),"on"+(n=n[0].toUpperCase()+n.slice(1)))}$e(Lo,"onAnimationEnd"),$e(To,"onAnimationIteration"),$e(Mo,"onAnimationStart"),$e("dblclick","onDoubleClick"),$e("focusin","onFocus"),$e("focusout","onBlur"),$e(Fo,"onTransitionEnd")}(),l("onMouseEnter",["mouseout","mouseover"]),l("onMouseLeave",["mouseout","mouseover"]),l("onPointerEnter",["pointerout","pointerover"]),l("onPointerLeave",["pointerout","pointerover"]),r("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),r("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),r("onBeforeInput",["compositionend","keypress","textInput","paste"]),r("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),r("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),r("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Oo="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Io=new Set("cancel close invalid load scroll toggle".split(" ").concat(Oo)),Uo="_reactListening"+Math.random().toString(36).slice(2),Vo=/\r\n?/g,Ao=/\u0000|\uFFFD/g,Bo=null,Wo=null,Ho="function"==typeof setTimeout?setTimeout:void 0,Qo="function"==typeof clearTimeout?clearTimeout:void 0,jo="function"==typeof Promise?Promise:void 0,$o="function"==typeof queueMicrotask?queueMicrotask:void 0!==jo?function(e){return jo.resolve(null).then(e).catch(sn)}:Ho,qo=Math.random().toString(36).slice(2),Ko="__reactFiber$"+qo,Yo="__reactProps$"+qo,Xo="__reactContainer$"+qo,Go="__reactEvents$"+qo,Zo="__reactListeners$"+qo,Jo="__reactHandles$"+qo,ei=[],ni=-1,ti={},ri=vn(ti),li=vn(!1),ai=ti,ui=null,oi=!1,ii=!1,si=[],ci=0,fi=null,di=0,pi=[],mi=0,hi=null,gi=1,vi="",yi=null,bi=null,ki=!1,wi=null,Si=da.ReactCurrentBatchConfig,xi=Hn(!0),Ei=Hn(!1),Ci=vn(null),zi=null,Ni=null,Pi=null,_i=null,Li=Gn,Ti=!1,Mi={},Fi=vn(Mi),Ri=vn(Mi),Di=vn(Mi),Oi=vn(0),Ii=[],Ui=da.ReactCurrentDispatcher,Vi=da.ReactCurrentBatchConfig,Ai=0,Bi=null,Wi=null,Hi=null,Qi=!1,ji=!1,$i=0,qi=0,Ki={readContext:Kn,useCallback:pt,useContext:pt,useEffect:pt,useImperativeHandle:pt,useInsertionEffect:pt,useLayoutEffect:pt,useMemo:pt,useReducer:pt,useRef:pt,useState:pt,useDebugValue:pt,useDeferredValue:pt,useTransition:pt,useMutableSource:pt,useSyncExternalStore:pt,useId:pt,unstable_isNewReconciler:!1},Yi={readContext:Kn,useCallback:function(e,n){return vt().memoizedState=[e,void 0===n?null:n],e},useContext:Kn,useEffect:Rt,useImperativeHandle:function(e,n,t){return t=null!=t?t.concat([e]):null,Mt(4194308,4,Ut.bind(null,n,e),t)},useLayoutEffect:function(e,n){return Mt(4194308,4,e,n)},useInsertionEffect:function(e,n){return Mt(4,2,e,n)},useMemo:function(e,n){var t=vt();return n=void 0===n?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=vt();return n=void 0!==t?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=$t.bind(null,Bi,e),[r.memoizedState,e]},useRef:function(e){return e={current:e},vt().memoizedState=e},useState:_t,useDebugValue:At,useDeferredValue:function(e){return vt().memoizedState=e},useTransition:function(){var e=_t(!1),n=e[0];return e=Qt.bind(null,e[1]),vt().memoizedState=e,[n,e]},useMutableSource:function(e,n,t){},useSyncExternalStore:function(e,n,r){var l=Bi,a=vt();if(ki){if(void 0===r)throw Error(t(407));r=r()}else{if(r=n(),null===bs)throw Error(t(349));0!=(30&Ai)||Et(l,n,r)}a.memoizedState=r;var u={value:r,getSnapshot:n};return a.queue=u,Rt(zt.bind(null,l,u,e),[e]),l.flags|=2048,Lt(9,Ct.bind(null,l,u,r,n),void 0,null),r},useId:function(){var e=vt(),n=bs.identifierPrefix;if(ki){var t=vi;n=":"+n+"R"+(t=(gi&~(1<<32-yu(gi)-1)).toString(32)+t),0<(t=$i++)&&(n+="H"+t.toString(32)),n+=":"}else n=":"+n+"r"+(t=qi++).toString(32)+":";return e.memoizedState=n},unstable_isNewReconciler:!1},Xi={readContext:Kn,useCallback:Bt,useContext:Kn,useEffect:Dt,useImperativeHandle:Vt,useInsertionEffect:Ot,useLayoutEffect:It,useMemo:Wt,useReducer:kt,useRef:Tt,useState:function(e){return kt(bt)},useDebugValue:At,useDeferredValue:function(e){return Ht(yt(),Wi.memoizedState,e)},useTransition:function(){return[kt(bt)[0],yt().memoizedState]},useMutableSource:St,useSyncExternalStore:xt,useId:jt,unstable_isNewReconciler:!1},Gi={readContext:Kn,useCallback:Bt,useContext:Kn,useEffect:Dt,useImperativeHandle:Vt,useInsertionEffect:Ot,useLayoutEffect:It,useMemo:Wt,useReducer:wt,useRef:Tt,useState:function(e){return wt(bt)},useDebugValue:At,useDeferredValue:function(e){var n=yt();return null===Wi?n.memoizedState=e:Ht(n,Wi.memoizedState,e)},useTransition:function(){return[wt(bt)[0],yt().memoizedState]},useMutableSource:St,useSyncExternalStore:xt,useId:jt,unstable_isNewReconciler:!1},Zi={isMounted:function(e){return!!(e=e._reactInternals)&&H(e)===e},enqueueSetState:function(e,n,t){e=e._reactInternals;var r=rl(),l=ll(e),a=et(r,l);a.payload=n,null!=t&&(a.callback=t),null!==(n=nt(e,a,l))&&(al(n,e,l,r),tt(n,e,l))},enqueueReplaceState:function(e,n,t){e=e._reactInternals;var r=rl(),l=ll(e),a=et(r,l);a.tag=1,a.payload=n,null!=t&&(a.callback=t),null!==(n=nt(e,a,l))&&(al(n,e,l,r),tt(n,e,l))},enqueueForceUpdate:function(e,n){e=e._reactInternals;var t=rl(),r=ll(e),l=et(t,r);l.tag=2,null!=n&&(l.callback=n),null!==(n=nt(e,l,r))&&(al(n,e,r,t),tt(n,e,r))}},Ji="function"==typeof WeakMap?WeakMap:Map,es=da.ReactCurrentOwner,ns=!1,ts={dehydrated:null,treeContext:null,retryLane:0},rs=function(e,n,t,r){for(t=n.child;null!==t;){if(5===t.tag||6===t.tag)e.appendChild(t.stateNode);else if(4!==t.tag&&null!==t.child){t.child.return=t,t=t.child;continue}if(t===n)break;for(;null===t.sibling;){if(null===t.return||t.return===n)return;t=t.return}t.sibling.return=t.return,t=t.sibling}},ls=function(e,n){},as=function(e,n,t,r,l){var a=e.memoizedProps;if(a!==r){switch(e=n.stateNode,ut(Fi.current),l=null,t){case"input":a=y(e,a),r=y(e,r),l=[];break;case"select":a=La({},a,{value:void 0}),r=La({},r,{value:void 0}),l=[];break;case"textarea":a=C(e,a),r=C(e,r),l=[];break;default:"function"!=typeof a.onClick&&"function"==typeof r.onClick&&(e.onclick=un)}var u;for(s in F(t,r),t=null,a)if(!r.hasOwnProperty(s)&&a.hasOwnProperty(s)&&null!=a[s])if("style"===s){var o=a[s];for(u in o)o.hasOwnProperty(u)&&(t||(t={}),t[u]="")}else"dangerouslySetInnerHTML"!==s&&"children"!==s&&"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&"autoFocus"!==s&&(ra.hasOwnProperty(s)?l||(l=[]):(l=l||[]).push(s,null));for(s in r){var i=r[s];if(o=null!=a?a[s]:void 0,r.hasOwnProperty(s)&&i!==o&&(null!=i||null!=o))if("style"===s)if(o){for(u in o)!o.hasOwnProperty(u)||i&&i.hasOwnProperty(u)||(t||(t={}),t[u]="");for(u in i)i.hasOwnProperty(u)&&o[u]!==i[u]&&(t||(t={}),t[u]=i[u])}else t||(l||(l=[]),l.push(s,t)),t=i;else"dangerouslySetInnerHTML"===s?(i=i?i.__html:void 0,o=o?o.__html:void 0,null!=i&&o!==i&&(l=l||[]).push(s,i)):"children"===s?"string"!=typeof i&&"number"!=typeof i||(l=l||[]).push(s,""+i):"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&(ra.hasOwnProperty(s)?(null!=i&&"onScroll"===s&&Ye("scroll",e),l||o===i||(l=[])):(l=l||[]).push(s,i))}t&&(l=l||[]).push("style",t);var s=l;(n.updateQueue=s)&&(n.flags|=4)}},us=function(e,n,t,r){t!==r&&(n.flags|=4)},os=!1,is=!1,ss="function"==typeof WeakSet?WeakSet:Set,cs=null,fs=!1,ds=null,ps=!1,ms=Math.ceil,hs=da.ReactCurrentDispatcher,gs=da.ReactCurrentOwner,vs=da.ReactCurrentBatchConfig,ys=0,bs=null,ks=null,ws=0,Ss=0,xs=vn(0),Es=0,Cs=null,zs=0,Ns=0,Ps=0,_s=null,Ls=null,Ts=0,Ms=1/0,Fs=null,Rs=!1,Ds=null,Os=null,Is=!1,Us=null,Vs=0,As=0,Bs=null,Ws=-1,Hs=0,Qs=function(e,n,r){if(null!==e)if(e.memoizedProps!==n.pendingProps||li.current)ns=!0;else{if(0==(e.lanes&r)&&0==(128&n.flags))return ns=!1,function(e,n,t){switch(n.tag){case 3:kr(n),Un();break;case 5:st(n);break;case 1:wn(n.type)&&En(n);break;case 4:ot(n,n.stateNode.containerInfo);break;case 10:var r=n.type._context,l=n.memoizedProps.value;bn(Ci,r._currentValue),r._currentValue=l;break;case 13:if(null!==(r=n.memoizedState))return null!==r.dehydrated?(bn(Oi,1&Oi.current),n.flags|=128,null):0!=(t&n.child.childLanes)?xr(e,n,t):(bn(Oi,1&Oi.current),null!==(e=Lr(e,n,t))?e.sibling:null);bn(Oi,1&Oi.current);break;case 19:if(r=0!=(t&n.childLanes),0!=(128&e.flags)){if(r)return Pr(e,n,t);n.flags|=128}if(null!==(l=n.memoizedState)&&(l.rendering=null,l.tail=null,l.lastEffect=null),bn(Oi,Oi.current),r)break;return null;case 22:case 23:return n.lanes=0,hr(e,n,t)}return Lr(e,n,t)}(e,n,r);ns=0!=(131072&e.flags)}else ns=!1,ki&&0!=(1048576&n.flags)&&_n(n,di,n.index);switch(n.lanes=0,n.tag){case 2:var l=n.type;_r(e,n),e=n.pendingProps;var a=kn(n,ri.current);qn(n,r),a=ht(null,n,l,e,a,r);var u=gt();return n.flags|=1,"object"==typeof a&&null!==a&&"function"==typeof a.render&&void 0===a.$$typeof?(n.tag=1,n.memoizedState=null,n.updateQueue=null,wn(l)?(u=!0,En(n)):u=!1,n.memoizedState=null!==a.state&&void 0!==a.state?a.state:null,Zn(n),a.updater=Zi,n.stateNode=a,a._reactInternals=n,tr(n,l,e,r),n=br(null,n,l,!0,u,r)):(n.tag=0,ki&&u&&Ln(n),fr(null,n,a,r),n=n.child),n;case 16:l=n.elementType;e:{switch(_r(e,n),e=n.pendingProps,l=(a=l._init)(l._payload),n.type=l,a=n.tag=function(e){if("function"==typeof e)return Fl(e)?1:0;if(null!=e){if((e=e.$$typeof)===ka)return 11;if(e===xa)return 14}return 2}(l),e=Gt(l,e),a){case 0:n=vr(null,n,l,e,r);break e;case 1:n=yr(null,n,l,e,r);break e;case 11:n=dr(null,n,l,e,r);break e;case 14:n=pr(null,n,l,Gt(l.type,e),r);break e}throw Error(t(306,l,""))}return n;case 0:return l=n.type,a=n.pendingProps,vr(e,n,l,a=n.elementType===l?a:Gt(l,a),r);case 1:return l=n.type,a=n.pendingProps,yr(e,n,l,a=n.elementType===l?a:Gt(l,a),r);case 3:e:{if(kr(n),null===e)throw Error(t(387));l=n.pendingProps,a=(u=n.memoizedState).element,Jn(e,n),lt(n,l,null,r);var o=n.memoizedState;if(l=o.element,u.isDehydrated){if(u={element:l,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},n.updateQueue.baseState=u,n.memoizedState=u,256&n.flags){n=wr(e,n,l,r,a=rr(Error(t(423)),n));break e}if(l!==a){n=wr(e,n,l,r,a=rr(Error(t(424)),n));break e}for(bi=fn(n.stateNode.containerInfo.firstChild),yi=n,ki=!0,wi=null,r=Ei(n,null,l,r),n.child=r;r;)r.flags=-3&r.flags|4096,r=r.sibling}else{if(Un(),l===a){n=Lr(e,n,r);break e}fr(e,n,l,r)}n=n.child}return n;case 5:return st(n),null===e&&Dn(n),l=n.type,a=n.pendingProps,u=null!==e?e.memoizedProps:null,o=a.children,on(l,a)?o=null:null!==u&&on(l,u)&&(n.flags|=32),gr(e,n),fr(e,n,o,r),n.child;case 6:return null===e&&Dn(n),null;case 13:return xr(e,n,r);case 4:return ot(n,n.stateNode.containerInfo),l=n.pendingProps,null===e?n.child=xi(n,null,l,r):fr(e,n,l,r),n.child;case 11:return l=n.type,a=n.pendingProps,dr(e,n,l,a=n.elementType===l?a:Gt(l,a),r);case 7:return fr(e,n,n.pendingProps,r),n.child;case 8:case 12:return fr(e,n,n.pendingProps.children,r),n.child;case 10:e:{if(l=n.type._context,a=n.pendingProps,u=n.memoizedProps,o=a.value,bn(Ci,l._currentValue),l._currentValue=o,null!==u)if(wo(u.value,o)){if(u.children===a.children&&!li.current){n=Lr(e,n,r);break e}}else for(null!==(u=n.child)&&(u.return=n);null!==u;){var i=u.dependencies;if(null!==i){o=u.child;for(var s=i.firstContext;null!==s;){if(s.context===l){if(1===u.tag){(s=et(-1,r&-r)).tag=2;var c=u.updateQueue;if(null!==c){var f=(c=c.shared).pending;null===f?s.next=s:(s.next=f.next,f.next=s),c.pending=s}}u.lanes|=r,null!==(s=u.alternate)&&(s.lanes|=r),$n(u.return,r,n),i.lanes|=r;break}s=s.next}}else if(10===u.tag)o=u.type===n.type?null:u.child;else if(18===u.tag){if(null===(o=u.return))throw Error(t(341));o.lanes|=r,null!==(i=o.alternate)&&(i.lanes|=r),$n(o,r,n),o=u.sibling}else o=u.child;if(null!==o)o.return=u;else for(o=u;null!==o;){if(o===n){o=null;break}if(null!==(u=o.sibling)){u.return=o.return,o=u;break}o=o.return}u=o}fr(e,n,a.children,r),n=n.child}return n;case 9:return a=n.type,l=n.pendingProps.children,qn(n,r),l=l(a=Kn(a)),n.flags|=1,fr(e,n,l,r),n.child;case 14:return a=Gt(l=n.type,n.pendingProps),pr(e,n,l,a=Gt(l.type,a),r);case 15:return mr(e,n,n.type,n.pendingProps,r);case 17:return l=n.type,a=n.pendingProps,a=n.elementType===l?a:Gt(l,a),_r(e,n),n.tag=1,wn(l)?(e=!0,En(n)):e=!1,qn(n,r),er(n,l,a),tr(n,l,a,r),br(null,n,l,!0,e,r);case 19:return Pr(e,n,r);case 22:return hr(e,n,r)}throw Error(t(156,n.tag))},js=function(e,n,t,r){return new Ml(e,n,t,r)},$s="function"==typeof reportError?reportError:function(e){console.error(e)};Gl.prototype.render=Xl.prototype.render=function(e){var n=this._internalRoot;if(null===n)throw Error(t(409));Ql(e,n,null,null)},Gl.prototype.unmount=Xl.prototype.unmount=function(){var e=this._internalRoot;if(null!==e){this._internalRoot=null;var n=e.containerInfo;pl((function(){Ql(null,e,null,null)})),n[Xo]=null}},Gl.prototype.unstable_scheduleHydration=function(e){if(e){var n=Xs();e={blockedOn:null,target:e,priority:n};for(var t=0;t<Tu.length&&0!==n&&n<Tu[t].priority;t++);Tu.splice(t,0,e),0===t&&ae(e)}};var qs=function(e){switch(e.tag){case 3:var n=e.stateNode;if(n.current.memoizedState.isDehydrated){var t=K(n.pendingLanes);0!==t&&(ne(n,1|t),ul(n,su()),0==(6&ys)&&(tl(),Nn()))}break;case 13:pl((function(){var n=Gn(e,1);if(null!==n){var t=rl();al(n,e,1,t)}})),ql(e,1)}},Ks=function(e){if(13===e.tag){var n=Gn(e,134217728);null!==n&&al(n,e,134217728,rl()),ql(e,134217728)}},Ys=function(e){if(13===e.tag){var n=ll(e),t=Gn(e,n);null!==t&&al(t,e,n,rl()),ql(e,n)}},Xs=function(){return xu},Gs=function(e,n){var t=xu;try{return xu=e,n()}finally{xu=t}};Va=function(e,n,r){switch(n){case"input":if(w(e,r),n=r.name,"radio"===r.type&&null!=n){for(r=e;r.parentNode;)r=r.parentNode;for(r=r.querySelectorAll("input[name="+JSON.stringify(""+n)+'][type="radio"]'),n=0;n<r.length;n++){var l=r[n];if(l!==e&&l.form===e.form){var a=gn(l);if(!a)throw Error(t(90));g(l),w(l,a)}}}break;case"textarea":N(e,r);break;case"select":null!=(n=r.value)&&E(e,!!r.multiple,n,!1)}},function(e,n,t){Wa=e,Ha=t}(dl,0,pl);var Zs={usingClientEntryPoint:!1,Events:[mn,hn,gn,I,U,dl]};!function(e){if(e={bundleType:e.bundleType,version:e.version,rendererPackageName:e.rendererPackageName,rendererConfig:e.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:da.ReactCurrentDispatcher,findHostInstanceByFiber:Kl,findFiberByHostInstance:e.findFiberByHostInstance||Yl,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},"undefined"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)e=!1;else{var n=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(n.isDisabled||!n.supportsFiber)e=!0;else{try{gu=n.inject(e),vu=n}catch(e){}e=!!n.checkDCE}}}({findFiberByHostInstance:pn,bundleType:0,version:"18.3.1-next-f1338f8080-20240426",rendererPackageName:"react-dom"}),e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Zs,e.createPortal=function(e,n){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!Zl(n))throw Error(t(200));return function(e,n,t){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:ma,key:null==r?null:""+r,children:e,containerInfo:n,implementation:t}}(e,n,null,r)},e.createRoot=function(e,n){if(!Zl(e))throw Error(t(299));var r=!1,l="",a=$s;return null!=n&&(!0===n.unstable_strictMode&&(r=!0),void 0!==n.identifierPrefix&&(l=n.identifierPrefix),void 0!==n.onRecoverableError&&(a=n.onRecoverableError)),n=Bl(e,1,!1,null,0,r,0,l,a),e[Xo]=n.current,Ge(8===e.nodeType?e.parentNode:e),new Xl(n)},e.findDOMNode=function(e){if(null==e)return null;if(1===e.nodeType)return e;var n=e._reactInternals;if(void 0===n){if("function"==typeof e.render)throw Error(t(188));throw e=Object.keys(e).join(","),Error(t(268,e))}return e=null===(e=$(n))?null:e.stateNode},e.flushSync=function(e){return pl(e)},e.hydrate=function(e,n,r){if(!Jl(n))throw Error(t(200));return na(null,e,n,!0,r)},e.hydrateRoot=function(e,n,r){if(!Zl(e))throw Error(t(405));var l=null!=r&&r.hydratedSources||null,a=!1,u="",o=$s;if(null!=r&&(!0===r.unstable_strictMode&&(a=!0),void 0!==r.identifierPrefix&&(u=r.identifierPrefix),void 0!==r.onRecoverableError&&(o=r.onRecoverableError)),n=Hl(n,null,e,1,null!=r?r:null,a,0,u,o),e[Xo]=n.current,Ge(e),l)for(e=0;e<l.length;e++)a=(a=(r=l[e])._getVersion)(r._source),null==n.mutableSourceEagerHydrationData?n.mutableSourceEagerHydrationData=[r,a]:n.mutableSourceEagerHydrationData.push(r,a);return new Gl(n)},e.render=function(e,n,r){if(!Jl(n))throw Error(t(200));return na(null,e,n,!1,r)},e.unmountComponentAtNode=function(e){if(!Jl(e))throw Error(t(40));return!!e._reactRootContainer&&(pl((function(){na(null,null,e,!1,(function(){e._reactRootContainer=null,e[Xo]=null}))})),!0)},e.unstable_batchedUpdates=dl,e.unstable_renderSubtreeIntoContainer=function(e,n,r,l){if(!Jl(r))throw Error(t(200));if(null==e||void 0===e._reactInternals)throw Error(t(38));return na(e,n,r,!1,l)},e.version="18.3.1-next-f1338f8080-20240426"},"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],n):n((e=e||self).ReactDOM={},e.React)}(); react-jsx-runtime.js 0000644 00000134254 14720015030 0010464 0 ustar 00 /* * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development"). * This devtool is neither made for production nor for readable output files. * It uses "eval()" calls to create a separate source file in the browser devtools. * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) * or disable the default devtool with "devtool: false". * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). */ /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "./node_modules/react/cjs/react-jsx-runtime.development.js": /*!*****************************************************************!*\ !*** ./node_modules/react/cjs/react-jsx-runtime.development.js ***! \*****************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { eval("/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\n\nif (true) {\n (function() {\n'use strict';\n\nvar React = __webpack_require__(/*! react */ \"react\");\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types.\nvar REACT_ELEMENT_TYPE = Symbol.for('react.element');\nvar REACT_PORTAL_TYPE = Symbol.for('react.portal');\nvar REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');\nvar REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');\nvar REACT_PROFILER_TYPE = Symbol.for('react.profiler');\nvar REACT_PROVIDER_TYPE = Symbol.for('react.provider');\nvar REACT_CONTEXT_TYPE = Symbol.for('react.context');\nvar REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');\nvar REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');\nvar REACT_MEMO_TYPE = Symbol.for('react.memo');\nvar REACT_LAZY_TYPE = Symbol.for('react.lazy');\nvar REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\n// -----------------------------------------------------------------------------\n\nvar enableScopeAPI = false; // Experimental Create Event Handle API.\nvar enableCacheElement = false;\nvar enableTransitionTracing = false; // No known bugs, but needs performance testing\n\nvar enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber\n// stuff. Intended to enable React core members to more easily debug scheduling\n// issues in DEV builds.\n\nvar enableDebugTracing = false; // Track which Fiber(s) schedule render work.\n\nvar REACT_MODULE_REFERENCE;\n\n{\n REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');\n}\n\nfunction isValidElementType(type) {\n if (typeof type === 'string' || typeof type === 'function') {\n return true;\n } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).\n\n\n if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {\n return true;\n }\n\n if (typeof type === 'object' && type !== null) {\n if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object\n // types supported by any Flight configuration anywhere since\n // we don't know which Flight build this will end up being used\n // with.\n type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var displayName = outerType.displayName;\n\n if (displayName) {\n return displayName;\n }\n\n var functionName = innerType.displayName || innerType.name || '';\n return functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName;\n} // Keep in sync with react-reconciler/getComponentNameFromFiber\n\n\nfunction getContextName(type) {\n return type.displayName || 'Context';\n} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.\n\n\nfunction getComponentNameFromType(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return 'Profiler';\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n var context = type;\n return getContextName(context) + '.Consumer';\n\n case REACT_PROVIDER_TYPE:\n var provider = type;\n return getContextName(provider._context) + '.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n var outerName = type.displayName || null;\n\n if (outerName !== null) {\n return outerName;\n }\n\n return getComponentNameFromType(type.type) || 'Memo';\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n return getComponentNameFromType(init(payload));\n } catch (x) {\n return null;\n }\n }\n\n // eslint-disable-next-line no-fallthrough\n }\n }\n\n return null;\n}\n\nvar assign = Object.assign;\n\n// Helpers to patch console.logs to avoid logging during side-effect free\n// replaying on render function. This currently only patches the object\n// lazily which won't cover if the log function was extracted eagerly.\n// We could also eagerly patch the method.\nvar disabledDepth = 0;\nvar prevLog;\nvar prevInfo;\nvar prevWarn;\nvar prevError;\nvar prevGroup;\nvar prevGroupCollapsed;\nvar prevGroupEnd;\n\nfunction disabledLog() {}\n\ndisabledLog.__reactDisabledLog = true;\nfunction disableLogs() {\n {\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n prevLog = console.log;\n prevInfo = console.info;\n prevWarn = console.warn;\n prevError = console.error;\n prevGroup = console.group;\n prevGroupCollapsed = console.groupCollapsed;\n prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099\n\n var props = {\n configurable: true,\n enumerable: true,\n value: disabledLog,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n info: props,\n log: props,\n warn: props,\n error: props,\n group: props,\n groupCollapsed: props,\n groupEnd: props\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n disabledDepth++;\n }\n}\nfunction reenableLogs() {\n {\n disabledDepth--;\n\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n var props = {\n configurable: true,\n enumerable: true,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n log: assign({}, props, {\n value: prevLog\n }),\n info: assign({}, props, {\n value: prevInfo\n }),\n warn: assign({}, props, {\n value: prevWarn\n }),\n error: assign({}, props, {\n value: prevError\n }),\n group: assign({}, props, {\n value: prevGroup\n }),\n groupCollapsed: assign({}, props, {\n value: prevGroupCollapsed\n }),\n groupEnd: assign({}, props, {\n value: prevGroupEnd\n })\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n if (disabledDepth < 0) {\n error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');\n }\n }\n}\n\nvar ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;\nvar prefix;\nfunction describeBuiltInComponentFrame(name, source, ownerFn) {\n {\n if (prefix === undefined) {\n // Extract the VM specific prefix used by each line.\n try {\n throw Error();\n } catch (x) {\n var match = x.stack.trim().match(/\\n( *(at )?)/);\n prefix = match && match[1] || '';\n }\n } // We use the prefix to ensure our stacks line up with native stack frames.\n\n\n return '\\n' + prefix + name;\n }\n}\nvar reentry = false;\nvar componentFrameCache;\n\n{\n var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;\n componentFrameCache = new PossiblyWeakMap();\n}\n\nfunction describeNativeComponentFrame(fn, construct) {\n // If something asked for a stack inside a fake render, it should get ignored.\n if ( !fn || reentry) {\n return '';\n }\n\n {\n var frame = componentFrameCache.get(fn);\n\n if (frame !== undefined) {\n return frame;\n }\n }\n\n var control;\n reentry = true;\n var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.\n\n Error.prepareStackTrace = undefined;\n var previousDispatcher;\n\n {\n previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function\n // for warnings.\n\n ReactCurrentDispatcher.current = null;\n disableLogs();\n }\n\n try {\n // This should throw.\n if (construct) {\n // Something should be setting the props in the constructor.\n var Fake = function () {\n throw Error();\n }; // $FlowFixMe\n\n\n Object.defineProperty(Fake.prototype, 'props', {\n set: function () {\n // We use a throwing setter instead of frozen or non-writable props\n // because that won't throw in a non-strict mode function.\n throw Error();\n }\n });\n\n if (typeof Reflect === 'object' && Reflect.construct) {\n // We construct a different control for this case to include any extra\n // frames added by the construct call.\n try {\n Reflect.construct(Fake, []);\n } catch (x) {\n control = x;\n }\n\n Reflect.construct(fn, [], Fake);\n } else {\n try {\n Fake.call();\n } catch (x) {\n control = x;\n }\n\n fn.call(Fake.prototype);\n }\n } else {\n try {\n throw Error();\n } catch (x) {\n control = x;\n }\n\n fn();\n }\n } catch (sample) {\n // This is inlined manually because closure doesn't do it for us.\n if (sample && control && typeof sample.stack === 'string') {\n // This extracts the first frame from the sample that isn't also in the control.\n // Skipping one frame that we assume is the frame that calls the two.\n var sampleLines = sample.stack.split('\\n');\n var controlLines = control.stack.split('\\n');\n var s = sampleLines.length - 1;\n var c = controlLines.length - 1;\n\n while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {\n // We expect at least one stack frame to be shared.\n // Typically this will be the root most one. However, stack frames may be\n // cut off due to maximum stack limits. In this case, one maybe cut off\n // earlier than the other. We assume that the sample is longer or the same\n // and there for cut off earlier. So we should find the root most frame in\n // the sample somewhere in the control.\n c--;\n }\n\n for (; s >= 1 && c >= 0; s--, c--) {\n // Next we find the first one that isn't the same which should be the\n // frame that called our sample function and the control.\n if (sampleLines[s] !== controlLines[c]) {\n // In V8, the first line is describing the message but other VMs don't.\n // If we're about to return the first line, and the control is also on the same\n // line, that's a pretty good indicator that our sample threw at same line as\n // the control. I.e. before we entered the sample frame. So we ignore this result.\n // This can happen if you passed a class to function component, or non-function.\n if (s !== 1 || c !== 1) {\n do {\n s--;\n c--; // We may still have similar intermediate frames from the construct call.\n // The next one that isn't the same should be our match though.\n\n if (c < 0 || sampleLines[s] !== controlLines[c]) {\n // V8 adds a \"new\" prefix for native classes. Let's remove it to make it prettier.\n var _frame = '\\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled \"<anonymous>\"\n // but we have a user-provided \"displayName\"\n // splice it in to make the stack more readable.\n\n\n if (fn.displayName && _frame.includes('<anonymous>')) {\n _frame = _frame.replace('<anonymous>', fn.displayName);\n }\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, _frame);\n }\n } // Return the line we found.\n\n\n return _frame;\n }\n } while (s >= 1 && c >= 0);\n }\n\n break;\n }\n }\n }\n } finally {\n reentry = false;\n\n {\n ReactCurrentDispatcher.current = previousDispatcher;\n reenableLogs();\n }\n\n Error.prepareStackTrace = previousPrepareStackTrace;\n } // Fallback to just using the name if we couldn't make it throw.\n\n\n var name = fn ? fn.displayName || fn.name : '';\n var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, syntheticFrame);\n }\n }\n\n return syntheticFrame;\n}\nfunction describeFunctionComponentFrame(fn, source, ownerFn) {\n {\n return describeNativeComponentFrame(fn, false);\n }\n}\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {\n\n if (type == null) {\n return '';\n }\n\n if (typeof type === 'function') {\n {\n return describeNativeComponentFrame(type, shouldConstruct(type));\n }\n }\n\n if (typeof type === 'string') {\n return describeBuiltInComponentFrame(type);\n }\n\n switch (type) {\n case REACT_SUSPENSE_TYPE:\n return describeBuiltInComponentFrame('Suspense');\n\n case REACT_SUSPENSE_LIST_TYPE:\n return describeBuiltInComponentFrame('SuspenseList');\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n return describeFunctionComponentFrame(type.render);\n\n case REACT_MEMO_TYPE:\n // Memo may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n // Lazy may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);\n } catch (x) {}\n }\n }\n }\n\n return '';\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame.setExtraStackFrame(null);\n }\n }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n {\n // $FlowFixMe This is okay but Flow doesn't know it.\n var has = Function.call.bind(hasOwnProperty);\n\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n // eslint-disable-next-line react-internal/prod-error-codes\n var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');\n err.name = 'Invariant Violation';\n throw err;\n }\n\n error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n } catch (ex) {\n error$1 = ex;\n }\n\n if (error$1 && !(error$1 instanceof Error)) {\n setCurrentlyValidatingElement(element);\n\n error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);\n\n setCurrentlyValidatingElement(null);\n }\n\n if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error$1.message] = true;\n setCurrentlyValidatingElement(element);\n\n error('Failed %s type: %s', location, error$1.message);\n\n setCurrentlyValidatingElement(null);\n }\n }\n }\n }\n}\n\nvar isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare\n\nfunction isArray(a) {\n return isArrayImpl(a);\n}\n\n/*\n * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol\n * and Temporal.* types. See https://github.com/facebook/react/pull/22064.\n *\n * The functions in this module will throw an easier-to-understand,\n * easier-to-debug exception with a clear errors message message explaining the\n * problem. (Instead of a confusing exception thrown inside the implementation\n * of the `value` object).\n */\n// $FlowFixMe only called in DEV, so void return is not possible.\nfunction typeName(value) {\n {\n // toStringTag is needed for namespaced types like Temporal.Instant\n var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;\n var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';\n return type;\n }\n} // $FlowFixMe only called in DEV, so void return is not possible.\n\n\nfunction willCoercionThrow(value) {\n {\n try {\n testStringCoercion(value);\n return false;\n } catch (e) {\n return true;\n }\n }\n}\n\nfunction testStringCoercion(value) {\n // If you ended up here by following an exception call stack, here's what's\n // happened: you supplied an object or symbol value to React (as a prop, key,\n // DOM attribute, CSS property, string ref, etc.) and when React tried to\n // coerce it to a string using `'' + value`, an exception was thrown.\n //\n // The most common types that will cause this exception are `Symbol` instances\n // and Temporal objects like `Temporal.Instant`. But any object that has a\n // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this\n // exception. (Library authors do this to prevent users from using built-in\n // numeric operators like `+` or comparison operators like `>=` because custom\n // methods are needed to perform accurate arithmetic or comparison.)\n //\n // To fix the problem, coerce this object or symbol value to a string before\n // passing it to React. The most reliable way is usually `String(value)`.\n //\n // To find which value is throwing, check the browser or debugger console.\n // Before this exception was thrown, there should be `console.error` output\n // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the\n // problem and how that type was used: key, atrribute, input value prop, etc.\n // In most cases, this console output also shows the component and its\n // ancestor components where the exception happened.\n //\n // eslint-disable-next-line react-internal/safe-string-coercion\n return '' + value;\n}\nfunction checkKeyStringCoercion(value) {\n {\n if (willCoercionThrow(value)) {\n error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));\n\n return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n }\n }\n}\n\nvar ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;\nvar RESERVED_PROPS = {\n key: true,\n ref: true,\n __self: true,\n __source: true\n};\nvar specialPropKeyWarningShown;\nvar specialPropRefWarningShown;\nvar didWarnAboutStringRefs;\n\n{\n didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n {\n if (hasOwnProperty.call(config, 'ref')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n {\n if (hasOwnProperty.call(config, 'key')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.key !== undefined;\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config, self) {\n {\n if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {\n var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);\n\n if (!didWarnAboutStringRefs[componentName]) {\n error('Component \"%s\" contains the string ref \"%s\". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n {\n var warnAboutAccessingKey = function () {\n if (!specialPropKeyWarningShown) {\n specialPropKeyWarningShown = true;\n\n error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);\n }\n };\n\n warnAboutAccessingKey.isReactWarning = true;\n Object.defineProperty(props, 'key', {\n get: warnAboutAccessingKey,\n configurable: true\n });\n }\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n {\n var warnAboutAccessingRef = function () {\n if (!specialPropRefWarningShown) {\n specialPropRefWarningShown = true;\n\n error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);\n }\n };\n\n warnAboutAccessingRef.isReactWarning = true;\n Object.defineProperty(props, 'ref', {\n get: warnAboutAccessingRef,\n configurable: true\n });\n }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n var element = {\n // This tag allows us to uniquely identify this as a React Element\n $$typeof: REACT_ELEMENT_TYPE,\n // Built-in properties that belong on the element\n type: type,\n key: key,\n ref: ref,\n props: props,\n // Record the component responsible for creating this element.\n _owner: owner\n };\n\n {\n // The validation flag is currently mutative. We put it on\n // an external backing store so that we can freeze the whole object.\n // This can be replaced with a WeakMap once they are implemented in\n // commonly used development environments.\n element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n // the validation flag non-enumerable (where possible, which should\n // include every environment we run tests in), so the test framework\n // ignores it.\n\n Object.defineProperty(element._store, 'validated', {\n configurable: false,\n enumerable: false,\n writable: true,\n value: false\n }); // self and source are DEV only properties.\n\n Object.defineProperty(element, '_self', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: self\n }); // Two elements created in two different places should be considered\n // equal for testing purposes and therefore we hide it from enumeration.\n\n Object.defineProperty(element, '_source', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: source\n });\n\n if (Object.freeze) {\n Object.freeze(element.props);\n Object.freeze(element);\n }\n }\n\n return element;\n};\n/**\n * https://github.com/reactjs/rfcs/pull/107\n * @param {*} type\n * @param {object} props\n * @param {string} key\n */\n\nfunction jsxDEV(type, config, maybeKey, source, self) {\n {\n var propName; // Reserved names are extracted\n\n var props = {};\n var key = null;\n var ref = null; // Currently, key can be spread in as a prop. This causes a potential\n // issue if key is also explicitly declared (ie. <div {...props} key=\"Hi\" />\n // or <div key=\"Hi\" {...props} /> ). We want to deprecate key spread,\n // but as an intermediary step, we will use jsxDEV for everything except\n // <div {...props} key=\"Hi\" />, because we aren't currently able to tell if\n // key is explicitly declared to be undefined or not.\n\n if (maybeKey !== undefined) {\n {\n checkKeyStringCoercion(maybeKey);\n }\n\n key = '' + maybeKey;\n }\n\n if (hasValidKey(config)) {\n {\n checkKeyStringCoercion(config.key);\n }\n\n key = '' + config.key;\n }\n\n if (hasValidRef(config)) {\n ref = config.ref;\n warnIfStringRefCannotBeAutoConverted(config, self);\n } // Remaining properties are added to a new props object\n\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n props[propName] = config[propName];\n }\n } // Resolve default props\n\n\n if (type && type.defaultProps) {\n var defaultProps = type.defaultProps;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }\n\n if (key || ref) {\n var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n if (key) {\n defineKeyPropWarningGetter(props, displayName);\n }\n\n if (ref) {\n defineRefPropWarningGetter(props, displayName);\n }\n }\n\n return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n }\n}\n\nvar ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement$1(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame$1.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame$1.setExtraStackFrame(null);\n }\n }\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n propTypesMisspellWarningShown = false;\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\n\nfunction isValidElement(object) {\n {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n }\n}\n\nfunction getDeclarationErrorAddendum() {\n {\n if (ReactCurrentOwner$1.current) {\n var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);\n\n if (name) {\n return '\\n\\nCheck the render method of `' + name + '`.';\n }\n }\n\n return '';\n }\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n {\n if (source !== undefined) {\n var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n var lineNumber = source.lineNumber;\n return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n }\n\n return '';\n }\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n {\n var info = getDeclarationErrorAddendum();\n\n if (!info) {\n var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n if (parentName) {\n info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n }\n }\n\n return info;\n }\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n {\n if (!element._store || element._store.validated || element.key != null) {\n return;\n }\n\n element._store.validated = true;\n var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n // property, it may be the creator of the child that's responsible for\n // assigning it a key.\n\n var childOwner = '';\n\n if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {\n // Give the component that originally created this child.\n childOwner = \" It was passed a child from \" + getComponentNameFromType(element._owner.type) + \".\";\n }\n\n setCurrentlyValidatingElement$1(element);\n\n error('Each child in a list should have a unique \"key\" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);\n\n setCurrentlyValidatingElement$1(null);\n }\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n {\n if (typeof node !== 'object') {\n return;\n }\n\n if (isArray(node)) {\n for (var i = 0; i < node.length; i++) {\n var child = node[i];\n\n if (isValidElement(child)) {\n validateExplicitKey(child, parentType);\n }\n }\n } else if (isValidElement(node)) {\n // This element was passed in a valid location.\n if (node._store) {\n node._store.validated = true;\n }\n } else if (node) {\n var iteratorFn = getIteratorFn(node);\n\n if (typeof iteratorFn === 'function') {\n // Entry iterators used to provide implicit keys,\n // but now we print a separate warning for them later.\n if (iteratorFn !== node.entries) {\n var iterator = iteratorFn.call(node);\n var step;\n\n while (!(step = iterator.next()).done) {\n if (isValidElement(step.value)) {\n validateExplicitKey(step.value, parentType);\n }\n }\n }\n }\n }\n }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n {\n var type = element.type;\n\n if (type === null || type === undefined || typeof type === 'string') {\n return;\n }\n\n var propTypes;\n\n if (typeof type === 'function') {\n propTypes = type.propTypes;\n } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n // Inner props are checked in the reconciler.\n type.$$typeof === REACT_MEMO_TYPE)) {\n propTypes = type.propTypes;\n } else {\n return;\n }\n\n if (propTypes) {\n // Intentionally inside to avoid triggering lazy initializers:\n var name = getComponentNameFromType(type);\n checkPropTypes(propTypes, element.props, 'prop', name, element);\n } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:\n\n var _name = getComponentNameFromType(type);\n\n error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');\n }\n\n if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n }\n }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n {\n var keys = Object.keys(fragment.props);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (key !== 'children' && key !== 'key') {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n setCurrentlyValidatingElement$1(null);\n break;\n }\n }\n\n if (fragment.ref !== null) {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid attribute `ref` supplied to `React.Fragment`.');\n\n setCurrentlyValidatingElement$1(null);\n }\n }\n}\n\nvar didWarnAboutKeySpread = {};\nfunction jsxWithValidation(type, props, key, isStaticChildren, source, self) {\n {\n var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n // succeed and there will likely be errors in render.\n\n if (!validType) {\n var info = '';\n\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and named imports.\";\n }\n\n var sourceInfo = getSourceInfoErrorAddendum(source);\n\n if (sourceInfo) {\n info += sourceInfo;\n } else {\n info += getDeclarationErrorAddendum();\n }\n\n var typeString;\n\n if (type === null) {\n typeString = 'null';\n } else if (isArray(type)) {\n typeString = 'array';\n } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n typeString = \"<\" + (getComponentNameFromType(type.type) || 'Unknown') + \" />\";\n info = ' Did you accidentally export a JSX literal instead of a component?';\n } else {\n typeString = typeof type;\n }\n\n error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);\n }\n\n var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.\n // TODO: Drop this when these are no longer allowed as the type argument.\n\n if (element == null) {\n return element;\n } // Skip key warning if the type isn't valid since our key validation logic\n // doesn't expect a non-string/function type and can throw confusing errors.\n // We don't want exception behavior to differ between dev and prod.\n // (Rendering will throw with a helpful message and as soon as the type is\n // fixed, the key warnings will appear.)\n\n\n if (validType) {\n var children = props.children;\n\n if (children !== undefined) {\n if (isStaticChildren) {\n if (isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n validateChildKeys(children[i], type);\n }\n\n if (Object.freeze) {\n Object.freeze(children);\n }\n } else {\n error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');\n }\n } else {\n validateChildKeys(children, type);\n }\n }\n }\n\n {\n if (hasOwnProperty.call(props, 'key')) {\n var componentName = getComponentNameFromType(type);\n var keys = Object.keys(props).filter(function (k) {\n return k !== 'key';\n });\n var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';\n\n if (!didWarnAboutKeySpread[componentName + beforeExample]) {\n var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';\n\n error('A props object containing a \"key\" prop is being spread into JSX:\\n' + ' let props = %s;\\n' + ' <%s {...props} />\\n' + 'React keys must be passed directly to JSX without using spread:\\n' + ' let props = %s;\\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);\n\n didWarnAboutKeySpread[componentName + beforeExample] = true;\n }\n }\n }\n\n if (type === REACT_FRAGMENT_TYPE) {\n validateFragmentProps(element);\n } else {\n validatePropTypes(element);\n }\n\n return element;\n }\n} // These two functions exist to still get child warnings in dev\n// even with the prod transform. This means that jsxDEV is purely\n// opt-in behavior for better messages but that we won't stop\n// giving you warnings if you use production apis.\n\nfunction jsxWithValidationStatic(type, props, key) {\n {\n return jsxWithValidation(type, props, key, true);\n }\n}\nfunction jsxWithValidationDynamic(type, props, key) {\n {\n return jsxWithValidation(type, props, key, false);\n }\n}\n\nvar jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.\n// for now we can ship identical prod functions\n\nvar jsxs = jsxWithValidationStatic ;\n\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsx;\nexports.jsxs = jsxs;\n })();\n}\n\n\n//# sourceURL=webpack://WordPress/./node_modules/react/cjs/react-jsx-runtime.development.js?"); /***/ }), /***/ "./node_modules/react/jsx-runtime.js": /*!*******************************************!*\ !*** ./node_modules/react/jsx-runtime.js ***! \*******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { eval("\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/react-jsx-runtime.development.js */ \"./node_modules/react/cjs/react-jsx-runtime.development.js\");\n}\n\n\n//# sourceURL=webpack://WordPress/./node_modules/react/jsx-runtime.js?"); /***/ }), /***/ "react": /*!************************!*\ !*** external "React" ***! \************************/ /***/ ((module) => { module.exports = React; /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module can't be inlined because the eval devtool is used. /******/ var __webpack_exports__ = __webpack_require__("./node_modules/react/jsx-runtime.js"); /******/ window.ReactJSXRuntime = __webpack_exports__; /******/ /******/ })() ; wp-polyfill-inert.js 0000604 00000073016 14720015030 0010472 0 ustar 00 (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory() : typeof define === 'function' && define.amd ? define('inert', factory) : (factory()); }(this, (function () { 'use strict'; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * This work is licensed under the W3C Software and Document License * (http://www.w3.org/Consortium/Legal/2015/copyright-software-and-document). */ (function () { // Return early if we're not running inside of the browser. if (typeof window === 'undefined' || typeof Element === 'undefined') { return; } // Convenience function for converting NodeLists. /** @type {typeof Array.prototype.slice} */ var slice = Array.prototype.slice; /** * IE has a non-standard name for "matches". * @type {typeof Element.prototype.matches} */ var matches = Element.prototype.matches || Element.prototype.msMatchesSelector; /** @type {string} */ var _focusableElementsString = ['a[href]', 'area[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'details', 'summary', 'iframe', 'object', 'embed', 'video', '[contenteditable]'].join(','); /** * `InertRoot` manages a single inert subtree, i.e. a DOM subtree whose root element has an `inert` * attribute. * * Its main functions are: * * - to create and maintain a set of managed `InertNode`s, including when mutations occur in the * subtree. The `makeSubtreeUnfocusable()` method handles collecting `InertNode`s via registering * each focusable node in the subtree with the singleton `InertManager` which manages all known * focusable nodes within inert subtrees. `InertManager` ensures that a single `InertNode` * instance exists for each focusable node which has at least one inert root as an ancestor. * * - to notify all managed `InertNode`s when this subtree stops being inert (i.e. when the `inert` * attribute is removed from the root node). This is handled in the destructor, which calls the * `deregister` method on `InertManager` for each managed inert node. */ var InertRoot = function () { /** * @param {!HTMLElement} rootElement The HTMLElement at the root of the inert subtree. * @param {!InertManager} inertManager The global singleton InertManager object. */ function InertRoot(rootElement, inertManager) { _classCallCheck(this, InertRoot); /** @type {!InertManager} */ this._inertManager = inertManager; /** @type {!HTMLElement} */ this._rootElement = rootElement; /** * @type {!Set<!InertNode>} * All managed focusable nodes in this InertRoot's subtree. */ this._managedNodes = new Set(); // Make the subtree hidden from assistive technology if (this._rootElement.hasAttribute('aria-hidden')) { /** @type {?string} */ this._savedAriaHidden = this._rootElement.getAttribute('aria-hidden'); } else { this._savedAriaHidden = null; } this._rootElement.setAttribute('aria-hidden', 'true'); // Make all focusable elements in the subtree unfocusable and add them to _managedNodes this._makeSubtreeUnfocusable(this._rootElement); // Watch for: // - any additions in the subtree: make them unfocusable too // - any removals from the subtree: remove them from this inert root's managed nodes // - attribute changes: if `tabindex` is added, or removed from an intrinsically focusable // element, make that node a managed node. this._observer = new MutationObserver(this._onMutation.bind(this)); this._observer.observe(this._rootElement, { attributes: true, childList: true, subtree: true }); } /** * Call this whenever this object is about to become obsolete. This unwinds all of the state * stored in this object and updates the state of all of the managed nodes. */ _createClass(InertRoot, [{ key: 'destructor', value: function destructor() { this._observer.disconnect(); if (this._rootElement) { if (this._savedAriaHidden !== null) { this._rootElement.setAttribute('aria-hidden', this._savedAriaHidden); } else { this._rootElement.removeAttribute('aria-hidden'); } } this._managedNodes.forEach(function (inertNode) { this._unmanageNode(inertNode.node); }, this); // Note we cast the nulls to the ANY type here because: // 1) We want the class properties to be declared as non-null, or else we // need even more casts throughout this code. All bets are off if an // instance has been destroyed and a method is called. // 2) We don't want to cast "this", because we want type-aware optimizations // to know which properties we're setting. this._observer = /** @type {?} */null; this._rootElement = /** @type {?} */null; this._managedNodes = /** @type {?} */null; this._inertManager = /** @type {?} */null; } /** * @return {!Set<!InertNode>} A copy of this InertRoot's managed nodes set. */ }, { key: '_makeSubtreeUnfocusable', /** * @param {!Node} startNode */ value: function _makeSubtreeUnfocusable(startNode) { var _this2 = this; composedTreeWalk(startNode, function (node) { return _this2._visitNode(node); }); var activeElement = document.activeElement; if (!document.body.contains(startNode)) { // startNode may be in shadow DOM, so find its nearest shadowRoot to get the activeElement. var node = startNode; /** @type {!ShadowRoot|undefined} */ var root = undefined; while (node) { if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { root = /** @type {!ShadowRoot} */node; break; } node = node.parentNode; } if (root) { activeElement = root.activeElement; } } if (startNode.contains(activeElement)) { activeElement.blur(); // In IE11, if an element is already focused, and then set to tabindex=-1 // calling blur() will not actually move the focus. // To work around this we call focus() on the body instead. if (activeElement === document.activeElement) { document.body.focus(); } } } /** * @param {!Node} node */ }, { key: '_visitNode', value: function _visitNode(node) { if (node.nodeType !== Node.ELEMENT_NODE) { return; } var element = /** @type {!HTMLElement} */node; // If a descendant inert root becomes un-inert, its descendants will still be inert because of // this inert root, so all of its managed nodes need to be adopted by this InertRoot. if (element !== this._rootElement && element.hasAttribute('inert')) { this._adoptInertRoot(element); } if (matches.call(element, _focusableElementsString) || element.hasAttribute('tabindex')) { this._manageNode(element); } } /** * Register the given node with this InertRoot and with InertManager. * @param {!Node} node */ }, { key: '_manageNode', value: function _manageNode(node) { var inertNode = this._inertManager.register(node, this); this._managedNodes.add(inertNode); } /** * Unregister the given node with this InertRoot and with InertManager. * @param {!Node} node */ }, { key: '_unmanageNode', value: function _unmanageNode(node) { var inertNode = this._inertManager.deregister(node, this); if (inertNode) { this._managedNodes['delete'](inertNode); } } /** * Unregister the entire subtree starting at `startNode`. * @param {!Node} startNode */ }, { key: '_unmanageSubtree', value: function _unmanageSubtree(startNode) { var _this3 = this; composedTreeWalk(startNode, function (node) { return _this3._unmanageNode(node); }); } /** * If a descendant node is found with an `inert` attribute, adopt its managed nodes. * @param {!HTMLElement} node */ }, { key: '_adoptInertRoot', value: function _adoptInertRoot(node) { var inertSubroot = this._inertManager.getInertRoot(node); // During initialisation this inert root may not have been registered yet, // so register it now if need be. if (!inertSubroot) { this._inertManager.setInert(node, true); inertSubroot = this._inertManager.getInertRoot(node); } inertSubroot.managedNodes.forEach(function (savedInertNode) { this._manageNode(savedInertNode.node); }, this); } /** * Callback used when mutation observer detects subtree additions, removals, or attribute changes. * @param {!Array<!MutationRecord>} records * @param {!MutationObserver} self */ }, { key: '_onMutation', value: function _onMutation(records, self) { records.forEach(function (record) { var target = /** @type {!HTMLElement} */record.target; if (record.type === 'childList') { // Manage added nodes slice.call(record.addedNodes).forEach(function (node) { this._makeSubtreeUnfocusable(node); }, this); // Un-manage removed nodes slice.call(record.removedNodes).forEach(function (node) { this._unmanageSubtree(node); }, this); } else if (record.type === 'attributes') { if (record.attributeName === 'tabindex') { // Re-initialise inert node if tabindex changes this._manageNode(target); } else if (target !== this._rootElement && record.attributeName === 'inert' && target.hasAttribute('inert')) { // If a new inert root is added, adopt its managed nodes and make sure it knows about the // already managed nodes from this inert subroot. this._adoptInertRoot(target); var inertSubroot = this._inertManager.getInertRoot(target); this._managedNodes.forEach(function (managedNode) { if (target.contains(managedNode.node)) { inertSubroot._manageNode(managedNode.node); } }); } } }, this); } }, { key: 'managedNodes', get: function get() { return new Set(this._managedNodes); } /** @return {boolean} */ }, { key: 'hasSavedAriaHidden', get: function get() { return this._savedAriaHidden !== null; } /** @param {?string} ariaHidden */ }, { key: 'savedAriaHidden', set: function set(ariaHidden) { this._savedAriaHidden = ariaHidden; } /** @return {?string} */ , get: function get() { return this._savedAriaHidden; } }]); return InertRoot; }(); /** * `InertNode` initialises and manages a single inert node. * A node is inert if it is a descendant of one or more inert root elements. * * On construction, `InertNode` saves the existing `tabindex` value for the node, if any, and * either removes the `tabindex` attribute or sets it to `-1`, depending on whether the element * is intrinsically focusable or not. * * `InertNode` maintains a set of `InertRoot`s which are descendants of this `InertNode`. When an * `InertRoot` is destroyed, and calls `InertManager.deregister()`, the `InertManager` notifies the * `InertNode` via `removeInertRoot()`, which in turn destroys the `InertNode` if no `InertRoot`s * remain in the set. On destruction, `InertNode` reinstates the stored `tabindex` if one exists, * or removes the `tabindex` attribute if the element is intrinsically focusable. */ var InertNode = function () { /** * @param {!Node} node A focusable element to be made inert. * @param {!InertRoot} inertRoot The inert root element associated with this inert node. */ function InertNode(node, inertRoot) { _classCallCheck(this, InertNode); /** @type {!Node} */ this._node = node; /** @type {boolean} */ this._overrodeFocusMethod = false; /** * @type {!Set<!InertRoot>} The set of descendant inert roots. * If and only if this set becomes empty, this node is no longer inert. */ this._inertRoots = new Set([inertRoot]); /** @type {?number} */ this._savedTabIndex = null; /** @type {boolean} */ this._destroyed = false; // Save any prior tabindex info and make this node untabbable this.ensureUntabbable(); } /** * Call this whenever this object is about to become obsolete. * This makes the managed node focusable again and deletes all of the previously stored state. */ _createClass(InertNode, [{ key: 'destructor', value: function destructor() { this._throwIfDestroyed(); if (this._node && this._node.nodeType === Node.ELEMENT_NODE) { var element = /** @type {!HTMLElement} */this._node; if (this._savedTabIndex !== null) { element.setAttribute('tabindex', this._savedTabIndex); } else { element.removeAttribute('tabindex'); } // Use `delete` to restore native focus method. if (this._overrodeFocusMethod) { delete element.focus; } } // See note in InertRoot.destructor for why we cast these nulls to ANY. this._node = /** @type {?} */null; this._inertRoots = /** @type {?} */null; this._destroyed = true; } /** * @type {boolean} Whether this object is obsolete because the managed node is no longer inert. * If the object has been destroyed, any attempt to access it will cause an exception. */ }, { key: '_throwIfDestroyed', /** * Throw if user tries to access destroyed InertNode. */ value: function _throwIfDestroyed() { if (this.destroyed) { throw new Error('Trying to access destroyed InertNode'); } } /** @return {boolean} */ }, { key: 'ensureUntabbable', /** Save the existing tabindex value and make the node untabbable and unfocusable */ value: function ensureUntabbable() { if (this.node.nodeType !== Node.ELEMENT_NODE) { return; } var element = /** @type {!HTMLElement} */this.node; if (matches.call(element, _focusableElementsString)) { if ( /** @type {!HTMLElement} */element.tabIndex === -1 && this.hasSavedTabIndex) { return; } if (element.hasAttribute('tabindex')) { this._savedTabIndex = /** @type {!HTMLElement} */element.tabIndex; } element.setAttribute('tabindex', '-1'); if (element.nodeType === Node.ELEMENT_NODE) { element.focus = function () {}; this._overrodeFocusMethod = true; } } else if (element.hasAttribute('tabindex')) { this._savedTabIndex = /** @type {!HTMLElement} */element.tabIndex; element.removeAttribute('tabindex'); } } /** * Add another inert root to this inert node's set of managing inert roots. * @param {!InertRoot} inertRoot */ }, { key: 'addInertRoot', value: function addInertRoot(inertRoot) { this._throwIfDestroyed(); this._inertRoots.add(inertRoot); } /** * Remove the given inert root from this inert node's set of managing inert roots. * If the set of managing inert roots becomes empty, this node is no longer inert, * so the object should be destroyed. * @param {!InertRoot} inertRoot */ }, { key: 'removeInertRoot', value: function removeInertRoot(inertRoot) { this._throwIfDestroyed(); this._inertRoots['delete'](inertRoot); if (this._inertRoots.size === 0) { this.destructor(); } } }, { key: 'destroyed', get: function get() { return (/** @type {!InertNode} */this._destroyed ); } }, { key: 'hasSavedTabIndex', get: function get() { return this._savedTabIndex !== null; } /** @return {!Node} */ }, { key: 'node', get: function get() { this._throwIfDestroyed(); return this._node; } /** @param {?number} tabIndex */ }, { key: 'savedTabIndex', set: function set(tabIndex) { this._throwIfDestroyed(); this._savedTabIndex = tabIndex; } /** @return {?number} */ , get: function get() { this._throwIfDestroyed(); return this._savedTabIndex; } }]); return InertNode; }(); /** * InertManager is a per-document singleton object which manages all inert roots and nodes. * * When an element becomes an inert root by having an `inert` attribute set and/or its `inert` * property set to `true`, the `setInert` method creates an `InertRoot` object for the element. * The `InertRoot` in turn registers itself as managing all of the element's focusable descendant * nodes via the `register()` method. The `InertManager` ensures that a single `InertNode` instance * is created for each such node, via the `_managedNodes` map. */ var InertManager = function () { /** * @param {!Document} document */ function InertManager(document) { _classCallCheck(this, InertManager); if (!document) { throw new Error('Missing required argument; InertManager needs to wrap a document.'); } /** @type {!Document} */ this._document = document; /** * All managed nodes known to this InertManager. In a map to allow looking up by Node. * @type {!Map<!Node, !InertNode>} */ this._managedNodes = new Map(); /** * All inert roots known to this InertManager. In a map to allow looking up by Node. * @type {!Map<!Node, !InertRoot>} */ this._inertRoots = new Map(); /** * Observer for mutations on `document.body`. * @type {!MutationObserver} */ this._observer = new MutationObserver(this._watchForInert.bind(this)); // Add inert style. addInertStyle(document.head || document.body || document.documentElement); // Wait for document to be loaded. if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', this._onDocumentLoaded.bind(this)); } else { this._onDocumentLoaded(); } } /** * Set whether the given element should be an inert root or not. * @param {!HTMLElement} root * @param {boolean} inert */ _createClass(InertManager, [{ key: 'setInert', value: function setInert(root, inert) { if (inert) { if (this._inertRoots.has(root)) { // element is already inert return; } var inertRoot = new InertRoot(root, this); root.setAttribute('inert', ''); this._inertRoots.set(root, inertRoot); // If not contained in the document, it must be in a shadowRoot. // Ensure inert styles are added there. if (!this._document.body.contains(root)) { var parent = root.parentNode; while (parent) { if (parent.nodeType === 11) { addInertStyle(parent); } parent = parent.parentNode; } } } else { if (!this._inertRoots.has(root)) { // element is already non-inert return; } var _inertRoot = this._inertRoots.get(root); _inertRoot.destructor(); this._inertRoots['delete'](root); root.removeAttribute('inert'); } } /** * Get the InertRoot object corresponding to the given inert root element, if any. * @param {!Node} element * @return {!InertRoot|undefined} */ }, { key: 'getInertRoot', value: function getInertRoot(element) { return this._inertRoots.get(element); } /** * Register the given InertRoot as managing the given node. * In the case where the node has a previously existing inert root, this inert root will * be added to its set of inert roots. * @param {!Node} node * @param {!InertRoot} inertRoot * @return {!InertNode} inertNode */ }, { key: 'register', value: function register(node, inertRoot) { var inertNode = this._managedNodes.get(node); if (inertNode !== undefined) { // node was already in an inert subtree inertNode.addInertRoot(inertRoot); } else { inertNode = new InertNode(node, inertRoot); } this._managedNodes.set(node, inertNode); return inertNode; } /** * De-register the given InertRoot as managing the given inert node. * Removes the inert root from the InertNode's set of managing inert roots, and remove the inert * node from the InertManager's set of managed nodes if it is destroyed. * If the node is not currently managed, this is essentially a no-op. * @param {!Node} node * @param {!InertRoot} inertRoot * @return {?InertNode} The potentially destroyed InertNode associated with this node, if any. */ }, { key: 'deregister', value: function deregister(node, inertRoot) { var inertNode = this._managedNodes.get(node); if (!inertNode) { return null; } inertNode.removeInertRoot(inertRoot); if (inertNode.destroyed) { this._managedNodes['delete'](node); } return inertNode; } /** * Callback used when document has finished loading. */ }, { key: '_onDocumentLoaded', value: function _onDocumentLoaded() { // Find all inert roots in document and make them actually inert. var inertElements = slice.call(this._document.querySelectorAll('[inert]')); inertElements.forEach(function (inertElement) { this.setInert(inertElement, true); }, this); // Comment this out to use programmatic API only. this._observer.observe(this._document.body || this._document.documentElement, { attributes: true, subtree: true, childList: true }); } /** * Callback used when mutation observer detects attribute changes. * @param {!Array<!MutationRecord>} records * @param {!MutationObserver} self */ }, { key: '_watchForInert', value: function _watchForInert(records, self) { var _this = this; records.forEach(function (record) { switch (record.type) { case 'childList': slice.call(record.addedNodes).forEach(function (node) { if (node.nodeType !== Node.ELEMENT_NODE) { return; } var inertElements = slice.call(node.querySelectorAll('[inert]')); if (matches.call(node, '[inert]')) { inertElements.unshift(node); } inertElements.forEach(function (inertElement) { this.setInert(inertElement, true); }, _this); }, _this); break; case 'attributes': if (record.attributeName !== 'inert') { return; } var target = /** @type {!HTMLElement} */record.target; var inert = target.hasAttribute('inert'); _this.setInert(target, inert); break; } }, this); } }]); return InertManager; }(); /** * Recursively walk the composed tree from |node|. * @param {!Node} node * @param {(function (!HTMLElement))=} callback Callback to be called for each element traversed, * before descending into child nodes. * @param {?ShadowRoot=} shadowRootAncestor The nearest ShadowRoot ancestor, if any. */ function composedTreeWalk(node, callback, shadowRootAncestor) { if (node.nodeType == Node.ELEMENT_NODE) { var element = /** @type {!HTMLElement} */node; if (callback) { callback(element); } // Descend into node: // If it has a ShadowRoot, ignore all child elements - these will be picked // up by the <content> or <shadow> elements. Descend straight into the // ShadowRoot. var shadowRoot = /** @type {!HTMLElement} */element.shadowRoot; if (shadowRoot) { composedTreeWalk(shadowRoot, callback, shadowRoot); return; } // If it is a <content> element, descend into distributed elements - these // are elements from outside the shadow root which are rendered inside the // shadow DOM. if (element.localName == 'content') { var content = /** @type {!HTMLContentElement} */element; // Verifies if ShadowDom v0 is supported. var distributedNodes = content.getDistributedNodes ? content.getDistributedNodes() : []; for (var i = 0; i < distributedNodes.length; i++) { composedTreeWalk(distributedNodes[i], callback, shadowRootAncestor); } return; } // If it is a <slot> element, descend into assigned nodes - these // are elements from outside the shadow root which are rendered inside the // shadow DOM. if (element.localName == 'slot') { var slot = /** @type {!HTMLSlotElement} */element; // Verify if ShadowDom v1 is supported. var _distributedNodes = slot.assignedNodes ? slot.assignedNodes({ flatten: true }) : []; for (var _i = 0; _i < _distributedNodes.length; _i++) { composedTreeWalk(_distributedNodes[_i], callback, shadowRootAncestor); } return; } } // If it is neither the parent of a ShadowRoot, a <content> element, a <slot> // element, nor a <shadow> element recurse normally. var child = node.firstChild; while (child != null) { composedTreeWalk(child, callback, shadowRootAncestor); child = child.nextSibling; } } /** * Adds a style element to the node containing the inert specific styles * @param {!Node} node */ function addInertStyle(node) { if (node.querySelector('style#inert-style, link#inert-style')) { return; } var style = document.createElement('style'); style.setAttribute('id', 'inert-style'); style.textContent = '\n' + '[inert] {\n' + ' pointer-events: none;\n' + ' cursor: default;\n' + '}\n' + '\n' + '[inert], [inert] * {\n' + ' -webkit-user-select: none;\n' + ' -moz-user-select: none;\n' + ' -ms-user-select: none;\n' + ' user-select: none;\n' + '}\n'; node.appendChild(style); } if (!HTMLElement.prototype.hasOwnProperty('inert')) { /** @type {!InertManager} */ var inertManager = new InertManager(document); Object.defineProperty(HTMLElement.prototype, 'inert', { enumerable: true, /** @this {!HTMLElement} */ get: function get() { return this.hasAttribute('inert'); }, /** @this {!HTMLElement} */ set: function set(inert) { inertManager.setInert(this, inert); } }); } })(); }))); regenerator-runtime.js 0000604 00000061333 14720015030 0011072 0 ustar 00 /** * 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 defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }; 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 define(obj, key, value) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); return obj[key]; } try { // IE 8 has a broken Object.defineProperty that only works on DOM objects. define({}, ""); } catch (err) { define = function(obj, key, value) { return obj[key] = value; }; } 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. defineProperty(generator, "_invoke", { value: 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 = {}; define(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 = GeneratorFunctionPrototype; defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: true }); defineProperty( GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: true } ); GeneratorFunction.displayName = define( GeneratorFunctionPrototype, toStringTagSymbol, "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) { define(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; define(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). defineProperty(this, "_invoke", { value: enqueue }); } defineIteratorMethods(AsyncIterator.prototype); define(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 GeneratorResume behavior specified since ES2015: // ES2015 spec, step 3: https://262.ecma-international.org/6.0/#sec-generatorresume // Latest spec, step 2: https://tc39.es/ecma262/#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 methodName = context.method; var method = delegate.iterator[methodName]; if (method === undefined) { // A .throw or .return when the delegate iterator has no .throw // method, or a missing .next method, always terminate the // yield* loop. context.delegate = null; // Note: ["return"] must be used for ES3 parsing compatibility. if (methodName === "throw" && 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; } } if (methodName !== "return") { context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a '" + methodName + "' 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); define(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. define(Gp, iteratorSymbol, function() { return this; }); define(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(val) { var object = Object(val); 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 != null) { 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; } } throw new TypeError(typeof iterable + " is not iterable"); } 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. typeof module === "object" ? module.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, in modern engines // we can explicitly access globalThis. In older engines 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. if (typeof globalThis === "object") { globalThis.regeneratorRuntime = runtime; } else { Function("r", "regeneratorRuntime = r")(runtime); } }
| ver. 1.4 |
Github
|
.
| PHP 8.0.30 | Генерация страницы: 0.22 |
proxy
|
phpinfo
|
Настройка