UNPKG

brackets-viewer

Version:

A simple library to display tournament brackets (round-robin, single elimination, double elimination)

1 lines 181 kB
!function(){var t={7335:function(t,e,n){"use strict";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.createPopoverTitle=e.createTitle=void 0;const r=n(3886),o=n(1491);e.createTitle=function(t){const e=document.createElement("h1");return e.innerText=t,e},e.createPopoverTitle=function(t){const e=document.createElement("h4");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"),t&&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 r=document.createElement("section");return r.classList.add("group"),r.setAttribute("data-group-id",t.toString()),r.append(n),r},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 r=document.createElement("article");return r.classList.add("round"),r.setAttribute("data-round-id",t.toString()),r.append(n),r},e.createMatchContainer=function(t){const e=document.createElement("div");return e.classList.add("match"),t&&((0,r.isMatchGame)(t)?e.setAttribute("data-match-game-id",t.id.toString()):e.setAttribute("data-match-id",t.id.toString()),e.setAttribute("data-match-status",t.status.toString())),e},e.createMatchLabel=function(t,e,n){const r=document.createElement("span");return r.innerText=t||"",r.title=e,n&&r.addEventListener("click",n),r},e.createChildCountLabel=function(t,e){const n=document.createElement("span");return n.innerText=t,e&&n.addEventListener("click",e),n},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,o=(0,r.rankingHeader)(n),i=document.createElement("th");i.innerText=o.text,i.setAttribute("title",o.tooltip),e.append(i)}return e},e.setupHint=function(t,e){t.classList.add("hint"),t.innerText=e,t.title=e},e.setupBye=function(t){t.innerText=(0,o.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,o.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,o.t)("abbreviations.forfeit"):void 0===n.score&&(e.innerText=(0,o.t)("abbreviations.loss")))},e.addParticipantOrigin=function(t,e,n){const r=document.createElement("span");"before"===n?(r.innerText=`${e} `,t.prepend(r)):"after"===n&&(r.innerText=` (${e})`,t.append(r))},e.addParticipantImage=function(t,e){const n=document.createElement("img");n.src=e,t.prepend(n)},e.getBracketConnection=function(t,e,n,r,o,i){var a,s,u;const c={connectPrevious:!1,connectNext:!1};return"loser_bracket"===o?(c.connectPrevious=e>1&&(e%2==1?"square":"straight"),c.connectNext=e<n&&(e%2==0?"square":"straight")):(c.connectPrevious=e>1&&"square",c.connectNext=e<n?"square":!!i&&"straight"),t||2!==e||(("single_bracket"===o||"winner_bracket"===o)&&void 0===(null===(a=r.opponent1)||void 0===a?void 0:a.position)&&void 0===(null===(s=r.opponent2)||void 0===s?void 0:s.position)&&(c.connectPrevious=!1),"loser_bracket"===o&&void 0===(null===(u=r.opponent2)||void 0===u?void 0:u.position)&&(c.connectPrevious=!1)),c},e.getFinalConnection=function(t,e,n){return{connectPrevious:"grand_final"===t&&1===e&&"straight",connectNext:2===n&&1===e&&"straight"}},e.setupConnection=function(t,e,n){n.connectPrevious&&t.classList.add("connect-previous"),n.connectNext&&e.classList.add("connect-next"),"straight"===n.connectPrevious&&t.classList.add("straight"),"straight"===n.connectNext&&e.classList.add("straight")}},3886:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isMatchGame=e.isMatch=e.getRanking=e.rankingHeader=e.isMajorRound=e.getOriginAbbreviation=e.completeWithBlankMatches=e.findRoot=e.sortBy=e.splitByWithLeftovers=e.splitBy=void 0;const r=n(1491);function o(t,e,n,r){if(!n||null===n.id)return;const o=t[n.id]||{rank:0,id:0,played:0,wins:0,draws:0,losses:0,forfeits:0,scoreFor:0,scoreAgainst:0,scoreDifference:0,points:0};o.id=n.id,(n.forfeit||n.result)&&o.played++,"win"===n.result&&o.wins++,"draw"===n.result&&o.draws++,"loss"===n.result&&o.losses++,n.forfeit&&o.forfeits++,o.scoreFor+=n.score||0,o.scoreAgainst+=r&&r.score||0,o.scoreDifference=o.scoreFor-o.scoreAgainst,o.points=e(o),t[n.id]=o}function i(t){return"child_count"in t}e.splitBy=function(t,e){const n={};for(const r of t){const t=r[e];n[t]||(n[t]=[]),n[t].push(r)}return Object.values(n)},e.splitByWithLeftovers=function(t,e){var n;const r={};for(const o of t){const t=null!==(n=o[e])&&void 0!==n?n:"-1";r[t]||(r[t]=[]),r[t].push(o)}const o=[...Object.entries(r).filter((([t])=>"-1"!==t)).map((([t,e])=>e))];return o[-1]=r[-1],o},e.sortBy=function(t,e){return[...t].sort(((t,n)=>t[e]-n[e]))},e.findRoot=function(t){const e=document.querySelectorAll(t||".brackets-viewer");if(0===e.length)throw Error("Root not found. You must have at least one root element.");if(e.length>1)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 r=[];return"single_bracket"!==t&&"winner_bracket"!==t||(r=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&&(r=n.map((t=>{var e;return(null===(e=t.opponent2)||void 0===e?void 0:e.position)||null}))),0===r.filter((t=>null!==t)).length?{matches:e,fromToornament:!1}:{matches:r.map((t=>t&&e.find((e=>e.number===t))||null)),fromToornament:!0}},e.getOriginAbbreviation=function(t,e,n,o){return n=n||-1,e&&"loser_bracket"===t&&1===n||"single_bracket"===t||"winner_bracket"===t&&1===n?(0,r.t)("abbreviations.seed"):"loser_bracket"===t&&n%2==0&&"opponent1"===o?(0,r.t)("abbreviations.position"):null},e.isMajorRound=function(t){return 1===t||t%2==0},e.rankingHeader=function(t){return(0,r.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 r of t)o(n,e,r.opponent1,r.opponent2),o(n,e,r.opponent2,r.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)},e.isMatch=i,e.isMatchGame=function(t){return!i(t)}},1491:function(t,e,n){"use strict";var r=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.toI18nKey=e.t=e.addLocale=e.locales=void 0;const o=r(n(6073)),i=r(n(13)),a=n(7021),s=n(3886),u=r(n(9583)),c=r(n(8159));function l(t,e){return o.default.t(t,e)}function d(t){return t.replace("_","-")}e.locales={en:u.default,fr:c.default},o.default.use(i.default).init({fallbackLng:"en",debug:!1,resources:{en:{translation:e.locales.en},fr:{translation:e.locales.fr}}}),e.addLocale=async function(t,e){o.default.addResourceBundle(t,"translation",e,!0,!0),await o.default.changeLanguage()},e.t=l,e.toI18nKey=d,e.getOriginHint=function(t,e,n,r){if(1===t){if("single_bracket"===r)return t=>l("origin-hint.seed",{position:t});if("winner_bracket"===r)return t=>l("origin-hint.seed",{position:t});if("loser_bracket"===r&&n)return t=>l("origin-hint.seed",{position:t})}if((0,s.isMajorRound)(t)&&"loser_bracket"===r){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 r=Math.ceil((t+1)/2);return n?t=>l("origin-hint.winner-bracket",{round:r-1,position:t}):t=>l("origin-hint.winner-bracket",{round:r,position:t})}},e.getFinalOriginHint=function(t,e,n){return"single_elimination"===t?t=>l("origin-hint.consolation-final",{position:t}):"grand_final"===e?1===n?()=>l("origin-hint.grand-final"):void 0:t=>l(1===t?"origin-hint.double-elimination-consolation-final-opponent-1":"origin-hint.double-elimination-consolation-final-opponent-2")},e.getMatchLabel=function(t,e,n,r){if(void 0===e||void 0===n||void 0===r)return l("match-label.default",{matchNumber:t});const o=l("winner_bracket"===r?"match-label.winner-bracket":"loser_bracket"===r?"match-label.loser-bracket":"match-label.standard-bracket"),i=e===n-1,a=e===n;if("single_bracket"===r){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:o,matchNumber:t}):a?l("match-label.double-elimination-final",{matchPrefix:o}):l("match-label.double-elimination",{matchPrefix:o,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-${d(e)}`,{stage:t});default:return}},e.getRoundName=function({roundNumber:t,roundCount:e},n){return t===e?n("common.round-name-final"):n("common.round-name",{roundNumber:t})},e.getWinnerBracketRoundName=function({roundNumber:t,roundCount:e},n){return t===e?n("common.round-name-winner-bracket-final"):n("common.round-name-winner-bracket",{roundNumber:t})},e.getLoserBracketRoundName=function({roundNumber:t,roundCount:e},n){return t===e?n("common.round-name-loser-bracket-final"):n("common.round-name-loser-bracket",{roundNumber:t})}},825:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);o&&!("get"in o?!e.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),o=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)&&r(e,t,n);return o(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.BracketsViewer=void 0,n(1016);const a=n(7021),s=n(3886),u=i(n(7335)),c=i(n(1491)),l=n(9037);e.BracketsViewer=class{constructor(){this.participantRefs={},this.participants=[],this.participantImages=[],this.skipFirstRound=!1,this.alwaysConnectFirstRound=!1,this._onMatchClick=t=>{},this._onMatchLabelClick=t=>{}}getRoundName(t,e){var n,r;return(null===(r=(n=this.config).customRoundName)||void 0===r?void 0:r.call(n,t,c.t))||e(t,c.t)}set onMatchClicked(t){this._onMatchClick=t}async render(t,e){var n,r,o,i,a,u,c,l,d,p;if("string"==typeof t)throw Error("Using a CSS selector as the first argument is deprecated. Please look here: https://github.com/Drarig29/brackets-viewer.js");const f=document.createDocumentFragment();if(this.config={customRoundName:null==e?void 0:e.customRoundName,participantOriginPlacement:null!==(n=null==e?void 0:e.participantOriginPlacement)&&void 0!==n?n:"before",separatedChildCountLabel:null!==(r=null==e?void 0:e.separatedChildCountLabel)&&void 0!==r&&r,showSlotsOrigin:null===(o=null==e?void 0:e.showSlotsOrigin)||void 0===o||o,showLowerBracketSlotsOrigin:null===(i=null==e?void 0:e.showLowerBracketSlotsOrigin)||void 0===i||i,showPopoverOnMatchLabelClick:null===(a=null==e?void 0:e.showPopoverOnMatchLabelClick)||void 0===a||a,highlightParticipantOnHover:null===(u=null==e?void 0:e.highlightParticipantOnHover)||void 0===u||u,showRankingTable:null===(c=null==e?void 0:e.showRankingTable)||void 0===c||c},(null==e?void 0:e.onMatchClick)&&(this._onMatchClick=e.onMatchClick),(null==e?void 0:e.onMatchLabelClick)&&(this._onMatchLabelClick=e.onMatchLabelClick),!(null===(l=t.stages)||void 0===l?void 0:l.length))throw Error("The `data.stages` array is either empty or undefined");if(!(null===(d=t.participants)||void 0===d?void 0:d.length))throw Error("The `data.participants` array is either empty or undefined");if(!(null===(p=t.matches)||void 0===p?void 0:p.length))throw Error("The `data.matches` array is either empty or undefined");this.participants=t.participants,t.participants.forEach((t=>this.participantRefs[t.id]=[])),this.popover=document.createElement("div"),this.popover.setAttribute("popover","auto"),this.popover.addEventListener("toggle",(t=>{"closed"===t.newState&&this.clearPreviousPopoverSelections()})),f.append(this.popover),t.stages.forEach((e=>this.renderStage(f,{...t,stages:[e],matches:t.matches.filter((t=>t.stage_id===e.id)).map((n=>({...n,metadata:{stageType:e.type,games:t.matchGames.filter((t=>t.parent_id===n.id))}})))})));const h=(0,s.findRoot)(null==e?void 0:e.selector);(null==e?void 0:e.clear)&&(h.innerHTML=""),h.append(f)}updateMatch(t){var e,n,r,o,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===(r=null===(n=t.opponent1)||void 0===n?void 0:n.score)||void 0===r?void 0:r.toString());const c=s.querySelector(".participant:nth-of-type(2) .result");c&&(null===(o=t.opponent2)||void 0===o?void 0:o.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}async addLocale(t,e){await c.addLocale(t,e)}renderStage(t,e){var n;const r=e.stages[0];if(!(null===(n=e.matches)||void 0===n?void 0:n.length))throw Error(`No matches found for stage ${r.id}`);const o=(0,s.splitByWithLeftovers)(e.matches,"group_id");switch(this.stage=r,this.skipFirstRound=r.settings.skipFirstRound||!1,r.type){case"round_robin":this.renderRoundRobin(t,r,o);break;case"single_elimination":case"double_elimination":this.renderElimination(t,r,o);break;default:throw Error(`Unknown bracket type: ${r.type}`)}this.renderConsolationMatches(t,r,o)}renderRoundRobin(t,e,n){const r=u.createRoundRobinContainer(e.id);r.append(u.createTitle(e.name));let o=1;for(const t of n){const e=t[0].group_id,n=u.createGroupContainer(e,c.getGroupName(o++)),i=(0,s.splitBy)(t,"round_id").map((t=>(0,s.sortBy)(t,"number")));let a=1;for(const t of i){const e=t[0].round_id,r=this.getRoundName({roundNumber:a,roundCount:0,groupType:c.toI18nKey("round_robin")},c.getRoundName),o=u.createRoundContainer(e,r);for(const e of t)o.append(this.createMatch(e,!0));n.append(o),a++}this.config.showRankingTable&&n.append(this.createRanking(t)),r.append(n)}t.append(r)}renderElimination(t,e,n){const r=u.createEliminationContainer(e.id);r.append(u.createTitle(e.name)),"single_elimination"===e.type?this.renderSingleElimination(r,n):this.renderDoubleElimination(r,n),t.append(r)}renderConsolationMatches(t,e,n){const r=n[-1];if(!(null==r?void 0:r.length))return;const o=u.createBracketContainer(void 0,c.t("common.consolation")),i=u.createRoundsContainer();let a=0;for(const t of r)i.append(this.createMatch({...t,metadata:{label:c.t("match-label.default",{matchNumber:++a}),stageType:e.type,games:[]}},!0));o.append(i),t.append(o)}renderSingleElimination(t,e){const n=(0,s.splitBy)(e[0],"round_id").map((t=>(0,s.sortBy)(t,"number"))),{hasFinal:r,connectFinal:o,finalMatches:i}=this.getFinalInfoSingleElimination(e);this.renderBracket(t,n,c.getRoundName,"single_bracket",o),r&&this.renderFinal(t,"consolation_final",i)}renderDoubleElimination(t,e){const n=void 0!==e[1],r=(0,s.splitBy)(e[0],"round_id").map((t=>(0,s.sortBy)(t,"number"))),{hasFinal:o,connectFinal:i,grandFinalMatches:a,consolationFinalMatches:u}=this.getFinalInfoDoubleElimination(e);if(this.renderBracket(t,r,c.getWinnerBracketRoundName,"winner_bracket",i),n){const n=(0,s.splitBy)(e[1],"round_id").map((t=>(0,s.sortBy)(t,"number")));this.renderBracket(t,n,c.getLoserBracketRoundName,"loser_bracket")}o&&(this.renderFinal(t,"grand_final",a),this.renderFinal(t,"consolation_final",u))}getFinalInfoSingleElimination(t){var e;return{hasFinal:void 0!==t[1],connectFinal:!1,finalMatches:(0,s.sortBy)(null!==(e=t[1])&&void 0!==e?e:[],"number")}}getFinalInfoDoubleElimination(t){var e;const n=void 0!==t[2],r=(0,s.sortBy)(null!==(e=t[2])&&void 0!==e?e:[],"number"),o=r.filter((t=>1===t.number)),i=r.filter((t=>2===t.number));return{hasFinal:n,connectFinal:o.length>0,grandFinalMatches:o,consolationFinalMatches:i}}renderBracket(t,e,n,r,o){const i=e[0][0].group_id,a=e.length,d=u.createBracketContainer(i,c.getBracketName(this.stage,r)),p=u.createRoundsContainer(),{matches:f,fromToornament:h}=(0,s.completeWithBlankMatches)(r,e[0],e[1]);this.alwaysConnectFirstRound=!h;for(let t=0;t<e.length;t++){const i=e[t][0].round_id,s=t+1,d=this.getRoundName({roundNumber:s,roundCount:a,fractionOfFinal:l.helpers.getFractionOfFinal(s,a),groupType:c.toI18nKey(r)},n),g=u.createRoundContainer(i,d),m=h&&1===s?f:e[t];for(const t of m)g.append(t&&this.createBracketMatch({...t,metadata:{...t.metadata,roundNumber:s,roundCount:a,matchLocation:r,connectFinal:o}})||this.skipBracketMatch());p.append(g)}d.append(p),t.append(d)}renderFinal(t,e,n){if(0===n.length)return;const r=t.querySelector(".bracket .rounds");if(!r)throw Error("Upper bracket not found.");const o=n[0].opponent1,i=null===(null==o?void 0:o.id)||"win"===(null==o?void 0:o.result)?1:2,a=n.slice(0,i),s=a.length,l=({roundNumber:t,roundCount:n})=>c.getFinalMatchLabel(e,t,n);for(let t=0;t<a.length;t++){const n=t+1,o=this.getRoundName({roundNumber:n,roundCount:s,groupType:c.toI18nKey("final_group"),finalType:c.toI18nKey(e)},l),i={...a[t],metadata:{...a[t].metadata,roundNumber:n,roundCount:s,matchLocation:"final_group"}},d=u.createRoundContainer(i.round_id,o);d.append(this.createFinalMatch(e,i)),r.append(d)}}createRanking(t){const e=u.createTable(),n=(0,s.getRanking)(t);e.append(u.createRankingHeaders(n));for(const t of n)e.append(this.createRankingRow(t));return e}createRankingRow(t){const e=u.createRow(),n=0===t.played;for(const r in t){const o=r,i=t[o];if("id"===o){const t=this.participants.find((t=>t.id===i));if(void 0!==t){const n=u.createCell(t.name);this.setupMouseHover(t.id,n,!0),e.append(n);continue}}!n||"rank"!==o&&"points"!==o?e.append(u.createCell(i)):e.append(u.createCell("-"))}return e}createBracketMatch(t){const{roundNumber:e,roundCount:n,matchLocation:r,connectFinal:o}=t.metadata;if(void 0===e||void 0===n||void 0===r)throw Error(`The match's internal data is missing roundNumber, roundCount or matchLocation: ${JSON.stringify(t)}`);const i=u.getBracketConnection(this.alwaysConnectFirstRound,e,n,t,r,o),a=c.getMatchLabel(t.number,e,n,r),s=c.getOriginHint(e,n,this.skipFirstRound,r);return t.metadata.connection=i,t.metadata.label=a,t.metadata.originHint=s,this.createMatch(t,!0)}createFinalMatch(t,e){const{roundNumber:n,roundCount:r}=e.metadata;if(void 0===n||void 0===r)throw Error(`The match's internal data is missing roundNumber or roundCount: ${JSON.stringify(e)}`);const o=u.getFinalConnection(t,n,r),i=c.getFinalMatchLabel(t,n,r),a=c.getFinalOriginHint(e.metadata.stageType,t,n);return e.metadata.connection=o,e.metadata.label=i,e.metadata.originHint=a,this.createMatch(e,!0)}skipBracketMatch(){const t=u.createMatchContainer(),e=u.createOpponentsContainer(),n=this.createParticipant(null,!0),r=this.createParticipant(null,!0);return e.append(n,r),t.append(e),t.style.visibility="hidden",t}createMatch(t,e){const n=u.createMatchContainer(t),r=(0,s.isMatch)(t)?u.createOpponentsContainer((()=>this._onMatchClick(t))):u.createOpponentsContainer();if((0,s.isMatch)(t)&&t.status>=a.Status.Completed&&(t.metadata.originHint=void 0),(0,s.isMatch)(t)){const{originHint:n,matchLocation:o,roundNumber:i}=t.metadata,a=this.createParticipant(t.opponent1,e,"opponent1",n,o,i),s=this.createParticipant(t.opponent2,e,"opponent2",n,o,i);this.renderMatchLabel(r,t),r.append(a,s)}else{const n=this.createParticipant(t.opponent1,e,"opponent1"),o=this.createParticipant(t.opponent2,e,"opponent2");this.renderMatchLabel(r,t),r.append(n,o)}if(n.append(r),(0,s.isMatch)(t)){if(!t.metadata.connection)return n;u.setupConnection(r,n,t.metadata.connection)}return n}createParticipant(t,e,n,r,o,i){const a={participant:u.createParticipantContainer(t&&t.id),name:u.createNameContainer(),result:u.createResultContainer()};return null==t?u.setupBye(a.name):this.renderParticipant(a,t,n,r,o,i),a.participant.append(a.name,a.result),t&&null!==t.id&&this.setupMouseHover(t.id,a.participant,e),a.participant}renderParticipant(t,e,n,r,o,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,o,i)):this.renderHint(t.name,e,r,o),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){const{label:n}=e.metadata;if((0,s.isMatchGame)(e))return void t.append(u.createMatchLabel(n,c.getMatchStatus(e.status)));const r=n=>{n.stopPropagation(),this._onMatchLabelClick(e),e.child_count>0&&this.config.showPopoverOnMatchLabelClick&&(this.clearPreviousPopoverSelections(),t.classList.add("popover-selected"),this.showPopover(e))};if(this.config.separatedChildCountLabel)return t.append(u.createMatchLabel(n,c.getMatchStatus(e.status),r)),void(e.child_count>0&&t.append(u.createChildCountLabel(c.t("common.best-of-x",{x:e.child_count}),r)));if(e.child_count>0){const o=c.t("common.best-of-x",{x:e.child_count}),i=n?`${n}, ${o}`:o;t.append(u.createMatchLabel(i,c.getMatchStatus(e.status),r))}}showPopover(t){this.popover.innerText="";const{roundNumber:e,roundCount:n,matchLocation:r}=t.metadata,o=c.getMatchLabel(t.number,e,n,r),i=u.createPopoverTitle(o);this.popover.append(i);for(const e of t.metadata.games){const t=c.t("match-label.match-game",{gameNumber:e.number}),n=this.createMatch({...e,metadata:{label:t}},!1);this.popover.append(n)}try{this.popover.togglePopover()}catch{}}renderHint(t,e,n,r){void 0!==n&&void 0!==e.position&&this.config.showSlotsOrigin&&(this.config.showLowerBracketSlotsOrigin||"loser_bracket"!==r)&&u.setupHint(t,n(e.position))}renderParticipantOrigin(t,e,n,r,o){if(void 0===e.position||void 0===r)return;if(!this.config.participantOriginPlacement||"none"===this.config.participantOriginPlacement)return;if(!this.config.showSlotsOrigin)return;if(!this.config.showLowerBracketSlotsOrigin&&"loser_bracket"===r)return;const i=(0,s.getOriginAbbreviation)(r,this.skipFirstRound,o,n);if(!i)return;const a=`${i}${e.position}`;u.addParticipantOrigin(t,a,this.config.participantOriginPlacement)}setupMouseHover(t,e,n){if(!this.config.highlightParticipantOnHover)return;const r=t=>{e.addEventListener("mouseenter",(()=>{t.forEach((t=>t.classList.add("hover")))})),e.addEventListener("mouseleave",(()=>{t.forEach((t=>t.classList.remove("hover")))}))};if(!n)return void r([e]);const o=this.participantRefs[t];if(!o)throw Error(`The participant (id: ${t}) does not exist in the participants table.`);o.push(e),r(o)}clearPreviousPopoverSelections(){var t;null===(t=document.querySelector(".opponents.popover-selected"))||void 0===t||t.classList.remove("popover-selected")}}},945:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.BaseGetter=void 0;const r=n(4487);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 o=e[0],i=e.filter((t=>t.group_id===n.id));return[o,...i.filter((t=>r.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,r){return"loser_bracket"===e?this.getPreviousMatchesLB(t,n,r):"final_group"===e?this.getPreviousMatchesFinal(t,n,r):1===r?[]:this.getMatchesBeforeMajorRound(t,r)}async getPreviousMatchesFinal(t,e,n){return"single_elimination"===e.type?this.getPreviousMatchesFinalSingleElimination(t,e):this.getPreviousMatchesFinalDoubleElimination(t,n)}async getPreviousMatchesFinalSingleElimination(t,e){const n=await this.getUpperBracket(t.stage_id),o=r.getUpperBracketRoundCount(e.settings.size),i=await this.storage.selectFirst("round",{group_id:n.id,number:o-1});if(!i)throw Error("Semi finals round not found.");const a=await this.storage.select("match",{round_id:i.id});if(!a)throw Error("Error getting semi final matches.");return a}async getPreviousMatchesFinalDoubleElimination(t,e){if(e>1)return[await this.findMatch(t.group_id,e-1,1)];const n=await this.getUpperBracket(t.stage_id),r=await this.getLastRound(n.id),o=await this.storage.selectFirst("match",{round_id:r.id,number:1});if(!o)throw Error("Match not found.");const i=await this.getLoserBracket(t.stage_id);if(!i)throw Error("Loser bracket not found.");const a=await this.getLastRound(i.id),s=await this.storage.selectFirst("match",{round_id:a.id,number:1});if(!s)throw Error("Match not found.");return[o,s]}async getPreviousMatchesLB(t,e,n){if(e.settings.skipFirstRound&&1===n)return[];if(r.hasBye(t))return[];const o=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,o.id,a):n%2==0?this.getMatchesBeforeMinorRoundLB(t,o.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,r.getOriginPosition(t,"opponent1")),await this.findMatch(e,n,r.getOriginPosition(t,"opponent2"))]}async getMatchesBeforeMinorRoundLB(t,e,n,o){const i=r.getOriginPosition(t,"opponent1");return[await this.findMatch(e,o,i),await this.findMatch(t.group_id,n-1,t.number)]}async getNextMatches(t,e,n,r,o){switch(e){case"single_bracket":return this.getNextMatchesUpperBracket(t,n.type,r,o);case"winner_bracket":return this.getNextMatchesWB(t,n,r,o);case"loser_bracket":return this.getNextMatchesLB(t,n.type,r,o);case"final_group":return this.getNextMatchesFinal(t,r,o);default:throw Error("Unknown bracket kind.")}}async getNextMatchesWB(t,e,n,o){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=e.settings.size,c=r.getLoserOrdering(e.settings.seedOrdering,s),l=r.findLoserMatchNumber(u,s,t.number,c);return[...await this.getNextMatchesUpperBracket(t,e.type,n,o),await this.findMatch(i.id,s,l)]}async getNextMatchesUpperBracket(t,e,n,r){return"single_elimination"===e?this.getNextMatchesUpperBracketSingleElimination(t,e,n,r):"double_elimination"===e&&n===r?[await this.getFirstMatchFinal(t,e)]:[await this.getDiagonalMatch(t.group_id,n,t.number)]}async getNextMatchesUpperBracketSingleElimination(t,e,n,r){if(n===r-1){const r=await this.getFirstMatchFinal(t,e);return[await this.getDiagonalMatch(t.group_id,n,t.number),...r?[r]:[]]}return n===r?[]:[await this.getDiagonalMatch(t.group_id,n,t.number)]}async getNextMatchesLB(t,e,n,r){if(n===r){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});try{const e=await this.getUpperBracketFirstRound(t);return this.storage.select("match",{round_id:e.id})}catch{return[]}}async getUpperBracketFirstRound(t){const e=await this.storage.selectFirst("round",{stage_id:t,number:1},!1);if(!e)throw Error("Round not found.");return e}async getLastRound(t){const e=await this.storage.selectLast("round",{group_id:t},!1);if(!e)throw Error("Error getting rounds.");return e}async getFinalGroupId(t,e){const n="single_elimination"===e?2:3,r=await this.storage.selectFirst("group",{stage_id:t,number:n});return r?r.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,r.getDiagonalMatchNumber(n))}async getParallelMatch(t,e,n){return this.findMatch(t,e+1,n)}async findMatch(t,e,n){const r=await this.storage.selectFirst("round",{group_id:t,number:e});if(!r)throw Error("Round not found.");const o=await this.storage.selectFirst("match",{round_id:r.id,number:n});if(!o)throw Error("Match not found.");return o}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.")}}},4267:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.StageCreator=e.create=void 0;const r=n(2644),o=n(4487);e.create=async function(t){return new i(this.storage,t).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.enableByesInUpdate=!1,!this.stage.name)throw Error("You must provide a name for the stage.");if(void 0===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;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.id)throw Error("Something went wrong when creating the stage.");return await this.ensureSeedOrdering(t.id),t}setExisting(t,e){this.updateMode=!0,this.currentStageId=t,this.enableByesInUpdate=e}async roundRobin(){const t=await this.getRoundRobinGroups(),e=await this.createStage();for(let n=0;n<t.length;n++)await this.createRoundRobinGroup(e.id,n+1,t[n]);return e}async singleElimination(){var t,e;if(Array.isArray(null===(t=this.stage.settings)||void 0===t?void 0:t.seedOrdering)&&1!==(null===(e=this.stage.settings)||void 0===e?void 0:e.seedOrdering.length))throw Error("You must specify one seed ordering method.");const n=await this.getSlots(),o=await this.createStage(),i=this.getStandardBracketFirstRoundOrdering(),a=r.ordering[i](n),{losers:s}=await this.createStandardBracket(o.id,1,a);return await this.createConsolationFinal(o.id,s),o}async doubleElimination(){var t;if(this.stage.settings&&Array.isArray(this.stage.settings.seedOrdering)&&this.stage.settings.seedOrdering.length<1)throw Error("You must specify at least one seed ordering method.");const e=await this.getSlots(),n=await this.createStage(),o=this.getStandardBracketFirstRoundOrdering(),i=r.ordering[o](e);return(null===(t=this.stage.settings)||void 0===t?void 0:t.skipFirstRound)?await this.createDoubleEliminationSkipFirstRound(n.id,i):await this.createDoubleElimination(n.id,i),n}async createDoubleEliminationSkipFirstRound(t,e){var n;const{even:r,odd:i}=o.splitByParity(e),{losers:a,winner:s}=await this.createStandardBracket(t,1,r);if(o.isDoubleEliminationNecessary(null===(n=this.stage.settings)||void 0===n?void 0:n.size)){const e=await this.createLowerBracket(t,2,[i,...a]);await this.createGrandFinal(t,s,e)}}async createDoubleElimination(t,e){var n;const{losers:r,winner:i}=await this.createStandardBracket(t,1,e);if(o.isDoubleEliminationNecessary(null===(n=this.stage.settings)||void 0===n?void 0:n.size)){const e=await this.createLowerBracket(t,2,r);await this.createGrandFinal(t,i,e)}}async createRoundRobinGroup(t,e,n){var r;const i=await this.insertGroup({stage_id:t,number:e});if(-1===i)throw Error("Could not insert the group.");const a=o.makeRoundRobinMatches(n,null===(r=this.stage.settings)||void 0===r?void 0:r.roundRobinMode);for(let e=0;e<a.length;e++)await this.createRound(t,i,e+1,a[0].length,a[e])}async createStandardBracket(t,e,n){const r=o.getUpperBracketRoundCount(n.length),i=await this.insertGroup({stage_id:t,number:e});if(-1===i)throw Error("Could not insert the group.");let a=o.makePairs(n),s=1;const u=[];for(let e=r-1;e>=0;e--){const n=Math.pow(2,e);a=this.getCurrentDuels(a,n),u.push(a.map(o.byeLoser)),await this.createRound(t,i,s++,n,a)}return{losers:u,winner:o.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=o.getRoundPairCount(a);let u=0;const c=this.getMajorOrdering(a),l=r.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=o.makePairs(l),f=1;for(let e=0;e<s;e++){const r=Math.pow(2,s-e-1);p=this.getCurrentDuels(p,r,!0),await this.createRound(t,d,f++,r,p);const o=this.getMinorOrdering(a,e,s);p=this.getCurrentDuels(p,r,!1,n[u++],o),await this.createRound(t,d,f++,r,p)}return o.byeWinnerToGrandFinal(p[0])}async createUniqueMatchBracket(t,e,n){const r=await this.insertGroup({stage_id:t,number:e});if(-1===r)throw Error("Could not insert the group.");for(let e=0;e<n.length;e++)await this.createRound(t,r,e+1,1,[n[e]])}async createRound(t,e,n,r,o){const i=this.getMatchesChildCount(),a=await this.insertRound({number:n,stage_id:t,group_id:e});if(-1===a)throw Error("Could not insert the round.");for(let n=0;n<r;n++)await this.createMatch(t,e,a,n+1,o[n],i)}async createMatch(t,e,n,r,i,a){const s=o.toResultWithPosition(i[0]),u=o.toResultWithPosition(i[1]);if("round_robin"===this.stage.type&&null===s&&null===u)return;let c=null,l=o.getMatchStatus(i);if(this.updateMode){c=await this.storage.selectFirst("match",{round_id:n,number:r});const t=null==c?void 0:c.child_count;if(a=void 0===t?a:t,c){const t=o.getMatchStatus(c);t>l&&(l=t)}}const d=await this.insertMatch({number:r,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<a;e++)if(-1===await this.insertMatchGame({number:e+1,stage_id:t,parent_id:d,status:l,opponent1:o.toResult(i[0]),opponent2:o.toResult(i[1])}))throw Error("Could not insert the match game.")}getCurrentDuels(t,e,n,r,i){return void 0!==n&&!n||t.length!==e?void 0===n||n?o.transitionToMajor(t):o.transitionToMinor(t,r,i):t}async getSlots(t){var e;let n=this.stage.seedingIds||this.stage.seeding;const r=(null===(e=this.stage.settings)||void 0===e?void 0:e.size)||(null==n?void 0:n.length)||0;if(o.ensureValidSize(this.stage.type,r),r&&!n)return Array.from(Array(r),((t,e)=>({id:null,position:e+1})));if(!n)throw Error("Either size or seeding must be given.");return this.stage.settings={...this.stage.settings,size:r},o.ensureNoDuplicates(n),n=o.fixSeeding(n,r),"round_robin"!==this.stage.type&&this.stage.settings.balanceByes&&(n=o.balanceByes(n,this.stage.settings.size)),this.stage.seeding=n,void 0!==this.stage.seedingIds||o.isSeedingWithIds(n)?this.getSlotsUsingIds(n,t):this.getSlotsUsingNames(n,t)}async getSlotsUsingNames(t,e){const n=o.extractParticipantsFromSeeding(this.stage.tournamentId,t);if(!await this.registerParticipants(n))throw Error("Error registering the participants.");const r=await this.storage.select("participant",{tournament_id:this.stage.tournamentId});if(!r)throw Error("Error getting registered participant.");return o.mapParticipantsNamesToDatabase(t,r,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 o.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=>{var e;return null!==(e=t.number)&&void 0!==e?e:0}));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 r;if(!(null===(r=this.stage.settings)||void 0===r?void 0:r.seedOrdering))return this.seedOrdering.push(n),n;const o=this.stage.settings.seedOrdering[t];if(!o)return this.seedOrdering.push(n),n;if("elimination"===e&&o.match(/^groups\./))throw Error("You must specify a seed ordering method without a 'groups' prefix");if("groups"===e&&"natural"!==o&&!o.match(/^groups\./))throw Error("You must specify a seed ordering method with a 'groups' prefix");return o}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 o.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=r.ordering[s](u,this.stage.settings.groupCount);return o.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){var e;return this.getOrdering(1,"elimination",(null===(e=r.defaultMinorOrdering[t])||void 0===e?void 0:e[0])||"natural")}getMinorOrdering(t,e,n){var o;if(e!==n-1)return this.getOrdering(2+e,"elimination",(null===(o=r.defaultMinorOrdering[t])||void 0===o?void 0:o[1+e])||"natural")}async insertStage(t){let e=null;if(this.updateMode){if(e=await this.storage.select("stage",this.currentStageId),!e)throw Error("Stage not found.");const n={...e,...t,settings:{...e.settings,...t.settings}};if(!await this.storage.update("stage",this.currentStageId,n))throw Error("Could not update the stage.")}return 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=o.getUpdatedMatchResults(t,e,this.enableByesInUpdate);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=o.getUpdatedMatchResults(t,e,this.enableByesInUpdate);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={tournament_id:this.stage.tournamentId,name:this.stage.name,type:this.stage.type,number:t,settings:this.stage.settings||{}},n=await this.insertStage(e);if(-1===n)throw Error("Could not insert the stage.");return{...e,id:n}}async createConsolationFinal(t,e){var n;if(!(null===(n=this.stage.settings)||void 0===n?void 0:n.consolationFinal))return;const r=e[e.length-2];await this.createUniqueMatchBracket(t,2,[r])}async createGrandFinal(t,e,n){var r;const o=null===(r=this.stage.settings)||void 0===r?void 0:r.grandFinal;if("none"===o)return;const i=[[e,n]];"double"===o&&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 r=await this.storage.select("stage",t);if(!r)throw Error("Stage not found.");const o={...r,settings:{...r.settings,seedOrdering:this.seedOrdering}};if(!await this.storage.update("stage",t,o))throw Error("Could not update the stage.")}}e.StageCreator=i},3517:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.BaseUpdater=void 0;const r=n(7021),o=n(2644),i=n(4267),a=n(945),s=n(3576),u=n(4487);class c extends a.BaseGetter{async updateSeeding(t,{seeding:e,seedingIds:n}){var r,s;const u=await this.storage.select("stage",t);if(!u)throw Error("Stage not found.");const l=null!==(s=null===(r=n||e)||void 0===r?void 0:r.length)&&void 0!==s?s:0,d=new i.StageCreator(this.storage,{name:u.name,tournamentId:u.tournament_id,type:u.type,settings:{...u.settings,...0===l?{}:{size:l}},...n?{seedingIds:n}:{seeding:null!=e?e:void 0}});d.setExisting(t,!1);const p=a.BaseGetter.getSeedingOrdering(u.type,d),f=await d.getSlots(),h=await this.getSeedingMatches(u.id,u.type);if(!h)throw Error("Error getting matches associated to the seeding.");const g=o.ordering[p](f);c.assertCanUpdateSeeding(h,g),await d.run()}async confirmCurrentSeeding(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");const n=new s.Get(this.storage),r=await n.seeding(t),o=u.convertSlotsToSeeding(r.map(u.convertTBDtoBYE)),a=new i.StageCreator(this.storage,{name:e.name,tournamentId:e.tournament_id,type:e.type,settings:e.settings,seeding:o});a.setExisting(t,!0),await a.run()}async updateParentMatch(t,e){const n=await this.storage.select("match",t);if(!n)throw Error("Parent not found.");const r=await this.storage.select("match_game",{parent_id:t});if(!r)throw Error("No match games.");const o=u.getChildGamesResults(r),i=u.getParentMatchResults(n,o);u.setParentMatchCompleted(i,n.child_count,e),await this.updateMatch(n,i,!0)}static assertCanUpdateSeeding(t,e){var n,o;let i=0;for(const a of t){if(a.status===r.Status.Archived)throw Error("A match of round 1 is archived, which means round 2 was started.");const t=e[i++],s=e[i++];if(u.isMatchParticipantLocked(a)&&((null===(n=a.opponent1)||void 0===n?void 0:n.id)!==(null==t?void 0:t.id)||(null===(o=a.opponent2)||void 0===o?void 0:o.id)!==(null==s?void 0:s.id)))throw Error("A match is locked.")}}async updateRelatedMatches(t,e,n){const{roundNumber:r,roundCount:o}=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 s=u.getMatchLocation(i.type,a.number);e&&await this.updatePrevious(t,s,i,r),n&&await this.updateNext(t,s,i,r,o)}async updateMatch(t,e,n){if(!n&&u.isMatchUpdateLocked(t))throw Error("The match is locked.");const r=await this.storage.select("stage",t.stage_id);if(!r)throw Error("Stage not found.");const o=u.isRoundRobin(r),{statusChanged:i,resultChanged:a}=u.setMatchResults(t,e,o);await this.applyMatchUpdate(t),(i||a)&&(u.isRoundRobin(r)||await this.updateRelatedMatches(t,i,a))}async updateMatchGame(t,e){if(u.isMatchUpdateLocked(t))throw Error("The match game is locked.");const n=await this.storage.select("stage",t.stage_id);if(!n)throw Error("Stage not found.");const r=u.isRoundRobin(n);if(u.setMatchResults(t,e,r),!await this.storage.update("match_game",t.id,t))throw Error("Could not update the match game.");await this.updateParentMatch(t.parent_id,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:u.toResult(t.opponent1),opponent2:u.toResult(t.opponent2)};if((t.status<=r.Status.Ready||t.status===r.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,o){const i=await this.getPreviousMatches(t,e,n,o);0!==i.length&&(t.status>=r.Status.Running?await this.archiveMatches(i):await this.resetMatchesStatus(i))}async archiveMatches(t){for(const e of t)e.status!==r.Status.Archived&&(e.status=r.Status.Archived,await this.applyMatchUpdate(e))}async resetMatchesStatus(t){for(const e of t)e.status=u.getMatchStatus(e),await this.applyMatchUpdate(e)}async updateNext(t,e,n,o,i){const a=await this.getNextMatches(t,e,n,o,i);if(0===a.length)return void(t.status===r.Status.Completed&&await this.archiveMatches([t]));const s=u.getMatchResult(t),c=n.settings.skipFirstRound&&"winner_bracket"===e?o+1:o;s?await this.applyToNextMatches(u.setNextOpponent,t,e,c,i,a,s):await this.applyToNextMatches(u.resetNextOpponent,t,e,c,i,a)}async applyToNextMatches(t,e,n,r,o,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 s=u.getNextSide(e.number,r,o,n);if(i[0]&&(t(i[0