diff --git a/dist/brackets-viewer.min.js b/dist/brackets-viewer.min.js index ad10474..67e7322 100644 --- a/dist/brackets-viewer.min.js +++ b/dist/brackets-viewer.min.js @@ -1 +1 @@ -!function(){"use strict";var t={335:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.setupConnection=e.getFinalConnection=e.getBracketConnection=e.addParticipantImage=e.addParticipantOrigin=e.setupLoss=e.setupWin=e.setupBye=e.setupHint=e.createRankingHeaders=e.createCell=e.createRow=e.createTable=e.createResultContainer=e.createNameContainer=e.createParticipantContainer=e.createOpponentsContainer=e.createChildCountLabel=e.createMatchLabel=e.createMatchContainer=e.createRoundContainer=e.createRoundsContainer=e.createGroupContainer=e.createBracketContainer=e.createEliminationContainer=e.createRoundRobinContainer=e.createTitle=void 0;const o=n(886),r=n(491);e.createTitle=function(t){const e=document.createElement("h1");return e.innerText=t,e},e.createRoundRobinContainer=function(t){const e=document.createElement("div");return e.classList.add("round-robin"),e.setAttribute("data-stage-id",t.toString()),e},e.createEliminationContainer=function(t){const e=document.createElement("div");return e.classList.add("elimination"),e.setAttribute("data-stage-id",t.toString()),e},e.createBracketContainer=function(t,e){const n=document.createElement("section");if(n.classList.add("bracket"),n.setAttribute("data-group-id",t.toString()),e){const t=document.createElement("h2");t.innerText=e,n.append(t)}return n},e.createGroupContainer=function(t,e){const n=document.createElement("h2");n.innerText=e;const o=document.createElement("section");return o.classList.add("group"),o.setAttribute("data-group-id",t.toString()),o.append(n),o},e.createRoundsContainer=function(){const t=document.createElement("div");return t.classList.add("rounds"),t},e.createRoundContainer=function(t,e){const n=document.createElement("h3");n.innerText=e;const o=document.createElement("article");return o.classList.add("round"),o.setAttribute("data-round-id",t.toString()),o.append(n),o},e.createMatchContainer=function(t,e){const n=document.createElement("div");return n.classList.add("match"),void 0!==t&&n.setAttribute("data-match-id",t.toString()),void 0!==e&&n.setAttribute("data-match-status",e.toString()),n},e.createMatchLabel=function(t,e){const n=document.createElement("span");return n.innerText=t,n.title=e,n},e.createChildCountLabel=function(t){const e=document.createElement("span");return e.innerText=t,e},e.createOpponentsContainer=function(t){const e=document.createElement("div");return e.classList.add("opponents"),t&&e.addEventListener("click",t),e},e.createParticipantContainer=function(t){const e=document.createElement("div");return e.classList.add("participant"),null!=t&&e.setAttribute("data-participant-id",t.toString()),e},e.createNameContainer=function(){const t=document.createElement("div");return t.classList.add("name"),t},e.createResultContainer=function(){const t=document.createElement("div");return t.classList.add("result"),t},e.createTable=function(){return document.createElement("table")},e.createRow=function(){return document.createElement("tr")},e.createCell=function(t){const e=document.createElement("td");return e.innerText=String(t),e},e.createRankingHeaders=function(t){const e=document.createElement("tr"),n=t[0];for(const t in n){const n=t,r=(0,o.rankingHeader)(n),i=document.createElement("th");i.innerText=r.text,i.setAttribute("title",r.tooltip),e.append(i)}return e},e.setupHint=function(t,e){t.classList.add("hint"),t.innerText=e},e.setupBye=function(t){t.innerText=(0,r.t)("common.bye"),t.classList.add("bye")},e.setupWin=function(t,e,n){n.result&&"win"===n.result&&(t.classList.add("win"),void 0===n.score&&(e.innerText=(0,r.t)("abbreviations.win")))},e.setupLoss=function(t,e,n){(n.result&&"loss"===n.result||n.forfeit)&&(t.classList.add("loss"),n.forfeit?e.innerText=(0,r.t)("abbreviations.forfeit"):void 0===n.score&&(e.innerText=(0,r.t)("abbreviations.loss")))},e.addParticipantOrigin=function(t,e,n){const o=document.createElement("span");"before"===n?(o.innerText=`${e} `,t.prepend(o)):"after"===n&&(o.innerText=` (${e})`,t.append(o))},e.addParticipantImage=function(t,e){const n=document.createElement("img");n.src=e,t.prepend(n)},e.getBracketConnection=function(t,e,n,o,r,i){var a,s,u;const c={connectPrevious:!1,connectNext:!1};return"loser-bracket"===r?(c.connectPrevious=e>1&&(e%2==1?"square":"straight"),c.connectNext=e1&&"square",c.connectNext=e1)throw Error("Multiple possible roots were found. Please use `config.selector` to choose a specific root.");const n=e[0];if(!n.classList.contains("brackets-viewer"))throw Error("The selected root must have a `.brackets-viewer` class.");return n},e.completeWithBlankMatches=function(t,e,n){if(!n)return{matches:e,fromToornament:!1};let o=[];return"single-bracket"!==t&&"winner-bracket"!==t||(o=n.map((t=>{var e,n;return[(null===(e=t.opponent1)||void 0===e?void 0:e.position)||null,(null===(n=t.opponent2)||void 0===n?void 0:n.position)||null]})).flat()),"loser-bracket"===t&&(o=n.map((t=>{var e;return(null===(e=t.opponent2)||void 0===e?void 0:e.position)||null}))),0===o.filter((t=>null!==t)).length?{matches:e,fromToornament:!1}:{matches:o.map((t=>t&&e.find((e=>e.number===t))||null)),fromToornament:!0}},e.getOriginAbbreviation=function(t,e,n,r){return n=n||-1,e&&"loser-bracket"===t&&1===n||"single-bracket"===t||"winner-bracket"===t&&1===n?(0,o.t)("abbreviations.seed"):"loser-bracket"===t&&n%2==0&&"opponent1"===r?(0,o.t)("abbreviations.position"):null},e.isMajorRound=function(t){return 1===t||t%2==0},e.rankingHeader=function(t){return(0,o.t)(`ranking.${t}`,{returnObjects:!0})},e.getRanking=function(t,e){e=e||(t=>3*t.wins+1*t.draws+0*t.losses);const n={};for(const o of t)r(n,e,o.opponent1,o.opponent2),r(n,e,o.opponent2,o.opponent1);return function(t){const e=Object.values(t).sort(((t,e)=>t.points!==e.points?e.points-t.points:e.played-t.played)),n={value:0,lastPoints:-1};for(const t of e)t.rank=n.lastPoints!==t.points?++n.value:n.value,n.lastPoints=t.points;return e}(n)}},491:function(t,e,n){var o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.getLoserBracketRoundName=e.getWinnerBracketRoundName=e.getRoundName=e.getBracketName=e.getGroupName=e.getMatchStatus=e.getFinalMatchLabel=e.getMatchLabel=e.getFinalOriginHint=e.getOriginHint=e.t=e.addLocale=e.locales=void 0;const r=o(n(261)),i=o(n(71)),a=n(21),s=n(886),u=o(n(583)),c=o(n(159));function l(t,e){return r.default.t(t,e)}e.locales={en:u.default,fr:c.default},r.default.use(i.default).init({fallbackLng:"en",debug:!1,resources:{en:{translation:e.locales.en},fr:{translation:e.locales.fr}}}),e.addLocale=function(t,e){r.default.addResourceBundle(t,"translation",e,!0,!0),r.default.changeLanguage()},e.t=l,e.getOriginHint=function(t,e,n,o){if(1===t){if("single-bracket"===o)return t=>l("origin-hint.seed",{position:t});if("winner-bracket"===o)return t=>l("origin-hint.seed",{position:t});if("loser-bracket"===o&&n)return t=>l("origin-hint.seed",{position:t})}if((0,s.isMajorRound)(t)&&"loser-bracket"===o){if(t===e-2)return t=>l("origin-hint.winner-bracket-semi-final",{position:t});if(t===e)return()=>l("origin-hint.winner-bracket-final");const o=Math.ceil((t+1)/2);return n?t=>l("origin-hint.winner-bracket",{round:o-1,position:t}):t=>l("origin-hint.winner-bracket",{round:o,position:t})}},e.getFinalOriginHint=function(t,e){return"consolation_final"===t?t=>l("origin-hint.consolation-final",{position:t}):1===e?()=>l("origin-hint.grand-final"):void 0},e.getMatchLabel=function(t,e,n,o){const r=l("winner-bracket"===o?"match-label.winner-bracket":"loser-bracket"===o?"match-label.loser-bracket":"match-label.standard-bracket"),i=e===n-1,a=e===n;if("single-bracket"===o){if(i)return l("match-label.standard-bracket-semi-final",{matchNumber:t});if(a)return l("match-label.standard-bracket-final")}return i?l("match-label.double-elimination-semi-final",{matchPrefix:r,matchNumber:t}):a?l("match-label.double-elimination-final",{matchPrefix:r}):l("match-label.double-elimination",{matchPrefix:r,roundNumber:e,matchNumber:t})},e.getFinalMatchLabel=function(t,e,n){return"consolation_final"===t?l("match-label.consolation-final"):1===n?l("match-label.grand-final-single"):l("match-label.grand-final",{roundNumber:e})},e.getMatchStatus=function(t){switch(t){case a.Status.Locked:return l("match-status.locked");case a.Status.Waiting:return l("match-status.waiting");case a.Status.Ready:return l("match-status.ready");case a.Status.Running:return l("match-status.running");case a.Status.Completed:return l("match-status.completed");case a.Status.Archived:return l("match-status.archived");default:return"Unknown status"}},e.getGroupName=function(t){return l("common.group-name",{groupNumber:t})},e.getBracketName=function(t,e){switch(e){case"winner-bracket":case"loser-bracket":return l(`common.group-name-${e}`,{stage:t});default:return}},e.getRoundName=function(t,e){return t===e?l("common.round-name-final"):l("common.round-name",{roundNumber:t})},e.getWinnerBracketRoundName=function(t,e){return t===e?l("common.round-name-winner-bracket-final"):l("common.round-name-winner-bracket",{roundNumber:t})},e.getLoserBracketRoundName=function(t,e){return t===e?l("common.round-name-loser-bracket-final"):l("common.round-name-loser-bracket",{roundNumber:t})}},825:function(t,e,n){var o=this&&this.__createBinding||(Object.create?function(t,e,n,o){void 0===o&&(o=n),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,o){void 0===o&&(o=n),t[o]=e[n]}),r=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&o(e,t,n);return r(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.BracketsViewer=void 0,n(16);const a=n(21),s=n(886),u=i(n(335)),c=i(n(491));e.BracketsViewer=class{constructor(){this.participantRefs={},this.participants=[],this.participantImages=[],this.skipFirstRound=!1,this.alwaysConnectFirstRound=!1,this.onMatchClicked=t=>{}}async render(t,e){const n=document.createDocumentFragment();this.config={participantOriginPlacement:(null==e?void 0:e.participantOriginPlacement)||"before",separatedChildCountLabel:void 0!==(null==e?void 0:e.separatedChildCountLabel)&&e.separatedChildCountLabel,showSlotsOrigin:void 0===(null==e?void 0:e.showSlotsOrigin)||e.showSlotsOrigin,showLowerBracketSlotsOrigin:void 0===(null==e?void 0:e.showLowerBracketSlotsOrigin)||e.showLowerBracketSlotsOrigin,highlightParticipantOnHover:void 0===(null==e?void 0:e.highlightParticipantOnHover)||e.highlightParticipantOnHover},this.participants=t.participants,t.participants.forEach((t=>this.participantRefs[t.id]=[])),t.stages.forEach((e=>this.renderStage(n,{...t,stages:[e],matches:t.matches.filter((t=>t.stage_id===e.id))}))),(0,s.findRoot)(null==e?void 0:e.selector).append(n)}updateMatch(t){var e,n,o,r,i,a;const s=document.querySelector(`[data-match-id='${t.id}']`);if(!s)throw Error("Match not found.");s.setAttribute("data-match-status",t.status.toString());const u=s.querySelector(".participant:nth-of-type(1) .result");u&&(null===(e=t.opponent1)||void 0===e?void 0:e.score)&&(u.innerHTML=null===(o=null===(n=t.opponent1)||void 0===n?void 0:n.score)||void 0===o?void 0:o.toString());const c=s.querySelector(".participant:nth-of-type(2) .result");c&&(null===(r=t.opponent2)||void 0===r?void 0:r.score)&&(c.innerHTML=null===(a=null===(i=t.opponent2)||void 0===i?void 0:i.score)||void 0===a?void 0:a.toString())}addLocale(t,e){c.addLocale(t,e)}setParticipantImages(t){this.participantImages=t}renderStage(t,e){const n=e.stages[0],o=(0,s.splitBy)(e.matches,"group_id");switch(this.stage=n,this.skipFirstRound=n.settings.skipFirstRound||!1,n.type){case"round_robin":this.renderRoundRobin(t,n,o);break;case"single_elimination":case"double_elimination":this.renderElimination(t,n,o);break;default:throw Error(`Unknown bracket type: ${n.type}`)}}renderRoundRobin(t,e,n){const o=u.createRoundRobinContainer(e.id);o.append(u.createTitle(e.name));let r=1;for(const t of n){const e=t[0].group_id,n=u.createGroupContainer(e,c.getGroupName(r++)),i=(0,s.splitBy)(t,"round_id");let a=1;for(const t of i){const e=t[0].round_id,o=u.createRoundContainer(e,c.getRoundName(a++,0));for(const e of t)o.append(this.createMatch(e));n.append(o)}n.append(this.createRanking(t)),o.append(n)}t.append(o)}renderElimination(t,e,n){const o=u.createEliminationContainer(e.id);o.append(u.createTitle(e.name)),"single_elimination"===e.type?this.renderSingleElimination(o,n):this.renderDoubleElimination(o,n),t.append(o)}renderSingleElimination(t,e){const n=void 0!==e[1];this.renderBracket(t,(0,s.splitBy)(e[0],"round_id"),c.getRoundName,"single-bracket"),n&&this.renderFinal(t,"consolation_final",e[1])}renderDoubleElimination(t,e){const n=void 0!==e[1],o=void 0!==e[2];this.renderBracket(t,(0,s.splitBy)(e[0],"round_id"),c.getWinnerBracketRoundName,"winner-bracket",o),n&&this.renderBracket(t,(0,s.splitBy)(e[1],"round_id"),c.getLoserBracketRoundName,"loser-bracket"),o&&this.renderFinal(t,"grand_final",e[2])}renderBracket(t,e,n,o,r){const i=e[0][0].group_id,a=e.length,l=u.createBracketContainer(i,c.getBracketName(this.stage,o)),d=u.createRoundsContainer(),{matches:p,fromToornament:h}=(0,s.completeWithBlankMatches)(o,e[0],e[1]);this.alwaysConnectFirstRound=!h;for(let t=0;tt.id===i));if(void 0!==t){const n=u.createCell(t.name);this.setupMouseHover(t.id,n),e.append(n);continue}}!n||"rank"!==r&&"points"!==r?e.append(u.createCell(i)):e.append(u.createCell("-"))}return e}createBracketMatch(t,e,n,o,r){const i=u.getBracketConnection(this.alwaysConnectFirstRound,t,e,n,o,r),a=c.getMatchLabel(n.number,t,e,o),s=c.getOriginHint(t,e,this.skipFirstRound,o);return this.createMatch(n,o,i,a,s,t)}createFinalMatch(t,e,n,o){const r=n-1,i=u.getFinalConnection(t,n,e.length),a=c.getFinalMatchLabel(t,n,o),s=c.getFinalOriginHint(t,n);return this.createMatch(e[r],"final-group",i,a,s)}skipBracketMatch(){const t=u.createMatchContainer(),e=u.createOpponentsContainer(),n=this.createParticipant(null),o=this.createParticipant(null);return e.append(n,o),t.append(e),t.style.visibility="hidden",t}createMatch(t,e,n,o,r,i){const s=u.createMatchContainer(t.id,t.status),c=u.createOpponentsContainer((()=>this.onMatchClicked(t)));t.status>=a.Status.Completed&&(r=void 0);const l=this.createParticipant(t.opponent1,"opponent1",r,e,i),d=this.createParticipant(t.opponent2,"opponent2",r,e,i);return this.renderMatchLabel(c,t,o),c.append(l,d),s.append(c),n?(u.setupConnection(c,s,n),s):s}createParticipant(t,e,n,o,r){const i={participant:u.createParticipantContainer(t&&t.id),name:u.createNameContainer(),result:u.createResultContainer()};return null==t?u.setupBye(i.name):this.renderParticipant(i,t,e,n,o,r),i.participant.append(i.name,i.result),t&&null!==t.id&&this.setupMouseHover(t.id,i.participant),i.participant}renderParticipant(t,e,n,o,r,i){const a=this.participants.find((t=>t.id===e.id));a?(t.name.innerText=a.name,t.participant.setAttribute("title",a.name),this.renderParticipantImage(t.name,a.id),this.renderParticipantOrigin(t.name,e,n,r,i)):this.renderHint(t.name,e,o,r),t.result.innerText=`${void 0===e.score?"-":e.score}`,u.setupWin(t.participant,t.result,e),u.setupLoss(t.participant,t.result,e)}renderParticipantImage(t,e){const n=this.participantImages.find((t=>t.participantId===e));n&&u.addParticipantImage(t,n.imageUrl)}renderMatchLabel(t,e,n){const o=`Bo${e.child_count}`;if(n=n||"",this.config.separatedChildCountLabel)return t.append(u.createMatchLabel(n,c.getMatchStatus(e.status))),void(e.child_count>0&&t.append(u.createChildCountLabel(c.t("common.best-of-x",{x:e.child_count}))));if(e.child_count>0){const r=n?`${n}, ${o}`:o;t.append(u.createMatchLabel(r,c.getMatchStatus(e.status)))}}renderHint(t,e,n,o){void 0!==n&&void 0!==e.position&&this.config.showSlotsOrigin&&(this.config.showLowerBracketSlotsOrigin||"loser-bracket"!==o)&&u.setupHint(t,n(e.position))}renderParticipantOrigin(t,e,n,o,r){if(void 0===e.position||void 0===o)return;if(!this.config.participantOriginPlacement||"none"===this.config.participantOriginPlacement)return;if(!this.config.showSlotsOrigin)return;if(!this.config.showLowerBracketSlotsOrigin&&"loser-bracket"===o)return;const i=(0,s.getOriginAbbreviation)(o,this.skipFirstRound,r,n);if(!i)return;const a=i+e.position;u.addParticipantOrigin(t,a,this.config.participantOriginPlacement)}setupMouseHover(t,e){if(!this.config.highlightParticipantOnHover)return;const n=this.participantRefs[t];if(!n)throw Error(`The participant (id: ${t}) does not exist in the participants table.`);n.push(e),e.addEventListener("mouseover",(()=>{n.forEach((t=>t.classList.add("hover")))})),e.addEventListener("mouseleave",(()=>{n.forEach((t=>t.classList.remove("hover")))}))}}},945:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.BaseGetter=void 0;const o=n(487);e.BaseGetter=class{constructor(t){this.storage=t}async getOrderedRounds(t){if(!(null==t?void 0:t.settings.size))throw Error("The stage has no size.");return"single_elimination"===t.type?this.getOrderedRoundsSingleElimination(t.id):this.getOrderedRoundsDoubleElimination(t.id)}async getOrderedRoundsSingleElimination(t){return[await this.getUpperBracketFirstRound(t)]}async getOrderedRoundsDoubleElimination(t){const e=await this.storage.select("round",{stage_id:t});if(!e)throw Error("Error getting rounds.");const n=await this.getLoserBracket(t);if(!n)throw Error("Loser bracket not found.");const r=e[0],i=e.filter((t=>t.group_id===n.id));return[r,...i.filter((t=>o.isOrderingSupportedLoserBracket(t.number,i.length)))]}async getRoundPositionalInfo(t){const e=await this.storage.select("round",t);if(!e)throw Error("Round not found.");const n=await this.storage.select("round",{group_id:e.group_id});if(!n)throw Error("Error getting rounds.");return{roundNumber:e.number,roundCount:n.length}}async getPreviousMatches(t,e,n,o){return"loser_bracket"===e?this.getPreviousMatchesLB(t,n,o):"final_group"===e?this.getPreviousMatchesFinal(t,o):1===o?[]:this.getMatchesBeforeMajorRound(t,o)}async getPreviousMatchesFinal(t,e){if(e>1)return[await this.findMatch(t.group_id,e-1,1)];const n=await this.getUpperBracket(t.stage_id),o=await this.getLastRound(n.id),r=await this.storage.selectFirst("match",{round_id:o.id,number:1});if(null===r)throw Error("Match not found.");return[r]}async getPreviousMatchesLB(t,e,n){if(e.settings.skipFirstRound&&1===n)return[];if(o.hasBye(t))return[];const r=await this.getUpperBracket(t.stage_id),i=Math.ceil((n+1)/2),a=e.settings.skipFirstRound?i-1:i;return 1===n?this.getMatchesBeforeFirstRoundLB(t,r.id,a):n%2==0?this.getMatchesBeforeMinorRoundLB(t,r.id,n,a):this.getMatchesBeforeMajorRound(t,n)}async getMatchesBeforeMajorRound(t,e){return[await this.findMatch(t.group_id,e-1,2*t.number-1),await this.findMatch(t.group_id,e-1,2*t.number)]}async getMatchesBeforeFirstRoundLB(t,e,n){return[await this.findMatch(e,n,o.getOriginPosition(t,"opponent1")),await this.findMatch(e,n,o.getOriginPosition(t,"opponent2"))]}async getMatchesBeforeMinorRoundLB(t,e,n,r){const i=o.getOriginPosition(t,"opponent1");return[await this.findMatch(e,r,i),await this.findMatch(t.group_id,n-1,t.number)]}async getNextMatches(t,e,n,o,r){switch(e){case"single_bracket":return this.getNextMatchesUpperBracket(t,n.type,o,r);case"winner_bracket":return this.getNextMatchesWB(t,n,o,r);case"loser_bracket":return this.getNextMatchesLB(t,n.type,o,r);case"final_group":return this.getNextMatchesFinal(t,o,r);default:throw Error("Unknown bracket kind.")}}async getNextMatchesWB(t,e,n,r){const i=await this.getLoserBracket(t.stage_id);if(null===i)return[];const a=e.settings.skipFirstRound?n+1:n,s=a>1?2*(a-1):1,u=a>1?t.number:o.getDiagonalMatchNumber(t.number),c=e.settings.size,l=o.getLoserOrdering(e.settings.seedOrdering,s),d=o.findLoserMatchNumber(c,s,u,l);return[...await this.getNextMatchesUpperBracket(t,e.type,n,r),await this.findMatch(i.id,s,d)]}async getNextMatchesUpperBracket(t,e,n,o){return"single_elimination"===e?this.getNextMatchesUpperBracketSingleElimination(t,e,n,o):"double_elimination"===e&&n===o?[await this.getFirstMatchFinal(t,e)]:[await this.getDiagonalMatch(t.group_id,n,t.number)]}async getNextMatchesUpperBracketSingleElimination(t,e,n,o){if(n===o-1){const o=await this.getFirstMatchFinal(t,e);return[await this.getDiagonalMatch(t.group_id,n,t.number),...o?[o]:[]]}return n===o?[]:[await this.getDiagonalMatch(t.group_id,n,t.number)]}async getNextMatchesLB(t,e,n,o){if(n===o){const n=await this.getFirstMatchFinal(t,e);return n?[n]:[]}return n%2==1?this.getMatchAfterMajorRoundLB(t,n):this.getMatchAfterMinorRoundLB(t,n)}async getFirstMatchFinal(t,e){const n=await this.getFinalGroupId(t.stage_id,e);return null===n?null:this.findMatch(n,1,1)}async getNextMatchesFinal(t,e,n){return e===n?[]:[await this.findMatch(t.group_id,e+1,1)]}async getMatchAfterMajorRoundLB(t,e){return[await this.getParallelMatch(t.group_id,e,t.number)]}async getMatchAfterMinorRoundLB(t,e){return[await this.getDiagonalMatch(t.group_id,e,t.number)]}static getSeedingOrdering(t,e){return"round_robin"===t?e.getRoundRobinOrdering():e.getStandardBracketFirstRoundOrdering()}async getSeedingMatches(t,e){if("round_robin"===e)return this.storage.select("match",{stage_id:t});const n=await this.getUpperBracketFirstRound(t);return this.storage.select("match",{round_id:n.id})}async getUpperBracketFirstRound(t){const e=await this.storage.selectFirst("round",{stage_id:t,number:1});if(!e)throw Error("Round not found.");return e}async getLastRound(t){const e=await this.storage.selectLast("round",{group_id:t});if(!e)throw Error("Error getting rounds.");return e}async getFinalGroupId(t,e){const n="single_elimination"===e?2:3,o=await this.storage.selectFirst("group",{stage_id:t,number:n});return o?o.id:null}async getUpperBracket(t){const e=await this.storage.selectFirst("group",{stage_id:t,number:1});if(!e)throw Error("Winner bracket not found.");return e}async getLoserBracket(t){return this.storage.selectFirst("group",{stage_id:t,number:2})}async getDiagonalMatch(t,e,n){return this.findMatch(t,e+1,o.getDiagonalMatchNumber(n))}async getParallelMatch(t,e,n){return this.findMatch(t,e+1,n)}async findMatch(t,e,n){const o=await this.storage.selectFirst("round",{group_id:t,number:e});if(!o)throw Error("Round not found.");const r=await this.storage.selectFirst("match",{round_id:o.id,number:n});if(!r)throw Error("Match not found.");return r}async findMatchGame(t){if(void 0!==t.id){const e=await this.storage.select("match_game",t.id);if(!e)throw Error("Match game not found.");return e}if(void 0!==t.parent_id&&t.number){const e=await this.storage.selectFirst("match_game",{parent_id:t.parent_id,number:t.number});if(!e)throw Error("Match game not found.");return e}throw Error("No match game id nor parent id and number given.")}}},517:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.BaseUpdater=void 0;const o=n(21),r=n(644),i=n(765),a=n(945),s=n(487);class u extends a.BaseGetter{async updateSeeding(t,e){const n=await this.storage.select("stage",t);if(!n)throw Error("Stage not found.");if(e&&e.length!==n.settings.size)throw Error("The size of the seeding is incorrect.");const o=new i.Create(this.storage,{name:n.name,tournamentId:n.tournament_id,type:n.type,settings:n.settings,seeding:e||void 0});o.setExisting(t);const s=a.BaseGetter.getSeedingOrdering(n.type,o),c=await o.getSlots(),l=await this.getSeedingMatches(n.id,n.type);if(!l)throw Error("Error getting matches associated to the seeding.");const d=r.ordering[s](c);await u.assertCanUpdateSeeding(l,d),await o.run()}async updateParentMatch(t){const e=await this.storage.select("match",t);if(!e)throw Error("Parent not found.");const n=await this.storage.select("match_game",{parent_id:t});if(!n)throw Error("No match games.");const o=s.getChildGamesResults(n),r=s.getParentMatchResults(e,o),i=await this.storage.select("stage",e.stage_id);if(!i)throw Error("Stage not found.");const a=s.isRoundRobin(i);s.setParentMatchCompleted(r,e.child_count,a),await this.updateMatch(e,r,!0)}static async assertCanUpdateSeeding(t,e){var n,o;let r=0;for(const i of t){const t=e[r++],a=e[r++];if(s.isMatchParticipantLocked(i)&&((null===(n=i.opponent1)||void 0===n?void 0:n.id)!==(null==t?void 0:t.id)||(null===(o=i.opponent2)||void 0===o?void 0:o.id)!==(null==a?void 0:a.id)))throw Error("A match is locked.")}}async updateRelatedMatches(t,e,n){const{roundNumber:o,roundCount:r}=await this.getRoundPositionalInfo(t.round_id),i=await this.storage.select("stage",t.stage_id);if(!i)throw Error("Stage not found.");const a=await this.storage.select("group",t.group_id);if(!a)throw Error("Group not found.");const u=s.getMatchLocation(i.type,a.number);e&&await this.updatePrevious(t,u,i,o),n&&await this.updateNext(t,u,i,o,r)}async updateMatch(t,e,n){if(!n&&s.isMatchUpdateLocked(t))throw Error("The match is locked.");const{statusChanged:o,resultChanged:r}=s.setMatchResults(t,e);if(await this.applyMatchUpdate(t),!o&&!r)return;const i=await this.storage.select("stage",t.stage_id);if(!i)throw Error("Stage not found.");s.isRoundRobin(i)||await this.updateRelatedMatches(t,o,r)}async applyMatchUpdate(t){if(!await this.storage.update("match",t.id,t))throw Error("Could not update the match.");if(0===t.child_count)return;const e={opponent1:s.toResult(t.opponent1),opponent2:s.toResult(t.opponent2)};if((t.status<=o.Status.Ready||t.status===o.Status.Archived)&&(e.status=t.status),!await this.storage.update("match_game",{parent_id:t.id},e))throw Error("Could not update the match game.")}async updatePrevious(t,e,n,r){const i=await this.getPreviousMatches(t,e,n,r);0!==i.length&&(t.status>=o.Status.Running?await this.archiveMatches(i):await this.resetMatchesStatus(i))}async archiveMatches(t){for(const e of t)e.status=o.Status.Archived,await this.applyMatchUpdate(e)}async resetMatchesStatus(t){for(const e of t)e.status=s.getMatchStatus(e),await this.applyMatchUpdate(e)}async updateNext(t,e,n,o,r){const i=await this.getNextMatches(t,e,n,o,r);if(0===i.length)return;const a=s.getMatchResult(t),u=n.settings.skipFirstRound&&"winner_bracket"===e?o+1:o;a?await this.applyToNextMatches(s.setNextOpponent,t,e,u,r,i,a):await this.applyToNextMatches(s.resetNextOpponent,t,e,u,r,i)}async applyToNextMatches(t,e,n,o,r,i,a){if("final_group"===n){if(!i[0])throw Error("First next match is null.");return t(i[0],"opponent1",e,"opponent1"),t(i[0],"opponent2",e,"opponent2"),void await this.applyMatchUpdate(i[0])}const u=s.getNextSide(e.number,o,r,n);if(i[0]&&(t(i[0],u,e,a),await this.propagateByeWinners(i[0])),2===i.length){if(!i[1])throw Error("Second next match is null.");if("single_bracket"===n)t(i[1],u,e,a&&s.getOtherSide(a)),await this.applyMatchUpdate(i[1]);else{const n=s.getNextSideLoserBracket(e.number,i[1],o);t(i[1],n,e,a&&s.getOtherSide(a)),await this.propagateByeWinners(i[1])}}}async propagateByeWinners(t){s.setMatchResults(t,t),await this.applyMatchUpdate(t),s.hasBye(t)&&await this.updateRelatedMatches(t,!0,!0)}}e.BaseUpdater=u},765:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Create=e.create=void 0;const o=n(644),r=n(487);e.create=async function(t){const e=new i(this.storage,t);await e.run()};class i{constructor(t,e){if(this.storage=t,this.stage=e,this.stage.settings=this.stage.settings||{},this.seedOrdering=this.stage.settings.seedOrdering||[],this.updateMode=!1,!this.stage.name)throw Error("You must provide a name for the stage.");if(!Number.isInteger(this.stage.tournamentId))throw Error("You must provide a tournament id for the stage.");"round_robin"===e.type&&(this.stage.settings.roundRobinMode=this.stage.settings.roundRobinMode||"simple"),"single_elimination"===e.type&&(this.stage.settings.consolationFinal=this.stage.settings.consolationFinal||!1),"double_elimination"===e.type&&(this.stage.settings.grandFinal=this.stage.settings.grandFinal||"none"),this.stage.settings.matchesChildCount=this.stage.settings.matchesChildCount||0}async run(){let t=-1;switch(this.stage.type){case"round_robin":t=await this.roundRobin();break;case"single_elimination":t=await this.singleElimination();break;case"double_elimination":t=await this.doubleElimination();break;default:throw Error("Unknown stage type.")}if(-1===t)throw Error("Something went wrong when creating the stage.");await this.ensureSeedOrdering(t)}setExisting(t){this.updateMode=!0,this.currentStageId=t}async roundRobin(){const t=await this.getRoundRobinGroups(),e=await this.createStage();for(let n=0;n=0;e--){const n=Math.pow(2,e);a=this.getCurrentDuels(a,n),u.push(a.map(r.byeLoser)),await this.createRound(t,i,s++,n,a)}return{losers:u,winner:r.byeWinner(a[0])}}async createLowerBracket(t,e,n){var i;const a=null===(i=this.stage.settings)||void 0===i?void 0:i.size,s=r.getRoundPairCount(a);let u=0;const c=this.getMajorOrdering(a),l=o.ordering[c](n[u++]),d=await this.insertGroup({stage_id:t,number:e});if(-1===d)throw Error("Could not insert the group.");let p=r.makePairs(l),h=1;for(let e=0;el&&(l=t)}}const d=await this.insertMatch({number:o,stage_id:t,group_id:e,round_id:n,child_count:a,status:l,opponent1:s,opponent2:u},c);if(-1===d)throw Error("Could not insert the match.");for(let e=0;e({id:null,position:e+1})));if(!this.stage.seeding)throw Error("Either size or seeding must be given.");return this.stage.settings={...this.stage.settings,size:o},r.ensureNoDuplicates(this.stage.seeding),this.stage.seeding=r.fixSeeding(this.stage.seeding,o),"round_robin"!==this.stage.type&&this.stage.settings.balanceByes&&(this.stage.seeding=r.balanceByes(this.stage.seeding,this.stage.settings.size)),r.isSeedingWithIds(this.stage.seeding)?this.getSlotsUsingIds(this.stage.seeding,t):this.getSlotsUsingNames(this.stage.seeding,t)}async getSlotsUsingNames(t,e){const n=r.extractParticipantsFromSeeding(this.stage.tournamentId,t);if(!await this.registerParticipants(n))throw Error("Error registering the participants.");const o=await this.storage.select("participant",{tournament_id:this.stage.tournamentId});if(!o)throw Error("Error getting registered participant.");return r.mapParticipantsNamesToDatabase(t,o,e)}async getSlotsUsingIds(t,e){const n=await this.storage.select("participant",{tournament_id:this.stage.tournamentId});if(!n)throw Error("No available participants.");return r.mapParticipantsIdsToDatabase(t,n,e)}async getStageNumber(){const t=await this.storage.select("stage",{tournament_id:this.stage.tournamentId}),e=null==t?void 0:t.map((t=>t.number));if(void 0!==this.stage.number){if(null==e?void 0:e.includes(this.stage.number))throw Error("The given stage number already exists.");return this.stage.number}return(null==e?void 0:e.length)?Math.max(...e)+1:1}getMatchesChildCount(){var t;return(null===(t=this.stage.settings)||void 0===t?void 0:t.matchesChildCount)?this.stage.settings.matchesChildCount:0}getOrdering(t,e,n){var o;if(!(null===(o=this.stage.settings)||void 0===o?void 0:o.seedOrdering))return this.seedOrdering.push(n),n;const r=this.stage.settings.seedOrdering[t];if(!r)return this.seedOrdering.push(n),n;if("elimination"===e&&r.match(/^groups\./))throw Error("You must specify a seed ordering method without a 'groups' prefix");if("groups"===e&&"natural"!==r&&!r.match(/^groups\./))throw Error("You must specify a seed ordering method with a 'groups' prefix");return r}async getRoundRobinGroups(){var t,e,n,i,a;if(void 0===(null===(t=this.stage.settings)||void 0===t?void 0:t.groupCount)||!Number.isInteger(this.stage.settings.groupCount))throw Error("You must specify a group count for round-robin stages.");if(this.stage.settings.groupCount<=0)throw Error("You must provide a strictly positive group count.");if(null===(e=this.stage.settings)||void 0===e?void 0:e.manualOrdering){if((null===(n=this.stage.settings)||void 0===n?void 0:n.manualOrdering.length)!==(null===(i=this.stage.settings)||void 0===i?void 0:i.groupCount))throw Error("Group count in the manual ordering does not correspond to the given group count.");const t=null===(a=this.stage.settings)||void 0===a?void 0:a.manualOrdering.flat(),e=await this.getSlots(t);return r.makeGroups(e,this.stage.settings.groupCount)}if(Array.isArray(this.stage.settings.seedOrdering)&&1!==this.stage.settings.seedOrdering.length)throw Error("You must specify one seed ordering method.");const s=this.getRoundRobinOrdering(),u=await this.getSlots(),c=o.ordering[s](u,this.stage.settings.groupCount);return r.makeGroups(c,this.stage.settings.groupCount)}getRoundRobinOrdering(){return this.getOrdering(0,"groups","groups.effort_balanced")}getStandardBracketFirstRoundOrdering(){return this.getOrdering(0,"elimination","inner_outer")}getMajorOrdering(t){return this.getOrdering(1,"elimination",o.defaultMinorOrdering[t][0])}getMinorOrdering(t,e,n){if(e!==n-1)return this.getOrdering(2+e,"elimination",o.defaultMinorOrdering[t][1+e])}async insertStage(t){let e=null;return this.updateMode&&(e=await this.storage.select("stage",this.currentStageId)),e?e.id:this.storage.insert("stage",t)}async insertGroup(t){let e=null;return this.updateMode&&(e=await this.storage.selectFirst("group",{stage_id:t.stage_id,number:t.number})),e?e.id:this.storage.insert("group",t)}async insertRound(t){let e=null;return this.updateMode&&(e=await this.storage.selectFirst("round",{group_id:t.group_id,number:t.number})),e?e.id:this.storage.insert("round",t)}async insertMatch(t,e){if(!e)return this.storage.insert("match",t);const n=r.getUpdatedMatchResults(t,e);if(!await this.storage.update("match",e.id,n))throw Error("Could not update the match.");return e.id}async insertMatchGame(t){let e=null;if(this.updateMode&&(e=await this.storage.selectFirst("match_game",{parent_id:t.parent_id,number:t.number})),!e)return this.storage.insert("match_game",t);const n=r.getUpdatedMatchResults(t,e);if(!await this.storage.update("match_game",e.id,n))throw Error("Could not update the match game.");return e.id}async registerParticipants(t){const e=await this.storage.select("participant",{tournament_id:this.stage.tournamentId});if(!e||0===e.length)return this.storage.insert("participant",t);for(const n of t)if(!e.some((t=>t.name===n.name))&&-1===await this.storage.insert("participant",n))return!1;return!0}async createStage(){const t=await this.getStageNumber(),e=await this.insertStage({tournament_id:this.stage.tournamentId,name:this.stage.name,type:this.stage.type,number:t,settings:this.stage.settings||{}});if(-1===e)throw Error("Could not insert the stage.");return e}async createConsolationFinal(t,e){var n;if(!(null===(n=this.stage.settings)||void 0===n?void 0:n.consolationFinal))return;const o=e[e.length-2];await this.createUniqueMatchBracket(t,2,[o])}async createGrandFinal(t,e,n){var o;const r=null===(o=this.stage.settings)||void 0===o?void 0:o.grandFinal;if("none"===r)return;const i=[[e,n]];"double"===r&&i.push([{id:null},{id:null}]),await this.createUniqueMatchBracket(t,3,i)}async ensureSeedOrdering(t){var e,n;if((null===(n=null===(e=this.stage.settings)||void 0===e?void 0:e.seedOrdering)||void 0===n?void 0:n.length)===this.seedOrdering.length)return;const o=await this.storage.select("stage",t);if(!o)throw Error("Stage not found.");if(o.settings={...o.settings,seedOrdering:this.seedOrdering},!await this.storage.update("stage",t,o))throw Error("Could not update the stage.")}}e.Create=i},378:function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.Delete=void 0,e.Delete=class{constructor(t){this.storage=t}async stage(t){if(!await this.storage.delete("match_game",{stage_id:t}))throw Error("Could not delete match games.");if(!await this.storage.delete("match",{stage_id:t}))throw Error("Could not delete matches.");if(!await this.storage.delete("round",{stage_id:t}))throw Error("Could not delete rounds.");if(!await this.storage.delete("group",{stage_id:t}))throw Error("Could not delete groups.");if(!await this.storage.delete("stage",{id:t}))throw Error("Could not delete stages.")}}},63:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Find=void 0;const o=n(945),r=n(487);class i extends o.BaseGetter{async upperBracket(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");switch(e.type){case"round_robin":throw Error("Round-robin stages do not have an upper bracket.");case"single_elimination":case"double_elimination":return this.getUpperBracket(t);default:throw Error("Unknown stage type.")}}async loserBracket(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");switch(e.type){case"round_robin":throw Error("Round-robin stages do not have a loser bracket.");case"single_elimination":throw Error("Single elimination stages do not have a loser bracket.");case"double_elimination":const e=await this.getLoserBracket(t);if(!e)throw Error("Loser bracket not found.");return e;default:throw Error("Unknown stage type.")}}async previousMatches(t){const e=await this.storage.select("match",t);if(!e)throw Error("Match not found.");const n=await this.storage.select("stage",e.stage_id);if(!n)throw Error("Stage not found.");const o=await this.storage.select("group",e.group_id);if(!o)throw Error("Group not found.");const i=await this.storage.select("round",e.round_id);if(!i)throw Error("Round not found.");const a=r.getMatchLocation(n.type,o.number);return this.getPreviousMatches(e,a,n,i.number)}async nextMatches(t){const e=await this.storage.select("match",t);if(!e)throw Error("Match not found.");const n=await this.storage.select("stage",e.stage_id);if(!n)throw Error("Stage not found.");const o=await this.storage.select("group",e.group_id);if(!o)throw Error("Group not found.");const{roundNumber:i,roundCount:a}=await this.getRoundPositionalInfo(e.round_id),s=r.getMatchLocation(n.type,o.number),u=await this.getNextMatches(e,s,n,i,a);return r.getNonNull(u)}async match(t,e,n){return this.findMatch(t,e,n)}async matchGame(t){return this.findMatchGame(t)}}e.Find=i},576:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Get=void 0;const o=n(945),r=n(487);class i extends o.BaseGetter{async stageData(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");const n=await this.storage.select("group",{stage_id:t});if(!n)throw Error("Error getting groups.");const o=await this.storage.select("round",{stage_id:t});if(!o)throw Error("Error getting rounds.");const r=await this.storage.select("match",{stage_id:t});if(!r)throw Error("Error getting matches.");const i=await this.storage.select("participant",{tournament_id:e.tournament_id});if(!i)throw Error("Error getting participants.");return{stage:[e],group:n,round:o,match:r,match_game:await this.matchGames(r),participant:i}}async matchGames(t){const e=t.filter((t=>t.child_count>0)),n=await Promise.all(e.map((t=>this.storage.select("match_game",{parent_id:t.id}))));if(n.some((t=>null===t)))throw Error("Error getting match games.");return r.getNonNull(n).flat()}async seeding(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");return"round_robin"===e.type?this.roundRobinSeeding(e):this.eliminationSeeding(e)}async finalStandings(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");switch(e.type){case"round_robin":throw Error("A round-robin stage does not have standings.");case"single_elimination":return this.singleEliminationStandings(t);case"double_elimination":return this.doubleEliminationStandings(t);default:throw Error("Unknown stage type.")}}async roundRobinSeeding(t){if(void 0===t.settings.size)throw Error("The size of the seeding is undefined.");const e=await this.storage.select("match",{stage_id:t.id});if(!e)throw Error("Error getting matches.");const n=r.matchesToSeeding(e);if(n.lengtht&&t.position));return r.setArraySize(o,t.settings.size,null)}async eliminationSeeding(t){const e=await this.storage.selectFirst("round",{stage_id:t.id,number:1});if(!e)throw Error("Error getting the first round.");const n=await this.storage.select("match",{round_id:e.id});if(!n)throw Error("Error getting matches.");return r.matchesToSeeding(n)}async singleEliminationStandings(t){var e;const n=[],{stage:o,group:i,match:a,participant:s}=await this.stageData(t),[u]=o,[c,l]=i,d=a.filter((t=>t.group_id===c.id)).pop();if(!d)throw Error("Final not found.");n[0]=[r.findParticipant(s,r.getWinner(d))];const p=r.getLosers(s,a.filter((t=>t.group_id===c.id)));if(n.push(...p.reverse()),null===(e=u.settings)||void 0===e?void 0:e.consolationFinal){const t=a.filter((t=>t.group_id===l.id)).pop();if(!t)throw Error("Consolation final not found.");n[2][0]=r.findParticipant(s,r.getWinner(t)),n[2][1]=r.findParticipant(s,r.getLoser(t))}return r.makeFinalStandings(n)}async doubleEliminationStandings(t){var e,n;const o=[],{stage:i,group:a,match:s,participant:u}=await this.stageData(t),[c]=i,[l,d,p]=a;if("none"===(null===(e=c.settings)||void 0===e?void 0:e.grandFinal)){const t=s.filter((t=>t.group_id===l.id)).pop();if(!t)throw Error("WB final not found.");const e=s.filter((t=>t.group_id===d.id)).pop();if(!e)throw Error("LB final not found.");o[0]=[r.findParticipant(u,r.getWinner(t))],o[1]=[r.findParticipant(u,r.getWinner(e))]}else{const t=s.filter((t=>t.group_id===p.id)),e=r.getGrandFinalDecisiveMatch((null===(n=c.settings)||void 0===n?void 0:n.grandFinal)||"none",t);o[0]=[r.findParticipant(u,r.getWinner(e))],o[1]=[r.findParticipant(u,r.getLoser(e))]}const h=r.getLosers(u,s.filter((t=>t.group_id===d.id)));return o.push(...h.reverse()),r.makeFinalStandings(o)}}e.Get=i},487:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.setNextOpponent=e.getNextSideLoserBracket=e.getNextSide=e.findParticipant=e.getGrandFinalDecisiveMatch=e.makeFinalStandings=e.getLosers=e.getOriginPosition=e.getOpponentId=e.resetMatchResults=e.setMatchResults=e.getMatchStatus=e.hasBye=e.isMatchParticipantLocked=e.isMatchUpdateLocked=e.isMatchByeCompleted=e.isMatchWinCompleted=e.isMatchDrawCompleted=e.isMatchResultCompleted=e.isMatchForfeitCompleted=e.isMatchCompleted=e.isMatchStarted=e.getOtherSide=e.getSide=e.findPosition=e.getMatchResult=e.byeLoser=e.byeWinnerToGrandFinal=e.byeWinner=e.getLoser=e.getWinner=e.toResultWithPosition=e.toResult=e.ensureNotTied=e.ensureValidSize=e.fixSeeding=e.ensureEquallySized=e.ensureNoDuplicates=e.ensureEvenSized=e.makePairs=e.setArraySize=e.normalizeParticipant=e.makeNormalizedIdMapping=e.normalizeIds=e.balanceByes=e.makeGroups=e.assertRoundRobin=e.makeRoundRobinDistribution=e.makeRoundRobinMatches=e.splitByParity=void 0,e.getMatchLocation=e.isFinalGroup=e.isLoserBracket=e.isWinnerBracket=e.ensureNotRoundRobin=e.isRoundRobin=e.minScoreToWinBestOfX=e.getNearestPowerOfTwo=e.getDiagonalMatchNumber=e.getLowerBracketRoundCount=e.getLoserOrdering=e.getLoserRoundMatchCount=e.findLoserMatchNumber=e.isDoubleEliminationNecessary=e.getRoundPairCount=e.getUpperBracketRoundCount=e.isOrderingSupportedLoserBracket=e.isOrderingSupportedUpperBracket=e.ensureOrderingSupported=e.getSeedCount=e.getSeeds=e.getChildGamesResults=e.getUpdatedMatchResults=e.getParentMatchResults=e.setParentMatchCompleted=e.transitionToMinor=e.transitionToMajor=e.uniqueBy=e.getNonNull=e.sortSeeding=e.matchesToSeeding=e.mapParticipantsToDatabase=e.mapParticipantsIdsToDatabase=e.mapParticipantsNamesToDatabase=e.extractParticipantsFromSeeding=e.isSeedingWithIds=e.setForfeits=e.setResults=e.setCompleted=e.setScores=e.invertOpponents=e.handleOpponentsInversion=e.resetNextOpponent=void 0;const o=n(21),r=n(644);function i(t){const e=t.length,n=e%2==0?e:e+1,o=n-1,r=n/2,i=[];for(let a=0;a({...t,[n.id]:e++})),{})}function s(t,e){return null===t?null:{...t,id:null!==t.id?e[t.id]:null}}function u(t,e,n){return Array.from(Array(e),((e,o)=>t[o]||n))}function c(t){const e=d(t);return e?t[h(e)]:null}function l(t){return null===t[0]&&null===t[1]?null:null===t[0]&&null!==t[1]?{id:t[1].id}:null!==t[0]&&null===t[1]?{id:t[0].id}:{id:null}}function d(t){var e,n;if(!f(t))return null;if(w(t))return null;if(null===t.opponent1&&null===t.opponent2)return null;let o=null;if(("win"===(null===(e=t.opponent1)||void 0===e?void 0:e.result)||null===t.opponent2||t.opponent2.forfeit)&&(o="opponent1"),"win"===(null===(n=t.opponent2)||void 0===n?void 0:n.result)||null===t.opponent1||t.opponent1.forfeit){if(null!==o)throw Error("There are two winners.");o="opponent2"}return o}function p(t){return t%2==1?"opponent1":"opponent2"}function h(t){return"opponent1"===t?"opponent2":"opponent1"}function g(t){var e,n;return void 0!==(null===(e=t.opponent1)||void 0===e?void 0:e.score)||void 0!==(null===(n=t.opponent2)||void 0===n?void 0:n.score)}function f(t){return y(t)||m(t)||v(t)}function m(t){var e,n;return void 0!==(null===(e=t.opponent1)||void 0===e?void 0:e.forfeit)||void 0!==(null===(n=t.opponent2)||void 0===n?void 0:n.forfeit)}function v(t){return w(t)||b(t)}function w(t){var e,n;return"draw"===(null===(e=t.opponent1)||void 0===e?void 0:e.result)&&"draw"===(null===(n=t.opponent2)||void 0===n?void 0:n.result)}function b(t){var e,n,o,r;return"win"===(null===(e=t.opponent1)||void 0===e?void 0:e.result)||"win"===(null===(n=t.opponent2)||void 0===n?void 0:n.result)||"loss"===(null===(o=t.opponent1)||void 0===o?void 0:o.result)||"loss"===(null===(r=t.opponent2)||void 0===r?void 0:r.result)}function y(t){var e,n;return null===t.opponent1&&null!==(null===(e=t.opponent2)||void 0===e?void 0:e.id)||null===t.opponent2&&null!==(null===(n=t.opponent1)||void 0===n?void 0:n.id)||null===t.opponent1&&null===t.opponent2}function k(t){return null===t.opponent1||null===t.opponent2}function S(t){var e,n,r,i;const a=Array.isArray(t)?{opponent1:t[0],opponent2:t[1]}:t;return k(a)||null===(null===(e=a.opponent1)||void 0===e?void 0:e.id)&&null===(null===(n=a.opponent2)||void 0===n?void 0:n.id)?o.Status.Locked:null===(null===(r=a.opponent1)||void 0===r?void 0:r.id)||null===(null===(i=a.opponent2)||void 0===i?void 0:i.id)?o.Status.Waiting:f(a)?o.Status.Completed:g(a)?o.Status.Running:o.Status.Ready}function M(t){t.opponent1&&(t.opponent1.forfeit=void 0,t.opponent1.result=void 0),t.opponent2&&(t.opponent2.forfeit=void 0,t.opponent2.result=void 0),t.status=S(t)}function R(t,e){const n=t[e];return n&&n.id}function E(t,e){const n=t.find((t=>t.id===(null==e?void 0:e.id)));if(!n)throw Error("Participant not found.");return n}function x(t,e){var n,o,r,i;const a=null===(n=e.opponent1)||void 0===n?void 0:n.id,s=null===(o=e.opponent2)||void 0===o?void 0:o.id,u=null===(r=t.opponent1)||void 0===r?void 0:r.id,c=null===(i=t.opponent2)||void 0===i?void 0:i.id;if(Number.isInteger(a)&&a!==u&&a!==c)throw Error("The given opponent1 ID does not exist in this match.");if(Number.isInteger(s)&&s!==u&&s!==c)throw Error("The given opponent2 ID does not exist in this match.");(Number.isInteger(a)&&a===c||Number.isInteger(s)&&s===u)&&C(e)}function C(t){[t.opponent1,t.opponent2]=[t.opponent2,t.opponent1]}function _(t,e){var n,r,i,a;if((null===(n=e.opponent1)||void 0===n?void 0:n.score)===(null===(r=t.opponent1)||void 0===r?void 0:r.score)&&(null===(i=e.opponent2)||void 0===i?void 0:i.score)===(null===(a=t.opponent2)||void 0===a?void 0:a.score))return!1;const s=t.status;return t.status=o.Status.Running,e.opponent1&&t.opponent1&&(t.opponent1.score=e.opponent1.score),e.opponent2&&t.opponent2&&(t.opponent2.score=e.opponent2.score),t.status!==s}function L(t,e){t.status=o.Status.Completed,O(t,e,"win","loss"),O(t,e,"loss","win"),O(t,e,"draw","draw"),t.opponent1&&!t.opponent2&&(t.opponent1.result="win"),!t.opponent1&&t.opponent2&&(t.opponent2.result="win"),P(t,e)}function O(t,e,n,o){var r,i;if(e.opponent1&&e.opponent2){if("win"===e.opponent1.result&&"win"===e.opponent2.result)throw Error("There are two winners.");if("loss"===e.opponent1.result&&"loss"===e.opponent2.result)throw Error("There are two losers.");if(!0===e.opponent1.forfeit&&!0===e.opponent2.forfeit)throw Error("There are two forfeits.")}(null===(r=e.opponent1)||void 0===r?void 0:r.result)===n&&(t.opponent1?t.opponent1.result=n:t.opponent1={id:null,result:n},t.opponent2?t.opponent2.result=o:t.opponent2={id:null,result:o}),(null===(i=e.opponent2)||void 0===i?void 0:i.result)===n&&(t.opponent2?t.opponent2.result=n:t.opponent2={id:null,result:n},t.opponent1?t.opponent1.result=o:t.opponent1={id:null,result:o})}function P(t,e){var n,o;!0===(null===(n=e.opponent1)||void 0===n?void 0:n.forfeit)&&(t.opponent1&&(t.opponent1.forfeit=!0),t.opponent2?t.opponent2.result="win":t.opponent2={id:null,result:"win"}),!0===(null===(o=e.opponent2)||void 0===o?void 0:o.forfeit)&&(t.opponent2&&(t.opponent2.forfeit=!0),t.opponent1?t.opponent1.result="win":t.opponent1={id:null,result:"win"})}function N(t,e,n,o){const r=e.map(((e,o)=>{if(null===e)return null;const r=n.find((n=>n[t]===e));if(!r)throw Error(`Participant ${t} not found in database.`);return{id:r.id,position:o+1}}));if(!o)return r;if(o.length!==r.length)throw Error("Not enough seeds in at least one group of the manual ordering.");return o.map((t=>r[t-1]))}function B(t){const e=t.filter((t=>null!==t));if(e.sort(((t,e)=>t.position-e.position)),e.length===t.length)return e;const n=Object.fromEntries(e.map((t=>[t.position-1,t])));return Array.from({length:t.length},((t,e)=>n[e]||null))}function F(t){return t.filter((t=>null!==t))}function T(t,e,n,o){return j(t,e,n),1===e?2*o:o}function j(t,e,n){if(t&&!I(e,n))throw Error("This round does not support ordering.");if(!t&&!D(e))throw Error("This round does not support ordering.")}function D(t){return 1===t}function I(t,e){return 1===t||t%2==0&&te%2==0)),odd:t.filter(((t,e)=>e%2==1))}},e.makeRoundRobinMatches=function(t,e="simple"){const n=i(t);if("simple"===e)return n;const o=n.map((t=>[...t].reverse())).reverse();return[...n,...o]},e.makeRoundRobinDistribution=i,e.assertRoundRobin=function(t,e){const n=t.length,o=Math.floor(n/2),r=n%2==0?n-1:n;if(e.length!==r)throw Error("Round count is wrong");if(!e.every((t=>t.length===o)))throw Error("Not every round has the good number of matches");const i=Object.fromEntries(t.map((t=>[t,new Set])));for(const t of e){const e=new Set;for(const n of t){if(2!==n.length)throw Error("One match is not a pair");if(e.has(n[0]))throw Error("This team is already playing");if(e.add(n[0]),e.has(n[1]))throw Error("This team is already playing");if(e.add(n[1]),i[n[0]].has(n[1]))throw Error("The team has already matched this team");if(i[n[0]].add(n[1]),i[n[1]].has(n[0]))throw Error("The team has already matched this team");i[n[1]].add(n[0])}}},e.makeGroups=function(t,e){const n=Math.ceil(t.length/e),o=[];for(let e=0;enull!==t)),e=e||G(t.length),t.length[t,null])).flat(),e,null);const n=t.length,o=e-n,r=t.slice(0,n-o).filter(((t,e)=>e%2==0)).map(((e,n)=>[t[2*n],t[2*n+1]])),i=t.slice(n-o,n).map((t=>[t,null]));return u([...r.flat(),...i.flat()],e,null)},e.normalizeIds=function(t){const e={participant:a(t.participant),stage:a(t.stage),group:a(t.group),round:a(t.round),match:a(t.match),match_game:a(t.match_game)};return{participant:t.participant.map((t=>({...t,id:e.participant[t.id]}))),stage:t.stage.map((t=>({...t,id:e.stage[t.id]}))),group:t.group.map((t=>({...t,id:e.group[t.id],stage_id:e.stage[t.stage_id]}))),round:t.round.map((t=>({...t,id:e.round[t.id],stage_id:e.stage[t.stage_id],group_id:e.group[t.group_id]}))),match:t.match.map((t=>({...t,id:e.match[t.id],stage_id:e.stage[t.stage_id],group_id:e.group[t.group_id],round_id:e.round[t.round_id],opponent1:s(t.opponent1,e.participant),opponent2:s(t.opponent2,e.participant)}))),match_game:t.match_game.map((t=>({...t,id:e.match_game[t.id],stage_id:e.stage[t.stage_id],parent_id:e.match[t.parent_id],opponent1:s(t.opponent1,e.participant),opponent2:s(t.opponent2,e.participant)})))}},e.makeNormalizedIdMapping=a,e.normalizeParticipant=s,e.setArraySize=u,e.makePairs=function(t){return t.map(((e,n)=>n%2==0?[t[n],t[n+1]]:[])).filter((t=>2===t.length))},e.ensureEvenSized=function(t){if(t.length%2==1)throw Error("Array size must be even.")},e.ensureNoDuplicates=function(t){const e=F(t);if([...new Set(e)].lengthe)throw Error("The seeding has more participants than the size of the stage.");return t.length=o.Status.Running},e.hasBye=k,e.getMatchStatus=S,e.setMatchResults=function(t,e){const n=f(e),o=f(t);x(t,e);const r=_(t,e);return n&&o?(L(t,e),{statusChanged:!1,resultChanged:!0}):n&&!o?(L(t,e),{statusChanged:!0,resultChanged:!0}):!n&&o?(M(t),{statusChanged:!0,resultChanged:!0}):{statusChanged:r,resultChanged:!1}},e.resetMatchResults=M,e.getOpponentId=R,e.getOriginPosition=function(t,e){var n;const o=null===(n=t[e])||void 0===n?void 0:n.position;if(void 0===o)throw Error("Position is undefined.");return o},e.getLosers=function(t,e){const n=[];let o=null,r=-1;for(const i of e){i.round_id!==o&&(o=i.round_id,r++,n[r]=[]);const e=c(i);null!==e&&n[r].push(E(t,e))}return n},e.makeFinalStandings=function(t){const e=[];let n=1;for(const o of t){for(const t of o)e.push({id:t.id,name:t.name,rank:n});n++}return e},e.getGrandFinalDecisiveMatch=function(t,e){if("simple"===t)return e[0];if("double"===t)return"opponent2"===d(e[0])?e[1]:e[0];throw Error("The Grand Final is disabled.")},e.findParticipant=E,e.getNextSide=function(t,e,n,o){return"loser_bracket"===o&&e%2==1||"loser_bracket"===o&&e===n?"opponent2":p(t)},e.getNextSideLoserBracket=function(t,e,n){var o;return n>1||(null===(o=e.opponent1)||void 0===o?void 0:o.position)===t?"opponent1":"opponent2"},e.setNextOpponent=function(t,e,n,o){var r;t[e]=n[o]&&{id:R(n,o),position:null===(r=t[e])||void 0===r?void 0:r.position},t.status=S(t)},e.resetNextOpponent=function(t,e){var n;t[e]=t[e]&&{id:null,position:null===(n=t[e])||void 0===n?void 0:n.position},t.status=o.Status.Locked},e.handleOpponentsInversion=x,e.invertOpponents=C,e.setScores=_,e.setCompleted=L,e.setResults=O,e.setForfeits=P,e.isSeedingWithIds=function(t){return t.some((t=>"number"==typeof t))},e.extractParticipantsFromSeeding=function(t,e){return e.filter((t=>null!==t)).map((e=>({tournament_id:t,name:e})))},e.mapParticipantsNamesToDatabase=function(t,e,n){return N("name",t,e,n)},e.mapParticipantsIdsToDatabase=function(t,e,n){return N("id",t,e,n)},e.mapParticipantsToDatabase=N,e.matchesToSeeding=function(t){return B([].concat(...t.map((t=>[t.opponent1,t.opponent2]))))},e.sortSeeding=B,e.getNonNull=F,e.uniqueBy=function(t,e){const n=new Set;return t.filter((t=>{const o=e(t);return!o||!n.has(o)&&(n.add(o),!0)}))},e.transitionToMajor=function(t){const e=t.length/2,n=[];for(let o=0;o=i)t.opponent1.result="win";else if(t.opponent2.score>=i)t.opponent2.result="win";else if(t.opponent1.score===t.opponent2.score&&t.opponent1.score+t.opponent2.score>e-1){if(n)return t.opponent1.result="draw",void(t.opponent2.result="draw");throw Error("Match games result in a tie for the parent match.")}},e.getParentMatchResults=function(t,e){return{opponent1:{id:t.opponent1&&t.opponent1.id,score:e.opponent1},opponent2:{id:t.opponent2&&t.opponent2.id,score:e.opponent2}}},e.getUpdatedMatchResults=function(t,e){return{...e,...t,opponent1:{...e.opponent1,...t.opponent1},opponent2:{...e.opponent2,...t.opponent2}}},e.getChildGamesResults=function(t){const e={opponent1:0,opponent2:0};for(const n of t){const t=d(n);"opponent1"===t?e.opponent1++:"opponent2"===t&&e.opponent2++}return e},e.getSeeds=function(t,e,n,o){const r=T(t,e,n,o);return Array.from(Array(r),((t,e)=>e+1))},e.getSeedCount=T,e.ensureOrderingSupported=j,e.isOrderingSupportedUpperBracket=D,e.isOrderingSupportedLoserBracket=I,e.getUpperBracketRoundCount=A,e.getRoundPairCount=U,e.isDoubleEliminationNecessary=function(t){return t>2},e.findLoserMatchNumber=function(t,e,n,o){const i=W(t,e),a=Array.from(Array(i),((t,e)=>e+1));return(o?r.ordering[o](a):a).indexOf(n)+1},e.getLoserRoundMatchCount=W,e.getLoserOrdering=function(t,e){return t[1+Math.floor(e/2)]},e.getLowerBracketRoundCount=function(t){return 2*U(t)},e.getDiagonalMatchNumber=function(t){return Math.ceil(t/2)},e.getNearestPowerOfTwo=G,e.minScoreToWinBestOfX=z,e.isRoundRobin=H,e.ensureNotRoundRobin=function(t){if(H(t))throw Error("Impossible to update ordering in a round-robin stage.")},e.isWinnerBracket=V,e.isLoserBracket=q,e.isFinalGroup=$,e.getMatchLocation=function(t,e){return V(t,e)?"winner_bracket":q(t,e)?"loser_bracket":$(t,e)?"final_group":"single_bracket"}},37:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.helpers=e.BracketsManager=void 0;const o=n(76);Object.defineProperty(e,"BracketsManager",{enumerable:!0,get:function(){return o.BracketsManager}});const r=n(487);e.helpers={getWinner:r.getWinner,getLoser:r.getLoser,getMatchResult:r.getMatchResult,isMatchStarted:r.isMatchStarted,isMatchCompleted:r.isMatchCompleted,isMatchForfeitCompleted:r.isMatchForfeitCompleted,isMatchResultCompleted:r.isMatchResultCompleted,isMatchDrawCompleted:r.isMatchDrawCompleted,isMatchWinCompleted:r.isMatchWinCompleted,isMatchByeCompleted:r.isMatchByeCompleted,isMatchUpdateLocked:r.isMatchUpdateLocked,isMatchParticipantLocked:r.isMatchParticipantLocked,hasBye:r.hasBye,getUpperBracketRoundCount:r.getUpperBracketRoundCount,getRoundPairCount:r.getRoundPairCount,getLoserRoundMatchCount:r.getLoserRoundMatchCount,getLowerBracketRoundCount:r.getLowerBracketRoundCount,getNearestPowerOfTwo:r.getNearestPowerOfTwo,minScoreToWinBestOfX:r.minScoreToWinBestOfX,isRoundRobin:r.isRoundRobin,isWinnerBracket:r.isWinnerBracket,isLoserBracket:r.isLoserBracket,isFinalGroup:r.isFinalGroup,getMatchLocation:r.getMatchLocation}},76:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.BracketsManager=void 0;const o=n(765),r=n(576),i=n(11),a=n(378),s=n(63),u=n(369),c=n(487);e.BracketsManager=class{constructor(t){const e=t;e.selectFirst=async(t,e)=>{const n=await this.storage.select(t,e);return n&&0!==n.length?n[0]:null},e.selectLast=async(t,e)=>{const n=await this.storage.select(t,e);return n&&0!==n.length?n[n.length-1]:null},this.storage=e,this.get=new r.Get(this.storage),this.update=new i.Update(this.storage),this.delete=new a.Delete(this.storage),this.find=new s.Find(this.storage),this.reset=new u.Reset(this.storage)}async create(t){await o.create.call(this,t)}async import(t){if(t=c.normalizeIds(t),!await this.storage.delete("participant"))throw Error("Could not empty the participant table.");if(!await this.storage.insert("participant",t.participant))throw Error("Could not import participants.");if(!await this.storage.delete("stage"))throw Error("Could not empty the stage table.");if(!await this.storage.insert("stage",t.stage))throw Error("Could not import stages.");if(!await this.storage.delete("group"))throw Error("Could not empty the group table.");if(!await this.storage.insert("group",t.group))throw Error("Could not import groups.");if(!await this.storage.delete("round"))throw Error("Could not empty the round table.");if(!await this.storage.insert("round",t.round))throw Error("Could not import rounds.");if(!await this.storage.delete("match"))throw Error("Could not empty the match table.");if(!await this.storage.insert("match",t.match))throw Error("Could not import matches.");if(!await this.storage.delete("match_game"))throw Error("Could not empty the match_game table.");if(!await this.storage.insert("match_game",t.match_game))throw Error("Could not import match games.")}async export(){const t=await this.storage.select("participant");if(!t)throw Error("Error getting participants.");const e=await this.storage.select("stage");if(!e)throw Error("Error getting stages.");const n=await this.storage.select("group");if(!n)throw Error("Error getting groups.");const o=await this.storage.select("round");if(!o)throw Error("Error getting rounds.");const r=await this.storage.select("match");if(!r)throw Error("Error getting matches.");return{participant:t,stage:e,group:n,round:o,match:r,match_game:await this.get.matchGames(r)}}}},644:function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultMinorOrdering=e.ordering=void 0,e.ordering={natural:t=>[...t],reverse:t=>[...t].reverse(),half_shift:t=>[...t.slice(t.length/2),...t.slice(0,t.length/2)],reverse_half_shift:t=>[...t.slice(0,t.length/2).reverse(),...t.slice(t.length/2).reverse()],pair_flip:t=>{const e=[];for(let n=0;n{if(2===t.length)return t;const e=t.length/4,n=[t.slice(e,2*e),t.slice(2*e,3*e)],o=[t.slice(0,e),t.slice(3*e,4*e)],r={inner:t=>[t[0].pop(),t[1].shift()],outer:t=>[t[0].shift(),t[1].pop()]},i=[];function a(t,e){t[0].length>0&&t[1].length>0&&i.push(...r[e](t))}for(let t=0;t{const n=[];let o=0,r=0;for(;n.length=t.length&&(o=++r);return n},"groups.seed_optimized":(t,e)=>{const n=Array.from(Array(e),(t=>[]));for(let o=0;o{throw Error("Not implemented.")}},e.defaultMinorOrdering={4:["natural","reverse"],8:["natural","reverse","natural"],16:["natural","reverse_half_shift","reverse","natural"],32:["natural","reverse","half_shift","natural","natural"],64:["natural","reverse","half_shift","reverse","natural","natural"],128:["natural","reverse","half_shift","pair_flip","pair_flip","pair_flip","natural"]}},369:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Reset=void 0;const o=n(21),r=n(517),i=n(487);class a extends r.BaseUpdater{async matchResults(t){const e=await this.storage.select("match",t);if(!e)throw Error("Match not found.");if(e.child_count>0)throw Error("The parent match is controlled by its child games and its result cannot be reset.");const n=await this.storage.select("stage",e.stage_id);if(!n)throw Error("Stage not found.");const r=await this.storage.select("group",e.group_id);if(!r)throw Error("Group not found.");const{roundNumber:a,roundCount:s}=await this.getRoundPositionalInfo(e.round_id),u=i.getMatchLocation(n.type,r.number);if((await this.getNextMatches(e,u,n,a,s)).some((t=>t&&t.status>=o.Status.Running&&!i.isMatchByeCompleted(t))))throw Error("The match is locked.");i.resetMatchResults(e),await this.applyMatchUpdate(e),i.isRoundRobin(n)||await this.updateRelatedMatches(e,!0,!0)}async matchGameResults(t){const e=await this.storage.select("match_game",t);if(!e)throw Error("Match game not found.");if(i.resetMatchResults(e),!await this.storage.update("match_game",e.id,e))throw Error("Could not update the match game.");await this.updateParentMatch(e.parent_id)}async seeding(t){await this.updateSeeding(t,null)}}e.Reset=a},11:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Update=void 0;const o=n(21),r=n(644),i=n(517),a=n(487);class s extends i.BaseUpdater{async match(t){if(void 0===t.id)throw Error("No match id given.");const e=await this.storage.select("match",t.id);if(!e)throw Error("Match not found.");await this.updateMatch(e,t)}async matchGame(t){const e=await this.findMatchGame(t);if(a.isMatchUpdateLocked(e))throw Error("The match game is locked.");if(a.setMatchResults(e,t),!await this.storage.update("match_game",e.id,e))throw Error("Could not update the match game.");await this.updateParentMatch(e.parent_id)}async ordering(t,e){const n=await this.storage.select("stage",t);if(!n)throw Error("Stage not found.");a.ensureNotRoundRobin(n);const o=await this.getOrderedRounds(n);if(e.length!==o.length)throw Error("The count of seed orderings is incorrect.");for(let t=0;tt.status>o.Status.Ready)))throw Error("At least one match has started or is completed.");const i=await this.storage.select("stage",t.stage_id);if(!i)throw Error("Stage not found.");if(void 0===i.settings.size)throw Error("Undefined stage size.");const s=await this.storage.select("group",t.group_id);if(!s)throw Error("Group not found.");const u=a.isLoserBracket(i.type,s.number),c=a.getLowerBracketRoundCount(i.settings.size),l=a.getSeeds(u,t.number,c,n.length),d=r.ordering[e](l);await this.applyRoundOrdering(t.number,n,d)}async updateStageMatchChildCount(t,e){if(!await this.storage.update("match",{stage_id:t},{child_count:e}))throw Error("Could not update the match.");const n=await this.storage.select("match",{stage_id:t});if(!n)throw Error("This stage has no match.");for(const t of n)await this.adjustMatchChildGames(t,e)}async updateGroupMatchChildCount(t,e){if(!await this.storage.update("match",{group_id:t},{child_count:e}))throw Error("Could not update the match.");const n=await this.storage.select("match",{group_id:t});if(!n)throw Error("This group has no match.");for(const t of n)await this.adjustMatchChildGames(t,e)}async updateRoundMatchChildCount(t,e){if(!await this.storage.update("match",{round_id:t},{child_count:e}))throw Error("Could not update the match.");const n=await this.storage.select("match",{round_id:t});if(!n)throw Error("This round has no match.");for(const t of n)await this.adjustMatchChildGames(t,e)}async applyRoundOrdering(t,e,n){for(const o of e){const r={...o};if(r.opponent1=a.findPosition(e,n.shift()),1===t&&(r.opponent2=a.findPosition(e,n.shift())),!await this.storage.update("match",r.id,r))throw Error("Could not update the match.")}}async adjustMatchChildGames(t,e){const n=await this.storage.select("match_game",{parent_id:t.id});let o=n?n.length:0;for(;oe;){if(!await this.storage.delete("match_game",{parent_id:t.id,number:o}))throw Error("Could not adjust the match games when deleting.");o--}if(!await this.storage.update("match",t.id,{...t,child_count:e}))throw Error("Could not update the match.")}}e.Update=s},38:function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.InMemoryDatabase=void 0,e.InMemoryDatabase=class{data={participant:[],stage:[],group:[],round:[],match:[],match_game:[]};setData(t){this.data=t}makeFilter(t){return e=>{let n=!0;for(const o of Object.keys(t))n=n&&e[o]===t[o];return n}}reset(){this.data={participant:[],stage:[],group:[],round:[],match:[],match_game:[]}}insert(t,e){let n;if(n=this.data[t].length,!Array.isArray(e)){try{this.data[t].push({id:n,...e})}catch(t){return new Promise((t=>{t(-1)}))}return new Promise((t=>{t(n)}))}try{e.map((e=>{this.data[t].push({id:n++,...e})}))}catch(t){return new Promise((t=>{t(!1)}))}return new Promise((t=>{t(!0)}))}select(t,e){try{return new Promise(void 0===e?e=>{e(this.data[t])}:"number"==typeof e?n=>{n(this.data[t][e])}:n=>{n(this.data[t].filter(this.makeFilter(e))||null)})}catch(t){return new Promise((t=>{t(null)}))}}update(t,e,n){if("number"==typeof e)try{return this.data[t][e]=n,new Promise((t=>{t(!0)}))}catch(t){return new Promise((t=>{t(!1)}))}const o=this.data[t].filter(this.makeFilter(e));return o?(o.forEach((e=>{const o=this.data[t][e.id];for(const t in n)o[t]=n[t];this.data[t][e.id]=o})),new Promise((t=>{t(!0)}))):new Promise((t=>{t(!1)}))}delete(t,e){const n=this.data[t];if(!n)return new Promise((t=>{t(!1)}));if(!e)return this.data[t]=[],new Promise((t=>{t(!0)}));const o=this.makeFilter(e);return this.data[t]=n.filter((t=>!o(t))),new Promise((t=>{t(!0)}))}}},21:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Status=void 0;const o=n(854);Object.defineProperty(e,"Status",{enumerable:!0,get:function(){return o.Status}})},854:function(t,e){var n;Object.defineProperty(e,"__esModule",{value:!0}),e.Status=void 0,(n=e.Status||(e.Status={}))[n.Locked=0]="Locked",n[n.Waiting=1]="Waiting",n[n.Ready=2]="Ready",n[n.Running=3]="Running",n[n.Completed=4]="Completed",n[n.Archived=5]="Archived"},71:function(t,e,n){n.r(e);var o=n(671),r=n(144),i=[],a=i.forEach,s=i.slice;function u(t){return a.call(s.call(arguments,1),(function(e){if(e)for(var n in e)void 0===t[n]&&(t[n]=e[n])})),t}var c=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,l=function(t,e,n){var o=n||{};o.path=o.path||"/";var r=t+"="+encodeURIComponent(e);if(o.maxAge>0){var i=o.maxAge-0;if(isNaN(i))throw new Error("maxAge should be a Number");r+="; Max-Age="+Math.floor(i)}if(o.domain){if(!c.test(o.domain))throw new TypeError("option domain is invalid");r+="; Domain="+o.domain}if(o.path){if(!c.test(o.path))throw new TypeError("option path is invalid");r+="; Path="+o.path}if(o.expires){if("function"!=typeof o.expires.toUTCString)throw new TypeError("option expires is invalid");r+="; Expires="+o.expires.toUTCString()}if(o.httpOnly&&(r+="; HttpOnly"),o.secure&&(r+="; Secure"),o.sameSite)switch("string"==typeof o.sameSite?o.sameSite.toLowerCase():o.sameSite){case!0:r+="; SameSite=Strict";break;case"lax":r+="; SameSite=Lax";break;case"strict":r+="; SameSite=Strict";break;case"none":r+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r},d={name:"cookie",lookup:function(t){var e;if(t.lookupCookie&&"undefined"!=typeof document){var n=function(t){for(var e=t+"=",n=document.cookie.split(";"),o=0;o4&&void 0!==arguments[4]?arguments[4]:{path:"/",sameSite:"strict"};n&&(r.expires=new Date,r.expires.setTime(r.expires.getTime()+60*n*1e3)),o&&(r.domain=o),document.cookie=l(t,encodeURIComponent(e),r)}(e.lookupCookie,t,e.cookieMinutes,e.cookieDomain,e.cookieOptions)}},p={name:"querystring",lookup:function(t){var e;if("undefined"!=typeof window)for(var n=window.location.search.substring(1).split("&"),o=0;o0&&n[o].substring(0,r)===t.lookupQuerystring&&(e=n[o].substring(r+1))}return e}},h=null,g=function(){if(null!==h)return h;try{h="undefined"!==window&&null!==window.localStorage;var t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch(t){h=!1}return h},f={name:"localStorage",lookup:function(t){var e;if(t.lookupLocalStorage&&g()){var n=window.localStorage.getItem(t.lookupLocalStorage);n&&(e=n)}return e},cacheUserLanguage:function(t,e){e.lookupLocalStorage&&g()&&window.localStorage.setItem(e.lookupLocalStorage,t)}},m=null,v=function(){if(null!==m)return m;try{m="undefined"!==window&&null!==window.sessionStorage;var t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch(t){m=!1}return m},w={name:"sessionStorage",lookup:function(t){var e;if(t.lookupSessionStorage&&v()){var n=window.sessionStorage.getItem(t.lookupSessionStorage);n&&(e=n)}return e},cacheUserLanguage:function(t,e){e.lookupSessionStorage&&v()&&window.sessionStorage.setItem(e.lookupSessionStorage,t)}},b={name:"navigator",lookup:function(t){var e=[];if("undefined"!=typeof navigator){if(navigator.languages)for(var n=0;n0?e:void 0}},y={name:"htmlTag",lookup:function(t){var e,n=t.htmlTag||("undefined"!=typeof document?document.documentElement:null);return n&&"function"==typeof n.getAttribute&&(e=n.getAttribute("lang")),e}},k={name:"path",lookup:function(t){var e;if("undefined"!=typeof window){var n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);if(n instanceof Array)if("number"==typeof t.lookupFromPathIndex){if("string"!=typeof n[t.lookupFromPathIndex])return;e=n[t.lookupFromPathIndex].replace("/","")}else e=n[0].replace("/","")}return e}},S={name:"subdomain",lookup:function(t){var e;if("undefined"!=typeof window){var n=window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);n instanceof Array&&(e="number"==typeof t.lookupFromSubdomainIndex?n[t.lookupFromSubdomainIndex].replace("http://","").replace("https://","").replace(".",""):n[0].replace("http://","").replace("https://","").replace(".",""))}return e}},M=function(){function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};(0,o.Z)(this,t),this.type="languageDetector",this.detectors={},this.init(e,n)}return(0,r.Z)(t,[{key:"init",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.services=t,this.options=u(e,this.options||{},{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"]}),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=n,this.addDetector(d),this.addDetector(p),this.addDetector(f),this.addDetector(w),this.addDetector(b),this.addDetector(y),this.addDetector(k),this.addDetector(S)}},{key:"addDetector",value:function(t){this.detectors[t.name]=t}},{key:"detect",value:function(t){var e=this;t||(t=this.options.order);var n=[];return t.forEach((function(t){if(e.detectors[t]){var o=e.detectors[t].lookup(e.options);o&&"string"==typeof o&&(o=[o]),o&&(n=n.concat(o))}})),this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}},{key:"cacheUserLanguage",value:function(t,e){var n=this;e||(e=this.options.caches),e&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(t)>-1||e.forEach((function(e){n.detectors[e]&&n.detectors[e].cacheUserLanguage(t,n.options)})))}}]),t}();M.type="languageDetector",e.default=M},261:function(t,e,n){function o(t){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o(t)}function r(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{};(0,a.Z)(this,t),this.init(e,n)}return(0,s.Z)(t,[{key:"init",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.prefix=e.prefix||"i18next:",this.logger=t||h,this.options=e,this.debug=e.debug}},{key:"setDebug",value:function(t){this.debug=t}},{key:"log",value:function(){for(var t=arguments.length,e=new Array(t),n=0;n1?e-1:0),o=1;o-1?t.replace(/###/g,"."):t}function r(){return!t||"string"==typeof t}for(var i="string"!=typeof e?[].concat(e):e.split(".");i.length>1;){if(r())return{};var a=o(i.shift());!t[a]&&n&&(t[a]=new n),t=Object.prototype.hasOwnProperty.call(t,a)?t[a]:{}}return r()?{}:{obj:t,k:o(i.shift())}}function k(t,e,n){var o=y(t,e,Object);o.obj[o.k]=n}function S(t,e){var n=y(t,e),o=n.obj,r=n.k;if(o)return o[r]}function M(t,e,n){var o=S(t,n);return void 0!==o?o:S(e,n)}function R(t,e,n){for(var o in e)"__proto__"!==o&&"constructor"!==o&&(o in t?"string"==typeof t[o]||t[o]instanceof String||"string"==typeof e[o]||e[o]instanceof String?n&&(t[o]=e[o]):R(t[o],e[o],n):t[o]=e[o]);return t}function E(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var x={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};function C(t){return"string"==typeof t?t.replace(/[&<>"'\/]/g,(function(t){return x[t]})):t}var _="undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.userAgent.indexOf("MSIE")>-1;function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:".";if(t){if(t[e])return t[e];for(var o=e.split(n),r=t,i=0;ii+a;)a++,u=r[s=o.slice(i,i+a).join(n)];if(void 0===u)return;if("string"==typeof u)return u;if(s&&"string"==typeof u[s])return u[s];var c=o.slice(i+a).join(n);return c?L(u,c,n):void 0}r=r[o[i]]}return r}}var O=function(t){function e(t){var n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{ns:["translation"],defaultNS:"translation"};return(0,a.Z)(this,e),n=c(this,l(e).call(this)),_&&m.call(u(n)),n.data=t||{},n.options=o,void 0===n.options.keySeparator&&(n.options.keySeparator="."),void 0===n.options.ignoreJSONStructure&&(n.options.ignoreJSONStructure=!0),n}return p(e,t),(0,s.Z)(e,[{key:"addNamespaces",value:function(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}},{key:"removeNamespaces",value:function(t){var e=this.options.ns.indexOf(t);e>-1&&this.options.ns.splice(e,1)}},{key:"getResource",value:function(t,e,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},r=void 0!==o.keySeparator?o.keySeparator:this.options.keySeparator,i=void 0!==o.ignoreJSONStructure?o.ignoreJSONStructure:this.options.ignoreJSONStructure,a=[t,e];n&&"string"!=typeof n&&(a=a.concat(n)),n&&"string"==typeof n&&(a=a.concat(r?n.split(r):n)),t.indexOf(".")>-1&&(a=t.split("."));var s=S(this.data,a);return s||!i||"string"!=typeof n?s:L(this.data&&this.data[t]&&this.data[t][e],n,r)}},{key:"addResource",value:function(t,e,n,o){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{silent:!1},i=this.options.keySeparator;void 0===i&&(i=".");var a=[t,e];n&&(a=a.concat(i?n.split(i):n)),t.indexOf(".")>-1&&(o=e,e=(a=t.split("."))[1]),this.addNamespaces(e),k(this.data,a,o),r.silent||this.emit("added",t,e,n,o)}},{key:"addResources",value:function(t,e,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{silent:!1};for(var r in n)"string"!=typeof n[r]&&"[object Array]"!==Object.prototype.toString.apply(n[r])||this.addResource(t,e,r,n[r],{silent:!0});o.silent||this.emit("added",t,e,n)}},{key:"addResourceBundle",value:function(t,e,n,o,r){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{silent:!1},s=[t,e];t.indexOf(".")>-1&&(o=n,n=e,e=(s=t.split("."))[1]),this.addNamespaces(e);var u=S(this.data,s)||{};o?R(u,n,r):u=i({},u,n),k(this.data,s,u),a.silent||this.emit("added",t,e,n)}},{key:"removeResourceBundle",value:function(t,e){this.hasResourceBundle(t,e)&&delete this.data[t][e],this.removeNamespaces(e),this.emit("removed",t,e)}},{key:"hasResourceBundle",value:function(t,e){return void 0!==this.getResource(t,e)}},{key:"getResourceBundle",value:function(t,e){return e||(e=this.options.defaultNS),"v1"===this.options.compatibilityAPI?i({},{},this.getResource(t,e)):this.getResource(t,e)}},{key:"getDataByLanguage",value:function(t){return this.data[t]}},{key:"toJSON",value:function(){return this.data}}]),e}(m),P={processors:{},addPostProcessor:function(t){this.processors[t.name]=t},handle:function(t,e,n,o,r){var i=this;return t.forEach((function(t){i.processors[t]&&(e=i.processors[t].process(e,n,o,r))})),e}},N={},B=function(t){function e(t){var n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(0,a.Z)(this,e),n=c(this,l(e).call(this)),_&&m.call(u(n)),b(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,u(n)),n.options=o,void 0===n.options.keySeparator&&(n.options.keySeparator="."),n.logger=f.create("translator"),n}return p(e,t),(0,s.Z)(e,[{key:"changeLanguage",value:function(t){t&&(this.language=t)}},{key:"exists",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}};if(null==t)return!1;var n=this.resolve(t,e);return n&&void 0!==n.res}},{key:"extractFromKey",value:function(t,e){var n=void 0!==e.nsSeparator?e.nsSeparator:this.options.nsSeparator;void 0===n&&(n=":");var o=void 0!==e.keySeparator?e.keySeparator:this.options.keySeparator,r=e.ns||this.options.defaultNS;if(n&&t.indexOf(n)>-1){var i=t.match(this.interpolator.nestingRegexp);if(i&&i.length>0)return{key:t,namespaces:r};var a=t.split(n);(n!==o||n===o&&this.options.ns.indexOf(a[0])>-1)&&(r=a.shift()),t=a.join(o)}return"string"==typeof r&&(r=[r]),{key:t,namespaces:r}}},{key:"translate",value:function(t,n,r){var a=this;if("object"!==o(n)&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),n||(n={}),null==t)return"";Array.isArray(t)||(t=[String(t)]);var s=void 0!==n.keySeparator?n.keySeparator:this.options.keySeparator,u=this.extractFromKey(t[t.length-1],n),c=u.key,l=u.namespaces,d=l[l.length-1],p=n.lng||this.language,h=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(p&&"cimode"===p.toLowerCase()){if(h){var g=n.nsSeparator||this.options.nsSeparator;return d+g+c}return c}var f=this.resolve(t,n),m=f&&f.res,v=f&&f.usedKey||c,w=f&&f.exactUsedKey||c,b=Object.prototype.toString.apply(m),y=["[object Number]","[object Function]","[object RegExp]"],k=void 0!==n.joinArrays?n.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,M="string"!=typeof m&&"boolean"!=typeof m&&"number"!=typeof m;if(S&&m&&M&&y.indexOf(b)<0&&("string"!=typeof k||"[object Array]"!==b)){if(!n.returnObjects&&!this.options.returnObjects)return this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!"),this.options.returnedObjectHandler?this.options.returnedObjectHandler(v,m,i({},n,{ns:l})):"key '".concat(c," (").concat(this.language,")' returned an object instead of string.");if(s){var R="[object Array]"===b,E=R?[]:{},x=R?w:v;for(var C in m)if(Object.prototype.hasOwnProperty.call(m,C)){var _="".concat(x).concat(s).concat(C);E[C]=this.translate(_,i({},n,{joinArrays:!1,ns:l})),E[C]===_&&(E[C]=m[C])}m=E}}else if(S&&"string"==typeof k&&"[object Array]"===b)(m=m.join(k))&&(m=this.extendTranslation(m,t,n,r));else{var L=!1,O=!1,P=void 0!==n.count&&"string"!=typeof n.count,N=e.hasDefaultValue(n),B=P?this.pluralResolver.getSuffix(p,n.count):"",F=n["defaultValue".concat(B)]||n.defaultValue;!this.isValidLookup(m)&&N&&(L=!0,m=F),this.isValidLookup(m)||(O=!0,m=c);var T=n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey,j=T&&O?void 0:m,D=N&&F!==m&&this.options.updateMissing;if(O||L||D){if(this.logger.log(D?"updateKey":"missingKey",p,d,c,D?F:m),s){var I=this.resolve(c,i({},n,{keySeparator:!1}));I&&I.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}var A=[],U=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if("fallback"===this.options.saveMissingTo&&U&&U[0])for(var W=0;W1&&void 0!==arguments[1]?arguments[1]:{};return"string"==typeof t&&(t=[t]),t.forEach((function(t){if(!a.isValidLookup(e)){var u=a.extractFromKey(t,s),c=u.key;n=c;var l=u.namespaces;a.options.fallbackNS&&(l=l.concat(a.options.fallbackNS));var d=void 0!==s.count&&"string"!=typeof s.count,p=void 0!==s.context&&("string"==typeof s.context||"number"==typeof s.context)&&""!==s.context,h=s.lngs?s.lngs:a.languageUtils.toResolveHierarchy(s.lng||a.language,s.fallbackLng);l.forEach((function(t){a.isValidLookup(e)||(i=t,!N["".concat(h[0],"-").concat(t)]&&a.utils&&a.utils.hasLoadedNamespace&&!a.utils.hasLoadedNamespace(i)&&(N["".concat(h[0],"-").concat(t)]=!0,a.logger.warn('key "'.concat(n,'" for languages "').concat(h.join(", "),'" won\'t get resolved as namespace "').concat(i,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),h.forEach((function(n){if(!a.isValidLookup(e)){r=n;var i,u,l=c,h=[l];for(a.i18nFormat&&a.i18nFormat.addLookupKeys?a.i18nFormat.addLookupKeys(h,c,n,t,s):(d&&(i=a.pluralResolver.getSuffix(n,s.count)),d&&p&&h.push(l+i),p&&h.push(l+="".concat(a.options.contextSeparator).concat(s.context)),d&&h.push(l+=i));u=h.pop();)a.isValidLookup(e)||(o=u,e=a.getResource(n,t,u,s))}})))}))}})),{res:e,usedKey:n,exactUsedKey:o,usedLng:r,usedNS:i}}},{key:"isValidLookup",value:function(t){return!(void 0===t||!this.options.returnNull&&null===t||!this.options.returnEmptyString&&""===t)}},{key:"getResource",value:function(t,e,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,e,n,o):this.resourceStore.getResource(t,e,n,o)}}],[{key:"hasDefaultValue",value:function(t){var e="defaultValue";for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e===n.substring(0,e.length)&&void 0!==t[n])return!0;return!1}}]),e}(m);function F(t){return t.charAt(0).toUpperCase()+t.slice(1)}var T=function(){function t(e){(0,a.Z)(this,t),this.options=e,this.whitelist=this.options.supportedLngs||!1,this.supportedLngs=this.options.supportedLngs||!1,this.logger=f.create("languageUtils")}return(0,s.Z)(t,[{key:"getScriptPartFromCode",value:function(t){if(!t||t.indexOf("-")<0)return null;var e=t.split("-");return 2===e.length?null:(e.pop(),"x"===e[e.length-1].toLowerCase()?null:this.formatLanguageCode(e.join("-")))}},{key:"getLanguagePartFromCode",value:function(t){if(!t||t.indexOf("-")<0)return t;var e=t.split("-");return this.formatLanguageCode(e[0])}},{key:"formatLanguageCode",value:function(t){if("string"==typeof t&&t.indexOf("-")>-1){var e=["hans","hant","latn","cyrl","cans","mong","arab"],n=t.split("-");return this.options.lowerCaseLng?n=n.map((function(t){return t.toLowerCase()})):2===n.length?(n[0]=n[0].toLowerCase(),n[1]=n[1].toUpperCase(),e.indexOf(n[1].toLowerCase())>-1&&(n[1]=F(n[1].toLowerCase()))):3===n.length&&(n[0]=n[0].toLowerCase(),2===n[1].length&&(n[1]=n[1].toUpperCase()),"sgn"!==n[0]&&2===n[2].length&&(n[2]=n[2].toUpperCase()),e.indexOf(n[1].toLowerCase())>-1&&(n[1]=F(n[1].toLowerCase())),e.indexOf(n[2].toLowerCase())>-1&&(n[2]=F(n[2].toLowerCase()))),n.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}},{key:"isWhitelisted",value:function(t){return this.logger.deprecate("languageUtils.isWhitelisted",'function "isWhitelisted" will be renamed to "isSupportedCode" in the next major - please make sure to rename it\'s usage asap.'),this.isSupportedCode(t)}},{key:"isSupportedCode",value:function(t){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}},{key:"getBestMatchFromCodes",value:function(t){var e,n=this;return t?(t.forEach((function(t){if(!e){var o=n.formatLanguageCode(t);n.options.supportedLngs&&!n.isSupportedCode(o)||(e=o)}})),!e&&this.options.supportedLngs&&t.forEach((function(t){if(!e){var o=n.getLanguagePartFromCode(t);if(n.isSupportedCode(o))return e=o;e=n.options.supportedLngs.find((function(t){if(0===t.indexOf(o))return t}))}})),e||(e=this.getFallbackCodes(this.options.fallbackLng)[0]),e):null}},{key:"getFallbackCodes",value:function(t,e){if(!t)return[];if("function"==typeof t&&(t=t(e)),"string"==typeof t&&(t=[t]),"[object Array]"===Object.prototype.toString.apply(t))return t;if(!e)return t.default||[];var n=t[e];return n||(n=t[this.getScriptPartFromCode(e)]),n||(n=t[this.formatLanguageCode(e)]),n||(n=t[this.getLanguagePartFromCode(e)]),n||(n=t.default),n||[]}},{key:"toResolveHierarchy",value:function(t,e){var n=this,o=this.getFallbackCodes(e||this.options.fallbackLng||[],t),r=[],i=function(t){t&&(n.isSupportedCode(t)?r.push(t):n.logger.warn("rejecting language code not found in supportedLngs: ".concat(t)))};return"string"==typeof t&&t.indexOf("-")>-1?("languageOnly"!==this.options.load&&i(this.formatLanguageCode(t)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&i(this.getScriptPartFromCode(t)),"currentOnly"!==this.options.load&&i(this.getLanguagePartFromCode(t))):"string"==typeof t&&i(this.formatLanguageCode(t)),o.forEach((function(t){r.indexOf(t)<0&&i(n.formatLanguageCode(t))})),r}}]),t}(),j=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],D={1:function(t){return Number(t>1)},2:function(t){return Number(1!=t)},3:function(t){return 0},4:function(t){return Number(t%10==1&&t%100!=11?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2)},5:function(t){return Number(0==t?0:1==t?1:2==t?2:t%100>=3&&t%100<=10?3:t%100>=11?4:5)},6:function(t){return Number(1==t?0:t>=2&&t<=4?1:2)},7:function(t){return Number(1==t?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2)},8:function(t){return Number(1==t?0:2==t?1:8!=t&&11!=t?2:3)},9:function(t){return Number(t>=2)},10:function(t){return Number(1==t?0:2==t?1:t<7?2:t<11?3:4)},11:function(t){return Number(1==t||11==t?0:2==t||12==t?1:t>2&&t<20?2:3)},12:function(t){return Number(t%10!=1||t%100==11)},13:function(t){return Number(0!==t)},14:function(t){return Number(1==t?0:2==t?1:3==t?2:3)},15:function(t){return Number(t%10==1&&t%100!=11?0:t%10>=2&&(t%100<10||t%100>=20)?1:2)},16:function(t){return Number(t%10==1&&t%100!=11?0:0!==t?1:2)},17:function(t){return Number(1==t||t%10==1&&t%100!=11?0:1)},18:function(t){return Number(0==t?0:1==t?1:2)},19:function(t){return Number(1==t?0:0==t||t%100>1&&t%100<11?1:t%100>10&&t%100<20?2:3)},20:function(t){return Number(1==t?0:0==t||t%100>0&&t%100<20?1:2)},21:function(t){return Number(t%100==1?1:t%100==2?2:t%100==3||t%100==4?3:0)},22:function(t){return Number(1==t?0:2==t?1:(t<0||t>10)&&t%10==0?2:3)}};function I(){var t={};return j.forEach((function(e){e.lngs.forEach((function(n){t[n]={numbers:e.nr,plurals:D[e.fc]}}))})),t}var A=function(){function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};(0,a.Z)(this,t),this.languageUtils=e,this.options=n,this.logger=f.create("pluralResolver"),this.rules=I()}return(0,s.Z)(t,[{key:"addRule",value:function(t,e){this.rules[t]=e}},{key:"getRule",value:function(t){return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}},{key:"needsPlural",value:function(t){var e=this.getRule(t);return e&&e.numbers.length>1}},{key:"getPluralFormsOfKey",value:function(t,e){return this.getSuffixes(t).map((function(t){return e+t}))}},{key:"getSuffixes",value:function(t){var e=this,n=this.getRule(t);return n?n.numbers.map((function(n){return e.getSuffix(t,n)})):[]}},{key:"getSuffix",value:function(t,e){var n=this,o=this.getRule(t);if(o){var r=o.noAbs?o.plurals(e):o.plurals(Math.abs(e)),i=o.numbers[r];this.options.simplifyPluralSuffix&&2===o.numbers.length&&1===o.numbers[0]&&(2===i?i="plural":1===i&&(i=""));var a=function(){return n.options.prepend&&i.toString()?n.options.prepend+i.toString():i.toString()};return"v1"===this.options.compatibilityJSON?1===i?"":"number"==typeof i?"_plural_".concat(i.toString()):a():"v2"===this.options.compatibilityJSON||this.options.simplifyPluralSuffix&&2===o.numbers.length&&1===o.numbers[0]?a():this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString()}return this.logger.warn("no plural rule found for: ".concat(t)),""}}]),t}(),U=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,a.Z)(this,t),this.logger=f.create("interpolator"),this.options=e,this.format=e.interpolation&&e.interpolation.format||function(t){return t},this.init(e)}return(0,s.Z)(t,[{key:"init",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});var e=t.interpolation;this.escape=void 0!==e.escape?e.escape:C,this.escapeValue=void 0===e.escapeValue||e.escapeValue,this.useRawValueToEscape=void 0!==e.useRawValueToEscape&&e.useRawValueToEscape,this.prefix=e.prefix?E(e.prefix):e.prefixEscaped||"{{",this.suffix=e.suffix?E(e.suffix):e.suffixEscaped||"}}",this.formatSeparator=e.formatSeparator?e.formatSeparator:e.formatSeparator||",",this.unescapePrefix=e.unescapeSuffix?"":e.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":e.unescapeSuffix||"",this.nestingPrefix=e.nestingPrefix?E(e.nestingPrefix):e.nestingPrefixEscaped||E("$t("),this.nestingSuffix=e.nestingSuffix?E(e.nestingSuffix):e.nestingSuffixEscaped||E(")"),this.nestingOptionsSeparator=e.nestingOptionsSeparator?e.nestingOptionsSeparator:e.nestingOptionsSeparator||",",this.maxReplaces=e.maxReplaces?e.maxReplaces:1e3,this.alwaysFormat=void 0!==e.alwaysFormat&&e.alwaysFormat,this.resetRegExp()}},{key:"reset",value:function(){this.options&&this.init(this.options)}},{key:"resetRegExp",value:function(){var t="".concat(this.prefix,"(.+?)").concat(this.suffix);this.regexp=new RegExp(t,"g");var e="".concat(this.prefix).concat(this.unescapePrefix,"(.+?)").concat(this.unescapeSuffix).concat(this.suffix);this.regexpUnescape=new RegExp(e,"g");var n="".concat(this.nestingPrefix,"(.+?)").concat(this.nestingSuffix);this.nestingRegexp=new RegExp(n,"g")}},{key:"interpolate",value:function(t,e,n,o){var r,a,s,u=this,c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function l(t){return t.replace(/\$/g,"$$$$")}var d=function(t){if(t.indexOf(u.formatSeparator)<0){var r=M(e,c,t);return u.alwaysFormat?u.format(r,void 0,n,i({},o,e,{interpolationkey:t})):r}var a=t.split(u.formatSeparator),s=a.shift().trim(),l=a.join(u.formatSeparator).trim();return u.format(M(e,c,s),l,n,i({},o,e,{interpolationkey:s}))};this.resetRegExp();var p=o&&o.missingInterpolationHandler||this.options.missingInterpolationHandler,h=o&&o.interpolation&&o.interpolation.skipOnVariables||this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:function(t){return l(t)}},{regex:this.regexp,safeValue:function(t){return u.escapeValue?l(u.escape(t)):l(t)}}].forEach((function(e){for(s=0;r=e.regex.exec(t);){if(void 0===(a=d(r[1].trim())))if("function"==typeof p){var n=p(t,r,o);a="string"==typeof n?n:""}else{if(h){a=r[0];continue}u.logger.warn("missed to pass in variable ".concat(r[1]," for interpolating ").concat(t)),a=""}else"string"==typeof a||u.useRawValueToEscape||(a=w(a));var i=e.safeValue(a);if(t=t.replace(r[0],i),h?(e.regex.lastIndex+=i.length,e.regex.lastIndex-=r[0].length):e.regex.lastIndex=0,++s>=u.maxReplaces)break}})),t}},{key:"nest",value:function(t,e){var n,o,r=this,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=i({},a);function u(t,e){var n=this.nestingOptionsSeparator;if(t.indexOf(n)<0)return t;var o=t.split(new RegExp("".concat(n,"[ ]*{"))),r="{".concat(o[1]);t=o[0],r=(r=this.interpolate(r,s)).replace(/'/g,'"');try{s=JSON.parse(r),e&&(s=i({},e,s))}catch(e){return this.logger.warn("failed parsing options string in nesting for key ".concat(t),e),"".concat(t).concat(n).concat(r)}return delete s.defaultValue,t}for(s.applyPostProcessor=!1,delete s.defaultValue;n=this.nestingRegexp.exec(t);){var c=[],l=!1;if(-1!==n[0].indexOf(this.formatSeparator)&&!/{.*}/.test(n[1])){var d=n[1].split(this.formatSeparator).map((function(t){return t.trim()}));n[1]=d.shift(),c=d,l=!0}if((o=e(u.call(this,n[1].trim(),s),s))&&n[0]===t&&"string"!=typeof o)return o;"string"!=typeof o&&(o=w(o)),o||(this.logger.warn("missed to resolve ".concat(n[1]," for nesting ").concat(t)),o=""),l&&(o=c.reduce((function(t,e){return r.format(t,e,a.lng,i({},a,{interpolationkey:n[1].trim()}))}),o.trim())),t=t.replace(n[0],o),this.regexp.lastIndex=0}return t}}]),t}(),W=function(t){function e(t,n,o){var r,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return(0,a.Z)(this,e),r=c(this,l(e).call(this)),_&&m.call(u(r)),r.backend=t,r.store=n,r.services=o,r.languageUtils=o.languageUtils,r.options=i,r.logger=f.create("backendConnector"),r.state={},r.queue=[],r.backend&&r.backend.init&&r.backend.init(o,i.backend,i),r}return p(e,t),(0,s.Z)(e,[{key:"queueLoad",value:function(t,e,n,o){var r=this,i=[],a=[],s=[],u=[];return t.forEach((function(t){var o=!0;e.forEach((function(e){var s="".concat(t,"|").concat(e);!n.reload&&r.store.hasResourceBundle(t,e)?r.state[s]=2:r.state[s]<0||(1===r.state[s]?a.indexOf(s)<0&&a.push(s):(r.state[s]=1,o=!1,a.indexOf(s)<0&&a.push(s),i.indexOf(s)<0&&i.push(s),u.indexOf(e)<0&&u.push(e)))})),o||s.push(t)})),(i.length||a.length)&&this.queue.push({pending:a,loaded:{},errors:[],callback:o}),{toLoad:i,pending:a,toLoadLanguages:s,toLoadNamespaces:u}}},{key:"loaded",value:function(t,e,n){var o=t.split("|"),r=o[0],i=o[1];e&&this.emit("failedLoading",r,i,e),n&&this.store.addResourceBundle(r,i,n),this.state[t]=e?-1:2;var a={};this.queue.forEach((function(n){var o,s,u,c,l;o=n.loaded,s=i,(c=(u=y(o,[r],Object)).obj)[l=u.k]=c[l]||[],c[l].push(s),function(t,e){for(var n=t.indexOf(e);-1!==n;)t.splice(n,1),n=t.indexOf(e)}(n.pending,t),e&&n.errors.push(e),0!==n.pending.length||n.done||(Object.keys(n.loaded).forEach((function(t){a[t]||(a[t]=[]),n.loaded[t].length&&n.loaded[t].forEach((function(e){a[t].indexOf(e)<0&&a[t].push(e)}))})),n.done=!0,n.errors.length?n.callback(n.errors):n.callback())})),this.emit("loaded",a),this.queue=this.queue.filter((function(t){return!t.done}))}},{key:"read",value:function(t,e,n){var o=this,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:350,a=arguments.length>5?arguments[5]:void 0;return t.length?this.backend[n](t,e,(function(s,u){s&&u&&r<5?setTimeout((function(){o.read.call(o,t,e,n,r+1,2*i,a)}),i):a(s,u)})):a(null,{})}},{key:"prepareLoading",value:function(t,e){var n=this,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),r&&r();"string"==typeof t&&(t=this.languageUtils.toResolveHierarchy(t)),"string"==typeof e&&(e=[e]);var i=this.queueLoad(t,e,o,r);if(!i.toLoad.length)return i.pending.length||r(),null;i.toLoad.forEach((function(t){n.loadOne(t)}))}},{key:"load",value:function(t,e,n){this.prepareLoading(t,e,{},n)}},{key:"reload",value:function(t,e,n){this.prepareLoading(t,e,{reload:!0},n)}},{key:"loadOne",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",o=t.split("|"),r=o[0],i=o[1];this.read(r,i,"read",void 0,void 0,(function(o,a){o&&e.logger.warn("".concat(n,"loading namespace ").concat(i," for language ").concat(r," failed"),o),!o&&a&&e.logger.log("".concat(n,"loaded namespace ").concat(i," for language ").concat(r),a),e.loaded(t,o,a)}))}},{key:"saveMissing",value:function(t,e,n,o,r){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(e)?this.logger.warn('did not save key "'.concat(n,'" as the namespace "').concat(e,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"):null!=n&&""!==n&&(this.backend&&this.backend.create&&this.backend.create(t,e,n,o,null,i({},a,{isUpdate:r})),t&&t[0]&&this.store.addResource(t[0],e,n,o))}}]),e}(m);function G(){return{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,whitelist:!1,nonExplicitWhitelist:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!0,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(t){var e={};if("object"===o(t[1])&&(e=t[1]),"string"==typeof t[1]&&(e.defaultValue=t[1]),"string"==typeof t[2]&&(e.tDescription=t[2]),"object"===o(t[2])||"object"===o(t[3])){var n=t[3]||t[2];Object.keys(n).forEach((function(t){e[t]=n[t]}))}return e},interpolation:{escapeValue:!0,format:function(t,e,n,o){return t},prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!1}}}function z(t){return"string"==typeof t.ns&&(t.ns=[t.ns]),"string"==typeof t.fallbackLng&&(t.fallbackLng=[t.fallbackLng]),"string"==typeof t.fallbackNS&&(t.fallbackNS=[t.fallbackNS]),t.whitelist&&(t.whitelist&&t.whitelist.indexOf("cimode")<0&&(t.whitelist=t.whitelist.concat(["cimode"])),t.supportedLngs=t.whitelist),t.nonExplicitWhitelist&&(t.nonExplicitSupportedLngs=t.nonExplicitWhitelist),t.supportedLngs&&t.supportedLngs.indexOf("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t}function H(){}var V=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=arguments.length>1?arguments[1]:void 0;if((0,a.Z)(this,e),t=c(this,l(e).call(this)),_&&m.call(u(t)),t.options=z(n),t.services={},t.logger=f,t.modules={external:[]},o&&!t.isInitialized&&!n.isClone){if(!t.options.initImmediate)return t.init(n,o),c(t,u(t));setTimeout((function(){t.init(n,o)}),0)}return t}return p(e,t),(0,s.Z)(e,[{key:"init",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;function o(t){return t?"function"==typeof t?new t:t:null}if("function"==typeof e&&(n=e,e={}),e.whitelist&&!e.supportedLngs&&this.logger.deprecate("whitelist",'option "whitelist" will be renamed to "supportedLngs" in the next major - please make sure to rename this option asap.'),e.nonExplicitWhitelist&&!e.nonExplicitSupportedLngs&&this.logger.deprecate("whitelist",'options "nonExplicitWhitelist" will be renamed to "nonExplicitSupportedLngs" in the next major - please make sure to rename this option asap.'),this.options=i({},G(),this.options,z(e)),this.format=this.options.interpolation.format,n||(n=H),!this.options.isClone){this.modules.logger?f.init(o(this.modules.logger),this.options):f.init(null,this.options);var r=new T(this.options);this.store=new O(this.options.resources,this.options);var a=this.services;a.logger=f,a.resourceStore=this.store,a.languageUtils=r,a.pluralResolver=new A(r,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),a.interpolator=new U(this.options),a.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},a.backendConnector=new W(o(this.modules.backend),a.resourceStore,a,this.options),a.backendConnector.on("*",(function(e){for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r1?n-1:0),r=1;r0&&"dev"!==s[0]&&(this.options.lng=s[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");var u=["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"];u.forEach((function(e){t[e]=function(){var n;return(n=t.store)[e].apply(n,arguments)}}));var c=["addResource","addResources","addResourceBundle","removeResourceBundle"];c.forEach((function(e){t[e]=function(){var n;return(n=t.store)[e].apply(n,arguments),t}}));var l=v(),d=function(){var e=function(e,o){t.isInitialized&&!t.initializedStoreOnce&&t.logger.warn("init: i18next is already initialized. You should call init just once!"),t.isInitialized=!0,t.options.isClone||t.logger.log("initialized",t.options),t.emit("initialized",t.options),l.resolve(o),n(e,o)};if(t.languages&&"v1"!==t.options.compatibilityAPI&&!t.isInitialized)return e(null,t.t.bind(t));t.changeLanguage(t.options.lng,e)};return this.options.resources||!this.options.initImmediate?d():setTimeout(d,0),l}},{key:"loadResources",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:H,o=n,r="string"==typeof t?t:this.language;if("function"==typeof t&&(o=t),!this.options.resources||this.options.partialBundledLanguages){if(r&&"cimode"===r.toLowerCase())return o();var i=[],a=function(t){t&&e.services.languageUtils.toResolveHierarchy(t).forEach((function(t){i.indexOf(t)<0&&i.push(t)}))};if(r)a(r);else{var s=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);s.forEach((function(t){return a(t)}))}this.options.preload&&this.options.preload.forEach((function(t){return a(t)})),this.services.backendConnector.load(i,this.options.ns,o)}else o(null)}},{key:"reloadResources",value:function(t,e,n){var o=v();return t||(t=this.languages),e||(e=this.options.ns),n||(n=H),this.services.backendConnector.reload(t,e,(function(t){o.resolve(),n(t)})),o}},{key:"use",value:function(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===t.type&&(this.modules.backend=t),("logger"===t.type||t.log&&t.warn&&t.error)&&(this.modules.logger=t),"languageDetector"===t.type&&(this.modules.languageDetector=t),"i18nFormat"===t.type&&(this.modules.i18nFormat=t),"postProcessor"===t.type&&P.addPostProcessor(t),"3rdParty"===t.type&&this.modules.external.push(t),this}},{key:"changeLanguage",value:function(t,e){var n=this;this.isLanguageChangingTo=t;var o=v();this.emit("languageChanging",t);var r=function(r){t||r||!n.services.languageDetector||(r=[]);var i="string"==typeof r?r:n.services.languageUtils.getBestMatchFromCodes(r);i&&(n.language||(n.language=i,n.languages=n.services.languageUtils.toResolveHierarchy(i)),n.translator.language||n.translator.changeLanguage(i),n.services.languageDetector&&n.services.languageDetector.cacheUserLanguage(i)),n.loadResources(i,(function(t){!function(t,r){r?(n.language=r,n.languages=n.services.languageUtils.toResolveHierarchy(r),n.translator.changeLanguage(r),n.isLanguageChangingTo=void 0,n.emit("languageChanged",r),n.logger.log("languageChanged",r)):n.isLanguageChangingTo=void 0,o.resolve((function(){return n.t.apply(n,arguments)})),e&&e(t,(function(){return n.t.apply(n,arguments)}))}(t,i)}))};return t||!this.services.languageDetector||this.services.languageDetector.async?!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect(r):r(t):r(this.services.languageDetector.detect()),o}},{key:"getFixedT",value:function(t,e,n){var r=this,a=function t(e,a){var s;if("object"!==o(a)){for(var u=arguments.length,c=new Array(u>2?u-2:0),l=2;l1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;var o=this.languages[0],r=!!this.options&&this.options.fallbackLng,i=this.languages[this.languages.length-1];if("cimode"===o.toLowerCase())return!0;var a=function(t,n){var o=e.services.backendConnector.state["".concat(t,"|").concat(n)];return-1===o||2===o};if(n.precheck){var s=n.precheck(this,a);if(void 0!==s)return s}return!!this.hasResourceBundle(o,t)||!this.services.backendConnector.backend||!(!a(o,t)||r&&!a(i,t))}},{key:"loadNamespaces",value:function(t,e){var n=this,o=v();return this.options.ns?("string"==typeof t&&(t=[t]),t.forEach((function(t){n.options.ns.indexOf(t)<0&&n.options.ns.push(t)})),this.loadResources((function(t){o.resolve(),e&&e(t)})),o):(e&&e(),Promise.resolve())}},{key:"loadLanguages",value:function(t,e){var n=v();"string"==typeof t&&(t=[t]);var o=this.options.preload||[],r=t.filter((function(t){return o.indexOf(t)<0}));return r.length?(this.options.preload=o.concat(r),this.loadResources((function(t){n.resolve(),e&&e(t)})),n):(e&&e(),Promise.resolve())}},{key:"dir",value:function(t){return t||(t=this.languages&&this.languages.length>0?this.languages[0]:this.language),t?["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam"].indexOf(this.services.languageUtils.getLanguagePartFromCode(t))>=0?"rtl":"ltr":"rtl"}},{key:"createInstance",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return new e(t,n)}},{key:"cloneInstance",value:function(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:H,r=i({},this.options,n,{isClone:!0}),a=new e(r),s=["store","services","language"];return s.forEach((function(e){a[e]=t[e]})),a.services=i({},this.services),a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a.translator=new B(a.services,a.options),a.translator.on("*",(function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),o=1;o1&&(e%2==1?"square":"straight"),c.connectNext=e1&&"square",c.connectNext=e1)throw Error("Multiple possible roots were found. Please use `config.selector` to choose a specific root.");const n=e[0];if(!n.classList.contains("brackets-viewer"))throw Error("The selected root must have a `.brackets-viewer` class.");return n},e.completeWithBlankMatches=function(t,e,n){if(!n)return{matches:e,fromToornament:!1};let o=[];return"single-bracket"!==t&&"winner-bracket"!==t||(o=n.map((t=>{var e,n;return[(null===(e=t.opponent1)||void 0===e?void 0:e.position)||null,(null===(n=t.opponent2)||void 0===n?void 0:n.position)||null]})).flat()),"loser-bracket"===t&&(o=n.map((t=>{var e;return(null===(e=t.opponent2)||void 0===e?void 0:e.position)||null}))),0===o.filter((t=>null!==t)).length?{matches:e,fromToornament:!1}:{matches:o.map((t=>t&&e.find((e=>e.number===t))||null)),fromToornament:!0}},e.getOriginAbbreviation=function(t,e,n,r){return n=n||-1,e&&"loser-bracket"===t&&1===n||"single-bracket"===t||"winner-bracket"===t&&1===n?(0,o.t)("abbreviations.seed"):"loser-bracket"===t&&n%2==0&&"opponent1"===r?(0,o.t)("abbreviations.position"):null},e.isMajorRound=function(t){return 1===t||t%2==0},e.rankingHeader=function(t){return(0,o.t)(`ranking.${t}`,{returnObjects:!0})},e.getRanking=function(t,e){e=e||(t=>3*t.wins+1*t.draws+0*t.losses);const n={};for(const o of t)r(n,e,o.opponent1,o.opponent2),r(n,e,o.opponent2,o.opponent1);return function(t){const e=Object.values(t).sort(((t,e)=>t.points!==e.points?e.points-t.points:e.played-t.played)),n={value:0,lastPoints:-1};for(const t of e)t.rank=n.lastPoints!==t.points?++n.value:n.value,n.lastPoints=t.points;return e}(n)}},491:function(t,e,n){var o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.getLoserBracketRoundName=e.getWinnerBracketRoundName=e.getRoundName=e.getBracketName=e.getGroupName=e.getMatchStatus=e.getFinalMatchLabel=e.getMatchLabel=e.getFinalOriginHint=e.getOriginHint=e.t=e.addLocale=e.locales=void 0;const r=o(n(261)),i=o(n(71)),a=n(21),s=n(886),u=o(n(583)),c=o(n(159));function l(t,e){return r.default.t(t,e)}e.locales={en:u.default,fr:c.default},r.default.use(i.default).init({fallbackLng:"en",debug:!1,resources:{en:{translation:e.locales.en},fr:{translation:e.locales.fr}}}),e.addLocale=function(t,e){r.default.addResourceBundle(t,"translation",e,!0,!0),r.default.changeLanguage()},e.t=l,e.getOriginHint=function(t,e,n,o){if(1===t){if("single-bracket"===o)return t=>l("origin-hint.seed",{position:t});if("winner-bracket"===o)return t=>l("origin-hint.seed",{position:t});if("loser-bracket"===o&&n)return t=>l("origin-hint.seed",{position:t})}if((0,s.isMajorRound)(t)&&"loser-bracket"===o){if(t===e-2)return t=>l("origin-hint.winner-bracket-semi-final",{position:t});if(t===e)return()=>l("origin-hint.winner-bracket-final");const o=Math.ceil((t+1)/2);return n?t=>l("origin-hint.winner-bracket",{round:o-1,position:t}):t=>l("origin-hint.winner-bracket",{round:o,position:t})}},e.getFinalOriginHint=function(t,e){return"consolation_final"===t?t=>l("origin-hint.consolation-final",{position:t}):1===e?()=>l("origin-hint.grand-final"):void 0},e.getMatchLabel=function(t,e,n,o){const r=l("winner-bracket"===o?"match-label.winner-bracket":"loser-bracket"===o?"match-label.loser-bracket":"match-label.standard-bracket"),i=e===n-1,a=e===n;if("single-bracket"===o){if(i)return l("match-label.standard-bracket-semi-final",{matchNumber:t});if(a)return l("match-label.standard-bracket-final")}return i?l("match-label.double-elimination-semi-final",{matchPrefix:r,matchNumber:t}):a?l("match-label.double-elimination-final",{matchPrefix:r}):l("match-label.double-elimination",{matchPrefix:r,roundNumber:e,matchNumber:t})},e.getFinalMatchLabel=function(t,e,n){return"consolation_final"===t?l("match-label.consolation-final"):1===n?l("match-label.grand-final-single"):l("match-label.grand-final",{roundNumber:e})},e.getMatchStatus=function(t){switch(t){case a.Status.Locked:return l("match-status.locked");case a.Status.Waiting:return l("match-status.waiting");case a.Status.Ready:return l("match-status.ready");case a.Status.Running:return l("match-status.running");case a.Status.Completed:return l("match-status.completed");case a.Status.Archived:return l("match-status.archived");default:return"Unknown status"}},e.getGroupName=function(t){return l("common.group-name",{groupNumber:t})},e.getBracketName=function(t,e){switch(e){case"winner-bracket":case"loser-bracket":return l(`common.group-name-${e}`,{stage:t});default:return}},e.getRoundName=function(t,e){return t===e?l("common.round-name-final"):l("common.round-name",{roundNumber:t})},e.getWinnerBracketRoundName=function(t,e){return t===e?l("common.round-name-winner-bracket-final"):l("common.round-name-winner-bracket",{roundNumber:t})},e.getLoserBracketRoundName=function(t,e){return t===e?l("common.round-name-loser-bracket-final"):l("common.round-name-loser-bracket",{roundNumber:t})}},825:function(t,e,n){var o=this&&this.__createBinding||(Object.create?function(t,e,n,o){void 0===o&&(o=n),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,o){void 0===o&&(o=n),t[o]=e[n]}),r=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&o(e,t,n);return r(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.BracketsViewer=void 0,n(16);const a=n(21),s=n(886),u=i(n(335)),c=i(n(491));e.BracketsViewer=class{constructor(){this.participantRefs={},this.participants=[],this.participantImages=[],this.skipFirstRound=!1,this.alwaysConnectFirstRound=!1,this._onMatchClick=t=>{}}set onMatchClicked(t){this._onMatchClick=t}async render(t,e){const n=document.createDocumentFragment();this.config={participantOriginPlacement:(null==e?void 0:e.participantOriginPlacement)||"before",separatedChildCountLabel:void 0!==(null==e?void 0:e.separatedChildCountLabel)&&e.separatedChildCountLabel,showSlotsOrigin:void 0===(null==e?void 0:e.showSlotsOrigin)||e.showSlotsOrigin,showLowerBracketSlotsOrigin:void 0===(null==e?void 0:e.showLowerBracketSlotsOrigin)||e.showLowerBracketSlotsOrigin,highlightParticipantOnHover:void 0===(null==e?void 0:e.highlightParticipantOnHover)||e.highlightParticipantOnHover},this.config.onMatchClick&&(this._onMatchClick=this.config.onMatchClick),this.participants=t.participants,t.participants.forEach((t=>this.participantRefs[t.id]=[])),t.stages.forEach((e=>this.renderStage(n,{...t,stages:[e],matches:t.matches.filter((t=>t.stage_id===e.id))}))),(0,s.findRoot)(null==e?void 0:e.selector).append(n)}updateMatch(t){var e,n,o,r,i,a;const s=document.querySelector(`[data-match-id='${t.id}']`);if(!s)throw Error("Match not found.");s.setAttribute("data-match-status",t.status.toString());const u=s.querySelector(".participant:nth-of-type(1) .result");u&&(null===(e=t.opponent1)||void 0===e?void 0:e.score)&&(u.innerHTML=null===(o=null===(n=t.opponent1)||void 0===n?void 0:n.score)||void 0===o?void 0:o.toString());const c=s.querySelector(".participant:nth-of-type(2) .result");c&&(null===(r=t.opponent2)||void 0===r?void 0:r.score)&&(c.innerHTML=null===(a=null===(i=t.opponent2)||void 0===i?void 0:i.score)||void 0===a?void 0:a.toString())}setParticipantImages(t){this.participantImages=t}addLocale(t,e){c.addLocale(t,e)}renderStage(t,e){const n=e.stages[0],o=(0,s.splitBy)(e.matches,"group_id");switch(this.stage=n,this.skipFirstRound=n.settings.skipFirstRound||!1,n.type){case"round_robin":this.renderRoundRobin(t,n,o);break;case"single_elimination":case"double_elimination":this.renderElimination(t,n,o);break;default:throw Error(`Unknown bracket type: ${n.type}`)}}renderRoundRobin(t,e,n){const o=u.createRoundRobinContainer(e.id);o.append(u.createTitle(e.name));let r=1;for(const t of n){const e=t[0].group_id,n=u.createGroupContainer(e,c.getGroupName(r++)),i=(0,s.splitBy)(t,"round_id");let a=1;for(const t of i){const e=t[0].round_id,o=u.createRoundContainer(e,c.getRoundName(a++,0));for(const e of t)o.append(this.createMatch(e));n.append(o)}n.append(this.createRanking(t)),o.append(n)}t.append(o)}renderElimination(t,e,n){const o=u.createEliminationContainer(e.id);o.append(u.createTitle(e.name)),"single_elimination"===e.type?this.renderSingleElimination(o,n):this.renderDoubleElimination(o,n),t.append(o)}renderSingleElimination(t,e){const n=void 0!==e[1];this.renderBracket(t,(0,s.splitBy)(e[0],"round_id"),c.getRoundName,"single-bracket"),n&&this.renderFinal(t,"consolation_final",e[1])}renderDoubleElimination(t,e){const n=void 0!==e[1],o=void 0!==e[2];this.renderBracket(t,(0,s.splitBy)(e[0],"round_id"),c.getWinnerBracketRoundName,"winner-bracket",o),n&&this.renderBracket(t,(0,s.splitBy)(e[1],"round_id"),c.getLoserBracketRoundName,"loser-bracket"),o&&this.renderFinal(t,"grand_final",e[2])}renderBracket(t,e,n,o,r){const i=e[0][0].group_id,a=e.length,l=u.createBracketContainer(i,c.getBracketName(this.stage,o)),d=u.createRoundsContainer(),{matches:p,fromToornament:h}=(0,s.completeWithBlankMatches)(o,e[0],e[1]);this.alwaysConnectFirstRound=!h;for(let t=0;tt.id===i));if(void 0!==t){const n=u.createCell(t.name);this.setupMouseHover(t.id,n),e.append(n);continue}}!n||"rank"!==r&&"points"!==r?e.append(u.createCell(i)):e.append(u.createCell("-"))}return e}createBracketMatch(t,e,n,o,r){const i=u.getBracketConnection(this.alwaysConnectFirstRound,t,e,n,o,r),a=c.getMatchLabel(n.number,t,e,o),s=c.getOriginHint(t,e,this.skipFirstRound,o);return this.createMatch(n,o,i,a,s,t)}createFinalMatch(t,e,n,o){const r=n-1,i=u.getFinalConnection(t,n,e.length),a=c.getFinalMatchLabel(t,n,o),s=c.getFinalOriginHint(t,n);return this.createMatch(e[r],"final-group",i,a,s)}skipBracketMatch(){const t=u.createMatchContainer(),e=u.createOpponentsContainer(),n=this.createParticipant(null),o=this.createParticipant(null);return e.append(n,o),t.append(e),t.style.visibility="hidden",t}createMatch(t,e,n,o,r,i){const s=u.createMatchContainer(t.id,t.status),c=u.createOpponentsContainer((()=>this._onMatchClick(t)));t.status>=a.Status.Completed&&(r=void 0);const l=this.createParticipant(t.opponent1,"opponent1",r,e,i),d=this.createParticipant(t.opponent2,"opponent2",r,e,i);return this.renderMatchLabel(c,t,o),c.append(l,d),s.append(c),n?(u.setupConnection(c,s,n),s):s}createParticipant(t,e,n,o,r){const i={participant:u.createParticipantContainer(t&&t.id),name:u.createNameContainer(),result:u.createResultContainer()};return null==t?u.setupBye(i.name):this.renderParticipant(i,t,e,n,o,r),i.participant.append(i.name,i.result),t&&null!==t.id&&this.setupMouseHover(t.id,i.participant),i.participant}renderParticipant(t,e,n,o,r,i){const a=this.participants.find((t=>t.id===e.id));a?(t.name.innerText=a.name,t.participant.setAttribute("title",a.name),this.renderParticipantImage(t.name,a.id),this.renderParticipantOrigin(t.name,e,n,r,i)):this.renderHint(t.name,e,o,r),t.result.innerText=`${void 0===e.score?"-":e.score}`,u.setupWin(t.participant,t.result,e),u.setupLoss(t.participant,t.result,e)}renderParticipantImage(t,e){const n=this.participantImages.find((t=>t.participantId===e));n&&u.addParticipantImage(t,n.imageUrl)}renderMatchLabel(t,e,n){const o=`Bo${e.child_count}`;if(n=n||"",this.config.separatedChildCountLabel)return t.append(u.createMatchLabel(n,c.getMatchStatus(e.status))),void(e.child_count>0&&t.append(u.createChildCountLabel(c.t("common.best-of-x",{x:e.child_count}))));if(e.child_count>0){const r=n?`${n}, ${o}`:o;t.append(u.createMatchLabel(r,c.getMatchStatus(e.status)))}}renderHint(t,e,n,o){void 0!==n&&void 0!==e.position&&this.config.showSlotsOrigin&&(this.config.showLowerBracketSlotsOrigin||"loser-bracket"!==o)&&u.setupHint(t,n(e.position))}renderParticipantOrigin(t,e,n,o,r){if(void 0===e.position||void 0===o)return;if(!this.config.participantOriginPlacement||"none"===this.config.participantOriginPlacement)return;if(!this.config.showSlotsOrigin)return;if(!this.config.showLowerBracketSlotsOrigin&&"loser-bracket"===o)return;const i=(0,s.getOriginAbbreviation)(o,this.skipFirstRound,r,n);if(!i)return;const a=i+e.position;u.addParticipantOrigin(t,a,this.config.participantOriginPlacement)}setupMouseHover(t,e){if(!this.config.highlightParticipantOnHover)return;const n=this.participantRefs[t];if(!n)throw Error(`The participant (id: ${t}) does not exist in the participants table.`);n.push(e),e.addEventListener("mouseover",(()=>{n.forEach((t=>t.classList.add("hover")))})),e.addEventListener("mouseleave",(()=>{n.forEach((t=>t.classList.remove("hover")))}))}}},945:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.BaseGetter=void 0;const o=n(487);e.BaseGetter=class{constructor(t){this.storage=t}async getOrderedRounds(t){if(!(null==t?void 0:t.settings.size))throw Error("The stage has no size.");return"single_elimination"===t.type?this.getOrderedRoundsSingleElimination(t.id):this.getOrderedRoundsDoubleElimination(t.id)}async getOrderedRoundsSingleElimination(t){return[await this.getUpperBracketFirstRound(t)]}async getOrderedRoundsDoubleElimination(t){const e=await this.storage.select("round",{stage_id:t});if(!e)throw Error("Error getting rounds.");const n=await this.getLoserBracket(t);if(!n)throw Error("Loser bracket not found.");const r=e[0],i=e.filter((t=>t.group_id===n.id));return[r,...i.filter((t=>o.isOrderingSupportedLoserBracket(t.number,i.length)))]}async getRoundPositionalInfo(t){const e=await this.storage.select("round",t);if(!e)throw Error("Round not found.");const n=await this.storage.select("round",{group_id:e.group_id});if(!n)throw Error("Error getting rounds.");return{roundNumber:e.number,roundCount:n.length}}async getPreviousMatches(t,e,n,o){return"loser_bracket"===e?this.getPreviousMatchesLB(t,n,o):"final_group"===e?this.getPreviousMatchesFinal(t,o):1===o?[]:this.getMatchesBeforeMajorRound(t,o)}async getPreviousMatchesFinal(t,e){if(e>1)return[await this.findMatch(t.group_id,e-1,1)];const n=await this.getUpperBracket(t.stage_id),o=await this.getLastRound(n.id),r=await this.storage.selectFirst("match",{round_id:o.id,number:1});if(null===r)throw Error("Match not found.");return[r]}async getPreviousMatchesLB(t,e,n){if(e.settings.skipFirstRound&&1===n)return[];if(o.hasBye(t))return[];const r=await this.getUpperBracket(t.stage_id),i=Math.ceil((n+1)/2),a=e.settings.skipFirstRound?i-1:i;return 1===n?this.getMatchesBeforeFirstRoundLB(t,r.id,a):n%2==0?this.getMatchesBeforeMinorRoundLB(t,r.id,n,a):this.getMatchesBeforeMajorRound(t,n)}async getMatchesBeforeMajorRound(t,e){return[await this.findMatch(t.group_id,e-1,2*t.number-1),await this.findMatch(t.group_id,e-1,2*t.number)]}async getMatchesBeforeFirstRoundLB(t,e,n){return[await this.findMatch(e,n,o.getOriginPosition(t,"opponent1")),await this.findMatch(e,n,o.getOriginPosition(t,"opponent2"))]}async getMatchesBeforeMinorRoundLB(t,e,n,r){const i=o.getOriginPosition(t,"opponent1");return[await this.findMatch(e,r,i),await this.findMatch(t.group_id,n-1,t.number)]}async getNextMatches(t,e,n,o,r){switch(e){case"single_bracket":return this.getNextMatchesUpperBracket(t,n.type,o,r);case"winner_bracket":return this.getNextMatchesWB(t,n,o,r);case"loser_bracket":return this.getNextMatchesLB(t,n.type,o,r);case"final_group":return this.getNextMatchesFinal(t,o,r);default:throw Error("Unknown bracket kind.")}}async getNextMatchesWB(t,e,n,r){const i=await this.getLoserBracket(t.stage_id);if(null===i)return[];const a=e.settings.skipFirstRound?n+1:n,s=a>1?2*(a-1):1,u=a>1?t.number:o.getDiagonalMatchNumber(t.number),c=e.settings.size,l=o.getLoserOrdering(e.settings.seedOrdering,s),d=o.findLoserMatchNumber(c,s,u,l);return[...await this.getNextMatchesUpperBracket(t,e.type,n,r),await this.findMatch(i.id,s,d)]}async getNextMatchesUpperBracket(t,e,n,o){return"single_elimination"===e?this.getNextMatchesUpperBracketSingleElimination(t,e,n,o):"double_elimination"===e&&n===o?[await this.getFirstMatchFinal(t,e)]:[await this.getDiagonalMatch(t.group_id,n,t.number)]}async getNextMatchesUpperBracketSingleElimination(t,e,n,o){if(n===o-1){const o=await this.getFirstMatchFinal(t,e);return[await this.getDiagonalMatch(t.group_id,n,t.number),...o?[o]:[]]}return n===o?[]:[await this.getDiagonalMatch(t.group_id,n,t.number)]}async getNextMatchesLB(t,e,n,o){if(n===o){const n=await this.getFirstMatchFinal(t,e);return n?[n]:[]}return n%2==1?this.getMatchAfterMajorRoundLB(t,n):this.getMatchAfterMinorRoundLB(t,n)}async getFirstMatchFinal(t,e){const n=await this.getFinalGroupId(t.stage_id,e);return null===n?null:this.findMatch(n,1,1)}async getNextMatchesFinal(t,e,n){return e===n?[]:[await this.findMatch(t.group_id,e+1,1)]}async getMatchAfterMajorRoundLB(t,e){return[await this.getParallelMatch(t.group_id,e,t.number)]}async getMatchAfterMinorRoundLB(t,e){return[await this.getDiagonalMatch(t.group_id,e,t.number)]}static getSeedingOrdering(t,e){return"round_robin"===t?e.getRoundRobinOrdering():e.getStandardBracketFirstRoundOrdering()}async getSeedingMatches(t,e){if("round_robin"===e)return this.storage.select("match",{stage_id:t});const n=await this.getUpperBracketFirstRound(t);return this.storage.select("match",{round_id:n.id})}async getUpperBracketFirstRound(t){const e=await this.storage.selectFirst("round",{stage_id:t,number:1});if(!e)throw Error("Round not found.");return e}async getLastRound(t){const e=await this.storage.selectLast("round",{group_id:t});if(!e)throw Error("Error getting rounds.");return e}async getFinalGroupId(t,e){const n="single_elimination"===e?2:3,o=await this.storage.selectFirst("group",{stage_id:t,number:n});return o?o.id:null}async getUpperBracket(t){const e=await this.storage.selectFirst("group",{stage_id:t,number:1});if(!e)throw Error("Winner bracket not found.");return e}async getLoserBracket(t){return this.storage.selectFirst("group",{stage_id:t,number:2})}async getDiagonalMatch(t,e,n){return this.findMatch(t,e+1,o.getDiagonalMatchNumber(n))}async getParallelMatch(t,e,n){return this.findMatch(t,e+1,n)}async findMatch(t,e,n){const o=await this.storage.selectFirst("round",{group_id:t,number:e});if(!o)throw Error("Round not found.");const r=await this.storage.selectFirst("match",{round_id:o.id,number:n});if(!r)throw Error("Match not found.");return r}async findMatchGame(t){if(void 0!==t.id){const e=await this.storage.select("match_game",t.id);if(!e)throw Error("Match game not found.");return e}if(void 0!==t.parent_id&&t.number){const e=await this.storage.selectFirst("match_game",{parent_id:t.parent_id,number:t.number});if(!e)throw Error("Match game not found.");return e}throw Error("No match game id nor parent id and number given.")}}},517:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.BaseUpdater=void 0;const o=n(21),r=n(644),i=n(765),a=n(945),s=n(487);class u extends a.BaseGetter{async updateSeeding(t,e){const n=await this.storage.select("stage",t);if(!n)throw Error("Stage not found.");if(e&&e.length!==n.settings.size)throw Error("The size of the seeding is incorrect.");const o=new i.Create(this.storage,{name:n.name,tournamentId:n.tournament_id,type:n.type,settings:n.settings,seeding:e||void 0});o.setExisting(t);const s=a.BaseGetter.getSeedingOrdering(n.type,o),c=await o.getSlots(),l=await this.getSeedingMatches(n.id,n.type);if(!l)throw Error("Error getting matches associated to the seeding.");const d=r.ordering[s](c);await u.assertCanUpdateSeeding(l,d),await o.run()}async updateParentMatch(t){const e=await this.storage.select("match",t);if(!e)throw Error("Parent not found.");const n=await this.storage.select("match_game",{parent_id:t});if(!n)throw Error("No match games.");const o=s.getChildGamesResults(n),r=s.getParentMatchResults(e,o),i=await this.storage.select("stage",e.stage_id);if(!i)throw Error("Stage not found.");const a=s.isRoundRobin(i);s.setParentMatchCompleted(r,e.child_count,a),await this.updateMatch(e,r,!0)}static async assertCanUpdateSeeding(t,e){var n,o;let r=0;for(const i of t){const t=e[r++],a=e[r++];if(s.isMatchParticipantLocked(i)&&((null===(n=i.opponent1)||void 0===n?void 0:n.id)!==(null==t?void 0:t.id)||(null===(o=i.opponent2)||void 0===o?void 0:o.id)!==(null==a?void 0:a.id)))throw Error("A match is locked.")}}async updateRelatedMatches(t,e,n){const{roundNumber:o,roundCount:r}=await this.getRoundPositionalInfo(t.round_id),i=await this.storage.select("stage",t.stage_id);if(!i)throw Error("Stage not found.");const a=await this.storage.select("group",t.group_id);if(!a)throw Error("Group not found.");const u=s.getMatchLocation(i.type,a.number);e&&await this.updatePrevious(t,u,i,o),n&&await this.updateNext(t,u,i,o,r)}async updateMatch(t,e,n){if(!n&&s.isMatchUpdateLocked(t))throw Error("The match is locked.");const{statusChanged:o,resultChanged:r}=s.setMatchResults(t,e);if(await this.applyMatchUpdate(t),!o&&!r)return;const i=await this.storage.select("stage",t.stage_id);if(!i)throw Error("Stage not found.");s.isRoundRobin(i)||await this.updateRelatedMatches(t,o,r)}async applyMatchUpdate(t){if(!await this.storage.update("match",t.id,t))throw Error("Could not update the match.");if(0===t.child_count)return;const e={opponent1:s.toResult(t.opponent1),opponent2:s.toResult(t.opponent2)};if((t.status<=o.Status.Ready||t.status===o.Status.Archived)&&(e.status=t.status),!await this.storage.update("match_game",{parent_id:t.id},e))throw Error("Could not update the match game.")}async updatePrevious(t,e,n,r){const i=await this.getPreviousMatches(t,e,n,r);0!==i.length&&(t.status>=o.Status.Running?await this.archiveMatches(i):await this.resetMatchesStatus(i))}async archiveMatches(t){for(const e of t)e.status=o.Status.Archived,await this.applyMatchUpdate(e)}async resetMatchesStatus(t){for(const e of t)e.status=s.getMatchStatus(e),await this.applyMatchUpdate(e)}async updateNext(t,e,n,o,r){const i=await this.getNextMatches(t,e,n,o,r);if(0===i.length)return;const a=s.getMatchResult(t),u=n.settings.skipFirstRound&&"winner_bracket"===e?o+1:o;a?await this.applyToNextMatches(s.setNextOpponent,t,e,u,r,i,a):await this.applyToNextMatches(s.resetNextOpponent,t,e,u,r,i)}async applyToNextMatches(t,e,n,o,r,i,a){if("final_group"===n){if(!i[0])throw Error("First next match is null.");return t(i[0],"opponent1",e,"opponent1"),t(i[0],"opponent2",e,"opponent2"),void await this.applyMatchUpdate(i[0])}const u=s.getNextSide(e.number,o,r,n);if(i[0]&&(t(i[0],u,e,a),await this.propagateByeWinners(i[0])),2===i.length){if(!i[1])throw Error("Second next match is null.");if("single_bracket"===n)t(i[1],u,e,a&&s.getOtherSide(a)),await this.applyMatchUpdate(i[1]);else{const n=s.getNextSideLoserBracket(e.number,i[1],o);t(i[1],n,e,a&&s.getOtherSide(a)),await this.propagateByeWinners(i[1])}}}async propagateByeWinners(t){s.setMatchResults(t,t),await this.applyMatchUpdate(t),s.hasBye(t)&&await this.updateRelatedMatches(t,!0,!0)}}e.BaseUpdater=u},765:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Create=e.create=void 0;const o=n(644),r=n(487);e.create=async function(t){const e=new i(this.storage,t);await e.run()};class i{constructor(t,e){if(this.storage=t,this.stage=e,this.stage.settings=this.stage.settings||{},this.seedOrdering=this.stage.settings.seedOrdering||[],this.updateMode=!1,!this.stage.name)throw Error("You must provide a name for the stage.");if(!Number.isInteger(this.stage.tournamentId))throw Error("You must provide a tournament id for the stage.");"round_robin"===e.type&&(this.stage.settings.roundRobinMode=this.stage.settings.roundRobinMode||"simple"),"single_elimination"===e.type&&(this.stage.settings.consolationFinal=this.stage.settings.consolationFinal||!1),"double_elimination"===e.type&&(this.stage.settings.grandFinal=this.stage.settings.grandFinal||"none"),this.stage.settings.matchesChildCount=this.stage.settings.matchesChildCount||0}async run(){let t=-1;switch(this.stage.type){case"round_robin":t=await this.roundRobin();break;case"single_elimination":t=await this.singleElimination();break;case"double_elimination":t=await this.doubleElimination();break;default:throw Error("Unknown stage type.")}if(-1===t)throw Error("Something went wrong when creating the stage.");await this.ensureSeedOrdering(t)}setExisting(t){this.updateMode=!0,this.currentStageId=t}async roundRobin(){const t=await this.getRoundRobinGroups(),e=await this.createStage();for(let n=0;n=0;e--){const n=Math.pow(2,e);a=this.getCurrentDuels(a,n),u.push(a.map(r.byeLoser)),await this.createRound(t,i,s++,n,a)}return{losers:u,winner:r.byeWinner(a[0])}}async createLowerBracket(t,e,n){var i;const a=null===(i=this.stage.settings)||void 0===i?void 0:i.size,s=r.getRoundPairCount(a);let u=0;const c=this.getMajorOrdering(a),l=o.ordering[c](n[u++]),d=await this.insertGroup({stage_id:t,number:e});if(-1===d)throw Error("Could not insert the group.");let p=r.makePairs(l),h=1;for(let e=0;el&&(l=t)}}const d=await this.insertMatch({number:o,stage_id:t,group_id:e,round_id:n,child_count:a,status:l,opponent1:s,opponent2:u},c);if(-1===d)throw Error("Could not insert the match.");for(let e=0;e({id:null,position:e+1})));if(!this.stage.seeding)throw Error("Either size or seeding must be given.");return this.stage.settings={...this.stage.settings,size:o},r.ensureNoDuplicates(this.stage.seeding),this.stage.seeding=r.fixSeeding(this.stage.seeding,o),"round_robin"!==this.stage.type&&this.stage.settings.balanceByes&&(this.stage.seeding=r.balanceByes(this.stage.seeding,this.stage.settings.size)),r.isSeedingWithIds(this.stage.seeding)?this.getSlotsUsingIds(this.stage.seeding,t):this.getSlotsUsingNames(this.stage.seeding,t)}async getSlotsUsingNames(t,e){const n=r.extractParticipantsFromSeeding(this.stage.tournamentId,t);if(!await this.registerParticipants(n))throw Error("Error registering the participants.");const o=await this.storage.select("participant",{tournament_id:this.stage.tournamentId});if(!o)throw Error("Error getting registered participant.");return r.mapParticipantsNamesToDatabase(t,o,e)}async getSlotsUsingIds(t,e){const n=await this.storage.select("participant",{tournament_id:this.stage.tournamentId});if(!n)throw Error("No available participants.");return r.mapParticipantsIdsToDatabase(t,n,e)}async getStageNumber(){const t=await this.storage.select("stage",{tournament_id:this.stage.tournamentId}),e=null==t?void 0:t.map((t=>t.number));if(void 0!==this.stage.number){if(null==e?void 0:e.includes(this.stage.number))throw Error("The given stage number already exists.");return this.stage.number}return(null==e?void 0:e.length)?Math.max(...e)+1:1}getMatchesChildCount(){var t;return(null===(t=this.stage.settings)||void 0===t?void 0:t.matchesChildCount)?this.stage.settings.matchesChildCount:0}getOrdering(t,e,n){var o;if(!(null===(o=this.stage.settings)||void 0===o?void 0:o.seedOrdering))return this.seedOrdering.push(n),n;const r=this.stage.settings.seedOrdering[t];if(!r)return this.seedOrdering.push(n),n;if("elimination"===e&&r.match(/^groups\./))throw Error("You must specify a seed ordering method without a 'groups' prefix");if("groups"===e&&"natural"!==r&&!r.match(/^groups\./))throw Error("You must specify a seed ordering method with a 'groups' prefix");return r}async getRoundRobinGroups(){var t,e,n,i,a;if(void 0===(null===(t=this.stage.settings)||void 0===t?void 0:t.groupCount)||!Number.isInteger(this.stage.settings.groupCount))throw Error("You must specify a group count for round-robin stages.");if(this.stage.settings.groupCount<=0)throw Error("You must provide a strictly positive group count.");if(null===(e=this.stage.settings)||void 0===e?void 0:e.manualOrdering){if((null===(n=this.stage.settings)||void 0===n?void 0:n.manualOrdering.length)!==(null===(i=this.stage.settings)||void 0===i?void 0:i.groupCount))throw Error("Group count in the manual ordering does not correspond to the given group count.");const t=null===(a=this.stage.settings)||void 0===a?void 0:a.manualOrdering.flat(),e=await this.getSlots(t);return r.makeGroups(e,this.stage.settings.groupCount)}if(Array.isArray(this.stage.settings.seedOrdering)&&1!==this.stage.settings.seedOrdering.length)throw Error("You must specify one seed ordering method.");const s=this.getRoundRobinOrdering(),u=await this.getSlots(),c=o.ordering[s](u,this.stage.settings.groupCount);return r.makeGroups(c,this.stage.settings.groupCount)}getRoundRobinOrdering(){return this.getOrdering(0,"groups","groups.effort_balanced")}getStandardBracketFirstRoundOrdering(){return this.getOrdering(0,"elimination","inner_outer")}getMajorOrdering(t){return this.getOrdering(1,"elimination",o.defaultMinorOrdering[t][0])}getMinorOrdering(t,e,n){if(e!==n-1)return this.getOrdering(2+e,"elimination",o.defaultMinorOrdering[t][1+e])}async insertStage(t){let e=null;return this.updateMode&&(e=await this.storage.select("stage",this.currentStageId)),e?e.id:this.storage.insert("stage",t)}async insertGroup(t){let e=null;return this.updateMode&&(e=await this.storage.selectFirst("group",{stage_id:t.stage_id,number:t.number})),e?e.id:this.storage.insert("group",t)}async insertRound(t){let e=null;return this.updateMode&&(e=await this.storage.selectFirst("round",{group_id:t.group_id,number:t.number})),e?e.id:this.storage.insert("round",t)}async insertMatch(t,e){if(!e)return this.storage.insert("match",t);const n=r.getUpdatedMatchResults(t,e);if(!await this.storage.update("match",e.id,n))throw Error("Could not update the match.");return e.id}async insertMatchGame(t){let e=null;if(this.updateMode&&(e=await this.storage.selectFirst("match_game",{parent_id:t.parent_id,number:t.number})),!e)return this.storage.insert("match_game",t);const n=r.getUpdatedMatchResults(t,e);if(!await this.storage.update("match_game",e.id,n))throw Error("Could not update the match game.");return e.id}async registerParticipants(t){const e=await this.storage.select("participant",{tournament_id:this.stage.tournamentId});if(!e||0===e.length)return this.storage.insert("participant",t);for(const n of t)if(!e.some((t=>t.name===n.name))&&-1===await this.storage.insert("participant",n))return!1;return!0}async createStage(){const t=await this.getStageNumber(),e=await this.insertStage({tournament_id:this.stage.tournamentId,name:this.stage.name,type:this.stage.type,number:t,settings:this.stage.settings||{}});if(-1===e)throw Error("Could not insert the stage.");return e}async createConsolationFinal(t,e){var n;if(!(null===(n=this.stage.settings)||void 0===n?void 0:n.consolationFinal))return;const o=e[e.length-2];await this.createUniqueMatchBracket(t,2,[o])}async createGrandFinal(t,e,n){var o;const r=null===(o=this.stage.settings)||void 0===o?void 0:o.grandFinal;if("none"===r)return;const i=[[e,n]];"double"===r&&i.push([{id:null},{id:null}]),await this.createUniqueMatchBracket(t,3,i)}async ensureSeedOrdering(t){var e,n;if((null===(n=null===(e=this.stage.settings)||void 0===e?void 0:e.seedOrdering)||void 0===n?void 0:n.length)===this.seedOrdering.length)return;const o=await this.storage.select("stage",t);if(!o)throw Error("Stage not found.");if(o.settings={...o.settings,seedOrdering:this.seedOrdering},!await this.storage.update("stage",t,o))throw Error("Could not update the stage.")}}e.Create=i},378:function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.Delete=void 0,e.Delete=class{constructor(t){this.storage=t}async stage(t){if(!await this.storage.delete("match_game",{stage_id:t}))throw Error("Could not delete match games.");if(!await this.storage.delete("match",{stage_id:t}))throw Error("Could not delete matches.");if(!await this.storage.delete("round",{stage_id:t}))throw Error("Could not delete rounds.");if(!await this.storage.delete("group",{stage_id:t}))throw Error("Could not delete groups.");if(!await this.storage.delete("stage",{id:t}))throw Error("Could not delete stages.")}}},63:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Find=void 0;const o=n(945),r=n(487);class i extends o.BaseGetter{async upperBracket(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");switch(e.type){case"round_robin":throw Error("Round-robin stages do not have an upper bracket.");case"single_elimination":case"double_elimination":return this.getUpperBracket(t);default:throw Error("Unknown stage type.")}}async loserBracket(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");switch(e.type){case"round_robin":throw Error("Round-robin stages do not have a loser bracket.");case"single_elimination":throw Error("Single elimination stages do not have a loser bracket.");case"double_elimination":const e=await this.getLoserBracket(t);if(!e)throw Error("Loser bracket not found.");return e;default:throw Error("Unknown stage type.")}}async previousMatches(t){const e=await this.storage.select("match",t);if(!e)throw Error("Match not found.");const n=await this.storage.select("stage",e.stage_id);if(!n)throw Error("Stage not found.");const o=await this.storage.select("group",e.group_id);if(!o)throw Error("Group not found.");const i=await this.storage.select("round",e.round_id);if(!i)throw Error("Round not found.");const a=r.getMatchLocation(n.type,o.number);return this.getPreviousMatches(e,a,n,i.number)}async nextMatches(t){const e=await this.storage.select("match",t);if(!e)throw Error("Match not found.");const n=await this.storage.select("stage",e.stage_id);if(!n)throw Error("Stage not found.");const o=await this.storage.select("group",e.group_id);if(!o)throw Error("Group not found.");const{roundNumber:i,roundCount:a}=await this.getRoundPositionalInfo(e.round_id),s=r.getMatchLocation(n.type,o.number),u=await this.getNextMatches(e,s,n,i,a);return r.getNonNull(u)}async match(t,e,n){return this.findMatch(t,e,n)}async matchGame(t){return this.findMatchGame(t)}}e.Find=i},576:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Get=void 0;const o=n(945),r=n(487);class i extends o.BaseGetter{async stageData(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");const n=await this.storage.select("group",{stage_id:t});if(!n)throw Error("Error getting groups.");const o=await this.storage.select("round",{stage_id:t});if(!o)throw Error("Error getting rounds.");const r=await this.storage.select("match",{stage_id:t});if(!r)throw Error("Error getting matches.");const i=await this.storage.select("participant",{tournament_id:e.tournament_id});if(!i)throw Error("Error getting participants.");return{stage:[e],group:n,round:o,match:r,match_game:await this.matchGames(r),participant:i}}async matchGames(t){const e=t.filter((t=>t.child_count>0)),n=await Promise.all(e.map((t=>this.storage.select("match_game",{parent_id:t.id}))));if(n.some((t=>null===t)))throw Error("Error getting match games.");return r.getNonNull(n).flat()}async seeding(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");return"round_robin"===e.type?this.roundRobinSeeding(e):this.eliminationSeeding(e)}async finalStandings(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");switch(e.type){case"round_robin":throw Error("A round-robin stage does not have standings.");case"single_elimination":return this.singleEliminationStandings(t);case"double_elimination":return this.doubleEliminationStandings(t);default:throw Error("Unknown stage type.")}}async roundRobinSeeding(t){if(void 0===t.settings.size)throw Error("The size of the seeding is undefined.");const e=await this.storage.select("match",{stage_id:t.id});if(!e)throw Error("Error getting matches.");const n=r.matchesToSeeding(e);if(n.lengtht&&t.position));return r.setArraySize(o,t.settings.size,null)}async eliminationSeeding(t){const e=await this.storage.selectFirst("round",{stage_id:t.id,number:1});if(!e)throw Error("Error getting the first round.");const n=await this.storage.select("match",{round_id:e.id});if(!n)throw Error("Error getting matches.");return r.matchesToSeeding(n)}async singleEliminationStandings(t){var e;const n=[],{stage:o,group:i,match:a,participant:s}=await this.stageData(t),[u]=o,[c,l]=i,d=a.filter((t=>t.group_id===c.id)).pop();if(!d)throw Error("Final not found.");n[0]=[r.findParticipant(s,r.getWinner(d))];const p=r.getLosers(s,a.filter((t=>t.group_id===c.id)));if(n.push(...p.reverse()),null===(e=u.settings)||void 0===e?void 0:e.consolationFinal){const t=a.filter((t=>t.group_id===l.id)).pop();if(!t)throw Error("Consolation final not found.");n[2][0]=r.findParticipant(s,r.getWinner(t)),n[2][1]=r.findParticipant(s,r.getLoser(t))}return r.makeFinalStandings(n)}async doubleEliminationStandings(t){var e,n;const o=[],{stage:i,group:a,match:s,participant:u}=await this.stageData(t),[c]=i,[l,d,p]=a;if("none"===(null===(e=c.settings)||void 0===e?void 0:e.grandFinal)){const t=s.filter((t=>t.group_id===l.id)).pop();if(!t)throw Error("WB final not found.");const e=s.filter((t=>t.group_id===d.id)).pop();if(!e)throw Error("LB final not found.");o[0]=[r.findParticipant(u,r.getWinner(t))],o[1]=[r.findParticipant(u,r.getWinner(e))]}else{const t=s.filter((t=>t.group_id===p.id)),e=r.getGrandFinalDecisiveMatch((null===(n=c.settings)||void 0===n?void 0:n.grandFinal)||"none",t);o[0]=[r.findParticipant(u,r.getWinner(e))],o[1]=[r.findParticipant(u,r.getLoser(e))]}const h=r.getLosers(u,s.filter((t=>t.group_id===d.id)));return o.push(...h.reverse()),r.makeFinalStandings(o)}}e.Get=i},487:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.setNextOpponent=e.getNextSideLoserBracket=e.getNextSide=e.findParticipant=e.getGrandFinalDecisiveMatch=e.makeFinalStandings=e.getLosers=e.getOriginPosition=e.getOpponentId=e.resetMatchResults=e.setMatchResults=e.getMatchStatus=e.hasBye=e.isMatchParticipantLocked=e.isMatchUpdateLocked=e.isMatchByeCompleted=e.isMatchWinCompleted=e.isMatchDrawCompleted=e.isMatchResultCompleted=e.isMatchForfeitCompleted=e.isMatchCompleted=e.isMatchStarted=e.getOtherSide=e.getSide=e.findPosition=e.getMatchResult=e.byeLoser=e.byeWinnerToGrandFinal=e.byeWinner=e.getLoser=e.getWinner=e.toResultWithPosition=e.toResult=e.ensureNotTied=e.ensureValidSize=e.fixSeeding=e.ensureEquallySized=e.ensureNoDuplicates=e.ensureEvenSized=e.makePairs=e.setArraySize=e.normalizeParticipant=e.makeNormalizedIdMapping=e.normalizeIds=e.balanceByes=e.makeGroups=e.assertRoundRobin=e.makeRoundRobinDistribution=e.makeRoundRobinMatches=e.splitByParity=void 0,e.getMatchLocation=e.isFinalGroup=e.isLoserBracket=e.isWinnerBracket=e.ensureNotRoundRobin=e.isRoundRobin=e.minScoreToWinBestOfX=e.getNearestPowerOfTwo=e.getDiagonalMatchNumber=e.getLowerBracketRoundCount=e.getLoserOrdering=e.getLoserRoundMatchCount=e.findLoserMatchNumber=e.isDoubleEliminationNecessary=e.getRoundPairCount=e.getUpperBracketRoundCount=e.isOrderingSupportedLoserBracket=e.isOrderingSupportedUpperBracket=e.ensureOrderingSupported=e.getSeedCount=e.getSeeds=e.getChildGamesResults=e.getUpdatedMatchResults=e.getParentMatchResults=e.setParentMatchCompleted=e.transitionToMinor=e.transitionToMajor=e.uniqueBy=e.getNonNull=e.sortSeeding=e.matchesToSeeding=e.mapParticipantsToDatabase=e.mapParticipantsIdsToDatabase=e.mapParticipantsNamesToDatabase=e.extractParticipantsFromSeeding=e.isSeedingWithIds=e.setForfeits=e.setResults=e.setCompleted=e.setScores=e.invertOpponents=e.handleOpponentsInversion=e.resetNextOpponent=void 0;const o=n(21),r=n(644);function i(t){const e=t.length,n=e%2==0?e:e+1,o=n-1,r=n/2,i=[];for(let a=0;a({...t,[n.id]:e++})),{})}function s(t,e){return null===t?null:{...t,id:null!==t.id?e[t.id]:null}}function u(t,e,n){return Array.from(Array(e),((e,o)=>t[o]||n))}function c(t){const e=d(t);return e?t[h(e)]:null}function l(t){return null===t[0]&&null===t[1]?null:null===t[0]&&null!==t[1]?{id:t[1].id}:null!==t[0]&&null===t[1]?{id:t[0].id}:{id:null}}function d(t){var e,n;if(!f(t))return null;if(w(t))return null;if(null===t.opponent1&&null===t.opponent2)return null;let o=null;if(("win"===(null===(e=t.opponent1)||void 0===e?void 0:e.result)||null===t.opponent2||t.opponent2.forfeit)&&(o="opponent1"),"win"===(null===(n=t.opponent2)||void 0===n?void 0:n.result)||null===t.opponent1||t.opponent1.forfeit){if(null!==o)throw Error("There are two winners.");o="opponent2"}return o}function p(t){return t%2==1?"opponent1":"opponent2"}function h(t){return"opponent1"===t?"opponent2":"opponent1"}function g(t){var e,n;return void 0!==(null===(e=t.opponent1)||void 0===e?void 0:e.score)||void 0!==(null===(n=t.opponent2)||void 0===n?void 0:n.score)}function f(t){return y(t)||m(t)||v(t)}function m(t){var e,n;return void 0!==(null===(e=t.opponent1)||void 0===e?void 0:e.forfeit)||void 0!==(null===(n=t.opponent2)||void 0===n?void 0:n.forfeit)}function v(t){return w(t)||b(t)}function w(t){var e,n;return"draw"===(null===(e=t.opponent1)||void 0===e?void 0:e.result)&&"draw"===(null===(n=t.opponent2)||void 0===n?void 0:n.result)}function b(t){var e,n,o,r;return"win"===(null===(e=t.opponent1)||void 0===e?void 0:e.result)||"win"===(null===(n=t.opponent2)||void 0===n?void 0:n.result)||"loss"===(null===(o=t.opponent1)||void 0===o?void 0:o.result)||"loss"===(null===(r=t.opponent2)||void 0===r?void 0:r.result)}function y(t){var e,n;return null===t.opponent1&&null!==(null===(e=t.opponent2)||void 0===e?void 0:e.id)||null===t.opponent2&&null!==(null===(n=t.opponent1)||void 0===n?void 0:n.id)||null===t.opponent1&&null===t.opponent2}function k(t){return null===t.opponent1||null===t.opponent2}function S(t){var e,n,r,i;const a=Array.isArray(t)?{opponent1:t[0],opponent2:t[1]}:t;return k(a)||null===(null===(e=a.opponent1)||void 0===e?void 0:e.id)&&null===(null===(n=a.opponent2)||void 0===n?void 0:n.id)?o.Status.Locked:null===(null===(r=a.opponent1)||void 0===r?void 0:r.id)||null===(null===(i=a.opponent2)||void 0===i?void 0:i.id)?o.Status.Waiting:f(a)?o.Status.Completed:g(a)?o.Status.Running:o.Status.Ready}function M(t){t.opponent1&&(t.opponent1.forfeit=void 0,t.opponent1.result=void 0),t.opponent2&&(t.opponent2.forfeit=void 0,t.opponent2.result=void 0),t.status=S(t)}function R(t,e){const n=t[e];return n&&n.id}function E(t,e){const n=t.find((t=>t.id===(null==e?void 0:e.id)));if(!n)throw Error("Participant not found.");return n}function C(t,e){var n,o,r,i;const a=null===(n=e.opponent1)||void 0===n?void 0:n.id,s=null===(o=e.opponent2)||void 0===o?void 0:o.id,u=null===(r=t.opponent1)||void 0===r?void 0:r.id,c=null===(i=t.opponent2)||void 0===i?void 0:i.id;if(Number.isInteger(a)&&a!==u&&a!==c)throw Error("The given opponent1 ID does not exist in this match.");if(Number.isInteger(s)&&s!==u&&s!==c)throw Error("The given opponent2 ID does not exist in this match.");(Number.isInteger(a)&&a===c||Number.isInteger(s)&&s===u)&&x(e)}function x(t){[t.opponent1,t.opponent2]=[t.opponent2,t.opponent1]}function _(t,e){var n,r,i,a;if((null===(n=e.opponent1)||void 0===n?void 0:n.score)===(null===(r=t.opponent1)||void 0===r?void 0:r.score)&&(null===(i=e.opponent2)||void 0===i?void 0:i.score)===(null===(a=t.opponent2)||void 0===a?void 0:a.score))return!1;const s=t.status;return t.status=o.Status.Running,e.opponent1&&t.opponent1&&(t.opponent1.score=e.opponent1.score),e.opponent2&&t.opponent2&&(t.opponent2.score=e.opponent2.score),t.status!==s}function L(t,e){t.status=o.Status.Completed,O(t,e,"win","loss"),O(t,e,"loss","win"),O(t,e,"draw","draw"),t.opponent1&&!t.opponent2&&(t.opponent1.result="win"),!t.opponent1&&t.opponent2&&(t.opponent2.result="win"),P(t,e)}function O(t,e,n,o){var r,i;if(e.opponent1&&e.opponent2){if("win"===e.opponent1.result&&"win"===e.opponent2.result)throw Error("There are two winners.");if("loss"===e.opponent1.result&&"loss"===e.opponent2.result)throw Error("There are two losers.");if(!0===e.opponent1.forfeit&&!0===e.opponent2.forfeit)throw Error("There are two forfeits.")}(null===(r=e.opponent1)||void 0===r?void 0:r.result)===n&&(t.opponent1?t.opponent1.result=n:t.opponent1={id:null,result:n},t.opponent2?t.opponent2.result=o:t.opponent2={id:null,result:o}),(null===(i=e.opponent2)||void 0===i?void 0:i.result)===n&&(t.opponent2?t.opponent2.result=n:t.opponent2={id:null,result:n},t.opponent1?t.opponent1.result=o:t.opponent1={id:null,result:o})}function P(t,e){var n,o;!0===(null===(n=e.opponent1)||void 0===n?void 0:n.forfeit)&&(t.opponent1&&(t.opponent1.forfeit=!0),t.opponent2?t.opponent2.result="win":t.opponent2={id:null,result:"win"}),!0===(null===(o=e.opponent2)||void 0===o?void 0:o.forfeit)&&(t.opponent2&&(t.opponent2.forfeit=!0),t.opponent1?t.opponent1.result="win":t.opponent1={id:null,result:"win"})}function N(t,e,n,o){const r=e.map(((e,o)=>{if(null===e)return null;const r=n.find((n=>n[t]===e));if(!r)throw Error(`Participant ${t} not found in database.`);return{id:r.id,position:o+1}}));if(!o)return r;if(o.length!==r.length)throw Error("Not enough seeds in at least one group of the manual ordering.");return o.map((t=>r[t-1]))}function B(t){const e=t.filter((t=>null!==t));if(e.sort(((t,e)=>t.position-e.position)),e.length===t.length)return e;const n=Object.fromEntries(e.map((t=>[t.position-1,t])));return Array.from({length:t.length},((t,e)=>n[e]||null))}function F(t){return t.filter((t=>null!==t))}function T(t,e,n,o){return j(t,e,n),1===e?2*o:o}function j(t,e,n){if(t&&!I(e,n))throw Error("This round does not support ordering.");if(!t&&!D(e))throw Error("This round does not support ordering.")}function D(t){return 1===t}function I(t,e){return 1===t||t%2==0&&te%2==0)),odd:t.filter(((t,e)=>e%2==1))}},e.makeRoundRobinMatches=function(t,e="simple"){const n=i(t);if("simple"===e)return n;const o=n.map((t=>[...t].reverse())).reverse();return[...n,...o]},e.makeRoundRobinDistribution=i,e.assertRoundRobin=function(t,e){const n=t.length,o=Math.floor(n/2),r=n%2==0?n-1:n;if(e.length!==r)throw Error("Round count is wrong");if(!e.every((t=>t.length===o)))throw Error("Not every round has the good number of matches");const i=Object.fromEntries(t.map((t=>[t,new Set])));for(const t of e){const e=new Set;for(const n of t){if(2!==n.length)throw Error("One match is not a pair");if(e.has(n[0]))throw Error("This team is already playing");if(e.add(n[0]),e.has(n[1]))throw Error("This team is already playing");if(e.add(n[1]),i[n[0]].has(n[1]))throw Error("The team has already matched this team");if(i[n[0]].add(n[1]),i[n[1]].has(n[0]))throw Error("The team has already matched this team");i[n[1]].add(n[0])}}},e.makeGroups=function(t,e){const n=Math.ceil(t.length/e),o=[];for(let e=0;enull!==t)),e=e||G(t.length),t.length[t,null])).flat(),e,null);const n=t.length,o=e-n,r=t.slice(0,n-o).filter(((t,e)=>e%2==0)).map(((e,n)=>[t[2*n],t[2*n+1]])),i=t.slice(n-o,n).map((t=>[t,null]));return u([...r.flat(),...i.flat()],e,null)},e.normalizeIds=function(t){const e={participant:a(t.participant),stage:a(t.stage),group:a(t.group),round:a(t.round),match:a(t.match),match_game:a(t.match_game)};return{participant:t.participant.map((t=>({...t,id:e.participant[t.id]}))),stage:t.stage.map((t=>({...t,id:e.stage[t.id]}))),group:t.group.map((t=>({...t,id:e.group[t.id],stage_id:e.stage[t.stage_id]}))),round:t.round.map((t=>({...t,id:e.round[t.id],stage_id:e.stage[t.stage_id],group_id:e.group[t.group_id]}))),match:t.match.map((t=>({...t,id:e.match[t.id],stage_id:e.stage[t.stage_id],group_id:e.group[t.group_id],round_id:e.round[t.round_id],opponent1:s(t.opponent1,e.participant),opponent2:s(t.opponent2,e.participant)}))),match_game:t.match_game.map((t=>({...t,id:e.match_game[t.id],stage_id:e.stage[t.stage_id],parent_id:e.match[t.parent_id],opponent1:s(t.opponent1,e.participant),opponent2:s(t.opponent2,e.participant)})))}},e.makeNormalizedIdMapping=a,e.normalizeParticipant=s,e.setArraySize=u,e.makePairs=function(t){return t.map(((e,n)=>n%2==0?[t[n],t[n+1]]:[])).filter((t=>2===t.length))},e.ensureEvenSized=function(t){if(t.length%2==1)throw Error("Array size must be even.")},e.ensureNoDuplicates=function(t){const e=F(t);if([...new Set(e)].lengthe)throw Error("The seeding has more participants than the size of the stage.");return t.length=o.Status.Running},e.hasBye=k,e.getMatchStatus=S,e.setMatchResults=function(t,e){const n=f(e),o=f(t);C(t,e);const r=_(t,e);return n&&o?(L(t,e),{statusChanged:!1,resultChanged:!0}):n&&!o?(L(t,e),{statusChanged:!0,resultChanged:!0}):!n&&o?(M(t),{statusChanged:!0,resultChanged:!0}):{statusChanged:r,resultChanged:!1}},e.resetMatchResults=M,e.getOpponentId=R,e.getOriginPosition=function(t,e){var n;const o=null===(n=t[e])||void 0===n?void 0:n.position;if(void 0===o)throw Error("Position is undefined.");return o},e.getLosers=function(t,e){const n=[];let o=null,r=-1;for(const i of e){i.round_id!==o&&(o=i.round_id,r++,n[r]=[]);const e=c(i);null!==e&&n[r].push(E(t,e))}return n},e.makeFinalStandings=function(t){const e=[];let n=1;for(const o of t){for(const t of o)e.push({id:t.id,name:t.name,rank:n});n++}return e},e.getGrandFinalDecisiveMatch=function(t,e){if("simple"===t)return e[0];if("double"===t)return"opponent2"===d(e[0])?e[1]:e[0];throw Error("The Grand Final is disabled.")},e.findParticipant=E,e.getNextSide=function(t,e,n,o){return"loser_bracket"===o&&e%2==1||"loser_bracket"===o&&e===n?"opponent2":p(t)},e.getNextSideLoserBracket=function(t,e,n){var o;return n>1||(null===(o=e.opponent1)||void 0===o?void 0:o.position)===t?"opponent1":"opponent2"},e.setNextOpponent=function(t,e,n,o){var r;t[e]=n[o]&&{id:R(n,o),position:null===(r=t[e])||void 0===r?void 0:r.position},t.status=S(t)},e.resetNextOpponent=function(t,e){var n;t[e]=t[e]&&{id:null,position:null===(n=t[e])||void 0===n?void 0:n.position},t.status=o.Status.Locked},e.handleOpponentsInversion=C,e.invertOpponents=x,e.setScores=_,e.setCompleted=L,e.setResults=O,e.setForfeits=P,e.isSeedingWithIds=function(t){return t.some((t=>"number"==typeof t))},e.extractParticipantsFromSeeding=function(t,e){return e.filter((t=>null!==t)).map((e=>({tournament_id:t,name:e})))},e.mapParticipantsNamesToDatabase=function(t,e,n){return N("name",t,e,n)},e.mapParticipantsIdsToDatabase=function(t,e,n){return N("id",t,e,n)},e.mapParticipantsToDatabase=N,e.matchesToSeeding=function(t){return B([].concat(...t.map((t=>[t.opponent1,t.opponent2]))))},e.sortSeeding=B,e.getNonNull=F,e.uniqueBy=function(t,e){const n=new Set;return t.filter((t=>{const o=e(t);return!o||!n.has(o)&&(n.add(o),!0)}))},e.transitionToMajor=function(t){const e=t.length/2,n=[];for(let o=0;o=i)t.opponent1.result="win";else if(t.opponent2.score>=i)t.opponent2.result="win";else if(t.opponent1.score===t.opponent2.score&&t.opponent1.score+t.opponent2.score>e-1){if(n)return t.opponent1.result="draw",void(t.opponent2.result="draw");throw Error("Match games result in a tie for the parent match.")}},e.getParentMatchResults=function(t,e){return{opponent1:{id:t.opponent1&&t.opponent1.id,score:e.opponent1},opponent2:{id:t.opponent2&&t.opponent2.id,score:e.opponent2}}},e.getUpdatedMatchResults=function(t,e){return{...e,...t,opponent1:{...e.opponent1,...t.opponent1},opponent2:{...e.opponent2,...t.opponent2}}},e.getChildGamesResults=function(t){const e={opponent1:0,opponent2:0};for(const n of t){const t=d(n);"opponent1"===t?e.opponent1++:"opponent2"===t&&e.opponent2++}return e},e.getSeeds=function(t,e,n,o){const r=T(t,e,n,o);return Array.from(Array(r),((t,e)=>e+1))},e.getSeedCount=T,e.ensureOrderingSupported=j,e.isOrderingSupportedUpperBracket=D,e.isOrderingSupportedLoserBracket=I,e.getUpperBracketRoundCount=A,e.getRoundPairCount=U,e.isDoubleEliminationNecessary=function(t){return t>2},e.findLoserMatchNumber=function(t,e,n,o){const i=W(t,e),a=Array.from(Array(i),((t,e)=>e+1));return(o?r.ordering[o](a):a).indexOf(n)+1},e.getLoserRoundMatchCount=W,e.getLoserOrdering=function(t,e){return t[1+Math.floor(e/2)]},e.getLowerBracketRoundCount=function(t){return 2*U(t)},e.getDiagonalMatchNumber=function(t){return Math.ceil(t/2)},e.getNearestPowerOfTwo=G,e.minScoreToWinBestOfX=z,e.isRoundRobin=H,e.ensureNotRoundRobin=function(t){if(H(t))throw Error("Impossible to update ordering in a round-robin stage.")},e.isWinnerBracket=V,e.isLoserBracket=q,e.isFinalGroup=$,e.getMatchLocation=function(t,e){return V(t,e)?"winner_bracket":q(t,e)?"loser_bracket":$(t,e)?"final_group":"single_bracket"}},37:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.helpers=e.BracketsManager=void 0;const o=n(76);Object.defineProperty(e,"BracketsManager",{enumerable:!0,get:function(){return o.BracketsManager}});const r=n(487);e.helpers={getWinner:r.getWinner,getLoser:r.getLoser,getMatchResult:r.getMatchResult,isMatchStarted:r.isMatchStarted,isMatchCompleted:r.isMatchCompleted,isMatchForfeitCompleted:r.isMatchForfeitCompleted,isMatchResultCompleted:r.isMatchResultCompleted,isMatchDrawCompleted:r.isMatchDrawCompleted,isMatchWinCompleted:r.isMatchWinCompleted,isMatchByeCompleted:r.isMatchByeCompleted,isMatchUpdateLocked:r.isMatchUpdateLocked,isMatchParticipantLocked:r.isMatchParticipantLocked,hasBye:r.hasBye,getUpperBracketRoundCount:r.getUpperBracketRoundCount,getRoundPairCount:r.getRoundPairCount,getLoserRoundMatchCount:r.getLoserRoundMatchCount,getLowerBracketRoundCount:r.getLowerBracketRoundCount,getNearestPowerOfTwo:r.getNearestPowerOfTwo,minScoreToWinBestOfX:r.minScoreToWinBestOfX,isRoundRobin:r.isRoundRobin,isWinnerBracket:r.isWinnerBracket,isLoserBracket:r.isLoserBracket,isFinalGroup:r.isFinalGroup,getMatchLocation:r.getMatchLocation}},76:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.BracketsManager=void 0;const o=n(765),r=n(576),i=n(11),a=n(378),s=n(63),u=n(369),c=n(487);e.BracketsManager=class{constructor(t){const e=t;e.selectFirst=async(t,e)=>{const n=await this.storage.select(t,e);return n&&0!==n.length?n[0]:null},e.selectLast=async(t,e)=>{const n=await this.storage.select(t,e);return n&&0!==n.length?n[n.length-1]:null},this.storage=e,this.get=new r.Get(this.storage),this.update=new i.Update(this.storage),this.delete=new a.Delete(this.storage),this.find=new s.Find(this.storage),this.reset=new u.Reset(this.storage)}async create(t){await o.create.call(this,t)}async import(t){if(t=c.normalizeIds(t),!await this.storage.delete("participant"))throw Error("Could not empty the participant table.");if(!await this.storage.insert("participant",t.participant))throw Error("Could not import participants.");if(!await this.storage.delete("stage"))throw Error("Could not empty the stage table.");if(!await this.storage.insert("stage",t.stage))throw Error("Could not import stages.");if(!await this.storage.delete("group"))throw Error("Could not empty the group table.");if(!await this.storage.insert("group",t.group))throw Error("Could not import groups.");if(!await this.storage.delete("round"))throw Error("Could not empty the round table.");if(!await this.storage.insert("round",t.round))throw Error("Could not import rounds.");if(!await this.storage.delete("match"))throw Error("Could not empty the match table.");if(!await this.storage.insert("match",t.match))throw Error("Could not import matches.");if(!await this.storage.delete("match_game"))throw Error("Could not empty the match_game table.");if(!await this.storage.insert("match_game",t.match_game))throw Error("Could not import match games.")}async export(){const t=await this.storage.select("participant");if(!t)throw Error("Error getting participants.");const e=await this.storage.select("stage");if(!e)throw Error("Error getting stages.");const n=await this.storage.select("group");if(!n)throw Error("Error getting groups.");const o=await this.storage.select("round");if(!o)throw Error("Error getting rounds.");const r=await this.storage.select("match");if(!r)throw Error("Error getting matches.");return{participant:t,stage:e,group:n,round:o,match:r,match_game:await this.get.matchGames(r)}}}},644:function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultMinorOrdering=e.ordering=void 0,e.ordering={natural:t=>[...t],reverse:t=>[...t].reverse(),half_shift:t=>[...t.slice(t.length/2),...t.slice(0,t.length/2)],reverse_half_shift:t=>[...t.slice(0,t.length/2).reverse(),...t.slice(t.length/2).reverse()],pair_flip:t=>{const e=[];for(let n=0;n{if(2===t.length)return t;const e=t.length/4,n=[t.slice(e,2*e),t.slice(2*e,3*e)],o=[t.slice(0,e),t.slice(3*e,4*e)],r={inner:t=>[t[0].pop(),t[1].shift()],outer:t=>[t[0].shift(),t[1].pop()]},i=[];function a(t,e){t[0].length>0&&t[1].length>0&&i.push(...r[e](t))}for(let t=0;t{const n=[];let o=0,r=0;for(;n.length=t.length&&(o=++r);return n},"groups.seed_optimized":(t,e)=>{const n=Array.from(Array(e),(t=>[]));for(let o=0;o{throw Error("Not implemented.")}},e.defaultMinorOrdering={4:["natural","reverse"],8:["natural","reverse","natural"],16:["natural","reverse_half_shift","reverse","natural"],32:["natural","reverse","half_shift","natural","natural"],64:["natural","reverse","half_shift","reverse","natural","natural"],128:["natural","reverse","half_shift","pair_flip","pair_flip","pair_flip","natural"]}},369:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Reset=void 0;const o=n(21),r=n(517),i=n(487);class a extends r.BaseUpdater{async matchResults(t){const e=await this.storage.select("match",t);if(!e)throw Error("Match not found.");if(e.child_count>0)throw Error("The parent match is controlled by its child games and its result cannot be reset.");const n=await this.storage.select("stage",e.stage_id);if(!n)throw Error("Stage not found.");const r=await this.storage.select("group",e.group_id);if(!r)throw Error("Group not found.");const{roundNumber:a,roundCount:s}=await this.getRoundPositionalInfo(e.round_id),u=i.getMatchLocation(n.type,r.number);if((await this.getNextMatches(e,u,n,a,s)).some((t=>t&&t.status>=o.Status.Running&&!i.isMatchByeCompleted(t))))throw Error("The match is locked.");i.resetMatchResults(e),await this.applyMatchUpdate(e),i.isRoundRobin(n)||await this.updateRelatedMatches(e,!0,!0)}async matchGameResults(t){const e=await this.storage.select("match_game",t);if(!e)throw Error("Match game not found.");if(i.resetMatchResults(e),!await this.storage.update("match_game",e.id,e))throw Error("Could not update the match game.");await this.updateParentMatch(e.parent_id)}async seeding(t){await this.updateSeeding(t,null)}}e.Reset=a},11:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Update=void 0;const o=n(21),r=n(644),i=n(517),a=n(487);class s extends i.BaseUpdater{async match(t){if(void 0===t.id)throw Error("No match id given.");const e=await this.storage.select("match",t.id);if(!e)throw Error("Match not found.");await this.updateMatch(e,t)}async matchGame(t){const e=await this.findMatchGame(t);if(a.isMatchUpdateLocked(e))throw Error("The match game is locked.");if(a.setMatchResults(e,t),!await this.storage.update("match_game",e.id,e))throw Error("Could not update the match game.");await this.updateParentMatch(e.parent_id)}async ordering(t,e){const n=await this.storage.select("stage",t);if(!n)throw Error("Stage not found.");a.ensureNotRoundRobin(n);const o=await this.getOrderedRounds(n);if(e.length!==o.length)throw Error("The count of seed orderings is incorrect.");for(let t=0;tt.status>o.Status.Ready)))throw Error("At least one match has started or is completed.");const i=await this.storage.select("stage",t.stage_id);if(!i)throw Error("Stage not found.");if(void 0===i.settings.size)throw Error("Undefined stage size.");const s=await this.storage.select("group",t.group_id);if(!s)throw Error("Group not found.");const u=a.isLoserBracket(i.type,s.number),c=a.getLowerBracketRoundCount(i.settings.size),l=a.getSeeds(u,t.number,c,n.length),d=r.ordering[e](l);await this.applyRoundOrdering(t.number,n,d)}async updateStageMatchChildCount(t,e){if(!await this.storage.update("match",{stage_id:t},{child_count:e}))throw Error("Could not update the match.");const n=await this.storage.select("match",{stage_id:t});if(!n)throw Error("This stage has no match.");for(const t of n)await this.adjustMatchChildGames(t,e)}async updateGroupMatchChildCount(t,e){if(!await this.storage.update("match",{group_id:t},{child_count:e}))throw Error("Could not update the match.");const n=await this.storage.select("match",{group_id:t});if(!n)throw Error("This group has no match.");for(const t of n)await this.adjustMatchChildGames(t,e)}async updateRoundMatchChildCount(t,e){if(!await this.storage.update("match",{round_id:t},{child_count:e}))throw Error("Could not update the match.");const n=await this.storage.select("match",{round_id:t});if(!n)throw Error("This round has no match.");for(const t of n)await this.adjustMatchChildGames(t,e)}async applyRoundOrdering(t,e,n){for(const o of e){const r={...o};if(r.opponent1=a.findPosition(e,n.shift()),1===t&&(r.opponent2=a.findPosition(e,n.shift())),!await this.storage.update("match",r.id,r))throw Error("Could not update the match.")}}async adjustMatchChildGames(t,e){const n=await this.storage.select("match_game",{parent_id:t.id});let o=n?n.length:0;for(;oe;){if(!await this.storage.delete("match_game",{parent_id:t.id,number:o}))throw Error("Could not adjust the match games when deleting.");o--}if(!await this.storage.update("match",t.id,{...t,child_count:e}))throw Error("Could not update the match.")}}e.Update=s},38:function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.InMemoryDatabase=void 0,e.InMemoryDatabase=class{data={participant:[],stage:[],group:[],round:[],match:[],match_game:[]};setData(t){this.data=t}makeFilter(t){return e=>{let n=!0;for(const o of Object.keys(t))n=n&&e[o]===t[o];return n}}reset(){this.data={participant:[],stage:[],group:[],round:[],match:[],match_game:[]}}insert(t,e){let n;if(n=this.data[t].length,!Array.isArray(e)){try{this.data[t].push({id:n,...e})}catch(t){return new Promise((t=>{t(-1)}))}return new Promise((t=>{t(n)}))}try{e.map((e=>{this.data[t].push({id:n++,...e})}))}catch(t){return new Promise((t=>{t(!1)}))}return new Promise((t=>{t(!0)}))}select(t,e){try{return new Promise(void 0===e?e=>{e(this.data[t])}:"number"==typeof e?n=>{n(this.data[t][e])}:n=>{n(this.data[t].filter(this.makeFilter(e))||null)})}catch(t){return new Promise((t=>{t(null)}))}}update(t,e,n){if("number"==typeof e)try{return this.data[t][e]=n,new Promise((t=>{t(!0)}))}catch(t){return new Promise((t=>{t(!1)}))}const o=this.data[t].filter(this.makeFilter(e));return o?(o.forEach((e=>{const o=this.data[t][e.id];for(const t in n)o[t]=n[t];this.data[t][e.id]=o})),new Promise((t=>{t(!0)}))):new Promise((t=>{t(!1)}))}delete(t,e){const n=this.data[t];if(!n)return new Promise((t=>{t(!1)}));if(!e)return this.data[t]=[],new Promise((t=>{t(!0)}));const o=this.makeFilter(e);return this.data[t]=n.filter((t=>!o(t))),new Promise((t=>{t(!0)}))}}},21:function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.Status=void 0;const o=n(854);Object.defineProperty(e,"Status",{enumerable:!0,get:function(){return o.Status}})},854:function(t,e){var n;Object.defineProperty(e,"__esModule",{value:!0}),e.Status=void 0,(n=e.Status||(e.Status={}))[n.Locked=0]="Locked",n[n.Waiting=1]="Waiting",n[n.Ready=2]="Ready",n[n.Running=3]="Running",n[n.Completed=4]="Completed",n[n.Archived=5]="Archived"},71:function(t,e,n){n.r(e);var o=n(671),r=n(144),i=[],a=i.forEach,s=i.slice;function u(t){return a.call(s.call(arguments,1),(function(e){if(e)for(var n in e)void 0===t[n]&&(t[n]=e[n])})),t}var c=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,l=function(t,e,n){var o=n||{};o.path=o.path||"/";var r=t+"="+encodeURIComponent(e);if(o.maxAge>0){var i=o.maxAge-0;if(isNaN(i))throw new Error("maxAge should be a Number");r+="; Max-Age="+Math.floor(i)}if(o.domain){if(!c.test(o.domain))throw new TypeError("option domain is invalid");r+="; Domain="+o.domain}if(o.path){if(!c.test(o.path))throw new TypeError("option path is invalid");r+="; Path="+o.path}if(o.expires){if("function"!=typeof o.expires.toUTCString)throw new TypeError("option expires is invalid");r+="; Expires="+o.expires.toUTCString()}if(o.httpOnly&&(r+="; HttpOnly"),o.secure&&(r+="; Secure"),o.sameSite)switch("string"==typeof o.sameSite?o.sameSite.toLowerCase():o.sameSite){case!0:r+="; SameSite=Strict";break;case"lax":r+="; SameSite=Lax";break;case"strict":r+="; SameSite=Strict";break;case"none":r+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r},d={name:"cookie",lookup:function(t){var e;if(t.lookupCookie&&"undefined"!=typeof document){var n=function(t){for(var e=t+"=",n=document.cookie.split(";"),o=0;o4&&void 0!==arguments[4]?arguments[4]:{path:"/",sameSite:"strict"};n&&(r.expires=new Date,r.expires.setTime(r.expires.getTime()+60*n*1e3)),o&&(r.domain=o),document.cookie=l(t,encodeURIComponent(e),r)}(e.lookupCookie,t,e.cookieMinutes,e.cookieDomain,e.cookieOptions)}},p={name:"querystring",lookup:function(t){var e;if("undefined"!=typeof window)for(var n=window.location.search.substring(1).split("&"),o=0;o0&&n[o].substring(0,r)===t.lookupQuerystring&&(e=n[o].substring(r+1))}return e}},h=null,g=function(){if(null!==h)return h;try{h="undefined"!==window&&null!==window.localStorage;var t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch(t){h=!1}return h},f={name:"localStorage",lookup:function(t){var e;if(t.lookupLocalStorage&&g()){var n=window.localStorage.getItem(t.lookupLocalStorage);n&&(e=n)}return e},cacheUserLanguage:function(t,e){e.lookupLocalStorage&&g()&&window.localStorage.setItem(e.lookupLocalStorage,t)}},m=null,v=function(){if(null!==m)return m;try{m="undefined"!==window&&null!==window.sessionStorage;var t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch(t){m=!1}return m},w={name:"sessionStorage",lookup:function(t){var e;if(t.lookupSessionStorage&&v()){var n=window.sessionStorage.getItem(t.lookupSessionStorage);n&&(e=n)}return e},cacheUserLanguage:function(t,e){e.lookupSessionStorage&&v()&&window.sessionStorage.setItem(e.lookupSessionStorage,t)}},b={name:"navigator",lookup:function(t){var e=[];if("undefined"!=typeof navigator){if(navigator.languages)for(var n=0;n0?e:void 0}},y={name:"htmlTag",lookup:function(t){var e,n=t.htmlTag||("undefined"!=typeof document?document.documentElement:null);return n&&"function"==typeof n.getAttribute&&(e=n.getAttribute("lang")),e}},k={name:"path",lookup:function(t){var e;if("undefined"!=typeof window){var n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);if(n instanceof Array)if("number"==typeof t.lookupFromPathIndex){if("string"!=typeof n[t.lookupFromPathIndex])return;e=n[t.lookupFromPathIndex].replace("/","")}else e=n[0].replace("/","")}return e}},S={name:"subdomain",lookup:function(t){var e;if("undefined"!=typeof window){var n=window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);n instanceof Array&&(e="number"==typeof t.lookupFromSubdomainIndex?n[t.lookupFromSubdomainIndex].replace("http://","").replace("https://","").replace(".",""):n[0].replace("http://","").replace("https://","").replace(".",""))}return e}},M=function(){function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};(0,o.Z)(this,t),this.type="languageDetector",this.detectors={},this.init(e,n)}return(0,r.Z)(t,[{key:"init",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.services=t,this.options=u(e,this.options||{},{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"]}),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=n,this.addDetector(d),this.addDetector(p),this.addDetector(f),this.addDetector(w),this.addDetector(b),this.addDetector(y),this.addDetector(k),this.addDetector(S)}},{key:"addDetector",value:function(t){this.detectors[t.name]=t}},{key:"detect",value:function(t){var e=this;t||(t=this.options.order);var n=[];return t.forEach((function(t){if(e.detectors[t]){var o=e.detectors[t].lookup(e.options);o&&"string"==typeof o&&(o=[o]),o&&(n=n.concat(o))}})),this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}},{key:"cacheUserLanguage",value:function(t,e){var n=this;e||(e=this.options.caches),e&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(t)>-1||e.forEach((function(e){n.detectors[e]&&n.detectors[e].cacheUserLanguage(t,n.options)})))}}]),t}();M.type="languageDetector",e.default=M},261:function(t,e,n){function o(t){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o(t)}function r(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{};(0,a.Z)(this,t),this.init(e,n)}return(0,s.Z)(t,[{key:"init",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.prefix=e.prefix||"i18next:",this.logger=t||h,this.options=e,this.debug=e.debug}},{key:"setDebug",value:function(t){this.debug=t}},{key:"log",value:function(){for(var t=arguments.length,e=new Array(t),n=0;n1?e-1:0),o=1;o-1?t.replace(/###/g,"."):t}function r(){return!t||"string"==typeof t}for(var i="string"!=typeof e?[].concat(e):e.split(".");i.length>1;){if(r())return{};var a=o(i.shift());!t[a]&&n&&(t[a]=new n),t=Object.prototype.hasOwnProperty.call(t,a)?t[a]:{}}return r()?{}:{obj:t,k:o(i.shift())}}function k(t,e,n){var o=y(t,e,Object);o.obj[o.k]=n}function S(t,e){var n=y(t,e),o=n.obj,r=n.k;if(o)return o[r]}function M(t,e,n){var o=S(t,n);return void 0!==o?o:S(e,n)}function R(t,e,n){for(var o in e)"__proto__"!==o&&"constructor"!==o&&(o in t?"string"==typeof t[o]||t[o]instanceof String||"string"==typeof e[o]||e[o]instanceof String?n&&(t[o]=e[o]):R(t[o],e[o],n):t[o]=e[o]);return t}function E(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var C={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};function x(t){return"string"==typeof t?t.replace(/[&<>"'\/]/g,(function(t){return C[t]})):t}var _="undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.userAgent.indexOf("MSIE")>-1;function L(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:".";if(t){if(t[e])return t[e];for(var o=e.split(n),r=t,i=0;ii+a;)a++,u=r[s=o.slice(i,i+a).join(n)];if(void 0===u)return;if("string"==typeof u)return u;if(s&&"string"==typeof u[s])return u[s];var c=o.slice(i+a).join(n);return c?L(u,c,n):void 0}r=r[o[i]]}return r}}var O=function(t){function e(t){var n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{ns:["translation"],defaultNS:"translation"};return(0,a.Z)(this,e),n=c(this,l(e).call(this)),_&&m.call(u(n)),n.data=t||{},n.options=o,void 0===n.options.keySeparator&&(n.options.keySeparator="."),void 0===n.options.ignoreJSONStructure&&(n.options.ignoreJSONStructure=!0),n}return p(e,t),(0,s.Z)(e,[{key:"addNamespaces",value:function(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}},{key:"removeNamespaces",value:function(t){var e=this.options.ns.indexOf(t);e>-1&&this.options.ns.splice(e,1)}},{key:"getResource",value:function(t,e,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},r=void 0!==o.keySeparator?o.keySeparator:this.options.keySeparator,i=void 0!==o.ignoreJSONStructure?o.ignoreJSONStructure:this.options.ignoreJSONStructure,a=[t,e];n&&"string"!=typeof n&&(a=a.concat(n)),n&&"string"==typeof n&&(a=a.concat(r?n.split(r):n)),t.indexOf(".")>-1&&(a=t.split("."));var s=S(this.data,a);return s||!i||"string"!=typeof n?s:L(this.data&&this.data[t]&&this.data[t][e],n,r)}},{key:"addResource",value:function(t,e,n,o){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{silent:!1},i=this.options.keySeparator;void 0===i&&(i=".");var a=[t,e];n&&(a=a.concat(i?n.split(i):n)),t.indexOf(".")>-1&&(o=e,e=(a=t.split("."))[1]),this.addNamespaces(e),k(this.data,a,o),r.silent||this.emit("added",t,e,n,o)}},{key:"addResources",value:function(t,e,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{silent:!1};for(var r in n)"string"!=typeof n[r]&&"[object Array]"!==Object.prototype.toString.apply(n[r])||this.addResource(t,e,r,n[r],{silent:!0});o.silent||this.emit("added",t,e,n)}},{key:"addResourceBundle",value:function(t,e,n,o,r){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{silent:!1},s=[t,e];t.indexOf(".")>-1&&(o=n,n=e,e=(s=t.split("."))[1]),this.addNamespaces(e);var u=S(this.data,s)||{};o?R(u,n,r):u=i({},u,n),k(this.data,s,u),a.silent||this.emit("added",t,e,n)}},{key:"removeResourceBundle",value:function(t,e){this.hasResourceBundle(t,e)&&delete this.data[t][e],this.removeNamespaces(e),this.emit("removed",t,e)}},{key:"hasResourceBundle",value:function(t,e){return void 0!==this.getResource(t,e)}},{key:"getResourceBundle",value:function(t,e){return e||(e=this.options.defaultNS),"v1"===this.options.compatibilityAPI?i({},{},this.getResource(t,e)):this.getResource(t,e)}},{key:"getDataByLanguage",value:function(t){return this.data[t]}},{key:"toJSON",value:function(){return this.data}}]),e}(m),P={processors:{},addPostProcessor:function(t){this.processors[t.name]=t},handle:function(t,e,n,o,r){var i=this;return t.forEach((function(t){i.processors[t]&&(e=i.processors[t].process(e,n,o,r))})),e}},N={},B=function(t){function e(t){var n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(0,a.Z)(this,e),n=c(this,l(e).call(this)),_&&m.call(u(n)),b(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,u(n)),n.options=o,void 0===n.options.keySeparator&&(n.options.keySeparator="."),n.logger=f.create("translator"),n}return p(e,t),(0,s.Z)(e,[{key:"changeLanguage",value:function(t){t&&(this.language=t)}},{key:"exists",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}};if(null==t)return!1;var n=this.resolve(t,e);return n&&void 0!==n.res}},{key:"extractFromKey",value:function(t,e){var n=void 0!==e.nsSeparator?e.nsSeparator:this.options.nsSeparator;void 0===n&&(n=":");var o=void 0!==e.keySeparator?e.keySeparator:this.options.keySeparator,r=e.ns||this.options.defaultNS;if(n&&t.indexOf(n)>-1){var i=t.match(this.interpolator.nestingRegexp);if(i&&i.length>0)return{key:t,namespaces:r};var a=t.split(n);(n!==o||n===o&&this.options.ns.indexOf(a[0])>-1)&&(r=a.shift()),t=a.join(o)}return"string"==typeof r&&(r=[r]),{key:t,namespaces:r}}},{key:"translate",value:function(t,n,r){var a=this;if("object"!==o(n)&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),n||(n={}),null==t)return"";Array.isArray(t)||(t=[String(t)]);var s=void 0!==n.keySeparator?n.keySeparator:this.options.keySeparator,u=this.extractFromKey(t[t.length-1],n),c=u.key,l=u.namespaces,d=l[l.length-1],p=n.lng||this.language,h=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(p&&"cimode"===p.toLowerCase()){if(h){var g=n.nsSeparator||this.options.nsSeparator;return d+g+c}return c}var f=this.resolve(t,n),m=f&&f.res,v=f&&f.usedKey||c,w=f&&f.exactUsedKey||c,b=Object.prototype.toString.apply(m),y=["[object Number]","[object Function]","[object RegExp]"],k=void 0!==n.joinArrays?n.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,M="string"!=typeof m&&"boolean"!=typeof m&&"number"!=typeof m;if(S&&m&&M&&y.indexOf(b)<0&&("string"!=typeof k||"[object Array]"!==b)){if(!n.returnObjects&&!this.options.returnObjects)return this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!"),this.options.returnedObjectHandler?this.options.returnedObjectHandler(v,m,i({},n,{ns:l})):"key '".concat(c," (").concat(this.language,")' returned an object instead of string.");if(s){var R="[object Array]"===b,E=R?[]:{},C=R?w:v;for(var x in m)if(Object.prototype.hasOwnProperty.call(m,x)){var _="".concat(C).concat(s).concat(x);E[x]=this.translate(_,i({},n,{joinArrays:!1,ns:l})),E[x]===_&&(E[x]=m[x])}m=E}}else if(S&&"string"==typeof k&&"[object Array]"===b)(m=m.join(k))&&(m=this.extendTranslation(m,t,n,r));else{var L=!1,O=!1,P=void 0!==n.count&&"string"!=typeof n.count,N=e.hasDefaultValue(n),B=P?this.pluralResolver.getSuffix(p,n.count):"",F=n["defaultValue".concat(B)]||n.defaultValue;!this.isValidLookup(m)&&N&&(L=!0,m=F),this.isValidLookup(m)||(O=!0,m=c);var T=n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey,j=T&&O?void 0:m,D=N&&F!==m&&this.options.updateMissing;if(O||L||D){if(this.logger.log(D?"updateKey":"missingKey",p,d,c,D?F:m),s){var I=this.resolve(c,i({},n,{keySeparator:!1}));I&&I.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}var A=[],U=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if("fallback"===this.options.saveMissingTo&&U&&U[0])for(var W=0;W1&&void 0!==arguments[1]?arguments[1]:{};return"string"==typeof t&&(t=[t]),t.forEach((function(t){if(!a.isValidLookup(e)){var u=a.extractFromKey(t,s),c=u.key;n=c;var l=u.namespaces;a.options.fallbackNS&&(l=l.concat(a.options.fallbackNS));var d=void 0!==s.count&&"string"!=typeof s.count,p=void 0!==s.context&&("string"==typeof s.context||"number"==typeof s.context)&&""!==s.context,h=s.lngs?s.lngs:a.languageUtils.toResolveHierarchy(s.lng||a.language,s.fallbackLng);l.forEach((function(t){a.isValidLookup(e)||(i=t,!N["".concat(h[0],"-").concat(t)]&&a.utils&&a.utils.hasLoadedNamespace&&!a.utils.hasLoadedNamespace(i)&&(N["".concat(h[0],"-").concat(t)]=!0,a.logger.warn('key "'.concat(n,'" for languages "').concat(h.join(", "),'" won\'t get resolved as namespace "').concat(i,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),h.forEach((function(n){if(!a.isValidLookup(e)){r=n;var i,u,l=c,h=[l];for(a.i18nFormat&&a.i18nFormat.addLookupKeys?a.i18nFormat.addLookupKeys(h,c,n,t,s):(d&&(i=a.pluralResolver.getSuffix(n,s.count)),d&&p&&h.push(l+i),p&&h.push(l+="".concat(a.options.contextSeparator).concat(s.context)),d&&h.push(l+=i));u=h.pop();)a.isValidLookup(e)||(o=u,e=a.getResource(n,t,u,s))}})))}))}})),{res:e,usedKey:n,exactUsedKey:o,usedLng:r,usedNS:i}}},{key:"isValidLookup",value:function(t){return!(void 0===t||!this.options.returnNull&&null===t||!this.options.returnEmptyString&&""===t)}},{key:"getResource",value:function(t,e,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,e,n,o):this.resourceStore.getResource(t,e,n,o)}}],[{key:"hasDefaultValue",value:function(t){var e="defaultValue";for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e===n.substring(0,e.length)&&void 0!==t[n])return!0;return!1}}]),e}(m);function F(t){return t.charAt(0).toUpperCase()+t.slice(1)}var T=function(){function t(e){(0,a.Z)(this,t),this.options=e,this.whitelist=this.options.supportedLngs||!1,this.supportedLngs=this.options.supportedLngs||!1,this.logger=f.create("languageUtils")}return(0,s.Z)(t,[{key:"getScriptPartFromCode",value:function(t){if(!t||t.indexOf("-")<0)return null;var e=t.split("-");return 2===e.length?null:(e.pop(),"x"===e[e.length-1].toLowerCase()?null:this.formatLanguageCode(e.join("-")))}},{key:"getLanguagePartFromCode",value:function(t){if(!t||t.indexOf("-")<0)return t;var e=t.split("-");return this.formatLanguageCode(e[0])}},{key:"formatLanguageCode",value:function(t){if("string"==typeof t&&t.indexOf("-")>-1){var e=["hans","hant","latn","cyrl","cans","mong","arab"],n=t.split("-");return this.options.lowerCaseLng?n=n.map((function(t){return t.toLowerCase()})):2===n.length?(n[0]=n[0].toLowerCase(),n[1]=n[1].toUpperCase(),e.indexOf(n[1].toLowerCase())>-1&&(n[1]=F(n[1].toLowerCase()))):3===n.length&&(n[0]=n[0].toLowerCase(),2===n[1].length&&(n[1]=n[1].toUpperCase()),"sgn"!==n[0]&&2===n[2].length&&(n[2]=n[2].toUpperCase()),e.indexOf(n[1].toLowerCase())>-1&&(n[1]=F(n[1].toLowerCase())),e.indexOf(n[2].toLowerCase())>-1&&(n[2]=F(n[2].toLowerCase()))),n.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}},{key:"isWhitelisted",value:function(t){return this.logger.deprecate("languageUtils.isWhitelisted",'function "isWhitelisted" will be renamed to "isSupportedCode" in the next major - please make sure to rename it\'s usage asap.'),this.isSupportedCode(t)}},{key:"isSupportedCode",value:function(t){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}},{key:"getBestMatchFromCodes",value:function(t){var e,n=this;return t?(t.forEach((function(t){if(!e){var o=n.formatLanguageCode(t);n.options.supportedLngs&&!n.isSupportedCode(o)||(e=o)}})),!e&&this.options.supportedLngs&&t.forEach((function(t){if(!e){var o=n.getLanguagePartFromCode(t);if(n.isSupportedCode(o))return e=o;e=n.options.supportedLngs.find((function(t){if(0===t.indexOf(o))return t}))}})),e||(e=this.getFallbackCodes(this.options.fallbackLng)[0]),e):null}},{key:"getFallbackCodes",value:function(t,e){if(!t)return[];if("function"==typeof t&&(t=t(e)),"string"==typeof t&&(t=[t]),"[object Array]"===Object.prototype.toString.apply(t))return t;if(!e)return t.default||[];var n=t[e];return n||(n=t[this.getScriptPartFromCode(e)]),n||(n=t[this.formatLanguageCode(e)]),n||(n=t[this.getLanguagePartFromCode(e)]),n||(n=t.default),n||[]}},{key:"toResolveHierarchy",value:function(t,e){var n=this,o=this.getFallbackCodes(e||this.options.fallbackLng||[],t),r=[],i=function(t){t&&(n.isSupportedCode(t)?r.push(t):n.logger.warn("rejecting language code not found in supportedLngs: ".concat(t)))};return"string"==typeof t&&t.indexOf("-")>-1?("languageOnly"!==this.options.load&&i(this.formatLanguageCode(t)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&i(this.getScriptPartFromCode(t)),"currentOnly"!==this.options.load&&i(this.getLanguagePartFromCode(t))):"string"==typeof t&&i(this.formatLanguageCode(t)),o.forEach((function(t){r.indexOf(t)<0&&i(n.formatLanguageCode(t))})),r}}]),t}(),j=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],D={1:function(t){return Number(t>1)},2:function(t){return Number(1!=t)},3:function(t){return 0},4:function(t){return Number(t%10==1&&t%100!=11?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2)},5:function(t){return Number(0==t?0:1==t?1:2==t?2:t%100>=3&&t%100<=10?3:t%100>=11?4:5)},6:function(t){return Number(1==t?0:t>=2&&t<=4?1:2)},7:function(t){return Number(1==t?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2)},8:function(t){return Number(1==t?0:2==t?1:8!=t&&11!=t?2:3)},9:function(t){return Number(t>=2)},10:function(t){return Number(1==t?0:2==t?1:t<7?2:t<11?3:4)},11:function(t){return Number(1==t||11==t?0:2==t||12==t?1:t>2&&t<20?2:3)},12:function(t){return Number(t%10!=1||t%100==11)},13:function(t){return Number(0!==t)},14:function(t){return Number(1==t?0:2==t?1:3==t?2:3)},15:function(t){return Number(t%10==1&&t%100!=11?0:t%10>=2&&(t%100<10||t%100>=20)?1:2)},16:function(t){return Number(t%10==1&&t%100!=11?0:0!==t?1:2)},17:function(t){return Number(1==t||t%10==1&&t%100!=11?0:1)},18:function(t){return Number(0==t?0:1==t?1:2)},19:function(t){return Number(1==t?0:0==t||t%100>1&&t%100<11?1:t%100>10&&t%100<20?2:3)},20:function(t){return Number(1==t?0:0==t||t%100>0&&t%100<20?1:2)},21:function(t){return Number(t%100==1?1:t%100==2?2:t%100==3||t%100==4?3:0)},22:function(t){return Number(1==t?0:2==t?1:(t<0||t>10)&&t%10==0?2:3)}};function I(){var t={};return j.forEach((function(e){e.lngs.forEach((function(n){t[n]={numbers:e.nr,plurals:D[e.fc]}}))})),t}var A=function(){function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};(0,a.Z)(this,t),this.languageUtils=e,this.options=n,this.logger=f.create("pluralResolver"),this.rules=I()}return(0,s.Z)(t,[{key:"addRule",value:function(t,e){this.rules[t]=e}},{key:"getRule",value:function(t){return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}},{key:"needsPlural",value:function(t){var e=this.getRule(t);return e&&e.numbers.length>1}},{key:"getPluralFormsOfKey",value:function(t,e){return this.getSuffixes(t).map((function(t){return e+t}))}},{key:"getSuffixes",value:function(t){var e=this,n=this.getRule(t);return n?n.numbers.map((function(n){return e.getSuffix(t,n)})):[]}},{key:"getSuffix",value:function(t,e){var n=this,o=this.getRule(t);if(o){var r=o.noAbs?o.plurals(e):o.plurals(Math.abs(e)),i=o.numbers[r];this.options.simplifyPluralSuffix&&2===o.numbers.length&&1===o.numbers[0]&&(2===i?i="plural":1===i&&(i=""));var a=function(){return n.options.prepend&&i.toString()?n.options.prepend+i.toString():i.toString()};return"v1"===this.options.compatibilityJSON?1===i?"":"number"==typeof i?"_plural_".concat(i.toString()):a():"v2"===this.options.compatibilityJSON||this.options.simplifyPluralSuffix&&2===o.numbers.length&&1===o.numbers[0]?a():this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString()}return this.logger.warn("no plural rule found for: ".concat(t)),""}}]),t}(),U=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,a.Z)(this,t),this.logger=f.create("interpolator"),this.options=e,this.format=e.interpolation&&e.interpolation.format||function(t){return t},this.init(e)}return(0,s.Z)(t,[{key:"init",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});var e=t.interpolation;this.escape=void 0!==e.escape?e.escape:x,this.escapeValue=void 0===e.escapeValue||e.escapeValue,this.useRawValueToEscape=void 0!==e.useRawValueToEscape&&e.useRawValueToEscape,this.prefix=e.prefix?E(e.prefix):e.prefixEscaped||"{{",this.suffix=e.suffix?E(e.suffix):e.suffixEscaped||"}}",this.formatSeparator=e.formatSeparator?e.formatSeparator:e.formatSeparator||",",this.unescapePrefix=e.unescapeSuffix?"":e.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":e.unescapeSuffix||"",this.nestingPrefix=e.nestingPrefix?E(e.nestingPrefix):e.nestingPrefixEscaped||E("$t("),this.nestingSuffix=e.nestingSuffix?E(e.nestingSuffix):e.nestingSuffixEscaped||E(")"),this.nestingOptionsSeparator=e.nestingOptionsSeparator?e.nestingOptionsSeparator:e.nestingOptionsSeparator||",",this.maxReplaces=e.maxReplaces?e.maxReplaces:1e3,this.alwaysFormat=void 0!==e.alwaysFormat&&e.alwaysFormat,this.resetRegExp()}},{key:"reset",value:function(){this.options&&this.init(this.options)}},{key:"resetRegExp",value:function(){var t="".concat(this.prefix,"(.+?)").concat(this.suffix);this.regexp=new RegExp(t,"g");var e="".concat(this.prefix).concat(this.unescapePrefix,"(.+?)").concat(this.unescapeSuffix).concat(this.suffix);this.regexpUnescape=new RegExp(e,"g");var n="".concat(this.nestingPrefix,"(.+?)").concat(this.nestingSuffix);this.nestingRegexp=new RegExp(n,"g")}},{key:"interpolate",value:function(t,e,n,o){var r,a,s,u=this,c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function l(t){return t.replace(/\$/g,"$$$$")}var d=function(t){if(t.indexOf(u.formatSeparator)<0){var r=M(e,c,t);return u.alwaysFormat?u.format(r,void 0,n,i({},o,e,{interpolationkey:t})):r}var a=t.split(u.formatSeparator),s=a.shift().trim(),l=a.join(u.formatSeparator).trim();return u.format(M(e,c,s),l,n,i({},o,e,{interpolationkey:s}))};this.resetRegExp();var p=o&&o.missingInterpolationHandler||this.options.missingInterpolationHandler,h=o&&o.interpolation&&o.interpolation.skipOnVariables||this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:function(t){return l(t)}},{regex:this.regexp,safeValue:function(t){return u.escapeValue?l(u.escape(t)):l(t)}}].forEach((function(e){for(s=0;r=e.regex.exec(t);){if(void 0===(a=d(r[1].trim())))if("function"==typeof p){var n=p(t,r,o);a="string"==typeof n?n:""}else{if(h){a=r[0];continue}u.logger.warn("missed to pass in variable ".concat(r[1]," for interpolating ").concat(t)),a=""}else"string"==typeof a||u.useRawValueToEscape||(a=w(a));var i=e.safeValue(a);if(t=t.replace(r[0],i),h?(e.regex.lastIndex+=i.length,e.regex.lastIndex-=r[0].length):e.regex.lastIndex=0,++s>=u.maxReplaces)break}})),t}},{key:"nest",value:function(t,e){var n,o,r=this,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=i({},a);function u(t,e){var n=this.nestingOptionsSeparator;if(t.indexOf(n)<0)return t;var o=t.split(new RegExp("".concat(n,"[ ]*{"))),r="{".concat(o[1]);t=o[0],r=(r=this.interpolate(r,s)).replace(/'/g,'"');try{s=JSON.parse(r),e&&(s=i({},e,s))}catch(e){return this.logger.warn("failed parsing options string in nesting for key ".concat(t),e),"".concat(t).concat(n).concat(r)}return delete s.defaultValue,t}for(s.applyPostProcessor=!1,delete s.defaultValue;n=this.nestingRegexp.exec(t);){var c=[],l=!1;if(-1!==n[0].indexOf(this.formatSeparator)&&!/{.*}/.test(n[1])){var d=n[1].split(this.formatSeparator).map((function(t){return t.trim()}));n[1]=d.shift(),c=d,l=!0}if((o=e(u.call(this,n[1].trim(),s),s))&&n[0]===t&&"string"!=typeof o)return o;"string"!=typeof o&&(o=w(o)),o||(this.logger.warn("missed to resolve ".concat(n[1]," for nesting ").concat(t)),o=""),l&&(o=c.reduce((function(t,e){return r.format(t,e,a.lng,i({},a,{interpolationkey:n[1].trim()}))}),o.trim())),t=t.replace(n[0],o),this.regexp.lastIndex=0}return t}}]),t}(),W=function(t){function e(t,n,o){var r,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return(0,a.Z)(this,e),r=c(this,l(e).call(this)),_&&m.call(u(r)),r.backend=t,r.store=n,r.services=o,r.languageUtils=o.languageUtils,r.options=i,r.logger=f.create("backendConnector"),r.state={},r.queue=[],r.backend&&r.backend.init&&r.backend.init(o,i.backend,i),r}return p(e,t),(0,s.Z)(e,[{key:"queueLoad",value:function(t,e,n,o){var r=this,i=[],a=[],s=[],u=[];return t.forEach((function(t){var o=!0;e.forEach((function(e){var s="".concat(t,"|").concat(e);!n.reload&&r.store.hasResourceBundle(t,e)?r.state[s]=2:r.state[s]<0||(1===r.state[s]?a.indexOf(s)<0&&a.push(s):(r.state[s]=1,o=!1,a.indexOf(s)<0&&a.push(s),i.indexOf(s)<0&&i.push(s),u.indexOf(e)<0&&u.push(e)))})),o||s.push(t)})),(i.length||a.length)&&this.queue.push({pending:a,loaded:{},errors:[],callback:o}),{toLoad:i,pending:a,toLoadLanguages:s,toLoadNamespaces:u}}},{key:"loaded",value:function(t,e,n){var o=t.split("|"),r=o[0],i=o[1];e&&this.emit("failedLoading",r,i,e),n&&this.store.addResourceBundle(r,i,n),this.state[t]=e?-1:2;var a={};this.queue.forEach((function(n){var o,s,u,c,l;o=n.loaded,s=i,(c=(u=y(o,[r],Object)).obj)[l=u.k]=c[l]||[],c[l].push(s),function(t,e){for(var n=t.indexOf(e);-1!==n;)t.splice(n,1),n=t.indexOf(e)}(n.pending,t),e&&n.errors.push(e),0!==n.pending.length||n.done||(Object.keys(n.loaded).forEach((function(t){a[t]||(a[t]=[]),n.loaded[t].length&&n.loaded[t].forEach((function(e){a[t].indexOf(e)<0&&a[t].push(e)}))})),n.done=!0,n.errors.length?n.callback(n.errors):n.callback())})),this.emit("loaded",a),this.queue=this.queue.filter((function(t){return!t.done}))}},{key:"read",value:function(t,e,n){var o=this,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:350,a=arguments.length>5?arguments[5]:void 0;return t.length?this.backend[n](t,e,(function(s,u){s&&u&&r<5?setTimeout((function(){o.read.call(o,t,e,n,r+1,2*i,a)}),i):a(s,u)})):a(null,{})}},{key:"prepareLoading",value:function(t,e){var n=this,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),r&&r();"string"==typeof t&&(t=this.languageUtils.toResolveHierarchy(t)),"string"==typeof e&&(e=[e]);var i=this.queueLoad(t,e,o,r);if(!i.toLoad.length)return i.pending.length||r(),null;i.toLoad.forEach((function(t){n.loadOne(t)}))}},{key:"load",value:function(t,e,n){this.prepareLoading(t,e,{},n)}},{key:"reload",value:function(t,e,n){this.prepareLoading(t,e,{reload:!0},n)}},{key:"loadOne",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",o=t.split("|"),r=o[0],i=o[1];this.read(r,i,"read",void 0,void 0,(function(o,a){o&&e.logger.warn("".concat(n,"loading namespace ").concat(i," for language ").concat(r," failed"),o),!o&&a&&e.logger.log("".concat(n,"loaded namespace ").concat(i," for language ").concat(r),a),e.loaded(t,o,a)}))}},{key:"saveMissing",value:function(t,e,n,o,r){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(e)?this.logger.warn('did not save key "'.concat(n,'" as the namespace "').concat(e,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"):null!=n&&""!==n&&(this.backend&&this.backend.create&&this.backend.create(t,e,n,o,null,i({},a,{isUpdate:r})),t&&t[0]&&this.store.addResource(t[0],e,n,o))}}]),e}(m);function G(){return{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,whitelist:!1,nonExplicitWhitelist:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!0,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(t){var e={};if("object"===o(t[1])&&(e=t[1]),"string"==typeof t[1]&&(e.defaultValue=t[1]),"string"==typeof t[2]&&(e.tDescription=t[2]),"object"===o(t[2])||"object"===o(t[3])){var n=t[3]||t[2];Object.keys(n).forEach((function(t){e[t]=n[t]}))}return e},interpolation:{escapeValue:!0,format:function(t,e,n,o){return t},prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!1}}}function z(t){return"string"==typeof t.ns&&(t.ns=[t.ns]),"string"==typeof t.fallbackLng&&(t.fallbackLng=[t.fallbackLng]),"string"==typeof t.fallbackNS&&(t.fallbackNS=[t.fallbackNS]),t.whitelist&&(t.whitelist&&t.whitelist.indexOf("cimode")<0&&(t.whitelist=t.whitelist.concat(["cimode"])),t.supportedLngs=t.whitelist),t.nonExplicitWhitelist&&(t.nonExplicitSupportedLngs=t.nonExplicitWhitelist),t.supportedLngs&&t.supportedLngs.indexOf("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t}function H(){}var V=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=arguments.length>1?arguments[1]:void 0;if((0,a.Z)(this,e),t=c(this,l(e).call(this)),_&&m.call(u(t)),t.options=z(n),t.services={},t.logger=f,t.modules={external:[]},o&&!t.isInitialized&&!n.isClone){if(!t.options.initImmediate)return t.init(n,o),c(t,u(t));setTimeout((function(){t.init(n,o)}),0)}return t}return p(e,t),(0,s.Z)(e,[{key:"init",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;function o(t){return t?"function"==typeof t?new t:t:null}if("function"==typeof e&&(n=e,e={}),e.whitelist&&!e.supportedLngs&&this.logger.deprecate("whitelist",'option "whitelist" will be renamed to "supportedLngs" in the next major - please make sure to rename this option asap.'),e.nonExplicitWhitelist&&!e.nonExplicitSupportedLngs&&this.logger.deprecate("whitelist",'options "nonExplicitWhitelist" will be renamed to "nonExplicitSupportedLngs" in the next major - please make sure to rename this option asap.'),this.options=i({},G(),this.options,z(e)),this.format=this.options.interpolation.format,n||(n=H),!this.options.isClone){this.modules.logger?f.init(o(this.modules.logger),this.options):f.init(null,this.options);var r=new T(this.options);this.store=new O(this.options.resources,this.options);var a=this.services;a.logger=f,a.resourceStore=this.store,a.languageUtils=r,a.pluralResolver=new A(r,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),a.interpolator=new U(this.options),a.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},a.backendConnector=new W(o(this.modules.backend),a.resourceStore,a,this.options),a.backendConnector.on("*",(function(e){for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r1?n-1:0),r=1;r0&&"dev"!==s[0]&&(this.options.lng=s[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");var u=["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"];u.forEach((function(e){t[e]=function(){var n;return(n=t.store)[e].apply(n,arguments)}}));var c=["addResource","addResources","addResourceBundle","removeResourceBundle"];c.forEach((function(e){t[e]=function(){var n;return(n=t.store)[e].apply(n,arguments),t}}));var l=v(),d=function(){var e=function(e,o){t.isInitialized&&!t.initializedStoreOnce&&t.logger.warn("init: i18next is already initialized. You should call init just once!"),t.isInitialized=!0,t.options.isClone||t.logger.log("initialized",t.options),t.emit("initialized",t.options),l.resolve(o),n(e,o)};if(t.languages&&"v1"!==t.options.compatibilityAPI&&!t.isInitialized)return e(null,t.t.bind(t));t.changeLanguage(t.options.lng,e)};return this.options.resources||!this.options.initImmediate?d():setTimeout(d,0),l}},{key:"loadResources",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:H,o=n,r="string"==typeof t?t:this.language;if("function"==typeof t&&(o=t),!this.options.resources||this.options.partialBundledLanguages){if(r&&"cimode"===r.toLowerCase())return o();var i=[],a=function(t){t&&e.services.languageUtils.toResolveHierarchy(t).forEach((function(t){i.indexOf(t)<0&&i.push(t)}))};if(r)a(r);else{var s=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);s.forEach((function(t){return a(t)}))}this.options.preload&&this.options.preload.forEach((function(t){return a(t)})),this.services.backendConnector.load(i,this.options.ns,o)}else o(null)}},{key:"reloadResources",value:function(t,e,n){var o=v();return t||(t=this.languages),e||(e=this.options.ns),n||(n=H),this.services.backendConnector.reload(t,e,(function(t){o.resolve(),n(t)})),o}},{key:"use",value:function(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===t.type&&(this.modules.backend=t),("logger"===t.type||t.log&&t.warn&&t.error)&&(this.modules.logger=t),"languageDetector"===t.type&&(this.modules.languageDetector=t),"i18nFormat"===t.type&&(this.modules.i18nFormat=t),"postProcessor"===t.type&&P.addPostProcessor(t),"3rdParty"===t.type&&this.modules.external.push(t),this}},{key:"changeLanguage",value:function(t,e){var n=this;this.isLanguageChangingTo=t;var o=v();this.emit("languageChanging",t);var r=function(r){t||r||!n.services.languageDetector||(r=[]);var i="string"==typeof r?r:n.services.languageUtils.getBestMatchFromCodes(r);i&&(n.language||(n.language=i,n.languages=n.services.languageUtils.toResolveHierarchy(i)),n.translator.language||n.translator.changeLanguage(i),n.services.languageDetector&&n.services.languageDetector.cacheUserLanguage(i)),n.loadResources(i,(function(t){!function(t,r){r?(n.language=r,n.languages=n.services.languageUtils.toResolveHierarchy(r),n.translator.changeLanguage(r),n.isLanguageChangingTo=void 0,n.emit("languageChanged",r),n.logger.log("languageChanged",r)):n.isLanguageChangingTo=void 0,o.resolve((function(){return n.t.apply(n,arguments)})),e&&e(t,(function(){return n.t.apply(n,arguments)}))}(t,i)}))};return t||!this.services.languageDetector||this.services.languageDetector.async?!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect(r):r(t):r(this.services.languageDetector.detect()),o}},{key:"getFixedT",value:function(t,e,n){var r=this,a=function t(e,a){var s;if("object"!==o(a)){for(var u=arguments.length,c=new Array(u>2?u-2:0),l=2;l1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;var o=this.languages[0],r=!!this.options&&this.options.fallbackLng,i=this.languages[this.languages.length-1];if("cimode"===o.toLowerCase())return!0;var a=function(t,n){var o=e.services.backendConnector.state["".concat(t,"|").concat(n)];return-1===o||2===o};if(n.precheck){var s=n.precheck(this,a);if(void 0!==s)return s}return!!this.hasResourceBundle(o,t)||!this.services.backendConnector.backend||!(!a(o,t)||r&&!a(i,t))}},{key:"loadNamespaces",value:function(t,e){var n=this,o=v();return this.options.ns?("string"==typeof t&&(t=[t]),t.forEach((function(t){n.options.ns.indexOf(t)<0&&n.options.ns.push(t)})),this.loadResources((function(t){o.resolve(),e&&e(t)})),o):(e&&e(),Promise.resolve())}},{key:"loadLanguages",value:function(t,e){var n=v();"string"==typeof t&&(t=[t]);var o=this.options.preload||[],r=t.filter((function(t){return o.indexOf(t)<0}));return r.length?(this.options.preload=o.concat(r),this.loadResources((function(t){n.resolve(),e&&e(t)})),n):(e&&e(),Promise.resolve())}},{key:"dir",value:function(t){return t||(t=this.languages&&this.languages.length>0?this.languages[0]:this.language),t?["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam"].indexOf(this.services.languageUtils.getLanguagePartFromCode(t))>=0?"rtl":"ltr":"rtl"}},{key:"createInstance",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return new e(t,n)}},{key:"cloneInstance",value:function(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:H,r=i({},this.options,n,{isClone:!0}),a=new e(r),s=["store","services","language"];return s.forEach((function(e){a[e]=t[e]})),a.services=i({},this.services),a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a.translator=new B(a.services,a.options),a.translator.on("*",(function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),o=1;o { }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + private _onMatchClick: MatchClickCallback = (match: Match): void => { }; + + /** + * @deprecated + * @param callback A callback to be called when a match is clicked. + */ + public set onMatchClicked(callback: MatchClickCallback) { + this._onMatchClick = callback; + } /** * Renders data generated with `brackets-manager.js`. If multiple stages are given, they will all be displayed. @@ -51,6 +61,9 @@ export class BracketsViewer { highlightParticipantOnHover: config?.highlightParticipantOnHover !== undefined ? config.highlightParticipantOnHover : true, }; + if (this.config.onMatchClick) + this._onMatchClick = this.config.onMatchClick; + this.participants = data.participants; data.participants.forEach(participant => this.participantRefs[participant.id] = []); @@ -99,7 +112,7 @@ export class BracketsViewer { * @param name Name of the locale. * @param locale Contents of the locale. */ - public addLocale(name: string, locale: Locale): void { + public addLocale(name: string, locale: Locale): void { lang.addLocale(name, locale); } @@ -392,7 +405,7 @@ export class BracketsViewer { */ private createMatch(match: Match, matchLocation?: BracketType, connection?: Connection, label?: string, originHint?: OriginHint, roundNumber?: number): HTMLElement { const matchContainer = dom.createMatchContainer(match.id, match.status); - const opponents = dom.createOpponentsContainer(() => this.onMatchClicked(match)); + const opponents = dom.createOpponentsContainer(() => this._onMatchClick(match)); if (match.status >= Status.Completed) originHint = undefined; diff --git a/src/types.d.ts b/src/types.d.ts index 8e9e7db..d2f469a 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -44,6 +44,11 @@ export type Side = 'opponent1' | 'opponent2'; * An optional config to provide to `brackets-viewer.js` */ export interface Config { + /** + * A callback to be called when a match is clicked. + */ + onMatchClick?: MatchClickCallback; + /** * An optional selector to select the root element. */ @@ -105,6 +110,11 @@ export type OriginHint = (position: number) => string; */ export type RoundName = (roundNumber: number, roundCount: number) => string; +/** + * A function called when a match is clicked. + */ +export type MatchClickCallback = (match: Match) => void; + /** * Contains the information about the connections of a match. */