tods-competition-factory 2.2.15 → 2.2.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var iL=Object.defineProperty;var Zt=(t,e)=>{for(var r in e)iL(t,r,{get:e[r],enumerable:!0})};function Ba(){return"2.2.15"}var SA={};Zt(SA,{competitionGovernor:()=>NU,drawsGovernor:()=>CN,entriesGovernor:()=>LN,eventGovernor:()=>zN,generationGovernor:()=>eM,matchUpFormatGovernor:()=>_y,matchUpGovernor:()=>EM,mocksGovernor:()=>II,participantGovernor:()=>JM,policyGovernor:()=>iN,publishingGovernor:()=>aR,queryGovernor:()=>MN,reportGovernor:()=>cR,scheduleGovernor:()=>yR,scoreGovernor:()=>jg,tieFormatGovernor:()=>bR,tournamentGovernor:()=>HR,venueGovernor:()=>JR});var NU={};Zt(NU,{getLinkedTournamentIds:()=>su,getTournamentIds:()=>hp,linkTournaments:()=>AU,mutate:()=>PU,query:()=>DU,unlinkTournament:()=>UU,unlinkTournaments:()=>EU});var PU={};Zt(PU,{linkTournaments:()=>AU,unlinkTournament:()=>UU,unlinkTournaments:()=>EU});var ca="SINGLES",kt="SINGLES",Oi="DOUBLES",xt="DOUBLES",xr="TEAM",Yt="TEAM",aC={SINGLES_MATCHUP:ca,SINGLES:kt,DOUBLES_MATCHUP:Oi,DOUBLES:xt,TEAM_MATCHUP:xr,TEAM:Yt};var PI={[kt]:[kt,"S"],[xt]:[xt,"D"],[Yt]:[Yt,"T"],S:[kt,"S"],D:[xt,"D"],T:[Yt,"T"]};function le(t,e){return(t??0)-(e??0)}function mt(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function On(t){return isNaN(t)?!1:t&&(t&t-1)===0}function EA(t){if(!t.length)return;let e=[...t].sort(le),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function cC(t){if(!On(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Sm(t){return isNaN(t)?0:t%2&&t+1||t}function Tm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function te(t){return!isNaN(parseFloat(t))}function DI(t){let e=mt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function es(t){if(isNaN(t))return!1;for(;!On(t);)t++;return t}function po(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function It(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function uC(t=1,e=3,r=!0){let n=0;for(let o=0;o<e;o++)n+=Math.random()*(t/e);return r&&t>1?Math.round(n):n}function sL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function UA(t,e,r,n,o=2){let i=1-Math.random(),s=1-Math.random(),a=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s);return a=a/10+.5,a>1||a<0?a=UA(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=sL(a,n)),parseFloat(a.toFixed(o))}function wl(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function ut(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function pC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function hr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Ha(t){return It(t)?t:1/0}function Tr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function mC(t){return PA(Tr(t))}function PA(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function aL(t,e,r){return r.indexOf(t)===e}function NI(t){return t.filter(aL)}function Zr(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function yn(t){let e=Math.floor(Math.random()*t.length);return t[e]}function tt(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function mo(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function qt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function DA(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Fe(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function dC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function lC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Ee(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function NA(t,[e,...r]){return t.length?[t.slice(0,e),...NA(t.slice(e),[...r,e])]:[]}function fC(t){return t.reduce((e,r)=>{let n=e[e.length-1];return(!n||n[n.length-1]!==r-1)&&e.push([]),e[e.length-1].push(r),e},[])}function MI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function RI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Ll(t,e,r){return Array.isArray(t)?t.reduce((n,o,i)=>{let s=r?!!(Math.floor(i/e)%2):!1,a=i%e,c=s?e-1-a:a;return n[c]||(n[c]=[]),n[c].push(o),n},[]):[]}function gC(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return tt(r,n+1).filter(o=>!t.includes(o))}function Wr(t){return typeof t=="function"}function Vt(t){return typeof t=="string"}function ht(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function IC(t,e){if(!ht(t)||!ht(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o of r)if(t[o]!==e[o])return!1;return!0}function bI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var hC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function CI(t,e){if(t===void 0)return null;if(!ht(t)||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>CI(i))}:{[o]:e?n(t[o]):CI(t[o])}))}function MA(t){return Array.isArray(t)?t.length+t.map(MA).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>MA(t[e])).reduce((e,r)=>e+r,0):0}function SC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=MA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function Fc(t,e){return!Array.isArray(t)||!Vt(e)?!1:qt(t,PI[e]).length}var C={success:!0},RA="error",TC={SUCCESS:C,ERROR:RA};function vI({collectionValueProfiles:t,matchUpCount:e}){let r=[];if(!Array.isArray(t))return r.push(`collectionValueProfiles is not an array: ${t}`),{errors:r};if(t.length&&t.length!==e)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(let o of t){if(typeof o!="object")return r.push(`valueProfile is not type object: ${o}`),{errors:r};let{matchUpValue:i,collectionPosition:s}=o;if(typeof i!="number"||typeof s!="number"||s>e||s<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}let n=t.map(o=>o.collectionPosition);return n.length!==ut(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...C}}var vC={};Zt(vC,{addNotice:()=>dt,callListener:()=>Dm,createInstanceState:()=>LE,cycleMutationStatus:()=>pf,deepCopyEnabled:()=>uf,deleteNotice:()=>$I,deleteNotices:()=>ki,disableNotifications:()=>FE,enableNotifications:()=>cf,getDevContext:()=>Pr,getMethods:()=>mf,getNotices:()=>qI,getProvider:()=>KI,getTopics:()=>Lr,getTournamentId:()=>ns,getTournamentRecord:()=>df,getTournamentRecords:()=>Fo,globalLog:()=>VE,handleCaughtError:()=>ip,hasTopic:()=>np,removeTournamentRecord:()=>GE,setDeepCopy:()=>Wc,setDevContext:()=>Hc,setGlobalLog:()=>RC,setGlobalMethods:()=>CC,setGlobalSubscriptions:()=>FL,setMethods:()=>bC,setStateMethods:()=>BE,setStateProvider:()=>wL,setSubscriptions:()=>kL,setTournamentId:()=>op,setTournamentRecord:()=>kE,setTournamentRecords:()=>Nm,timeKeeper:()=>LL});var OI={message:"Chronological error; time violation.",code:"ANACHRONISM"},ym={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},CA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},_I={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},Lt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},q={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Wa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ua={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},pa={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},bA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},br={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Xo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},Fl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},kl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},ja={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},vA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},OA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},cL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Gl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ya={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},qu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},yC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Rs={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Cs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Am={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},$u={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},xI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},qa={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},sn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},_A={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},xA={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},wA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},LA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},FA={message:"Invalid action",code:"ERR_INVALID_ACTION"},wI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},kA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},GA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},VA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},Vl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},BA={message:"Existing round",code:"ERR_EXISTING_ROUND"},uL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Ur={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},wt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Bl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},mi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},HA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Wn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Ot={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},jr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},WA={message:"Event exists",code:"ERR_EXISTING_EVENT"},jA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},YA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Hl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},qA={message:"Missing stage",code:"ERR_MISSING_STAGE"},_i={message:"Invalid stage",code:"ERR_INVALID_STAGE"},$A={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},KA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},zA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},LI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},$a={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Wl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},ma={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Lo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},jl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Yl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},QA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},bs={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},ar={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},rs={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},xe={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Jn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Sr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},dr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},FI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Ku={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},pL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},XA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},kI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},JA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},GI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},mL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},kc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},dL={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},ql={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},lL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},$l={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},fL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},gL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},xi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},it={message:"Missing value",code:"ERR_MISSING_VALUE"},ZA={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},tE={message:"Missing date",code:"ERR_MISSING_DATE"},eE={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Em={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Kl={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},rE={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},je={message:"Invalid Date",code:"ERR_INVALID_DATE"},Eo={message:"Invalid time",code:"ERR_INVALID_TIME"},nE={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var VI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},oE={message:"Invalid score",code:"ERR_INVALID_SCORE"},Um={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var AC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},zl={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},iE={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},zu={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},BI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Pm={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},wi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},dn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},wr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},sE={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},An={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},aE={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Li={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Ka={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},ie={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},re={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},cE={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},IL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},uE={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Uo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},pE={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},mE={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},dE={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},vs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Qu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Ql={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Xl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},HI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},EC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},UC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},lE={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},fE={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},WI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},gE={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Jl={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},IE={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Zl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Gc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},hE={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Os={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},SE={message:"Court exists",code:"ERR_EXISTING_COURT"},TE={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Fi={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Jo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},yE={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},jI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},AE={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},EE={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},PC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},tf={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},UE={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},ef={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},rf={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Vc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},PE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},za={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},DE={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},_s={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},NE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Xu={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},ME={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},RE={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},lo={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Ju={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Bc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},V={message:"Invalid values",code:"ERR_INVALID_VALUES"},CE={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},nf={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},bE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Zu={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},of={message:"Value unchanged",code:"ABORT_UNCHANGED"},Ce={message:"Not found",code:"ERR_NOT_FOUND"},tp={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},vE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},sf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},OE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},_E={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},YI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},af={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Qa={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},xE={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},ep={message:"Scores present",code:"ERR_SCORES_PRESENT"},DC={ANACHRONISM:OI,CANNOT_CHANGE_WINNING_SIDE:Pm,CANNOT_MODIFY_TIEFORMAT:zl,CANNOT_MODIFY_PARTICIPANT_TYPE:iE,CANNOT_REMOVE_MAIN_STRUCTURE:CA,CANNOT_REMOVE_PARTICIPANTS:zu,CATEGORY_MISMATCH:BI,COURT_EXISTS:SE,COURT_NOT_FOUND:Os,DRAW_DEFINITION_NOT_FOUND:br,DRAW_ID_EXISTS:_A,DRAW_POSITION_ACTIVE:qu,DRAW_POSITION_ASSIGNED:ja,DRAW_POSITION_NOT_CLEARED:OA,DRAW_POSITION_NOT_FOUND:cL,DRAW_SIZE_MISMATCH:xI,DUPLICATE_ENTRY:ym,DUPLICATE_VALUE:CE,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:fE,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:lE,EVENT_EXISTS:WA,EVENT_NOT_FOUND:jr,EXISTING_DRAW_DEFINITIONS:bA,EXISTING_END_TIME:jI,EXISTING_FLIGHT:vE,EXISTING_MATCHUP_ID:_E,EXISTING_OUTCOME:OE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:vs,EXISTING_PARTICIPANT:Qu,EXISTING_POLICY_TYPE:GI,EXISTING_PROFILE:sf,EXISTING_ROUND:BA,EXISTING_STAGE:YI,EXISTING_STRUCTURE:af,INCOMPATIBLE_MATCHUP_STATUS:Wl,INCOMPLETE_SOURCE_STRUCTURE:Fl,INSUFFICIENT_DRAW_POSITIONS:Jl,INVALID_ACTION:FA,INVALID_ASSIGNMENT:wI,INVALID_BOOKINGS:Em,INVALID_CATEGORY:Bc,INVALID_COLLECTION_DEFINITION:RE,INVALID_CONFIGURATION:ME,INVALID_DATE_AVAILABILITY:Kl,INVALID_DATE:je,INVALID_DRAW_DEFINITION:pa,INVALID_DRAW_POSITION_FOR_SEEDING:kl,INVALID_DRAW_POSITION:Rs,INVALID_DRAW_SIZE:$u,INVALID_END_TIME:yE,INVALID_ENTRIES:YA,INVALID_EVENT_TYPE:Wn,INVALID_GAME_SCORES:VI,INVALID_GENDER:Ju,INVALID_MATCHUP_FORMAT:jl,INVALID_MATCHUP_STATUS:ma,INVALID_MATCHUP_STATUS_BYE:zA,INVALID_MATCHUP:dr,INVALID_OBJECT:lo,INVALID_PARTICIPANT_ID:dn,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:sE,INVALID_PARTICIPANT_SEEDING:xA,INVALID_PARTICIPANT_TYPE:An,INVALID_PARTICIPANT:wi,INVALID_POLICY_DEFINITION:JA,INVALID_RECORDS:_I,INVALID_SCALE_ITEM:za,INVALID_SEED_NUMBER:GA,INVALID_SEED_POSITION:VA,INVALID_SET_NUMBER:lL,INVALID_SIDE_NUMBER:ql,INVALID_SCORE:oE,INVALID_STAGE:_i,INVALID_START_TIME:EE,INVALID_STRUCTURE:Xo,INVALID_STOP_TIME:AE,INVALID_TIE_FORMAT:Lo,INVALID_TIME:Eo,INVALID_TIME_ITEM:tf,INVALID_TOURNAMENT_DATES:nE,INVALID_TOURNAMENT_RECORD:Wa,INVALID_VALUES:V,INVALID_WINNING_SIDE:Um,MATCHUP_NOT_FOUND:xe,METHOD_NOT_FOUND:Qa,MISSING_ASSIGNMENTS:Hl,MISSING_ASYNC_STATE_PROVIDER:UE,MISSING_AVOIDANCE_POLICY:XA,MISSING_BIRTH_DATE:ZA,MISSING_COLLECTION_DEFINITION:QA,MISSING_COURT_ID:xi,MISSING_COURTS_INFO:hE,MISSING_DATE_AVAILABILITY:rE,MISSING_DATE:tE,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:sn,MISSING_DRAW_POSITION:Cs,MISSING_DRAW_POSITIONS:Ya,MISSING_DRAW_SIZE:qa,MISSING_ENTRIES:jA,MISSING_EVENT:Ot,MISSING_MATCHUP_FORMAT:Yl,MISSING_MATCHUP_ID:ar,MISSING_MATCHUP_IDS:rs,MISSING_MATCHUP:Sr,MISSING_MATCHUPS:Jn,MISSING_PARTICIPANT_COUNT:pE,MISSING_PARTICIPANT_ID:ie,MISSING_PARTICIPANT_IDS:Uo,MISSING_PARTICIPANT_ROLE:aE,MISSING_PARTICIPANT:Li,MISSING_PARTICIPANTS:Ka,MISSING_PENALTY_ID:Zl,MISSING_PENALTY_TYPE:IE,MISSING_PERSON_DETAILS:dE,MISSING_POLICY_ATTRIBUTES:kI,MISSING_POLICY_DEFINITION:Ku,MISSING_POLICY_TYPE:FI,MISSING_POSITION_ASSIGNMENTS:KA,MISSING_ROUND_NUMBER:uL,MISSING_SCHEDULE:PE,MISSING_SCORING_POLICY:dL,MISSING_SEED_ASSIGNMENTS:kA,MISSING_SEEDCOUNT_THRESHOLDS:LA,MISSING_SEEDING_POLICY:pL,MISSING_SET_NUMBER:fL,MISSING_SET_OBJECT:$l,MISSING_SIDE_NUMBER:gL,MISSING_STAGE:qA,MISSING_STRUCTURE_ID:Ur,MISSING_STRUCTURE:mi,MISSING_STRUCTURES:Bl,MISSING_TARGET_LINK:Vl,MISSING_TIE_FORMAT:bs,MISSING_TIME_ITEM:ef,MISSING_TIME_ITEMS:rf,MISSING_TOURNAMENT_ID:ua,MISSING_TOURNAMENT_RECORD:q,MISSING_TOURNAMENT_RECORDS:Lt,MISSING_VALUE:it,MISSING_VENUE_ID:Jo,MODIFICATIONS_FAILED:DE,NO_CANDIDATES:Xu,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:gE,NO_MODIFICATIONS_APPLIED:_s,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:WI,NO_PARTICIPANT_REMOVED:uE,NO_VALID_ACTIONS:bE,NO_VALID_ATTRIBUTES:Zu,NO_VALID_DATES:eE,NOT_FOUND:Ce,NOT_IMPLEMENTED:tp,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Ql,PARTICIPANT_ID_EXISTS:cE,PARTICIPANT_NOT_CHECKED_IN:mE,PARTICIPANT_NOT_FOUND:re,PARTICIPANT_PAIR_EXISTS:IL,PENALTY_NOT_FOUND:Gc,POLICY_NOT_ATTACHED:mL,POLICY_NOT_FOUND:kc,SCHEDULE_NOT_CLEARED:vA,SCHEDULED_MATCHUPS:xE,SCORES_PRESENT:ep,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:wA,STAGE_SEQUENCE_LIMIT:$A,STRUCTURE_NOT_FOUND:wt,TEAM_NOT_FOUND:nf,UNABLE_TO_ASSIGN_COURT:NE,UNLINKED_STRUCTURES:HA,UNRECOGNIZED_DRAW_TYPE:Gl,UNRECOGNIZED_MATCHUP_FORMAT:$a,UNRECOGNIZED_MATCHUP_STATUS:LI,VALUE_UNCHANGED:of,VENUE_EXISTS:TE};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},wE={addNotice:RL,callListener:_L,cycleMutationStatus:ML,deleteNotice:vL,deleteNotices:bL,disableNotifications:hL,enableNotifications:SL,getMethods:rp,getNotices:CL,getTopics:OL,getTournamentId:NC,getTournamentRecord:TL,getTournamentRecords:yL,removeTournamentRecord:PL,setMethods:NL,setSubscriptions:DL,setTournamentId:EL,setTournamentRecord:AL,setTournamentRecords:UL,handleCaughtError:xL};function hL(){Ze.disableNotifications=!0}function SL(){Ze.disableNotifications=!1}function NC(){return Ze.tournamentId}function TL(t){return Ze.tournamentRecords[t]}function yL(){return Ze.tournamentRecords}function AL(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Wa}}function EL(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:q}:(Ze.tournamentId=void 0,{success:!0})}function UL(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function PL(t){if(typeof t!="string")return{error:V};if(!Ze.tournamentRecords[t])return{error:Ce};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function DL(t){return typeof t.subscriptions!="object"?{error:V}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ze.subscriptions[e]=t.subscriptions[e]:delete Ze.subscriptions[e]}),{...C})}function NL(t){return typeof t!="object"?{error:V}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...C})}function ML(){let t=Ze.modified;return Ze.modified=!1,t}function RL({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...C}}function rp(){return Ze.methods??{}}function CL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function bL(){Ze.notices=[]}function vL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function OL(){return{topics:Object.keys(Ze.subscriptions)}}function _L({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function xL({engineName:t,methodName:e,params:r,err:n}){let o;return typeof n=="string"?o=n.toUpperCase():n instanceof Error&&(o=n.message),console.log("ERROR",{tournamentId:NC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var be={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},an=wE,MC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function wL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(qt(Object.keys(t),MC).length!==MC.length)throw new Error("Global state provider is missing required methods");return an=t,{success:!0}}function LE(){if(an.createInstanceState){try{an.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:UE}}function Pr(t){return!t||typeof t!="object"?be.devContext??!1:typeof be.devContext!="object"?!1:Object.keys(t).every(e=>be.devContext?.[e]===t[e])&&be.devContext}function LL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(be.timers).filter(o=>o!=="default"||be.timers[o].startTime).map(o=>{let i=be.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:be.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=be.timers[e].state==="stopped"?0:(r-(be.timers[e]?.startTime??0))/1e3,o=be.timers[e].elapsedTime+n;return{state:be.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!be.timers[e]||t==="reset"){if(e==="allTimers")return be.timers={default:{elapsedTime:0}},!0;be.timers[e]={startTime:r,state:"active",elapsedTime:0}}return be.timers[e].elapsedTime||(be.timers[e].elapsedTime=0),t==="stop"&&be.timers[e].state!=="stopped"&&(be.timers[e].state="stopped")&&(be.timers[e].elapsedTime+=(r-(be.timers[e]?.startTime??0))/1e3),t==="start"&&(be.timers[e].startTime=r)&&(be.timers[e].state="active"),be.timers[e]}function RC(t){Wr(t)?be.globalLog=t:delete be.globalLog}function Hc(t){be.devContext=t}function FE(){an.disableNotifications()}function cf(){an.enableNotifications()}function Wc(t,e){typeof t=="boolean"&&(be.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(be.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(be.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(be.deepCopyAttributes.stringify=e.stringify),e.threshold&&(be.deepCopyAttributes.threshold=e.threshold))}function uf(){return{enabled:be.deepCopy,...be.deepCopyAttributes}}function FL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{be.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:it,info:"missing subscriptions"}}function kL(t){return t?.subscriptions?an.setSubscriptions({subscriptions:t.subscriptions}):{error:it,info:"missing subscriptions"}}function CC(t){return t?typeof t!="object"?{error:V}:(Object.keys(t).forEach(e=>{Wr(t[e])&&(be.globalMethods[e]=t[e])}),{...C}):{error:it,info:"missing method declarations"}}function bC(t){return t?typeof t!="object"?{error:V}:an.setMethods(t):{error:it,info:"missing method declarations"}}function pf(){return an.cycleMutationStatus()}function dt(t){if(typeof t?.topic!="string")return;let e=be.globalSubscriptions[t.topic];return an.addNotice(t,e)}function mf(){return{...be.globalMethods,...an.getMethods()}}function qI(t){return an.getNotices(t)}function $I({key:t,topic:e}){return an.deleteNotice({key:t,topic:e})}function ki(){return an.deleteNotices()}function Lr(){return an.getTopics()}function np(t){return Lr()?.topics?.includes(t)}async function Dm(t){return an.callListener(t,be.globalSubscriptions)}function ns(){return an.getTournamentId()}function df(t){return an.getTournamentRecord(t)}function Fo(){return an.getTournamentRecords()}function kE(t){return an.setTournamentRecord(t)}function Nm(t){return an.setTournamentRecords(t)}function op(t){return an.setTournamentId(t)}function GE(t){return an.removeTournamentRecord(t)}function KI(){return an}function ip({engineName:t,methodName:e,params:r,err:n}){let o=Wr(an.handleCaughtError)&&an.handleCaughtError||wE.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function VE(t,e){if(be.globalLog)try{be.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),RC()}else console.log(e,t)}function BE(t,e,r,n){if(!ht(t))return{error:V};te||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Wr(a[u])?i[u]=a[u]:ht(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?CC(i):bC(i),{methods:i}}function GL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function ot(t,e,r,n){if(typeof t!="object"||t===null)return t;uf()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=GL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>ot(c))}:{[a]:n?t[a]:ot(t[a])}))}function x({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,ot(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var Pn="ANY",Qt="MALE",yr="MIXED",os="OTHER",ne="FEMALE",Mm={ANY:Pn,MALE:Qt,FEMALE:ne,MIXED:yr,OTHER:os};var VL="MIXED events can not contain mixed singles or { gender: ANY } collections",BL="events with { gender: ANY } can not contain MIXED singles collections";function Rm(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[Qt,ne].includes(r)&&r!==o?x({result:{valid:!1,error:Ju},context:{gender:o},stack:e}):r===yr&&(o===Pn||o===yr&&n!==xt)?x({result:{error:Ju,valid:!1},info:VL,stack:e}):r===Pn&&o===yr&&n!==xt?x({result:{error:Ju,valid:!1},info:BL,stack:e}):{valid:!0}}var HL="normal",HE="timed",WL="final",lf="NOAD",Cm="SET",OC={S:HL,F:WL};function sp(t,e){if(ht(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return jL(t,e)}function ff(t){return!isNaN(Number(t))&&Number(t)}function wC(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function jL(t,e){let r=ff(t.bestOf)||void 0,n=ff(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return wC(t.setFormat);let i=o&&`${Cm}${o}`||"",s=_C(t.setFormat,e),a=s&&`S:${s}`||"",c=_C(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function _C(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return wC(t);if(t.tiebreakSet)return xC(t.tiebreakSet);let r=ff(t.setTo);if(r){let n=t.NoAD&&lf||"",o=xC(t.tiebreakFormat),i=o&&`/${o}`||"",s=ff(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function xC(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&ff(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?lf:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ye(t){if(Vt(t)){let e=t.startsWith("T")&&HE||t.startsWith(Cm)&&Cm||"";if(e===HE){let r=GC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===Cm)return YL(t)}}function YL(t){let e=t.split("-"),r=gf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&LC(e[1]),s=e&&LC(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=ot({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function LC(t){if(t?.[1]===":"){let e=t.split(":"),r=OC[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=FC(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return GC(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&VC(s[2])||!1,c=!s?.[2]||a,u=s?gf(s[1]):void 0,p=kC(n),m=p!==!1,d=m&&p||u,l=FC(n.split("/")[1]),f=l!==!1,g={setTo:u};return a&&(g.NoAD=!0),l?(g.tiebreakFormat=l,g.tiebreakAt=d):g.noTiebreak=!0,u&&c&&f&&m&&g||!1}}}function kC(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?gf(r[1]):r[1])||!1}function FC(t){if(t)if(t.startsWith("TB")){let e=kC(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&VC(r[2]),i=!r?.[2]||o,s=gf(n);if(s&&i){let a={tiebreakTo:s};return e&&typeof e=="string"&&!It(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}else return!1}else return!1}function GC(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=gf(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2],s=[void 0,"P","G"].includes(i);if(i&&!s){let a=e.match(/^(\d+)(@)([A-Za-z]+)$/)?.[3];return a?(o.modifier=a,o):void 0}return i&&(o.based=r[2]),o}function VC(t){return t&&t.indexOf(lf)>=0}function gf(t){return isNaN(Number(t))?0:Number(t)}function Dr({matchUpFormat:t}){if(!Vt(t)||t==="")return!1;let e=Ye(t),r=t.match(/-S:([1-9])+\/TB(\d{1,2})@?([1-9]?)*/),n=r?.[1],o=r?.[2],i=r?.[3],s=t.match(/-F:([1-9])+\/TB(\d{1,2})@?([1-9]?)*/),a=s?.[1],c=s?.[2],u=s?.[3];return sp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var bm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,zI=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Po=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))([ T](0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/,xs=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))?([ T]?(0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/;function vm(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Et(t.scheduledTime)),!e)return;let r=Xt(t.scheduledTime),n=Et(e);return n&&r&&(n+=`T${r}`),n}function BC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function jc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||xs.test(Ja(t,!0,!0)))}function Nr(t){return Xa(t)||bm.test(t)}function qL(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return $L(r,{displaySeconds:!1})}function $L(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(Zn).join(":")}var Sf=t=>{let e=If(t)||Xa(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${Zn(n)}-${Zn(e.getUTCDate())}`};function KL(t){let e=If(t)||Xa(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function jn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function QI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function zL(t){return QI(t).getTime()}function If(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function ws(t,e){if(!Nr(t)||!Nr(e))return[];let r=Et(t)+"T00:00",n=Et(e)+"T00:00",o=new Date(r),i=new Date(n),s=If(i)&&If(o)&&u(o,i),a=[],c=0;if(s){let p=o,m=p.getTime();for(;m<=i.getTime()&&c<300;)c+=1,a.push(new Date(p)),m=p.setDate(p.getDate()+1)}return a.map(p=>jn(p));function u(p,m){return p<=m}}var QL=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function Xa(t){return typeof t!="string"?!1:QL.test(t)}function JI(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function $t(t){let e=Xt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function HC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[Zn(e),Zn(r)].join(":")}function hf(t){return JI(t)?t.split(":").slice(0,2).map(Zn).join(":"):void 0}function Xt(t){return Xa(t)&&t.indexOf("T")>0?hf(t.split("T").reverse()[0]):hf(t)}function Et(t){return Xa(t)||Po.test(t)?t.split("T")[0]:void 0}function ap(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Et(r.toISOString())}function XI(t){t=typeof t!="string"?"00:00":t;let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:r.hours,1:r.minutes}=e.time.split(":")||[],r.ampm=e.ampm,isNaN(r.hours)||isNaN(r.minutes)||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function XL(t){let e=XI(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(Zn).join(":")}function JL(t){let e=XI(t);if(!(typeof e=="object"&&!Object.keys(e).length))return e.ampm?t:(e.hours>12?(e.hours-=12,e.ampm="PM"):e.hours==="12"?e.ampm="PM":(e.hours==="00"&&(e.hours="12"),e.ampm="AM"),e.hours?.[0]==="0"&&(e.hours=e.hours.slice(1)),`${e.hours||"12"}:${e.minutes||"00"} ${e.ampm}`)}function Ja(t,e,r){let n=Et(t),o=Xt(t),i=n?o:t;return t?e&&(n&&r&&t||XL(i))||JL(i):void 0}function ZI(t,e){let r=XI(t),n=XI(e);if(parseInt(r.hours)<parseInt(n.hours))return-1;if(parseInt(r.hours)>parseInt(n.hours))return 1;if(r.hours===n.hours){if(parseInt(r.minutes)<parseInt(n.minutes))return-1;if(parseInt(r.minutes)>parseInt(n.minutes))return 1}return 0}function th(t,e=7){let r=Et(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return jn(o)}function ZL(t){return th(t)}function tF(t,e,r,n=!1){let o=new Date(e,0,1+(t-1)*7),i=n?0:1;return o.setDate(o.getDate()+(i-o.getDay())),jn(o,r)}function WC(t,e,r){let n=new Date(t,0);return jn(new Date(n.setDate(e)),r)}function ke(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(Zn),o=QI(e).setHours(r,n,0,0);return QI(o)}function da(t,e,r=!0){let n=new Date(t),i=(new Date(e).getTime()-n.getTime())/1e3/60;return r?Math.abs(Math.round(i)):Math.round(i)}function Yr(t,e){let r=Xt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return Xt(Tf(ke(r),n).toISOString())}function Tf(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function Zn(t){return t.toString()[1]?t:"0"+t}function Yn(t,e){let r=new Date(t),n=new Date(e);return r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()&&r.getDate()===n.getDate()}var eh={addDays:th,addWeek:ZL,addMinutesToTimeString:Yr,convertTime:Ja,getIsoDateString:vm,getUTCdateString:Sf,DateHHMM:qL,extractDate:Et,extractTime:Xt,formatDate:jn,getDateByWeek:tF,isISODateString:Xa,isDate:If,isTimeString:JI,offsetDate:QI,offsetTime:zL,sameDay:Yn,timeStringMinutes:$t,timeToDate:ke,timeUTC:KL,validTimeValue:jc,validDateString:bm,timeValidation:xs,dateValidation:Po};var eF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),rF=t=>t.filter(Boolean).every(te);function Ls(t){let e=t.category;if(typeof e!="object")return{error:Bc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(eF([r,n,o,a],"string")&&rF([i,s])&&[n,o].filter(Boolean).every(Nr)))return{error:Bc};let p=t.consideredDate??Et(new Date().toLocaleDateString("sv"));if(!Nr(p))return{error:je};let[m]=p.split("-").slice(0,3).map(G=>parseInt(G)),d=ap(p,-1),[l,f]=d.split("-").slice(1,3).map(G=>parseInt(G)),g=`${Zn(l)}-${Zn(f)}`,I=ap(p,1),[h,S]=I.split("-").slice(1,3).map(G=>parseInt(G)),T=`${Zn(h)}-${Zn(S)}`,y=s&&ap(p,-1*365*s),P=i&&ap(p,-1*365*i),U=[],A=G=>!U.includes(G)&&U.push(G);r=r??a;let E=/^([UO]?)(\d{1,2})([UO]?)$/,N=/^C(\d{1,2})-(\d{1,2})$/,D=r?.includes("-"),M=D&&r?.match(N),R=r?.match(E),b=(G,k)=>`${G}-${k}`,v=G=>{let k=m-G,H=b(k,T);e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==G-1&&(A(`Invalid submitted ageMax: ${i}`),P=void 0),i=G-1)},O=G=>{let k=m-G-1,H=b(k,T);e.ageMin&&e.ageMin>G&&A(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>G&&A(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==G&&(A(`Invalid submitted ageMax: ${i}`),y=void 0),i=G)},_=G=>{let k=m-G,H=b(k,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==G+1&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=G+1)},F=G=>{let k=m-G-1,H=b(k,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==G&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=G)},w=G=>{let[k,H,W]=(G.match(E)||[]).slice(1),Y=parseInt(H);k==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(Y)):k==="O"&&_(Y),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),O(Y)):W==="O"&&F(Y),n=n??y,o=o??P};if(M){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=m-e.ageMin;n=b(H,g)}if(e.ageMax){let H=m-e.ageMax-1;o=b(H,T)}let[G,k]=(r?.match(N)??[]).slice(1).map(H=>parseInt(H));G<=k?(s=G,i=k,c=!0):A(`Invalid combined age range ${r}`)}else D?r?.split("-").forEach(w):R?w(r):(s&&_(s),i&&O(i));i&&e.ageMin&&e.ageMin>i&&(A(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=ot({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return U.length&&(L.errors=U),L}function Yc({category:t}){if(!ht(t))return{error:V};let e=Ls({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!te(r)?x({result:{error:V},context:{ratingMax:r}}):n&&!te(n)?x({result:{error:V},context:{ratingMin:n}}):{...e}}function qc({childCategory:t,withDetails:e,category:r}){let n=Yc({category:r}),o=Yc({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=ot({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function $c({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:n=!0,referenceCategory:o,referenceGender:i,event:s}){i=i??s?.gender;let a="validateCollectionDefinition",c=[];if(typeof e!="object")return c.push(`collectionDefinition must be an object: ${e}`),x({result:{errors:c,error:lo},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Fc([kt,xt],I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`),[!!u?.length].concat([g,m,h,S].map(It)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let U=vI({collectionValueProfiles:u,matchUpCount:l});U.errors&&c.push(...U.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Dr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let U=Rm({referenceGender:i,matchUpType:I,gender:y});if(U.error)return x({context:{referenceGender:i,gender:y},result:U,stack:a})}if(t&&o&&T){let U=qc({category:o,childCategory:T});if(!U.valid)return x({result:{error:Bc},context:U,stack:a})}return c.length?x({result:{errors:c,error:RE},stack:a}):{valid:!0}}function cr(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=nF({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:h,scoreValue:S,collectionValue:T}=I;(h||S)&&!T&&(u=!0);let{valid:y,errors:P}=$c({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(P)&&a.push(...P),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),x({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:Lo},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===ut(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:x({result:{error:Lo},context:{tieFormat:o,errors:a},stack:s})}function nF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?x({result:{error:Lo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:x({result:{error:Lo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):x({result:{error:Lo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var Za="resourceSubType",tc="resourceType",ec="identifier",jC={RESOURCE_SUB_TYPE:Za,RESOURCE_TYPE:tc,IDENTIFIER:ec};function J(t,e,r,n,o=0){if(KI().makeDeepCopy)return KI().makeDeepCopy(t,e,r,n);let i=uf(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Wr(t)||t===null||typeof i?.threshold=="number"&&o>=i.threshold)return t;let p=Array.isArray(t)?[]:{},m=Object.keys(t).filter(l=>!r||!c||Array.isArray(c)&&!c.includes(l)||Wr(c)&&!c(l)),d=(l,f)=>{p[l]=Wr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Wr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=yf(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?d(l,f):Array.isArray(a)&&a.includes(l)&&Wr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:BC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function yf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function rh(t=1,e){return tt(0,t).map(()=>Dt(e))}function Dt(t){let e=[];for(let a=0;a<256;a++)e[a]=(a<16?"0":"")+a.toString(16);let r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0,i=Math.random()*4294967295|0,s=e[r&255]+e[r>>8&255]+e[r>>16&255]+e[r>>24&255]+"-"+e[n&255]+e[n>>8&255]+"-"+e[n>>16&15|64]+e[n>>24&255]+"-"+e[o&63|128]+e[o>>8&255]+"-"+e[o>>16&255]+e[o>>24&255]+e[i&255]+e[i>>8&255]+e[i>>16&255]+e[i>>24&255];return typeof t=="string"?`${t}_${s.replace(/-/g,"")}`:s}var nh={collectionDefinitions:[{collectionName:"Male Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpCount:4,matchUpValue:1,gender:"MALE"},{collectionName:"Female Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:4,matchUpValue:1},{collectionName:"Male Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:2,matchUpValue:1,gender:"MALE"},{collectionName:"Female Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:2,matchUpValue:1},{collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:4,matchUpValue:1,gender:"MIXED"}],tieFormatName:"USTA_GOLD_TEAM_CHALLENGE",winCriteria:{valueGoal:9}};var oh={collectionDefinitions:[{collectionName:"Round 1",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 2",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 3",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"Doubles Shuffle",unrestrictedSelections:!0,winCriteria:{aggregateValue:!0}};var ih={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_SOUTHERN_LEVEL_5",winCriteria:{valueGoal:8}};var sh={collectionDefinitions:[{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Tiebreak Doubles",matchUpCount:1,matchUpFormat:"SET1-S:TB10",matchUpType:"DOUBLES",matchUpValue:1,processCodes:["RANKING.IGNORE"]}],tieFormatName:"USTA_SECTION_BATTLE",winCriteria:{valueGoal:9}};var ah={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_INTERSECTIONAL",winCriteria:{valueGoal:8}};var ch={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Pro Circuit",winCriteria:{aggregateValue:!0}};var uh={collectionDefinitions:[{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO_MIXED",winCriteria:{valueGoal:2}};var ph={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:3},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:3},{scoreValue:1,matchUpType:"DOUBLES",collectionName:"Men's Doubles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Women's Doubles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Dual",winCriteria:{aggregateValue:!0}};var mh={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"USTA_BREWER_CUP",winCriteria:{valueGoal:4}};var dh={winCriteria:{valueGoal:23},tieFormatName:"USTA_OZAKI_CUP",collectionDefinitions:[{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},collectionName:"18U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},collectionName:"16U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},collectionName:"14U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},collectionName:"12U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1}]};var Dn="SET3-S:6/TB7",fF="SET3-S:6NOAD",WE="SET3-S:6/TB7-F:TB10",gF="SET3-S:4/TB7",IF="SET3-S:4/TB5@3",hF="SET1-S:T20",SF="SET1-S:8/TB7",TF="SET1-S:8/TB7@7",YC={FORMAT_STANDARD:Dn,FORMAT_STANDARD_NOAD:fF,FORMAT_ATP_DOUBLES:WE,FORMAT_SHORT_SETS:gF,FORMAT_FAST4:IF,FORMAT_PRO_SET:SF,FORMAT_COLLEGE_PRO_SET:TF,TIMED20:hF};var lh={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO",winCriteria:{valueGoal:2}};var fh={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA_COLLEGE",winCriteria:{valueGoal:4}};var gh={collectionDefinitions:[{collectionName:"Male Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_LEVEL_1",winCriteria:{valueGoal:10}};var Ih={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_WTT_ITT",winCriteria:{aggregateValue:!0}};var hh={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_ZONAL",winCriteria:{valueGoal:10}};var Sh={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}};var Th={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var Om="COLLEGE_DEFAULT",yh="COLLEGE_JUCO",Ah="COLLEGE_D3",jE="DOMINANT_DUO",YE="DOMINANT_DUO_MIXED",qE="LAVER_CUP",$E="TEAM_DOUBLES_3_AGGREGATION",KE="TIME_TENNIS_DUAL",zE="TIME_TENNIS_PRO_CIRCUIT",QE="USTA_BREWER_CUP",XE="USTA_OZAKI_CUP",JE="USTA_COLLEGE",ZE="USTA_GOLD_TEAM_CHALLENGE",tU="USTA_LEVEL_1",eU="USTA_INTERSECTIONAL",rU="USTA_SECTION_BATTLE",nU="USTA_SOUTHERN_LEVEL_5",oU="USTA_TOC",iU="USTA_WTT_ITT",sU="USTA_ZONAL",qC={COLLEGE_D3:Ah,COLLEGE_DEFAULT:Om,COLLEGE_JUCO:yh,DOMINANT_DUO:jE,DOMINANT_DUO_MIXED:YE,LAVER_CUP:qE,TEAM_DOUBLES_3_AGGREGATION:$E,TIME_TENNIS_DUAL:KE,TIME_TENNIS_PRO_CIRCUIT:zE,USTA_BREWER_CUP:QE,USTA_OZAKI_CUP:XE,USTA_COLLEGE:JE,USTA_GOLD_TEAM_CHALLENGE:ZE,USTA_INTERSECTIONAL:eU,USTA_LEVEL_1:tU,USTA_SECTION_BATTLE:rU,USTA_SOUTHERN_LEVEL_5:nU,USTA_TOC:oU,USTA_WTT_ITT:iU,USTA_ZONAL:sU};var KC="STANDARD",$C={[KC]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Ah]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Ah,valueGoal:5},[Om]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Om,valueGoal:4},[yh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:yh,valueGoal:5},[qE]:Sh,[jE]:lh,[YE]:uh,[$E]:oh,[KE]:ph,[zE]:ch,[QE]:mh,[XE]:dh,[JE]:fh,[ZE]:nh,[eU]:ah,[tU]:gh,[rU]:sh,[nU]:ih,[iU]:Ih,[oU]:Th,[sU]:hh},MF=t=>{let e=t?.namedFormat&&Object.keys($C).includes(t.namedFormat)?t.namedFormat:KC,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J($C[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Dt();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:WE,collectionName:"Doubles",matchUpType:xt,...s.doubles},{collectionId:a(1),matchUpFormat:Dn,collectionName:"Singles",matchUpType:kt,...s.singles}]},s.tieFormatName&&(n.tieFormatName=s.tieFormatName)):(s.collectionDefinitions.forEach((c,u)=>c.collectionId=a(u)),n=s),t?.hydrateCollections&&n.collectionDefinitions.forEach(c=>{o&&!c.category&&(c.category=o),i&&!c.gender&&(c.gender=i)}),n},to=MF;var qn="SINGLES",Fs="SINGLES",qr="DOUBLES",ko="DOUBLES",ve="TEAM",vr="TEAM",RF="AGE",CF="RATING",bF="BOTH",zC={AGE:RF,BOTH:bF,DOUBLES:qr,DOUBLES_EVENT:ko,RATING:CF,SINGLES:qn,SINGLES_EVENT:Fs,TEAM_EVENT:vr,TEAM:ve};var rt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",fe="PLAY_OFF",Kc=[rt,ct,qe,fe,$e],ks={[ct]:1,[rt]:2,[fe]:3,[qe]:3,[$e]:4},aU="finishingPositions",cU="aggregateEventStructures",uU={[rt]:1,[fe]:2,[qe]:3,[ct]:4,[$e]:5},QC={[fe]:1,[rt]:2,[qe]:3,[ct]:4,[$e]:5},zc="CLUSTER",XC="SEPARATE",di="WATERFALL",cp="ITEM",Ge="CONTAINER",ln="DRAW",up="RANDOM",En="TOP_DOWN",li="BOTTOM_UP",eo="POSITION",fo="WINNER",ro="LOSER",_n="FIRST_MATCHUP",$r="AD_HOC",vF="AD_HOC",la="FEED_IN",Qc="COMPASS",Xc="OLYMPIC",OF="SINGLE_ELIMINATION";var go="SINGLE_ELIMINATION",Jc="DOUBLE_ELIMINATION",Zc="FIRST_MATCH_LOSER_CONSOLATION",pp="FIRST_ROUND_LOSER_CONSOLATION",Gi="LUCKY_DRAW",Af="CURTIS_CONSOLATION",JC="CURTIS_CONSOLATION",Eh="FEED_IN_CHAMPIONSHIP_TO_SF",_m="FEED_IN_CHAMPIONSHIP_TO_SF",Uh="FEED_IN_CHAMPIONSHIP_TO_QF",xm="FEED_IN_CHAMPIONSHIP_TO_QF",Ph="FEED_IN_CHAMPIONSHIP_TO_R16",wm="FEED_IN_CHAMPIONSHIP_TO_R16",pU="MODIFIED_FEED_IN_CHAMPIONSHIP",Lm="MODIFIED_FEED_IN_CHAMPIONSHIP",mp="FEED_IN_CHAMPIONSHIP",ZC="DOUBLE_ROUND_ROBIN",Nn="ROUND_ROBIN",Io="ROUND_ROBIN_WITH_PLAYOFF",mU="DECIDER",dU="BACKDRAW",Ef={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-3":{name:"Northeast",abbreviation:"NE"},"0-1-1":{name:"South",abbreviation:"S"},"0-1-2":{name:"Southwest",abbreviation:"SW"},"0-2-1":{name:"Northwest",abbreviation:"NW"},"0-1-1-1":{name:"Southeast",abbreviation:"SE"}},Uf={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},fi="WIN_RATIO",Vi="ROUND_OUTCOME",lU=[Qc,Af,xm,wm,_m,mp,Uh,Ph,Eh,Zc,pp,Gi,Lm,Xc,fe,Io],_F=[$r,Qc,Af,Jc,xm,wm,_m,mp,la,Zc,pp,Gi,Lm,Xc,fe,Nn,Io,go],fU={MAIN:rt,QUALIFYING:ct,CONSOLATION:qe,ITEM:cp,CONTAINER:Ge,FIRST_MATCHUP:_n,WINNER:fo,LOSER:ro,AD_HOC:$r,FEED_IN:la,FLEX_ROUNDS:vF,COMPASS:Qc,PLAY_OFF:fe,OLYMPIC:Xc,KNOCKOUT:OF,SINGLE_ELIMINATION:go,DOUBLE_ELIMINATION:Jc,CURTIS:Af,FICSF:Eh,FICQF:Uh,FICR16:Ph,MFIC:pU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:Zc,FIRST_ROUND_LOSER_CONSOLATION:pp,MODIFIED_FEED_IN_CHAMPIONSHIP:Lm,FEED_IN_CHAMPIONSHIP_TO_R16:wm,FEED_IN_CHAMPIONSHIP_TO_QF:xm,FEED_IN_CHAMPIONSHIP_TO_SF:_m,FEED_IN_CHAMPIONSHIP:mp,LUCKY_DRAW:Gi,ROUND_ROBIN_WITH_PLAYOFF:Io,ROUND_ROBIN:Nn,DECIDER:mU,BACKDRAW:dU,COMPASS_ATTRIBUTES:Ef,OLYMPIC_ATTRIBUTES:Uf,DRAW:ln,RANDOM:up,TOP_DOWN:En,BOTTOM_UP:li,WATERFALL:di,WIN_RATIO:fi,ROUND_OUTCOME:Vi,MULTI_STRUCTURE_DRAWS:lU,generatedDrawTypes:_F,stageOrder:ks,finishOrder:uU,AGGREGATE_EVENT_STRUCTURES:cU,FINISHING_POSITIONS:aU},tb=fU;var Ne="tournamentRecords",Pf="policyDefinitions",se="tournamentRecord",Dh="onlineResource",Ve="drawDefinition",Nh="tieFormatName",Fm="matchUpFormat",no="participantId",Mh="scheduleDates",eb="tournamentId",rb="scheduleDate",nb="roundNumber",tu="structureId",Df="participant",rc="matchUpIds",Rh="entryStage",ob="policyType",gU="structures",Nf="eventType",fn="matchUpId",km="tieFormat",eu="inContext",dp="structure",lp="courtIds",ib="personId",fp="venueIds",Mf="matchUps",Ch="courtId",bh="eventId",xn="matchUp",vh="drawId",gn="error",Do="event",is="param",Rf="uuids",sb="averageMatchUpMinutes",ab="recoveryMinutes",cb="periodLength",ub="number";var Kr="object",Be="array";var tr="_validate",Oh="_message",Fr="_invalid",He="_ofType",Gm="_anyOf",Gs="_oneOf";var pb={[Dh]:t=>qt(Object.keys(t),[Za,tc,ec]).length===3,[Nh]:t=>t&&to({namedFormat:t}),[Rf]:t=>!t||Array.isArray(t)&&t.every(Vt),[km]:t=>!cr({tieFormat:t}).error,[Nf]:t=>[qn,qr,ve].includes(t),[Rh]:t=>Kc.includes(t)},xF={[Ne]:Lt,[se]:q,[Pf]:Ku,[Ve]:Z,[no]:ie,[Fm]:Yl,[eb]:ua,[tu]:Ur,[rc]:rs,[Df]:Li,[Dh]:lo,[Nf]:Wn,[gU]:Bl,[fn]:ar,[km]:Lo,[dp]:mi,[Ch]:xi,[Mf]:Jn,[bh]:jr,[xn]:Sr,[lp]:it,[fp]:it,[vh]:sn,[Do]:Ot},wF={[Ne]:Kr,[Pf]:Kr,[se]:Kr,[Ve]:Kr,[Dh]:Kr,[Mh]:Be,[Df]:Kr,[rc]:Be,[gU]:Be,[km]:Kr,[dp]:Kr,[lp]:Be,[fp]:Be,[Mf]:Be,[xn]:Kr,[Do]:Kr,[Rf]:Be};function et(t,e,r){if(!t&&!ht(t))return{error:V};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:V};let{paramError:n,errorParam:o}=kF(t,e);if(!n)return{valid:!0};let i=n[tr]&&(n[gn]||n[Fr])||t?.[o]===void 0&&(n[gn]||n[Fr]||xF[o]||V)||V,s=o??(n[Gs]&&Object.keys(n[Gs]).join(", "));return x({info:{param:s,message:n[Oh]},result:{error:i},stack:r})}function mb(t,e){let r=Object.keys(t),n=Object.keys(e);return qt(r,n)}function LF(t,e){if(!e)return;let r=mb(t,e);return r.length!==1?{error:V}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function FF(t,e){if(!e)return;let r=mb(t,e).filter(n=>t[n]);return r.length<1?{error:V}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function kF(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&LF(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&FF(t,a);if(d?.error)return d.error;d&&Object.assign(p,d);let l=Object.keys(p).filter(g=>typeof p[g]=="boolean"),f=l.find(g=>{let I=c&&!Wr(c),h=t[g]!==void 0&&!c&&GF(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!VF(t[g],c)||pb[g]&&!pb[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function GF(t,e,r){return r=r||wF[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function VF(t,e){return Wr(e)?e(t):!0}var Vm="DYNAMIC",gi="RANKING",Ii="RATING",hi="SCALE",ho="SEEDING",db={RANKING:gi,RATING:Ii,SCALE:hi,SEEDING:ho};function fa(t){let e=et(t,[{[Df]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(hi)&&[gi,Ii,ho].includes(o.split(".")[1])),n={ratings:{},rankings:{},seedings:{}};if(r?.length){let o=s=>r.filter(a=>a?.itemType===s).sort((a,c)=>new Date(a.createdAt||void 0).getTime()-new Date(c.createdAt||void 0).getTime()).pop(),i=ut(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===ho&&"seedings"||c===gi&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Bi(t){if(t===null)return{};let{source:e,template:r}=t||{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let h=I.map(S=>{let T={};return o(S,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=h}else I&&(a[l]={},o(I,g,a[l]));else{let h=i[l];if(Array.isArray(g)&&!g.includes(h))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=h)}}}}var _h="voluntaryConsolation",Si="competitiveBands",Cf="roundRobinTally",So="positionActions",er="matchUpActions",bf="rankingPoints",ga="roundNaming",Vs="participant",ru="progression",No="scheduling",nu="avoidance",BF="participant",HF="display",tn="scoring",wn="seeding",nc="feedIn",WF="audit",Bm="draws",lb={POLICY_TYPE_VOLUNTARY_CONSOLATION:_h,POLICY_TYPE_COMPETITIVE_BANDS:Si,POLICY_TYPE_ROUND_ROBIN_TALLY:Cf,POLICY_TYPE_POSITION_ACTIONS:So,POLICY_TYPE_MATCHUP_ACTIONS:er,POLICY_TYPE_RANKING_POINTS:bf,POLICY_TYPE_ROUND_NAMING:ga,POLICY_TYPE_PARTICIPANT:Vs,POLICY_TYPE_PROGRESSION:ru,POLICY_TYPE_SCHEDULING:No,POLICY_TYPE_AVOIDANCE:nu,POLICY_TYPE_DISPLAY:HF,POLICY_TYPE_PRIVACY:BF,POLICY_TYPE_FEED_IN:nc,POLICY_TYPE_SCORING:tn,POLICY_TYPE_SEEDING:wn,POLICY_TYPE_AUDIT:WF,POLICY_TYPE_DRAWS:Bm};function Go({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[Vs];if(r?.withScaleValues){let{ratings:u,rankings:p}=fa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Bi({template:c.participant,source:a})}return a}var fb="element required",gb="missing name";function fr(t){if(!t||typeof t!="object")return{error:it};if(t.element&&typeof t?.element!="object")return{error:V};if(!t?.name)return{error:it,info:gb};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=fr({element:r,name:t.name});if(n.error)return x({result:n,stack:"removeExtension"})}return{...C}}return{error:it,info:fb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:Ce}}function Ln({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function At(t){if(typeof t!="object")return{error:it};let e="addExtension";if(t?.element&&typeof t.element!="object")return x({result:{error:V},stack:e});if(!Ln({extension:t.extension}))return x({result:{error:V,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=At({extension:t.extension,element:o});if(i.error)return x({result:i,stack:e})}return{...C}}else return x({result:{error:it},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...C}}function vf(t){return!t||typeof t!="object"?{error:it}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:q}}function gp(t){return!t||typeof t!="object"?{error:it}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:br}}function Mo(t){return!t||typeof t!="object"?{error:it}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:jr}}function IU(t){if(!t||typeof t!="object")return{error:it};if(!t.participantId)return{error:ie};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:re}}function Of(t){return!t||typeof t!="object"?{error:it}:t.tournamentRecord?fr({element:t.tournamentRecord,name:t.name}):{error:q}}function hU(t){return!t||typeof t!="object"?{error:it}:t.drawDefinition?fr({element:t.drawDefinition,name:t.name}):{error:br}}function Ip(t){return!t||typeof t!="object"?{error:it}:t?.event?fr({element:t.event,name:t.name}):{error:jr}}function SU(t){if(!t||typeof t!="object")return{error:it};if(!t.participantId)return{error:ie};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?fr({element:r,name:t.name}):{error:re}}function hp({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var jF="extensionQueries";function lt({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:Ce}}return x({result:{error:it},stack:jF})}if(!Array.isArray(e.extensions))return{info:"no extensions"};let o=e.extensions.find(s=>s?.name===r);return{extension:o,info:o?void 0:Ce}}var YF="activeSuspension",ou="appliedPolicies",TU="context",Hm="delegatedOutcome",oo="disabled",Ia="disableAutoCalc",Wm="disableLinks",jm="display",ha="drawDeletions",qF="drawProfile",Ym="entryProfile",$F="eventProfile",KF="eventWithdrawalRequests",zF="factory",cn="flightProfile",xh="groupingAttribute",Ro="lineUps",Bs="linkedTournamentsIds",qm="matchUpHistory",wh="participantRepresentatives",Sa="personRequests",oc="positionActions",QF="rankingPoints",XF="registration",Mn="roundTarget",iu="scheduleLimits",Vo="scheduleTiming",Ta="schedulingProfile",JF="statusDetail",ic="subOrder",Zo="tally",$m="tieFormatModification",Lh={ACTIVE_SUSPENSION:YF,APPLIED_POLICIES:ou,CONTEXT:TU,DELEGATED_OUTCOME:Hm,DISABLED:oo,DISABLE_LINKS:Wm,DISABLE_AUTO_CALC:Ia,DISPLAY:jm,DRAW_DELETIONS:ha,DRAW_PROFILE:qF,ENTRY_PROFILE:Ym,EVENT_PROFILE:$F,EVENT_WITHDRAWAL_REQUESTS:KF,FLIGHT_PROFILE:cn,GROUPING_ATTRIBUTE:xh,LINEUPS:Ro,LINKED_TOURNAMENTS:Bs,MATCHUP_HISTORY:qm,PARTICIPANT_REPRESENTATIVES:wh,PERSON_REQUESTS:Sa,POSITION_ACTIONS:oc,RANKING_POINTS:QF,REGISTRATION:XF,ROUND_TARGET:Mn,SCHEDULE_LIMITS:iu,SCHEDULE_TIMING:Vo,SCHEDULING_PROFILE:Ta,STATUS_DETAIL:JF,SUB_ORDER:ic,TALLY:Zo,TIE_FORMAT_MODIFICATIONS:$m,FACTORY:zF},yU=[Hm,oo,Ia,Wm,cn,Ro,Bs,qm,wh,Sa,Mn,iu,Vo,Ta,ic,Zo,$m];function AU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let e=hp({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:Bs,value:{tournamentIds:r}}}):{...C}}function EU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let e=fr({name:Bs,tournamentRecords:t,discover:!0});return x({result:e,stack:"unlinkTournaments"})}function UU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:V};if(!e)return{error:ua};let r=hp({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ua};let o;return n.every(i=>{let s=t[i],{extension:a}=lt({element:s,name:Bs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=Of({name:Bs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=vf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var DU={};Zt(DU,{getLinkedTournamentIds:()=>su,getTournamentIds:()=>hp});function su({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:Lt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=lt({element:n,name:Bs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var CN={};Zt(CN,{adHocPositionSwap:()=>FP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Ag,addFinishingRounds:()=>Ua,addGoesTo:()=>$i,addPlayoffStructures:()=>Gp,addQualifyingStructure:()=>LP,addVoluntaryConsolationStage:()=>bP,addVoluntaryConsolationStructure:()=>dg,allPlayoffPositionsFilled:()=>xS,alternateDrawPositionAssignment:()=>TP,assignDrawPosition:()=>XP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>$P,attachPlayoffStructures:()=>vg,attachQualifyingStructure:()=>yg,attachStructures:()=>Og,autoSeeding:()=>J_,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Tc,checkValidEntries:()=>_d,deleteAdHocMatchUps:()=>JP,drawMatic:()=>qd,findDrawDefinition:()=>sT,generateAdHocMatchUps:()=>xu,generateAdHocRounds:()=>Yd,generateAndPopulatePlayoffStructures:()=>Cd,generateDrawDefinition:()=>wa,generateDrawMaticRound:()=>Fd,generateDrawStructuresAndLinks:()=>xd,generateDrawTypeAndModifyDrawDefinition:()=>wd,generateQualifyingStructure:()=>Pd,generateVoluntaryConsolation:()=>NT,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Nu,getDrawDefinitionTimeItem:()=>Xh,getDrawParticipantRepresentativeIds:()=>oT,getDrawStructures:()=>In,getDrawTypeCoercion:()=>Ou,getEligibleVoluntaryConsolationParticipants:()=>nT,getMatchUpsMap:()=>De,getParticipantIdFinishingPositions:()=>iT,getPositionAssignments:()=>Vp,getPositionsPlayedOff:()=>Ac,getSeedingThresholds:()=>PS,getSeedsCount:()=>_u,getStructureSeedAssignments:()=>nn,getTeamLineUp:()=>ms,getValidGroupSizes:()=>bp,isAdHoc:()=>ur,isCompletedStructure:()=>ai,isValidForQualifying:()=>TT,luckyLoserDrawPositionAssignment:()=>fP,modifyDrawDefinition:()=>KP,modifyDrawName:()=>_g,modifySeedAssignment:()=>yP,mutate:()=>eD,positionActions:()=>ST,pruneDrawDefinition:()=>QP,qualifierDrawPositionAssignment:()=>SP,query:()=>dD,removeDrawPositionAssignment:()=>Uu,removeRoundMatchUps:()=>ZP,removeSeededParticipant:()=>wP,removeStructure:()=>CP,renameStructures:()=>RP,resetDrawDefinition:()=>zP,resetQualifyingStructure:()=>vP,resetVoluntaryConsolationStructure:()=>LU,setDrawParticipantRepresentativeIds:()=>RU,setPositionAssignments:()=>IP,setStructureOrder:()=>MP,setSubOrder:()=>tD,shiftAdHocRounds:()=>gP,swapAdHocRounds:()=>hP,swapDrawPositionAssignments:()=>xP,updateTeamLineUp:()=>zi,withdrawParticipantAtDrawPosition:()=>dP});var eD={};Zt(eD,{adHocPositionSwap:()=>FP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Ag,addPlayoffStructures:()=>Gp,addQualifyingStructure:()=>LP,addVoluntaryConsolationStage:()=>bP,addVoluntaryConsolationStructure:()=>dg,alternateDrawPositionAssignment:()=>TP,assignDrawPosition:()=>XP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>$P,attachPlayoffStructures:()=>vg,attachQualifyingStructure:()=>yg,attachStructures:()=>Og,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Tc,deleteAdHocMatchUps:()=>JP,luckyLoserDrawPositionAssignment:()=>fP,modifyDrawDefinition:()=>KP,modifyDrawName:()=>_g,modifySeedAssignment:()=>yP,pruneDrawDefinition:()=>QP,qualifierDrawPositionAssignment:()=>SP,removeDrawPositionAssignment:()=>Uu,removeRoundMatchUps:()=>ZP,removeSeededParticipant:()=>wP,removeStructure:()=>CP,renameStructures:()=>RP,resetDrawDefinition:()=>zP,resetQualifyingStructure:()=>vP,resetVoluntaryConsolationStructure:()=>LU,setDrawParticipantRepresentativeIds:()=>RU,setPositionAssignments:()=>IP,setStructureOrder:()=>MP,setSubOrder:()=>tD,shiftAdHocRounds:()=>gP,swapAdHocRounds:()=>hP,swapDrawPositionAssignments:()=>xP,updateTeamLineUp:()=>zi,withdrawParticipantAtDrawPosition:()=>dP});var MU=t=>e=>t[e],Km=(t=[])=>t.map(Ue).filter(Boolean),_f=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>MU(t)("participantId");var Ue=(t={})=>MU(t)("matchUpId"),au=(t={})=>MU(t)("drawId");function RU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:br};if(!Array.isArray(t))return{error:V};let r=_f(e?.entries||[]);return t.length&&qt(t,r).length<t.length?{error:V}:gp({drawDefinition:e,extension:{name:wh,value:t}})}var Or="ABANDONED",sc="AWAITING_RESULT",Nt="BYE",io="CANCELLED",ge="COMPLETED",cu="DEAD_RUBBER",Rt="DEFAULTED",Me="DOUBLE_DEFAULT",Te="DOUBLE_WALKOVER",Fn="IN_PROGRESS",un="INCOMPLETE",CU="NOT_PLAYED",rr="RETIRED",ss="SUSPENDED",Jt="TO_BE_PLAYED",Ct="WALKOVER",Ib=[sc,ge,Rt,Fn,un,rr,ss],Fh=[sc,ge,Rt,Te,Me,Fn,un,rr,ss,Ct],kh=[Or,sc,Nt,io,ge,cu,Rt,Te,Me,Fn,un,CU,rr,ss,Jt,Ct],Gh=[Nt,Te,Me,ge,Rt,rr,Ct],Vh=[Or,sc,io,cu,Fn,un,CU,ss,Jt,void 0],pe=[io,Or,ge,cu,Rt,Te,Me,rr,Ct],zm=[Or,ge,Rt,Te,Me,Fn,rr,Ct],Bh=[Fn,un,ss,Jt],Hh={ABANDONED:Or,AWAITING_RESULT:sc,BYE:Nt,CANCELLED:io,COMPLETED:ge,DEAD_RUBBER:cu,DEFAULTED:Rt,DOUBLE_WALKOVER:Te,DOUBLE_DEFAULT:Me,IN_PROGRESS:Fn,INCOMPLETE:un,NOT_PLAYED:CU,RETIRED:rr,SUSPENDED:ss,TO_BE_PLAYED:Jt,WALKOVER:Ct};function Ti(t,e,r){let n=m=>lt({element:m,name:Mn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===cU&&QC,s=r?.mode===aU&&uU,a=s||i||ks,c=m=>m?.stage===rt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>pe.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(xf(t)||0)-(xf(e)||0)}function xf(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function at(t){let e=et(t,[{[Ve]:!0,[tu]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=In({drawDefinition:r}),i=o?.map(c=>c.structures?[...c.structures].concat(c):c).flat(),s=i?.find(c=>c.structureId===n);if(!s)return{error:wt};let a=s.structureType===cp?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function In({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&Z||!e?.structures&&Bl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=lt({element:f,name:Mn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Ti(f,g,i))??[],m=t?Object.assign({},...Kc.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:m};function d(f){return!a&&!Array.isArray(s)||a&&f.stage===a||Array.isArray(s)&&s.includes(f.stage)}function l(f){return!n&&!Array.isArray(r)||n&&f.stageSequence===n||Array.isArray(r)&&r.includes(f.stageSequence)}}function Wh({drawDefinition:t}){if(!t)return{error:Z};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=bt({structure:n}),s=i?.map(St).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function bt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:Z};if({structure:r,error:n}=at({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>bt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=KA,{positionAssignments:o,error:n}}function ye({drawDefinition:t,structureId:e,structure:r}){let n=bt({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var wf="addDrawDefinition",Sp="addMatchUps",ti="addParticipants",Lf="addScaleItems",bU="addEvent",jh="addVenue",yi="audit",Yh="dataIssue",Ff="deleteParticipants",kf="deleteVenue",Gf="deletedDrawIds",Vf="deletedMatchUpIds",Bf="modifyDrawDefinition",vU="modifyDrawEntries",OU="modifyEventEntries",Hf="modifyMatchUp",nr="modifyParticipants",Wf="modifyPositionAssignments",jf="modifySeedAssignments",Hi="modifyTournamentDetail",Ai="modifyVenue",Qm="mutations",qh="publishEvent",_U="publishEventSeeding",xU="publishOrderOfPlay",wU="publishParticipants",Yf="unPublishEvent",qf="unPublishEventSeeding",$f="unPublishOrderOfPlay",hb="unPublishParticipants",Tp="updateInContextMatchUp",Sb={ADD_DRAW_DEFINITION:wf,ADD_MATCHUPS:Sp,ADD_PARTICIPANTS:ti,ADD_SCALE_ITEMS:Lf,ADD_EVENT:bU,ADD_VENUE:jh,AUDIT:yi,DATA_ISSUE:Yh,DELETE_PARTICIPANTS:Ff,DELETE_VENUE:kf,DELETED_DRAW_IDS:Gf,DELETED_MATCHUP_IDS:Vf,MODIFY_DRAW_DEFINITION:Bf,MODIFY_DRAW_ENTRIES:vU,MODIFY_EVENT_ENTRIES:OU,MODIFY_MATCHUP:Hf,MODIFY_PARTICIPANTS:nr,MODIFY_POSITION_ASSIGNMENTS:Wf,MODIFY_SEED_ASSIGNMENTS:jf,MODIFY_TOURNAMENT_DETAIL:Hi,MODIFY_VENUE:Ai,MUTATIONS:Qm,PUBLISH_EVENT_SEEDING:_U,PUBLISH_EVENT:qh,PUBLISH_ORDER_OF_PLAY:xU,PUBLISH_PARTICIPANTS:wU,UNPUBLISH_EVENT_SEEDING:qf,UNPUBLISH_EVENT:Yf,UNPUBLISH_ORDER_OF_PLAY:$f,UPDATE_INCONTEXT_MATCHUP:Tp};function $h(t,e){if(!t)return{error:Z};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...C}}function Co({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&$h(t),dt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Sp}),{...C}}function Rn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&$h(t),dt({topic:Vf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)$I({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&vt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),dt({topic:Hf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(Sr),{error:Sr})}function Tb({tournamentId:t,inContextMatchUp:e}){return e?(dt({payload:{inContextMatchUp:e,tournamentId:t},topic:Tp,key:e.matchUpId}),{...C}):{error:Sr}}function ya({tournamentId:t,eventId:e,drawDefinition:r}){return r?($h(r),dt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:wf,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function yb({tournamentId:t,eventId:e,drawId:r}){return dt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Gf,key:r}),$I({key:r}),{...C}}function vt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?($h(t,r),dt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Bf,key:t.drawId}),{...C}):{error:Z}}function Kh({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:mi};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return dt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:jf,key:t.drawId}),vt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function bo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:mi};let o=bt({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return dt({topic:Wf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),vt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function LU({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:Z};let o=e.structures?.find(s=>s.stage===$e);if(!o)return{error:wt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Rn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),vt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function Xm({drawPositions:t,structure:e}){if([ct,rt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=bt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,extension:{name:Wm,value:!0}})})}function uu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[oc]===!1)return;let{extension:o}=lt({name:oc,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===rt);if(a){let c=bt({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:oc};At({element:n,extension:s})}function as({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function pu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===xt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===xt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Mr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var ac="SIGN_IN_STATUS",FU="SIGNED_OUT",mu="SIGNED_IN",Ar="TEAM",Tt="INDIVIDUAL",zr="GROUP",ft="PAIR",Ft="TEAM",du={TEAM_PARTICIPANT:Ar,INDIVIDUAL:Tt,GROUP:zr,TEAM:Ft,PAIR:ft},Ab={INDIVIDUAL:Tt,GROUP:zr,PAIR:ft,TEAM:Ft,SIGN_IN_STATUS:ac,SIGNED_OUT:FU,SIGNED_IN:mu};function lu({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===Ft),s=o.filter(c=>c.participantType===zr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===Tt){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function kU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function Eb(t){let e=Object.assign({},...ei.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return kU(e[t])}var ei=[{ioc:"",iso2:"",iso:"",label:"NONE",phone:""},{ioc:"AND",iso2:"AD",iso:"AND",label:"Andorra",phone:"376"},{ioc:"UAE",iso2:"AE",iso:"ARE",label:"United Arab Emirates",phone:"971"},{ioc:"AFG",iso2:"AF",iso:"AFG",label:"Afghanistan",phone:"93"},{ioc:"ANT",iso2:"AG",iso:"ATG",label:"Antigua and Barbuda",phone:"1-268"},{ioc:"AIA",iso2:"AI",iso:"AIA",label:"Anguilla",phone:"1-264"},{ioc:"ALB",iso2:"AL",iso:"ALB",label:"Albania",phone:"355"},{ioc:"ARM",iso2:"AM",iso:"ARM",label:"Armenia",phone:"374"},{ioc:"ANG",iso2:"AO",iso:"AGO",label:"Angola",phone:"244"},{ioc:"",iso2:"AQ",iso:"ATA",label:"Antarctica",phone:"672"},{ioc:"ARG",iso2:"AR",iso:"ARG",label:"Argentina",phone:"54"},{ioc:"ASA",iso2:"AS",iso:"ASM",label:"American Samoa",phone:"1-684"},{ioc:"AUT",iso2:"AT",iso:"AUT",label:"Austria",phone:"43"},{ioc:"AUS",iso2:"AU",iso:"AUS",label:"Australia",phone:"61",suggested:!0},{ioc:"ARU",iso2:"AW",iso:"ABW",label:"Aruba",phone:"297"},{ioc:"AZE",iso2:"AZ",iso:"AZE",label:"Azerbaijan",phone:"994"},{ioc:"BIH",iso2:"BA",iso:"BIH",label:"Bosnia and Herzegovina",phone:"387"},{ioc:"BAR",iso2:"BB",iso:"BRB",label:"Barbados",phone:"1-246"},{ioc:"BAN",iso2:"BD",iso:"BGD",label:"Bangladesh",phone:"880"},{ioc:"BEL",iso2:"BE",iso:"BEL",label:"Belgium",phone:"32"},{ioc:"BUR",iso2:"BF",iso:"BFA",label:"Burkina Faso",phone:"226"},{ioc:"BUL",iso2:"BG",iso:"BGR",label:"Bulgaria",phone:"359"},{ioc:"BRN",iso2:"BH",iso:"BHR",label:"Bahrain",phone:"973"},{ioc:"BDI",iso2:"BI",iso:"BDI",label:"Burundi",phone:"257"},{ioc:"BEN",iso2:"BJ",iso:"BEN",label:"Benin",phone:"229"},{ioc:"",iso2:"BL",iso:"BLM",label:"Saint Barthelemy",phone:"590"},{ioc:"BER",iso2:"BM",iso:"BMU",label:"Bermuda",phone:"1-441"},{ioc:"BRU",iso2:"BN",iso:"BRN",label:"Brunei Darussalam",phone:"673"},{ioc:"BOL",iso2:"BO",iso:"BOL",label:"Bolivia",phone:"591"},{ioc:"BRA",iso2:"BR",iso:"BRA",label:"Brazil",phone:"55"},{ioc:"BAH",iso2:"BS",iso:"BHS",label:"Bahamas",phone:"1-242"},{ioc:"BHU",iso2:"BT",iso:"BTN",label:"Bhutan",phone:"975"},{ioc:"",iso2:"BV",iso:"BVT",label:"Bouvet Island",phone:"47"},{ioc:"BOT",iso2:"BW",iso:"BWA",label:"Botswana",phone:"267"},{ioc:"BLR",iso2:"BY",iso:"BLR",label:"Belarus",phone:"375"},{ioc:"BIZ",iso2:"BZ",iso:"BLZ",label:"Belize",phone:"501"},{ioc:"CAN",iso2:"CA",iso:"CAN",label:"Canada",phone:"1",suggested:!0},{ioc:"",iso2:"CC",iso:"CCK",label:"Cocos (Keeling) Islands",phone:"61"},{ioc:"CGO",iso2:"CD",iso:"COG",label:"Congo, Republic of the",phone:"242"},{ioc:"CAF",iso2:"CF",iso:"CAF",label:"Central African Republic",phone:"236"},{ioc:"COD",iso2:"CG",iso:"CGD",label:"Congo, Democratic Republic of the",phone:"243"},{ioc:"SUI",iso2:"CH",iso:"CHE",label:"Switzerland",phone:"41"},{ioc:"CIV",iso2:"CI",iso:"CIV",label:"Cote d'Ivoire",phone:"225"},{ioc:"COK",iso2:"CK",iso:"COK",label:"Cook Islands",phone:"682"},{ioc:"CHI",iso2:"CL",iso:"CHL",label:"Chile",phone:"56"},{ioc:"CMR",iso2:"CM",iso:"CMR",label:"Cameroon",phone:"237"},{ioc:"CHN",iso2:"CN",iso:"CHN",label:"China",phone:"86"},{ioc:"COL",iso2:"CO",iso:"COL",label:"Colombia",phone:"57"},{ioc:"CRC",iso2:"CR",iso:"CRI",label:"Costa Rica",phone:"506"},{ioc:"CUB",iso2:"CU",iso:"CUB",label:"Cuba",phone:"53"},{ioc:"CPV",iso2:"CV",iso:"CPV",label:"Cape Verde",phone:"238"},{ioc:"CUW",iso2:"CW",iso:"CUW",label:"Curacao",phone:"599"},{ioc:"CXR",iso2:"CX",iso:"CXR",label:"Christmas Island",phone:"61"},{ioc:"CYP",iso2:"CY",iso:"CYP",label:"Cyprus",phone:"357"},{ioc:"CZE",iso2:"CZ",iso:"CZE",label:"Czech Republic",phone:"420"},{ioc:"GER",iso2:"DE",iso:"DEU",label:"Germany",phone:"49",suggested:!0},{ioc:"DJI",iso2:"DJ",iso:"DJI",label:"Djibouti",phone:"253"},{ioc:"DEN",iso2:"DK",iso:"DNK",label:"Denmark",phone:"45"},{ioc:"DMA",iso2:"DM",iso:"DMA",label:"Dominica",phone:"1-767"},{ioc:"DOM",iso2:"DO",iso:"DOM",label:"Dominican Republic",phone:"1-809"},{ioc:"ALG",iso2:"DZ",iso:"DZA",label:"Algeria",phone:"213"},{ioc:"ECU",iso2:"EC",iso:"ECU",label:"Ecuador",phone:"593"},{ioc:"EST",iso2:"EE",iso:"ESE",label:"Estonia",phone:"372"},{ioc:"EGY",iso2:"EG",iso:"EGY",label:"Egypt",phone:"20"},{ioc:"",iso2:"EH",iso:"ESH",label:"Western Sahara",phone:"212"},{ioc:"ERI",iso2:"ER",iso:"ERI",label:"Eritrea",phone:"291"},{ioc:"ESP",iso2:"ES",iso:"ESP",label:"Spain",phone:"34"},{ioc:"ETH",iso2:"ET",iso:"ETH",label:"Ethiopia",phone:"251"},{ioc:"FIN",iso2:"FI",iso:"FIN",label:"Finland",phone:"358"},{ioc:"FIJ",iso2:"FJ",iso:"FJI",label:"Fiji",phone:"679"},{ioc:"FLK",iso2:"FK",iso:"FLK",label:"Falkland Islands (Malvinas)",phone:"500"},{ioc:"FSM",iso2:"FM",iso:"FSM",label:"Micronesia, Federated States of",phone:"691"},{ioc:"FAR",iso2:"FO",iso:"FRO",label:"Faroe Islands",phone:"298"},{ioc:"FRA",iso2:"FR",iso:"FRA",label:"France",phone:"33",suggested:!0},{ioc:"GAB",iso2:"GA",iso:"GAB",label:"Gabon",phone:"241"},{ioc:"GBR",iso2:"GB",iso:"GBR",label:"United Kingdom",phone:"44"},{ioc:"GRN",iso2:"GD",iso:"GRD",label:"Grenada",phone:"1-473"},{ioc:"GEO",iso2:"GE",iso:"GEO",label:"Georgia",phone:"995"},{ioc:"FGU",iso2:"GF",iso:"GUF",label:"French Guiana",phone:"594"},{ioc:"",iso2:"GG",iso:"GGY",label:"Guernsey",phone:"44"},{ioc:"",iso2:"GH",iso:"GHA",label:"Ghana",phone:"233"},{ioc:"GIB",iso2:"GI",iso:"GIB",label:"Gibraltar",phone:"350"},{ioc:"GRL",iso2:"GL",iso:"GRL",label:"Greenland",phone:"299"},{ioc:"GAM",iso2:"GM",iso:"GMB",label:"Gambia",phone:"220"},{ioc:"GUI",iso2:"GN",iso:"GIN",label:"Guinea",phone:"224"},{ioc:"GUD",iso2:"GP",iso:"GLP",label:"Guadeloupe",phone:"590"},{ioc:"GEQ",iso2:"GQ",iso:"GNQ",label:"Equatorial Guinea",phone:"240"},{ioc:"GRE",iso2:"GR",iso:"GRC",label:"Greece",phone:"30"},{ioc:"",iso2:"GS",iso:"SGS",label:"South Georgia and the South Sandwich Islands",phone:"500"},{ioc:"GUA",iso2:"GT",iso:"GTM",label:"Guatemala",phone:"502"},{ioc:"GUM",iso2:"GU",iso:"GUM",label:"Guam",phone:"1-671"},{ioc:"GBS",iso2:"GW",iso:"GNB",label:"Guinea-Bissau",phone:"245"},{ioc:"GUY",iso2:"GY",iso:"GUY",label:"Guyana",phone:"592"},{ioc:"HKG",iso2:"HK",iso:"HKG",label:"Hong Kong",phone:"852"},{ioc:"",iso2:"HM",iso:"HMD",label:"Heard Island and McDonald Islands",phone:"672"},{ioc:"HON",iso2:"HN",iso:"HND",label:"Honduras",phone:"504"},{ioc:"CRO",iso2:"HR",iso:"HRV",label:"Croatia",phone:"385"},{ioc:"HAI",iso2:"HT",iso:"HTI",label:"Haiti",phone:"509"},{ioc:"HUN",iso2:"HU",iso:"HUN",label:"Hungary",phone:"36"},{ioc:"INA",iso2:"ID",iso:"IDN",label:"Indonesia",phone:"62"},{ioc:"IRL",iso2:"IE",iso:"IRL",label:"Ireland",phone:"353"},{ioc:"ISR",iso2:"IL",iso:"ISR",label:"Israel",phone:"972"},{ioc:"",iso2:"IM",iso:"IMN",label:"Isle of Man",phone:"44"},{ioc:"IND",iso2:"IN",iso:"IND",label:"India",phone:"91"},{ioc:"",iso2:"IO",iso:"IOT",label:"British Indian Ocean Territory",phone:"246"},{ioc:"IRQ",iso2:"IQ",iso:"IRQ",label:"Iraq",phone:"964"},{ioc:"IRI",iso2:"IR",iso:"IRN",label:"Iran, Islamic Republic of",phone:"98"},{ioc:"ISL",iso2:"IS",iso:"ISL",label:"Iceland",phone:"354"},{ioc:"ITA",iso2:"IT",iso:"ITA",label:"Italy",phone:"39"},{ioc:"",iso2:"JE",iso:"JEY",label:"Jersey",phone:"44"},{ioc:"JAM",iso2:"JM",iso:"JAM",label:"Jamaica",phone:"1-876"},{ioc:"JOR",iso2:"JO",iso:"JOR",label:"Jordan",phone:"962"},{ioc:"JPN",iso2:"JP",iso:"JPN",label:"Japan",phone:"81",suggested:!0},{ioc:"KEN",iso2:"KE",iso:"KEN",label:"Kenya",phone:"254"},{ioc:"KGZ",iso2:"KG",iso:"KGZ",label:"Kyrgyzstan",phone:"996"},{ioc:"CAM",iso2:"KH",iso:"KHM",label:"Cambodia",phone:"855"},{ioc:"KIR",iso2:"KI",iso:"KIR",label:"Kiribati",phone:"686"},{ioc:"COM",iso2:"KM",iso:"COM",label:"Comoros",phone:"269"},{ioc:"SKN",iso2:"KN",iso:"KNA",label:"Saint Kitts and Nevis",phone:"1-869"},{ioc:"KOR",iso2:"KP",iso:"KOR",label:"Korea, Democratic People's Republic of",phone:"850"},{ioc:"PRK",iso2:"KR",iso:"PRK",label:"Korea, Republic of",phone:"82"},{ioc:"KUW",iso2:"KW",iso:"KWT",label:"Kuwait",phone:"965"},{ioc:"CAY",iso2:"KY",iso:"CYM",label:"Cayman Islands",phone:"1-345"},{ioc:"KAZ",iso2:"KZ",iso:"KAZ",label:"Kazakhstan",phone:"7"},{ioc:"LAO",iso2:"LA",iso:"LAO",label:"Lao People's Democratic Republic",phone:"856"},{ioc:"LIB",iso2:"LB",iso:"LBN",label:"Lebanon",phone:"961"},{ioc:"LCA",iso2:"LC",iso:"LCA",label:"Saint Lucia",phone:"1-758"},{ioc:"LIE",iso2:"LI",iso:"LIE",label:"Liechtenstein",phone:"423"},{ioc:"SRI",iso2:"LK",iso:"LKA",label:"Sri Lanka",phone:"94"},{ioc:"LBR",iso2:"LR",iso:"LBR",label:"Liberia",phone:"231"},{ioc:"LES",iso2:"LS",iso:"LSO",label:"Lesotho",phone:"266"},{ioc:"LTU",iso2:"LT",iso:"LTU",label:"Lithuania",phone:"370"},{ioc:"LUX",iso2:"LU",iso:"LUX",label:"Luxembourg",phone:"352"},{ioc:"LAT",iso2:"LV",iso:"LVA",label:"Latvia",phone:"371"},{ioc:"LBA",iso2:"LY",iso:"LBY",label:"Libya",phone:"218"},{ioc:"MAR",iso2:"MA",iso:"MAR",label:"Morocco",phone:"212"},{ioc:"MON",iso2:"MC",iso:"MCO",label:"Monaco",phone:"377"},{ioc:"MDA",iso2:"MD",iso:"MDA",label:"Moldova, Republic of",phone:"373"},{ioc:"MNE",iso2:"ME",iso:"MNE",label:"Montenegro",phone:"382"},{ioc:"",iso2:"MF",iso:"MAF",label:"Saint Martin (French part)",phone:"590"},{ioc:"MAD",iso2:"MG",iso:"MDG",label:"Madagascar",phone:"261"},{ioc:"MSH",iso2:"MH",iso:"MHL",label:"Marshall Islands",phone:"692"},{ioc:"MKD",iso2:"MK",iso:"MKD",label:"Macedonia, the Former Yugoslav Republic of",phone:"389"},{ioc:"MLI",iso2:"ML",iso:"MLI",label:"Mali",phone:"223"},{ioc:"MYA",iso2:"MM",iso:"MMR",label:"Myanmar",phone:"95"},{ioc:"MGL",iso2:"MN",iso:"MNG",label:"Mongolia",phone:"976"},{ioc:"MAC",iso2:"MO",iso:"MAC",label:"Macao",phone:"853"},{ioc:"NMA",iso2:"MP",iso:"NMP",label:"Northern Mariana Islands",phone:"1-670"},{ioc:"MRT",iso2:"MQ",iso:"MTQ",label:"Martinique",phone:"596"},{ioc:"MTN",iso2:"MR",iso:"MRT",label:"Mauritania",phone:"222"},{ioc:"MNT",iso2:"MS",iso:"MSR",label:"Montserrat",phone:"1-664"},{ioc:"MLT",iso2:"MT",iso:"MLT",label:"Malta",phone:"356"},{ioc:"MRI",iso2:"MU",iso:"MUS",label:"Mauritius",phone:"230"},{ioc:"MDV",iso2:"MV",iso:"MDV",label:"Maldives",phone:"960"},{ioc:"MAW",iso2:"MW",iso:"MWI",label:"Malawi",phone:"265"},{ioc:"MEX",iso2:"MX",iso:"MEX",label:"Mexico",phone:"52"},{ioc:"MAS",iso2:"MY",iso:"MYS",label:"Malaysia",phone:"60"},{ioc:"MOZ",iso2:"MZ",iso:"MOZ",label:"Mozambique",phone:"258"},{ioc:"NAM",iso2:"NA",iso:"NAM",label:"Namibia",phone:"264"},{ioc:"NCL",iso2:"NC",iso:"NCL",label:"New Caledonia",phone:"687"},{ioc:"NIG",iso2:"NE",iso:"NER",label:"Niger",phone:"227"},{ioc:"NFI",iso2:"NF",iso:"NFK",label:"Norfolk Island",phone:"672"},{ioc:"NGR",iso2:"NG",iso:"NGA",label:"Nigeria",phone:"234"},{ioc:"NCA",iso2:"NI",iso:"NIC",label:"Nicaragua",phone:"505"},{ioc:"NED",iso2:"NL",iso:"NLD",label:"Netherlands",phone:"31"},{ioc:"NOR",iso2:"NO",iso:"NOR",label:"Norway",phone:"47"},{ioc:"NEP",iso2:"NP",iso:"NPL",label:"Nepal",phone:"977"},{ioc:"NRU",iso2:"NR",iso:"NRU",label:"Nauru",phone:"674"},{ioc:"NIU",iso2:"NU",iso:"NIU",label:"Niue",phone:"683"},{ioc:"NZL",iso2:"NZ",iso:"NZL",label:"New Zealand",phone:"64"},{ioc:"OMA",iso2:"OM",iso:"OMN",label:"Oman",phone:"968"},{ioc:"PAN",iso2:"PA",iso:"PAN",label:"Panama",phone:"507"},{ioc:"PER",iso2:"PE",iso:"PER",label:"Peru",phone:"51"},{ioc:"FPO",iso2:"PF",iso:"PYF",label:"French Polynesia",phone:"689"},{ioc:"PNG",iso2:"PG",iso:"PNG",label:"Papua New Guinea",phone:"675"},{ioc:"PHI",iso2:"PH",iso:"PHL",label:"Philippines",phone:"63"},{ioc:"PAK",iso2:"PK",iso:"PAK",label:"Pakistan",phone:"92"},{ioc:"POL",iso2:"PL",iso:"POL",label:"Poland",phone:"48"},{ioc:"SPM",iso2:"PM",iso:"SPM",label:"Saint Pierre and Miquelon",phone:"508"},{ioc:"",iso2:"PN",iso:"PCN",label:"Pitcairn",phone:"870"},{ioc:"PUR",iso2:"PR",iso:"PRI",label:"Puerto Rico",phone:"1"},{ioc:"PLE",iso2:"PS",iso:"PSE",label:"Palestine, State of",phone:"970"},{ioc:"POR",iso2:"PT",iso:"PRT",label:"Portugal",phone:"351"},{ioc:"PLW",iso2:"PW",iso:"PLW",label:"Palau",phone:"680"},{ioc:"PAR",iso2:"PY",iso:"PRY",label:"Paraguay",phone:"595"},{ioc:"QAT",iso2:"QA",iso:"QAT",label:"Qatar",phone:"974"},{ioc:"REU",iso2:"RE",iso:"REU",label:"Reunion",phone:"262"},{ioc:"ROU",iso2:"RO",iso:"ROU",label:"Romania",phone:"40"},{ioc:"SRB",iso2:"RS",iso:"SRB",label:"Serbia",phone:"381"},{ioc:"RUS",iso2:"RU",iso:"RUS",label:"Russia",phone:"7"},{ioc:"RWA",iso2:"RW",iso:"RWA",label:"Rwanda",phone:"250"},{ioc:"KSA",iso2:"SA",iso:"SAU",label:"Saudi Arabia",phone:"966"},{ioc:"SOL",iso2:"SB",iso:"SLB",label:"Solomon Islands",phone:"677"},{ioc:"SEY",iso2:"SC",iso:"SYC",label:"Seychelles",phone:"248"},{ioc:"SUD",iso2:"SD",iso:"SDN",label:"Sudan",phone:"249"},{ioc:"SWE",iso2:"SE",iso:"SWE",label:"Sweden",phone:"46"},{ioc:"SIN",iso2:"SG",iso:"SGP",label:"Singapore",phone:"65"},{ioc:"HEL",iso2:"SH",iso:"SHN",label:"Saint Helena",phone:"290"},{ioc:"SLO",iso2:"SI",iso:"SVN",label:"Slovenia",phone:"386"},{ioc:"",iso2:"SJ",iso:"SJM",label:"Svalbard and Jan Mayen",phone:"47"},{ioc:"SVK",iso2:"SK",iso:"SVK",label:"Slovakia",phone:"421"},{ioc:"SLE",iso2:"SL",iso:"SLE",label:"Sierra Leone",phone:"232"},{ioc:"SMR",iso2:"SM",iso:"SMR",label:"San Marino",phone:"378"},{ioc:"SEN",iso2:"SN",iso:"SEN",label:"Senegal",phone:"221"},{ioc:"SOM",iso2:"SO",iso:"SOM",label:"Somalia",phone:"252"},{ioc:"SUR",iso2:"SR",iso:"SUR",label:"Suriname",phone:"597"},{ioc:"",iso2:"SS",iso:"SSD",label:"South Sudan",phone:"211"},{ioc:"STP",iso2:"ST",iso:"STP",label:"Sao Tome and Principe",phone:"239"},{ioc:"ESA",iso2:"SV",iso:"SLV",label:"El Salvador",phone:"503"},{ioc:"",iso2:"SX",iso:"SMX",label:"Sint Maarten",phone:"1-721"},{ioc:"SYR",iso2:"SY",iso:"SYR",label:"Syria",phone:"963"},{ioc:"",iso2:"SZ",iso:"SWZ",label:"Swaziland",phone:"268"},{ioc:"TKS",iso2:"TC",iso:"TCA",label:"Turks and Caicos Islands",phone:"1-649"},{ioc:"CHA",iso2:"TD",iso:"TCD",label:"Chad",phone:"235"},{ioc:"",iso2:"TF",iso:"ATF",label:"French Southern Territories",phone:"262"},{ioc:"TOG",iso2:"TG",iso:"TGO",label:"Togo",phone:"228"},{ioc:"THA",iso2:"TH",iso:"THA",label:"Thailand",phone:"66"},{ioc:"TJK",iso2:"TJ",iso:"TJK",label:"Tajikistan",phone:"992"},{ioc:"",iso2:"TK",iso:"TKL",label:"Tokelau",phone:"690"},{ioc:"TLS",iso2:"TL",iso:"TLS",label:"Timor-Leste",phone:"670"},{ioc:"TKM",iso2:"TM",iso:"TKM",label:"Turkmenistan",phone:"993"},{ioc:"TUN",iso2:"TN",iso:"TUN",label:"Tunisia",phone:"216"},{ioc:"TGA",iso2:"TO",iso:"TON",label:"Tonga",phone:"676"},{ioc:"TUR",iso2:"TR",iso:"TUR",label:"Turkey",phone:"90"},{ioc:"TTO",iso2:"TT",iso:"TTO",label:"Trinidad and Tobago",phone:"1-868"},{ioc:"TUV",iso2:"TV",iso:"TUV",label:"Tuvalu",phone:"688"},{ioc:"TPE",iso2:"TW",iso:"TWN",label:"Taiwan",phone:"886"},{ioc:"TAN",iso2:"TZ",iso:"TZA",label:"United Republic of Tanzania",phone:"255"},{ioc:"UKR",iso2:"UA",iso:"UKR",label:"Ukraine",phone:"380"},{ioc:"UGA",iso2:"UG",iso:"UGA",label:"Uganda",phone:"256"},{ioc:"USA",iso2:"US",label:"United States",phone:"1",suggested:!0,iso:"USA"},{ioc:"URU",iso2:"UY",iso:"URY",label:"Uruguay",phone:"598"},{ioc:"UZB",iso2:"UZ",iso:"UZB",label:"Uzbekistan",phone:"998"},{ioc:"",iso2:"VA",iso:"VAT",label:"Holy See (Vatican City State)",phone:"379"},{ioc:"VIN",iso2:"VC",iso:"VCT",label:"Saint Vincent and the Grenadines",phone:"1-784"},{ioc:"VEN",iso2:"VE",iso:"VEN",label:"Venezuela",phone:"58"},{ioc:"IVB",iso2:"VG",iso:"VGB",label:"British Virgin Islands",phone:"1-284"},{ioc:"ISV",iso2:"VI",iso:"VIR",label:"US Virgin Islands",phone:"1-340"},{ioc:"VIE",iso2:"VN",iso:"VNM",label:"Vietnam",phone:"84"},{ioc:"VAN",iso2:"VU",iso:"VUT",label:"Vanuatu",phone:"678"},{ioc:"WAF",iso2:"WF",iso:"WLF",label:"Wallis and Futuna",phone:"681"},{ioc:"SAM",iso2:"WS",iso:"WSM",label:"Samoa",phone:"685"},{ioc:"KOS",iso2:"XK",iso:"KOS",label:"Kosovo",phone:"383"},{ioc:"YEM",iso2:"YE",iso:"YEM",label:"Yemen",phone:"967"},{ioc:"MAY",iso2:"YT",iso:"MYT",label:"Mayotte",phone:"262"},{ioc:"RSA",iso2:"ZA",iso:"ZAF",label:"South Africa",phone:"27"},{ioc:"ZAM",iso2:"ZM",iso:"ZMB",label:"Zambia",phone:"260"},{ioc:"ZIM",iso2:"ZW",iso:"ZWE",label:"Zimbabwe",phone:"263"}];function zh({participant:t,withISO2:e,withIOC:r}){let{person:n,individualParticipants:o}=t,i=[n,o?.map(({person:a})=>a)].flat().filter(Boolean);function s(a){let{nationalityCode:c}=a||{};if(c){let u=ei.find(({iso:p})=>p===c);r&&u?.ioc&&!a.iocNationalityCode&&(a.iocNationalityCode=u.ioc),e&&u?.iso2&&!a.iso2NationalityCode&&(a.iso2NationalityCode=u.iso2),u?.label&&!a.countryName&&(a.countryName=u.label)}}i.forEach(s)}function Ub({participantMap:t,template:e}){let r=Object.values(t);for(let n of r){let o=n.participant;if(o.individualParticipantIds?.length){o.individualParticipants=[];for(let i of o.individualParticipantIds){let s=t[i].participant;o.individualParticipants.push(e?Bi({template:e,source:s}):s)}}}}function To(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:re}}function Qh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=To({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:it}}function en(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=Qh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:V,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:rf};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=J(i.pop(),!1,!0);if(s){let a={timeItem:s,...C};return e&&Object.assign(a,{previousItems:i}),a}else return{info:Ce}}function Xh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:sn};if(!e.timeItems)return{info:Ce};let{timeItem:o,previousItems:i,info:s}=en({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function fu({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Ot};if(!n.timeItems)return{info:Ce};let{timeItem:o,previousItems:i,info:s}=en({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function Jm({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:q};if(!e.timeItems)return{info:Ce};let{timeItem:o,previousItems:i,info:s}=en({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Jh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:q};if(!r)return{error:ie};let i=To({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Ce};let{timeItem:a,previousItems:c,info:u}=en({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var ZF={[zr]:"groupParticipantIds",[ft]:"pairParticipantIds",[Ft]:"teamParticipantIds"},tk={[zr]:"groups",[Ft]:"teams"};function Zh({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,withGroupings:i,internalUse:s,withISO2:a,withIOC:c}){let u=[],p={};for(let d of r.participants??[]){let l=d?.participantId;l&&nk({participantMap:p,participantId:l})}for(let d of r.participants??[]){let l=J(d,e,s),{participantId:f,individualParticipantIds:g,participantType:I}=l;if(!p[f]){u.push(f);continue}if(Object.assign(p[f].participant,l),g){let h=rk({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=ek(l)),o){let{ratings:h,rankings:S,seedings:T}=fa({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&zh({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=ht(t)?t:void 0;Ub({participantMap:p,template:d})}let m;return i&&(m=lu({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function ek(t){let{timeItem:e}=en({itemType:ac,element:t});return e?.itemValue===mu}function rk({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){let i=[];for(let s of t){let a=r[s]?.participant;if(!a){i.push(s);continue}if(a[ZF[n]].push(o),[Ft,zr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=tk[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===ft){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function nk({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[kt]:{...r},[xt]:{...r},[Ft]:{...r},...r}}}function Bo({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return Zh({...t,...n,tournamentRecord:r});let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>zh({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=lu({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=fa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function yt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:FI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...C};function a(c){let p=c?.extensions?.find(m=>m.name===ou)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function vo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:FI};let{appliedPolicies:i}=yt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),s={};for(let a of t){let c=i?.[a];c&&(s[a]=c)}return Object.keys(s).length?{policyDefinitions:s}:{info:kc.message}}var tS="WALKOVER",GU="RETIRED",Zm="COMPETITIVE",cc="ROUTINE",uc="DECISIVE",td="winRatio";var ok={[Si]:{policyName:"Competitive Bands Default",profileBands:{[uc]:20,[cc]:50}}},ed=ok;function $n({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=vo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[Si]??s?.[Si]??ed[Si];i.policies[Si]=a}return i}function ri({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:q};let{appliedPolicies:i}=yt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:kc?.message}}function Aa({tournamentRecord:t,categoryName:e,categoryType:r,event:n}){e=e??n?.category?.categoryName??n?.category?.ageCategoryCode,r=r??n?.category?.categoryType??n?.category?.subType;let{policy:o}=ri({policyType:No,tournamentRecord:t,event:n}),s=(t?lt({element:t,name:Vo}).extension:void 0)?.value,c=(n&&lt({name:Vo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function Kf({drawDefinition:t,attributes:e}){let{extension:r}=lt({element:t,name:Ym}),n=r?.value||{};return e.forEach(o=>{Object.keys(o).forEach(i=>{n[i]?Object.assign(n[i],o[i]):n[i]=o[i]})}),r={name:Ym,value:n},gp({drawDefinition:t,extension:r}),{entryProfile:n}}function gu({drawDefinition:t}){let{extension:e}=lt({element:t,name:Ym});return{entryProfile:e?.value||{}}}var rn="ALTERNATE",zf="CONFIRMED",kr="DIRECT_ACCEPTANCE",rd="FEED_IN",Qf="JUNIOR_EXEMPT",cs="LUCKY_LOSER",Xf="ORGANISER_ACCEPTANCE",nd="QUALIFIER",ik="REGISTERED",Jf="SPECIAL_EXEMPT",Gr="UNGROUPED",Ei="UNPAIRED",Iu="WILDCARD",so="WITHDRAWN",Zf=[zf,kr,Qf,Xf,Jf],VU=[rd,cs,nd],ni=[zf,kr,rd,Qf,Xf,Jf,Iu],Qr=[zf,kr,Qf,cs,nd,Xf,Jf,Iu],BU=[rn,zf,kr,rd,Qf,cs,Xf,nd,ik,Jf,Gr,Ei,Iu,so],Pb={ALTERNATE:rn,CONFIRMED:zf,DIRECT_ACCEPTANCE:kr,DIRECT_ENTRY_STATUSES:ni,DRAW_SPECIFIC_STATUSES:VU,EQUIVALENT_ACCEPTANCE_STATUSES:Zf,FEED_IN:rd,JUNIOR_EXEMPT:Qf,LUCKY_LOSER:cs,ORGANISER_ACCEPTANCE:Xf,QUALIFIER:nd,SPECIAL_EXEMPT:Jf,STRUCTURE_SELECTED_STATUSES:Qr,UNGROUPED:Gr,UNPAIRED:Ei,VALID_ENTRY_STATUSES:BU,WILDCARD:Iu,WITHDRAWN:so};function tg({stage:t,drawDefinition:e}){let{entryProfile:r}=gu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&Kc.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return Kf({drawDefinition:e,attributes:o}),!0}return n}function Db({stage:t,drawDefinition:e}){let{entryProfile:r}=gu({drawDefinition:e});return r[t]?.alternates||0}function Nb({stage:t,drawDefinition:e}){let{entryProfile:r}=gu({drawDefinition:e});return r[t]?.wildcardsCount||0}function eS({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Ui({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=lt({name:Mn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===fe){let{playoffEntries:p,error:m}=sk({provisionalPositioning:t,drawDefinition:r,structureId:i});return m&&console.log("playoff entries error"),(p?.length?p:u).filter(d=>!e||d.placementGroup===e)}return u}function sk({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===eo&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===Ge&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=lt({element:h,name:Zo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],y=T.groupOrder||t&&T.provisionalOrder;return h.includes(y)||h.push(y),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:y,GEMscore:P}=S,U=T||t&&y,A=[...i??[]].sort(le).indexOf(U)+1;n.push({entryStage:fe,entryStatus:rd,placementGroup:A,groupingValue:d,participantId:h,GEMscore:P})})})}return{playoffEntries:n}}function Mb({stage:t,drawDefinition:e}){return ni.reduce((r,n)=>(eS({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function nn({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=bt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:wt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===fe&&r&&Ui({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let h=I+1;return{participantId:g.participantId,seedValue:h,seedProxy:!0,seedNumber:h}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=kA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function oi(t){if(!t)return;let{tieFormatId:e,tieFormats:r}=t;if(t.tieFormat)return t.tieFormat;if(e&&Array.isArray(r))return r.find(n=>n.tieFormatId===e)}function yp({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r.tieFormat)return r.tieFormat;if(r.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function We({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:yp({item:r,drawDefinition:t,structure:e,event:n})||yp({item:e,drawDefinition:t,structure:e,event:n})||oi(t)||oi(n)}}function Rb({matchUps:t}){let e=t.reduce((n,o)=>!o.collectionPosition||n.includes(o.collectionPosition)?n:n.concat(o.collectionPosition),[]).map(n=>({[n]:t.filter(o=>o.collectionPosition===n)}));return{collectionPositionMatchUps:Object.assign({},...e)}}function De({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function ii({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}function rS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ee(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(le);return n.map(i=>o.indexOf(i)+1)}function eg(t){if(!ht(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>It(i)||i===void 0||i===null);return n&&o}function Vr(t){return Array.isArray(t)?t.every(eg):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Vr(t))return{roundMatchUps:[],error:V};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?mt(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(le).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Yt)?l.filter(({matchUpType:h})=>h===Yt):l,I=h=>h.sort((S,T)=>le(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?mt(l.roundNumber):l.roundNumber;return d[f]||(d[f]=ot({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>mt(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&On(l)){let f=d+1,g=f+l/2;tt(f,g).forEach((h,S)=>{o[h]=tt(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!pe.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>mt(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(le),I=Ee(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ee(I,h),T=l.map(y=>{let{roundPosition:P}=y,U=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!P)return U;let A=U?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return U?.slice().sort(le);let E=qt(I,A).length!==A?.length;if(A?.length&&E)return A?.length===1?[A[0],void 0]:U?.slice().sort(le);let N=(P-1)*2;return S.slice(N,N+2).map(M=>A?.find(R=>M.includes(R)))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]&&s[d+1].matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).find(({matchUpsCount:d})=>!On(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function od(t){if(!Array.isArray(t))return"";let e=t.filter(te);return e.length?ut([Math.min(...e),Math.max(...e)]).join("-"):""}function Cb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:Z};if(!e)return{error:Ur};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==qe)return{error:_i,info:"Structure is not CONSOLATION stage"};let{links:o}=t,i=o?.filter(m=>m.target.structureId===e)||[],s=i?.reduce((m,d)=>{let{structureId:l}=d.source;return m.includes(l)?m:m.concat(l)},[])||[],a=Object.assign({},...s.map(m=>{let d=ii({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=ii({matchUpsMap:r,structureId:e}),{roundProfile:u}=Ke({matchUps:c}),p={};return i?.forEach(m=>{let{structureId:d,roundNumber:l}=m.source,{feedProfile:f,groupedOrder:g,positionInterleave:I,roundNumber:h}=m.target,S=a[d],T=S[1]?.drawPositions,P=S[l]?.matchUpsCount;if(!P)return;let U=P?T.length/P:0,A=T.length/U,E=T.slice(),N=rS({roundPositionsCount:A,groupedOrder:g}),D=N?.length||1;if(D<=A){let v=T.length/D,O=Ee(E,v);f===li&&O.forEach(_=>_.reverse()),E=N?.length&&N?.map(_=>O[_-1]).flat()||E}let M=Ee(E,U);if(I){let v=tt(0,I.interleave).map(()=>{}),O=tt(0,I.offset).map(()=>{});M=M.map(F=>[F,...v]),M.unshift(O),M=M.flat(1);let _=M.length-I.offset;M=M.slice(0,_)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;M.forEach((v,O)=>{let _=1+O*b;p[h][_]||(p[h][_]=od(v))})}),{sourceDrawPositionRanges:p}}function nS({drawDefinition:t}){if(typeof t!="object")return{error:pa};let e={},{structures:r=[],links:n=[]}=t||{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[qe,fe].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,h=r.find(T=>T.structureId===I).stage,S=[h,I,g,f].join("|");if(p[S])return;p[S]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:h})}}}function bb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Ur};if(!e){let c=ii({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ke({matchUps:c}),!e)return{error:it}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ee(p,p.length/u),d=m.map(od),l=m.map(S=>S.map(T=>T-i)).map(od),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ee(T,T.length/u)}).filter(Boolean),g=tt(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(le)).map(S=>ut(S)),I=g.map(S=>fC(S).map(od).join(", ")),h=Object.assign({},...tt(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function id({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Ke({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Gi)&&!r?.structures&&t&&o}function ur({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var rg={[ga]:{policyName:"Round Naming Default",namingConventions:{round:"Round",pre:"Pre"},qualifyingFinishMap:{1:"Final"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q",preQualifying:"P"},stageConstants:{[rt]:"",[fe]:"P",[ct]:"Q",[qe]:"C"}}},vb=rg;function Ob({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=ur({structure:r}),u=id({structure:r}),p=r.structures,m={},d=rg[ga],l=r.stage===ct,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===ct).map(({stageSequence:b})=>b??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,U=(t?.namingConventions||d.namingConventions).round,A=a&&a!==rt?a[0]:"",E=t?.stageConstants||d.stageConstants,N=a&&E?.[a]||A,D=`${I}${N}${g}`,M=o?Object.keys(o):[],R=l&&E?.[ct]?`${E?.[ct]}-`:"";if(p||c||u)Object.assign(m,...M.map(b=>{let v=`${R}${U} ${b}`,O=`${y}${b}`;return{[b]:{roundName:v,abbreviatedRoundName:O}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...M.map(v=>{if(!o?.[v])return;let{matchUpsCount:O,preFeedRound:_}=o[v],F=O*2,w=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,L=_?`-${T}`:"",G=`${w}${L}`,k=[D,s,G].filter(Boolean).join("-"),W=`${S[O]||`${y}${F}`}${L}`,Y=[D,s,W].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:Y,roundName:k}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var ak=(t,e)=>(t||0)+(e||0);function oS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&tS||r<=e[uc]&&uc||r<=e[cc]&&cc||Zm}function iS({score:t}){let e=t?.sets||[],r=e.reduce((o,i)=>(o[0]+=i.side1Score||0,o[1]+=i.side2Score||0,o),[0,0]),n=e.reduce((o,i)=>(o[0]+=i.side1TiebreakScore||0,o[1]+=i.side2TiebreakScore||0,o),[0,0]);return n.reduce(ak)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function ck(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function sS(t){return t.map(ck).sort().map(e=>parseFloat(e.toFixed(2)))}function hu({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:Sr};let{score:n,winningSide:o}=r;if(!o)return{error:V};let i=!e&&t&&ri({policyType:Si,tournamentRecord:t}).policy,s=e||i?.profileBands||ed[Si].profileBands,a=iS({score:n}),c=sS([a]),u=oS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function aS({matchUp:t}){if(!t)return{error:Sr};if(t&&!t.sides)return{error:dr};if(t&&!t.hasContext)return{error:Vc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Tt).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=ut(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...C}}var sd="CHECK_IN",ad="CHECK_OUT",uk="SCHEDULE",Wi="SCHEDULE.ASSIGNMENT.VENUE",ao="SCHEDULE.ALLOCATION.COURTS",Ho="SCHEDULE.ASSIGNMENT.COURT",Ap="SCHEDULE.COURT.ORDER",ji="SCHEDULE.DATE",pk="COMPLETED.DATE",cd="HOME_PARTICIPANT_ID",ng="SCHEDULE.ASSIGN.OFFICIAL",Yi="SCHEDULE.TIME.SCHEDULED",Oo="SCHEDULE.TIME.START",qi="SCHEDULE.TIME.STOP",Pi="SCHEDULE.TIME.RESUME",Di="SCHEDULE.TIME.END",Ep="SCHEDULE.TIME.MODIFIERS",_b="TO_BE_ANNOUNCED",xb="NEXT_AVAILABLE",wb="FOLLOWED_BY",Lb="AFTER_REST",Fb="RAIN_DELAY",mk="NOT_BEFORE",cS=[_b,xb,wb,Lb,Fb],dk="ELIGIBILITY",lk="REGISTRATION",fk="SUSPENSION",gk="MEDICAL",Ik="PENALTY",HU="SCALE",WU="RATING",jU="RANKING",og="SEEDING",_o="PUBLISH",Rr="PUBLIC",xo="STATUS",hk="MODIFICATION",Sk="RETRIEVAL",Tk="other",kb={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:cS,AFTER_REST:Lb,ALLOCATE_COURTS:ao,ASSIGN_COURT:Ho,ASSIGN_OFFICIAL:ng,ASSIGN_VENUE:Wi,CHECK_IN:sd,CHECK_OUT:ad,COMPLETED_DATE:pk,COURT_ORDER:Ap,ELIGIBILITY:dk,END_TIME:Di,FOLLOWED_BY:wb,MEDICAL:gk,MODIFICATION:hk,NEXT_AVAILABLE:xb,NOT_BEFORE:mk,OTHER:Tk,PENALTY:Ik,PUBLIC:Rr,PUBLISH:_o,RANKING:jU,RATING:WU,RAIN_DELAY:Fb,REGISTRATION:lk,RESUME_TIME:Pi,RETRIEVAL:Sk,SCALE:HU,SCHEDULE:uk,SCHEDULED_DATE:ji,SCHEDULED_TIME:Yi,SEEDING:og,START_TIME:Oo,STATUS:xo,STOP_TIME:qi,SUSPENSION:fk,TIME_MODIFIERS:Ep,TO_BE_ANNOUNCED:_b};function us({matchUp:t}){if(!t)return{error:Sr};if(!t.hasContext)return{error:Vc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:dr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=aS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[sd,ad].includes(u.itemType)).sort((u,p)=>(u.createdAt?new Date(u.createdAt).getTime():0)-(p.createdAt?new Date(p.createdAt).getTime():0)),a=i.map(u=>u.itemValue).filter(u=>i.filter(p=>p?.itemValue===u).reverse()[0].itemType===sd);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...C}}var me=t=>e=>{let r=ht(e)&&e?.matchUpType||Vt(e)&&e;return r&&PI[t].includes(r)};function Up(t){let{matchUpAverageTimes:e,matchUpFormat:r}=t||{},n=e?.map(({matchUpFormatCodes:a})=>a?.filter(c=>c===r)).flat().filter(Boolean).sort((a,c)=>(a?.length||0)-(c?.length||0))||[],i=n.includes(r)?r:n[0];return e?.find(({matchUpFormatCodes:a,averageTimes:c})=>a?.find(u=>i===u)&&c)?.averageTimes}function Pp(t){let{matchUpRecoveryTimes:e,averageMinutes:r,matchUpFormat:n}=t||{};return e?.find(({matchUpFormatCodes:o,averageTimes:i,recoveryTimes:s})=>{if(i&&r){let{greaterThan:a=0,lessThan:c=360}=i;if(r>a&&r<c)return!0}return o?.find(a=>a===n)&&s})?.recoveryTimes}function uS({timesBlockArray:t,categoryName:e,categoryType:r}){return t.filter(n=>Array.isArray(n)).map(n=>n.sort((o,i)=>(i.categoryNames?.length||0)-(o.categoryNames?.length||0)).find(({categoryTypes:o,categoryNames:i})=>!i?.length&&!o?.length||i?.includes(e)||o?.includes(r))).find(Boolean)}function Gb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Pp({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Pp({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Pp({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return uS({categoryName:i,categoryType:s,timesBlockArray:m})}function Vb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Up({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Up({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Up({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return uS({categoryName:e,categoryType:r,timesBlockArray:p})}var YU="DOUBLES_SINGLES",qU="SINGLES_DOUBLES",co="total",pS="participantConflict",Ea="matchUpConflict",$U="ISSUE_IDS",pc="CONFLICT",mc="WARNING",mS="ERROR",dS="ISSUE",ig="STATE",Bb={SINGLES_DOUBLES:qU,DOUBLES_SINGLES:YU,TOTAL:co,CONFLICT_MATCHUP_ORDER:Ea,CONFLICT_PARTICIPANTS:pS,SCHEDULE_ISSUE_IDS:$U,SCHEDULE_CONFLICT:pc,SCHEDULE_WARNING:mc,SCHEDULE_ERROR:mS,SCHEDULE_ISSUE:dS,SCHEDULE_STATE:ig};function Su({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:q};s=s??a?.eventType??Fs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Aa({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return Dp({eventType:s,timingDetails:p})}function Dp({timingDetails:t,eventType:e}){let r=Vb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Gb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=me(Fs)(e)?qU:YU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function KU(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Wo({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>KU(o)-KU(i)).pop(),n=r&&KU(r);return{itemValue:r?.itemValue,timeStamp:n}}function lS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Yi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Hs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function Np(t){if(zI.test(t)){let e=Sf();return new Date(`${e}T${t}`)}else return new Date(t)}function Hb({matchUp:t}){if(!t)return{error:Sr};if(!t.timeItems)return{error:rf};let e=t.timeItems.filter(n=>[Oo,qi,Pi,Di].includes(n?.itemType)).sort((n,o)=>Np(n.itemValue).getTime()-Np(o.itemValue).getTime()),r=e.reduce((n,o)=>{let i,s=o?.itemType?.split("."),c=`SCHEDULE.TIME.${o?.itemType?.startsWith("SCHEDULE.TIME")&&s[2]}`;switch(c){case Oo:i=0;break;case Di:if(n.lastValue&&[Oo,Pi].includes(n.lastType)){let u=Np(o.itemValue).getTime()-Np(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case qi:if([Oo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=Np(o.itemValue).getTime()-Np(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;default:i=n.milliseconds;break}return{milliseconds:i,lastType:c,lastValue:o.itemValue}},{milliseconds:0,lastType:void 0,lastValue:void 0});if([Oo,Pi].includes(r.lastType)){let n=new Date().getTime()-Np(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:yk(r.milliseconds),relevantTimeItems:e}}function yk(t){let e=(r,n=2)=>("00"+r).slice(-n);return e(t/36e5|0)+":"+e(t%36e5/6e4|0)+":"+e(t%6e4/1e3|0)}function Wb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{startTime:e.reduce((i,s)=>{let a=s.itemType===Oo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function dc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:V};let o=Mr(t);r.venueId||(r.venueId=Dt());let i;for(let s of Object.values(o)){let a=Ak({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||dt({topic:jh,payload:{venue:r}}),ot({...C,venue:i})}function Ak({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Dt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:TE}:(r&&At({element:n,extension:{value:r,name:TU}}),t.venues.push(n),e||dt({payload:{venue:n,tournamentId:t.tournamentId},topic:jh}),{...C,venue:J(n)})):{error:it,info:"missing venue"}:{error:q}}function jo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:q};if(!r)return{error:Jo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(su({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=jo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return dc({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:Fi}}function fS({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=jo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ps({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:q};if(!r)return{error:xi};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...C,court:o,venue:i};if(t){let a=(su({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ps({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&dc({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return x({result:{error:Os},stack:n})}function gS(t){return J(ps(t),!1,!0)}function ud({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:q};if(!r)return{error:xi};let n=ps({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...C,courtInfo:J(o,!1,e)}}function lc(t){let e=et(t,[{[se]:!0},{venueId:!0,[gn]:Jo}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=jo({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(ud({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:m})=>({venueAbbreviation:m,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...C,venueData:J(c,!1,!0)}}function jb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{endTime:e.reduce((i,s)=>{let a=s.itemType===Di&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:Ot};let n=lt({name:cn,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function ze(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Ht({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,...x({result:{error:jr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,...x({result:{error:br},context:{drawId:n,eventId:r},stack:o})}}function pd(t){let e=t.event,r=t.matchUpType,{scheduleVisibilityFilters:n,afterRecoveryTimes:o,tournamentRecord:i,usePublishState:s,scheduleTiming:a,matchUpFormat:c,publishStatus:u,matchUp:p}=t;if(!p)return{error:Sr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let U=t.drawDefinition||e?.drawDefinitions?.find(E=>E.drawId===p.drawId);!U&&i&&({drawDefinition:U,event:e}=ze({drawId:p.drawId,tournamentRecord:i}));let A=p.structureId&&U?.structures?.find(({structureId:E})=>E===p.structureId);r=t.matchUpType||A?.matchUpType||U?.matchUpType||e?.eventType!==ve&&e?.eventType}let{milliseconds:m,time:d}=Hb({matchUp:p}),{startTime:l}=Wb({matchUp:p}),{endTime:f}=jb({matchUp:p}),g,{eventIds:I,drawIds:h}=n??{};if((!I||I.includes(p.eventId))&&(!h||h.includes(p.drawId))){let U=Q=>Q.createdAt?new Date(Q.createdAt).getTime():0,A=new Map,E=p.timeItems?.toSorted((Q,pt)=>U(Q)-U(pt))??[];for(let Q of E)A.set(Q.itemType,Q.itemValue);let N=A.get(cd),D=A.get(ao),M=A.get(Yi),R=A.get(Ep),b=A.get(ji),v=A.get(ng),O=A.get(Ap),_=A.get(Wi),F=A.get(Ho),w,L,G,k,H,W=p.matchUpType??r;if(a&&M&&o&&W){let Q={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:L=0,recoveryMinutes:G=0,typeChangeRecoveryMinutes:k=0}=Dp({timingDetails:Q,eventType:W})),(L||G)&&(w=f?Yr(Xt(f),G):Yr(M,L+G)),k&&(H=f?Yr(Xt(f),k):Yr(M,L+k))}!b&&M&&(b=Et(M));let Y=vm({scheduledDate:b,scheduledTime:M}),$={},B=(i&&_&&lc({tournamentRecord:i,venueId:_}))?.venueData||{};_&&($[_]=B);let{venueName:K,venueAbbreviation:X,courtsInfo:j}=B,z=(F&&j?.find(Q=>Q.courtId===F))?.courtName;for(let Q of D||[]){if(!i)break;Q.venueId&&!$[Q.venueid]&&($[Q.venueId]=lc({venueId:Q.venueId,tournamentRecord:i})?.venueData);let pt=$[Q.venueId];Q.venueName=pt?.venueName;let st=pt?.courtsInfo?.find(Mt=>Mt.courtId===Q.courtId);Q.courtName=st?.courtName}g=ot({typeChangeTimeAfterRecovery:H,timeAfterRecovery:w,scheduledDate:b,scheduledTime:M,isoDateString:Y,homeParticipantId:N,venueAbbreviation:X,allocatedCourts:D,timeModifiers:R,venueName:K,venueId:_,courtOrder:O,courtName:z,courtId:F,official:v,typeChangeRecoveryMinutes:k,recoveryMinutes:G,averageMinutes:L,milliseconds:m,startTime:l,endTime:f,time:d})}else g=ot({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Hs({matchUp:p}),{scheduledTime:T}=lS({matchUp:p});if(s&&u?.displaySettings?.draws){let U=u.displaySettings.draws,A=(U?.[p.drawId]??U?.default)?.scheduleDetails;if(A){let E=(A.find(N=>S&&N.dates?.includes(S))??A.find(N=>!N.dates?.length))?.attributes;if(E){let N=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),E);g=Bi({source:g,template:N})}}}let P=p.matchUpStatus&&pe.includes(p.matchUpStatus)&&(Et(f)||Et(S)||Et(T))||void 0;return{schedule:g,endDate:P}}function Yb({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(RI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Fe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(MI(t)){let c=[...t].sort(le);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(mt(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Mp({collectionPosition:t,collectionId:e,lineUp:r}){let n=[],o=[];if(r){let i=a=>a===void 0?-1:a,s=r.map(a=>{let{collectionAssignments:c,participantId:u}=a,p=c?.find(m=>m.collectionPosition===t&&m.collectionId===e);return p&&{participantId:u,...p}}).filter(Boolean).sort((a,c)=>i(a.substitutionOrder)-i(c.substitutionOrder));for(let a of s){let{participantId:c,previousParticipantId:u,substitutionOrder:p}=a;n.includes(c)||(u&&o.push({previousParticipantId:u,substitutionOrder:p,participantId:c}),n=n.filter(m=>m!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function hn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:q};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return x({result:{error:Uo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===ft&&qt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return x({result:{error:re},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function ms({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:ie};let{extension:r}=lt({element:t,name:Ro});return{lineUp:(r?.value||{})[e]}}function qb({tournamentParticipants:t,positionAssignments:e,collectionPosition:r,drawPositions:n=[],participantMap:o,drawDefinition:i,collectionId:s,sideLineUps:a,matchUpType:c}){if(!s||!r)return{};let u=({attribute:m,lineUp:d,teamParticipant:l})=>{let{assignedParticipantIds:f,substitutions:g}=Mp({collectionPosition:r,collectionId:s,lineUp:d});if(c===xt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||hn({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[m]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[m]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[m]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let m=a?.map(d=>{let{teamParticipant:l,sideNumber:f}=d,g=d.lineUp||ms({participantId:l.teamParticipantId,drawDefinition:i})?.lineUp;return u({attribute:f,lineUp:g,teamParticipant:l})}).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...m)}}let p=n?.map(m=>{let d=e.find(I=>I.drawPosition===m)?.participantId,l=a?.find(I=>I?.drawPosition===m),f=l?.teamParticipant||d&&o?.[d]?.participant||t?.find(({participantId:I})=>I===d),g=l?.lineUp||ms({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function md(t){let e=et(t,[{[xn]:!0}]);if(e.error)return e;let r=t?.matchUp,n=r?.matchUpType;if(!n&&r?.sides?.length){let s=r.sides.find(({participant:a})=>a)?.participant?.participantType;n=s===Tt&&kt||s===ft&&xt||s===Ft&&Ft||void 0}return{matchUpType:n}}function $b({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:r,displaySideNumber:n,seedAssignments:o,drawPosition:i,isFeedRound:s,sideNumber:a}){let c=r.find(l=>l.drawPosition&&l.drawPosition===i),u=i&&t,p=a&&e,m=u?u[i]?.participantId:c?.participantId,d=c?Ek({displaySideNumber:n,seedAssignments:o,participantId:m,assignment:c,sideNumber:a}):{...p?.[a]};if(s&&(a===1?Object.assign(d,{participantFed:!0}):Object.assign(d,{participantAdvanced:!0})),i&&u){let l=u[i]?.teamParticipant,f=u[i]?.participant,g=u[i]?.substitutions;f&&(d.participant=f),g&&(d.substitutions=g),l&&(d.teamParticipant=l)}return d}function Ek({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Uk({seedAssignments:e,participantId:r});Object.assign(i,s,{participantId:r}),s?.seedNumber&&s?.seedValue===""&&(i.seedValue="~")}else n.bye&&Object.assign(i,{bye:!0});return n.qualifier&&Object.assign(i,{qualifier:!0}),i}function Uk({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function zU({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:m,appliedPolicies:d,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,publishStatus:P,scoringActive:U,matchUpTieId:A,isRoundRobin:E,roundProfile:N,sideLineUps:D,structure:M,context:R,matchUp:b,event:v}){c=c??{};let O=We({drawDefinition:y,structure:M,matchUp:b,event:v})?.tieFormat,{roundOffset:_,structureId:F,structureName:w,stage:L,stageSequence:G}=M,{drawId:k,drawName:H,drawType:W}=y??{},Y=O?.collectionDefinitions,$=b.collectionId&&Y?.find(jt=>jt.collectionId===b.collectionId),B=b.collectionId?$?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,K=b.matchUpType||$?.matchUpType||M?.matchUpType||y?.matchUpType||!me(ve)(v?.eventType)&&v?.eventType,X=l?Nt:b.matchUpStatus,{schedule:j,endDate:nt}=pd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:B,publishStatus:P,matchUpType:K,matchUp:b,event:v}),z=m??b.drawPositions??[],{collectionPosition:Q,collectionId:pt,roundPosition:st}=b,Mt=b.roundNumber??c.roundNumber,_t=pt?qb({tournamentParticipants:r,positionAssignments:n,collectionPosition:Q,participantMap:I,drawDefinition:y,drawPositions:z,collectionId:pt,sideLineUps:D,matchUpType:K}):void 0,Re=u?.[Mt]?.roundName||c.roundName,Kt=u?.[Mt]?.abbreviatedRoundName||c.abbreviatedRoundName,Ie=N?.[Mt]?.feedRound,_r=N?.[Mt]?.preFeedRound,pn=N?.[Mt]?.roundFactor,gr=o?.[Mt],Xe=st?gr?.[st]:void 0,ee=e?.[Mt],Ut=$?.category?{...R?.category||{},...$.category}:R?.category??v?.category,ce=b.processCodes?.length&&b.processCodes||$?.processCodes?.length&&$?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||v?.processCodes?.length&&v?.processCodes||p?.processCodes,ue=T?.withCompetitiveness&&hu({...h,matchUp:b}),we=b.finishingPositionRange??c.finishingPositionRange,zt=jt=>ot(jt,void 0,!0),Wt={...zt(R),...zt({matchUpFormat:b.matchUpType===ve?void 0:B,tieFormat:b.matchUpType!==ve?void 0:O,gender:$?.gender??v?.gender,roundOfPlay:L!==ct&&It(a)&&a+(Mt||0),endDate:b.endDate??nt,discipline:v?.discipline,category:Ut,finishingPositionRange:we,abbreviatedRoundName:Kt,drawPositionsRange:Xe,competitiveProfile:ue,structureName:w,stageSequence:G,drawPositions:z,matchUpStatus:X,processCodes:ce,isRoundRobin:E,matchUpTieId:A,preFeedRound:_r,matchUpType:K,roundFactor:pn,roundOffset:_,structureId:F,roundNumber:Mt,feedRound:Ie,roundName:Re,drawName:H,drawType:W,schedule:j,drawId:k,stage:L}),...J(zt(b),!0,!0)};if(B&&b.score?.scoreStringSide1){let jt=Ye(B),{bestOf:Pe,finalSetFormat:lr,setFormat:he}=jt??{};(lr?.tiebreakSet||he?.tiebreakSet||he?.timed)&&(Wt.score.sets=Wt.score.sets.sort((oe,Le)=>oe.setNumber-Le.setNumber).map((oe,Le)=>(Le+1===Pe?(lr?.tiebreakSet||lr?.timed)&&(oe.tiebreakSet=!0):(he?.tiebreakSet||he?.timed)&&(oe.tiebreakSet=!0),oe)))}if(Array.isArray(z)){let{orderedDrawPositions:jt,displayOrder:Pe}=Yb({drawPositions:z,roundProfile:N,roundNumber:Mt}),lr=N?.[Mt]?.feedRound,he=Pe[0]!==jt[0],Le=jt.concat(void 0,void 0).slice(0,2).map((Cr,Je)=>{let Hn=Je+1,de=he?3-Hn:Hn,Er=$b({..._t,positionAssignments:n,displaySideNumber:de,seedAssignments:f,drawPosition:Cr,isFeedRound:lr,sideNumber:Hn}),ts=b.sides?.find(aa=>aa.sideNumber===Hn),mn=st?(st-1)*2+Je+1:void 0,vi=mn?ee?.[mn]:void 0;return zt({sourceDrawPositionRange:vi,...ts,...Er})});Object.assign(Wt,J({sides:Le},!0,!0))}if(r&&Wt.sides){let jt=d?.[Vs],Pe=he=>{let oe=I?.[he]?.participant;return oe&&Bi({template:jt?.participant,source:oe})};if(Wt.sides.filter(Boolean).forEach(he=>{if(he.participantId){let oe=J(Pe(he.participantId)||(r?Go({policyDefinitions:d,participantId:he.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(oe){let Le,Cr;if(y?.entries){let Je=y.entries.find(de=>de.participantId===he.participantId),Hn=v?.entries?.find(de=>de.participantId===he.participantId);Le=Je?.entryStatus||Hn?.entryStatus,oe.entryStatus=Le,Je?.entryStage&&(Cr=Je.entryStage,oe.entryStage=Cr)}i!==!1?Object.assign(he,{participant:oe}):Object.assign(he,{participant:{entryStage:Cr,entryStatus:Le}})}}if(he?.participant?.individualParticipantIds?.length&&!he.participant.individualParticipants?.length){let oe=he.participant.individualParticipantIds.map(Le=>Pe(Le)||(r?Go({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:Le}):void 0));i!==!1&&Object.assign(he.participant,{individualParticipants:oe})}}),!Wt.matchUpType){let{matchUpType:he}=md({matchUp:Wt});he&&Object.assign(Wt,{matchUpType:he})}if(T?.inferGender&&(!Wt.gender||Wt.gender===yr)&&Wt.sides?.length===2&&Wt.matchUpType!==ve){let he=Wt.sides.map(oe=>{if(me(kt)(Wt.matchUpType))return oe.participant?.person?.sex;if(oe.participant?.individualParticipants?.length===2){let Le=ut(oe.participant.individualParticipants.map(Cr=>Cr.person?.sex)).filter(Boolean);if(Le.length===1)return Le[0]}});if(he.filter(Boolean).length===2&&ut(he).length===1){let oe=he[0];Wt.inferredGender=oe}}}if(Wt.tieMatchUps){let jt=Wt.matchUpStatus===Nt,Pe=Wt.sides?.map(({participant:lr,drawPosition:he,sideNumber:oe,lineUp:Le})=>{let Cr=lr?.participantType===ve&&lr;return{teamParticipant:Cr&&ot({participantRoleResponsibilities:Cr.participantRoleResponsibilities,participantOtherName:Cr.participanOthertName,participantName:Cr.participantName,participantId:Cr.participantId,teamId:Cr.teamId}),drawPosition:he,sideNumber:oe,lineUp:Le}});Wt.tieMatchUps=Wt.tieMatchUps.map(lr=>{let he=Wt.matchUpId,Le={finishingPositionRange:Wt.finishingPositionRange,abbreviatedRoundName:Kt,roundNumber:Mt,roundName:Re};return zU({tieDrawPositions:z,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:Pe,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:Le,appliedPolicies:d,isCollectionBye:jt,usePublishState:g,publishStatus:P,matchUpTieId:he,isRoundRobin:E,roundProfile:N,matchUp:lr,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:U,structure:M,context:R})})}let Ir=Wt.sides&&Wt.sides.filter(jt=>jt?.participantId).length===2,mr=!Wt.winningSide;if(Object.assign(Wt,{readyToScore:U&&Ir&&mr,hasContext:!0}),Ir){let{allParticipantsCheckedIn:jt,checkedInParticipantIds:Pe}=us({matchUp:Wt});Object.assign(Wt,{allParticipantsCheckedIn:jt,checkedInParticipantIds:Pe})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(jt=>delete Wt[jt]),Wt}function Kb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:ao});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function zb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Ho});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function Qb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Wi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function Ni(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:P,tournamentIds:U,matchUpTypes:A,structureIds:E,readyToScore:N,courtIds:D,eventIds:M,venueIds:R,drawIds:b,stages:v}=t,O=Array.isArray(y)?y.filter(Boolean):[],_=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],w=Array.isArray(v)?v.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],G=Array.isArray(p)?p.filter(Boolean):[],k=Array.isArray(f)?f.filter(Boolean):[],H=Array.isArray(d)?d.filter(Boolean):[],W=Array.isArray(c)?c.filter(Boolean):[],Y=Array.isArray(l)&&I?l.filter(Boolean):[],$=Array.isArray(A)&&g?A.filter(Boolean):[],B=Array.isArray(D)?D.filter(Boolean):[],K=Array.isArray(R)?R.filter(Boolean):[],X=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],j=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],nt=Array.isArray(U)?U.filter(Boolean):[],z=Array.isArray(M)?M.filter(Boolean):[],Q=Array.isArray(b)?b.filter(Boolean):[],pt=Array.isArray(E)?E.filter(Boolean):[];return e.filter(st=>{if(N&&!me(xr)(st)&&!st.readyToScore||st.winningSide&&s&&![1,2].includes(st.winningSide)||m!==void 0&&(m&&!st.tieMatchUps||!m&&st.tieMatchUps)||o!==void 0&&(o&&!st.collectionId||!o&&st.collectionId)||w.length&&!w.includes(st.stage)||L.length&&!L.includes(st.stageSequence)||G.length&&(!st.collectionId||!G.includes(st.collectionId))||k.length&&(!st.roundName||!k.includes(st.roundName))||H.length&&(!st.roundNumber||!H.includes(st.roundNumber))||W.length&&(!st.roundPosition||!W.includes(st.roundPosition))||_.length&&(!st.matchUpStatus||!_.includes(st.matchUpStatus))||F.length&&st.matchUpStatus&&F.includes(st.matchUpStatus)||Y.length&&!Y.includes(st.matchUpId)||$.length&&(!st.matchUpType||!Fc($,st.matchUpType))||X.length&&(!st.matchUpFormat||!X.includes(st.matchUpFormat)))return!1;if(j?.length){let{scheduledTime:Mt}=lS({matchUp:st}),{scheduledDate:_t}=Hs({matchUp:st}),Kt=Et(Mt)||_t;if(!j.find(Ie=>Yn(Ie,Kt)))return!1}if(B.length){let{courtId:Mt}=zb({matchUp:st}),{allocatedCourts:_t}=Kb({matchUp:st}),Re=_t?.map(({courtId:Kt})=>Kt);if(!B.filter(Boolean).includes(Mt)||Re?.includes(Mt))return!1}if(K.length){let{venueId:Mt}=Qb({matchUp:st});if(!K.filter(Boolean).includes(Mt))return!1}if(P){if(nt.length&&!nt.includes(st.tournamentId)||z.length&&!z.includes(st.eventId)||Q.length&&!Q.includes(st.drawId)||pt.length&&!pt.includes(st.structureId))return!1;let Mt=st.sides?.map(({participantId:_t})=>_t).filter(Boolean)??[];if(n&&Mt.length<n||O.length&&!O.some(Re=>Mt.includes(Re)))return!1}return!0})}function Pt(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:m,contextContent:d,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:mi,roundMatchUps:I,matchUps:[]};let h=Array.isArray(o?.eventIds)?o?.eventIds.filter(Boolean):[],S=Array.isArray(o?.structureIds)?o?.structureIds.filter(Boolean):[],T=Array.isArray(o?.drawIds)?o?.drawIds.filter(Boolean):[],y=!a?.eventId||!h?.length&&!n?.eventIds?.filter(Boolean).length||h?.includes(a.eventId)||n?.eventIds?.includes(a.eventId),P=!S?.length||S.includes(c.structureId),U=!s||!T?.length||T.includes(s.drawId);if(!y||!P||!U)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=$n({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:A}=yt({drawDefinition:s}),E={...t.tournamentAppliedPolicies,...A,...t.policyDefinitions},N=E?.scoring?.structures,D=c.stage&&N?.stage?.[c.stage],M=c.stageSequence&&D?.stageSequence?.[c.stageSequence],R=E?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned;f||(f=De({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:v}=ye({structure:c}),O=!R||v,{seedAssignments:_}=nn({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??_;let{structureId:F}=c;l=l||s&&nS({drawDefinition:s}).exitProfiles;let w=l?.[F],L=w?.length&&(w[0].split("-").map(B=>parseInt(B)).reduce((B,K)=>B+K)||0),G=!!c.structures,k=ii({matchUpsMap:f,structureId:F,inContext:u}),H=E?.[ga],W=Ob({roundNamingPolicy:H,drawDefinition:s,structure:c,matchUps:k}),{roundNamingProfile:Y,roundProfile:$}=W;if(I=W?.roundMatchUps??[],o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:B}=Cb({drawDefinition:s,matchUpsMap:f,structureId:F}),K=s?bb({drawDefinition:s,roundProfile:$,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0,X=t.tournamentParticipants,j=t.participantMap;!X?.length&&!j&&r&&({participants:X=[],participantMap:j}=Bo({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:r,contextProfile:i,inContext:u})),k=k.map(z=>zU({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:B,tournamentParticipants:X,positionAssignments:b,drawPositionsRanges:K,initialRoundOfPlay:L,roundNamingProfile:Y,tournamentRecord:r,appliedPolicies:E,seedAssignments:m,contextContent:d,participantMap:j,contextProfile:i,drawDefinition:s,scoringActive:O,isRoundRobin:G,roundProfile:$,structure:c,context:a,matchUp:z,event:p})),(k?.filter(z=>Array.isArray(z.tieMatchUps))).forEach(z=>{let Q=z.tieMatchUps;k=k.concat(...Q)}),n&&(k=Ni({processContext:!0,...n,matchUps:k}))}else(k?.filter(K=>Array.isArray(K.tieMatchUps))).forEach(K=>{let X=K.tieMatchUps;k=k.concat(...X)});return o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(k=Ni({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:k})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ke({matchUps:k}).roundMatchUps??[]),We({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=Rb({matchUps:k})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:G,roundProfile:$,matchUpsMap:f,matchUps:k}}function ds({matchUp:t}){return t?pe.includes(t?.matchUpStatus)||t?.winningSide:!1}function Tu({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structureId:T,inContext:y,structure:P,context:U,event:A}){!P&&T&&({structure:P}=at({drawDefinition:I,structureId:T}));let E=Pt({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structure:P,inContext:y,context:U,event:A}),N=[],D=[],M=[],R=[],b=[];if(E.error)return E;let{matchUps:v}=E,{assignedPositions:O}=ye({structure:P}),_=O?.filter(w=>w.participantId).map(w=>w.drawPosition),F;return v.filter(w=>{let L=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===Yt;return!(w.matchUpType!==Yt&&L)}).forEach(w=>{if(w.matchUpStatus===Or){N.push(w);return}w.matchUpType===Yt&&(F=!0);let L=w.collectionId,G=L&&w.sides?.every(K=>K.participantId),k=!L&&w.drawPositions?.filter(Boolean).length===2,H=!L&&w.drawPositions?.every(K=>_?.includes(K)),W=O?.filter(K=>K.bye).map(K=>K.drawPosition),Y=!L&&w.drawPositions?.find(K=>W?.includes(K)),B=Bh.includes(w.matchUpStatus)&&(G||k&&(!t||H));return Y?b.push(w):ds({matchUp:w})?D.push(w):B?M.push(w):R.push(w)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:P}}function Xb({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Ur};let{links:n}=Ws({drawDefinition:t,structureId:r}),o=n.source.reduce((s,a)=>!a.source.roundNumber||a.source.roundNumber===e?s.concat(a):s,[]),i=n.target.reduce((s,a)=>!a.target.roundNumber||a.target.roundNumber===e?s.concat(a):s,[]);return{links:{source:o,target:i}}}function IS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Fe(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[fo,ro].includes(o?.linkType)&&!o?.source?.roundNumber?x({result:{error:V},stack:"getTargetLink",context:o}):o}function Ws({drawDefinition:t,structureId:e,roundNumber:r}){return t?e?{links:(t.links||[]).filter(Boolean).reduce((i,s)=>(s.source?.structureId===e&&(!r||s.source.roundNumber===r)&&(i.source=i.source.concat(s)),s.target?.structureId===e&&(!r||s.target.roundNumber===r)&&(i.target=i.target.concat(s)),i),{source:[],target:[]})}:{error:Ur}:{error:Z}}function Jb({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function hS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:Vl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({drawDefinition:n,structureId:i}),{positionAssignments:m}=bt({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=tt(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let D=u.offset+(r-1)*u.interleave,M=r+D;h=Math.ceil(M/2),S=1-M%2}let T=g,y=g[h-1],P=rS({roundPositionsCount:g.length,groupedOrder:a}),U=P?.length||1;if(U<=g.length){let D=f/U,M=Ee(g,D);s===li&&M.forEach(R=>R.reverse()),T=P?.length&&P?.map(R=>M[R-1]).flat()||T}s===En?y=T[h-1]:s===li?((!P?.length||U>g.length)&&(h=l.length+1-h),y=T[h-1]):s===up&&Pr()&&console.log(tp,{feedProfile:s});let A=y&&l.reduce((D,M)=>M.roundPosition===y?M:D,void 0),E;A?.feedRound?(S=0,E=Math.min(...(A.drawPositions||[]).filter(Boolean))):E=A?.drawPositions?.length===2&&A?.drawPositions[S];let N=m?.find(({drawPosition:D})=>D===E);if(N){let{extension:D}=lt({element:N,name:Wm});if(D?.value)return{disabledDrawPosition:E}}return{matchUp:A,targetDrawPosition:E,matchUpDrawPositionIndex:S}}function pr({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Vi?Pk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Dk({matchUp:i})}function Pk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=Xb({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=IS({source:c,linkType:fo}),p=IS({linkCondition:_n,linkType:ro,source:c}),m=IS({source:c,linkType:ro}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,P,U,A,E,N;if(e&&(i||s)&&(U=i&&l!==ln&&t.find(({matchUpId:R})=>R===i),T=s&&f!==ln&&t.find(({matchUpId:R})=>R===s),U||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:U}};let{roundPosition:D}=o;N=N||t.filter(R=>R.structureId===n.structureId);let M=N.reduce((R,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?R+1:R,0);return m&&!T&&f!==ln&&({matchUpDrawPositionIndex:P,targetDrawPosition:y,matchUp:T}=hS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==ln&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=hS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!U&&l!==ln&&({matchUpDrawPositionIndex:E,targetDrawPosition:A,matchUp:U}=hS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),U||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:U}=Jb({structureMatchUps:N,matchUp:o})),ot({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:E,loserMatchUpDrawPositionIndex:P,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:U,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function Dk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Zb({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=at({drawDefinition:t,structureId:i});if(a?.finishingPosition===fi){let{roundNumber:c}=n,u=c&&mt(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Ke({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(le).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=pr({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=QU({upcomingMatchUp:u}),d=QU({upcomingMatchUp:p});if(n.matchUpStatus!==Nt&&p?.matchUpStatus===Nt){let{matchUp:f}=tv({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&QU({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&$t(m.schedule.scheduledTime)<$t(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&$t(d.schedule.scheduledTime)<$t(l)&&(r[d.matchUpId]=n.matchUpId,d.schedule.scheduleConflict=n.matchUpId)),Object.assign(n,{winnerTo:m,loserTo:d}),n.drawPositions?.filter(Boolean).length){let g=c.targetLinks?.loserTargetLink?.linkCondition===_n,I=Nk(n);if(I.length){let h=_f(u?.sides),S=_f(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,U=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&U.length<2&&U.push({bye:!0,tbd:!0}),y?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:A})=>A===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(y)),U?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(U))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function Nk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function tv({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Jt)return{matchUp:t};if(o===Nt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=pr({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},tv({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function QU(t){if(t?.upcomingMatchUp)return(({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s})=>({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s}))(t.upcomingMatchUp)}function ae(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=js(t);if(r.error)return x({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function js(t){if(!t?.drawDefinition)return{error:Z};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:y,context:P,event:U}=t,A=[],E=[],N=[],D=[],M=[];h&&!r&&(r=$n({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:U}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=lu({participants:e,participantsProfile:a})));let{structures:b}=In({drawDefinition:S});if(!b)return{error:wt};n||(n=De({drawDefinition:S}));let v=S&&nS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:w=[],pendingMatchUps:L=[],upcomingMatchUps:G=[],completedMatchUps:k=[],abandonedMatchUps:H=[]}=Tu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||T||d,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:v,matchUpsMap:n,structure:F,context:P,event:U});A=A.concat(...H),E=E.concat(...k),N=N.concat(...G),D=D.concat(...L),M=M.concat(...w)});let O=F=>(!l&&!T&&!d||(l&&(F=Ni({matchUps:F,...l})),d&&(F=Ni({matchUps:F,...d,processContext:!0}))),F),_={abandonedMatchUps:O(A),completedMatchUps:O(E),upcomingMatchUps:O(N),pendingMatchUps:O(D),byeMatchUps:O(M),matchUpsMap:n,...C,groupInfo:R};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:w,completed:L,upcoming:G,pending:k,bye:H}=F,W=[].concat(...w&&A||[],...L&&E||[],...G&&N||[],...k&&D||[],...H&&M||[]);Zb({inContextDrawMatchUps:W,drawDefinition:S})}return _}function Kn(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:h,event:S}=t;if(!S)return{error:Ot};let{eventId:T,eventName:y,endDate:P,eventType:U,category:A,gender:E,matchUpFormat:N}=S??{},D={...h,...ot({indoorOutDoor:S.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:S.surfaceCategory??p?.surfaceCategory,endDate:S.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:N,eventName:y,eventType:U,category:A,eventId:T,gender:E})};P&&(D.endDate=P),f&&!r&&(r=$n({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:S}));let M;if(!e?.length&&!n&&p){let O=Bo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=O.participantMap,e=O.participants??[],M=O.groupInfo}let R=S.drawDefinitions??[],b=Aa({tournamentRecord:p,event:S}).scheduleTiming;return{matchUps:R.flatMap(O=>{let{matchUps:_}=ae({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:D,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:O,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:b,nextMatchUps:g,inContext:I,event:S});return _??[]}),groupInfo:M}}function Ae(t){let e=et(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:q};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:m,contextProfile:d,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,h=t.tournamentId??u.tournamentId,S=u?.events??[];n||({participants:n,participantMap:r}=Bo({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:d,inContext:p}));let{appliedPolicies:T}=yt({tournamentRecord:u}),y={...I,tournamentId:h,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},P=$n({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:S.flatMap(A=>(y.eventDrawsCount=A.drawDefinitions?.length??0,Kn({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:m,contextContent:P,contextFilters:f,contextProfile:d,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:A}).matchUps??[])).concat(...u.matchUps??[])}}function Un({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}){if(typeof n!="object"||!Object.keys(n).length)return{error:Lt};let m=Object.keys(n).map(d=>{let l=n[d];return Ae({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...C,matchUps:m}}function Mi(t,e){return Mk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Mk(t,e){return(ks[t?.stage]||0)-(ks[e?.stage]||0)}function or(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:y,endDate:P,eventType:U,category:A,gender:E,matchUpFormat:N}=S??{},D={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:N,eventType:U,eventName:y,category:A,eventId:T,endDate:P,gender:E},M;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:M}=Bo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=$n({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...ae({context:D,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:d,contextProfile:l,matchUpFilters:m,participantMap:r,nextMatchUps:g,inContext:I,event:S}),groupInfo:M}}function ls({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=J(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}var XU=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:ls({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:ls({element:e,accessor:r})?.value}))||(typeof t=="string"&&ls({element:e,accessor:t}))?.value,Br=XU;function Ua({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Vr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Ke({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,m=p&&c?.[n-p]?.matchUpsCount,d=c&&Object.values(c).map(Br("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},y=d?.slice(I-1).reduce((R,b)=>R+(b||0),0),P=a&&I!==1,U=1+t+(P?r??0:0),A=1,E=tt(U,s?U+S*2:y+U+A),N=y+A-S,D=l(E.slice(N)),M=l(E.slice(0,N),!0);return T.finishingPositionRange={loser:D,winner:M},{[I]:T}})),g=Pr({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let h=I.roundNumber&&f[I.roundNumber];g&&!h&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=h?.finishingRound,I.finishingPositionRange=h?.finishingPositionRange}),i}function $i({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=ae({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Ua({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=pr({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=ii({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function on(t){let e=Mr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Jn};if(!Array.isArray(n))return{error:sn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:rs};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(P=>(P.drawDefinitions||[]).map(U=>U.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===eo),g=r;if(f.length){g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,P)=>{let U=P.source?.structureId,A=P.target?.structureId;return U&&A&&(p[A]=U),U&&!y.includes(U)&&y.push(U),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let P=y.containerStructureId||y.structureId;T.includes(P)&&c[P].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(U=>{u[y].matchUpIds.push(U)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(U=>u[y].participantIds.push(U))},S=T=>{let y=Object.keys(c).length;for(let P of T||[]){let{matchUpId:U,winnerMatchUpId:A,loserMatchUpId:E}=P;if(!a.length||a.includes(U)){if(I(U),o){let{individualParticipantIds:M}=pu(P);u[U].participantIds=M}A&&(I(A),h(U,A),m[A].push(U)),E&&(I(E),h(U,E),m[E].push(U)),u[U].sources.push(m[U]);let N=m[U].map(M=>u[M].sources[0]).flat(),D=m[U].map(M=>u[M].sources[1]).flat();if(u[U].sources.push(N,D),y){let M=P.containerStructureId||P.structureId,R=p[M];if(c[R])for(let b of c[R])I(b),h(b,U),m[b].push(U)}}}};if(s)$i({drawDefinition:s}),g?.length||(g=or({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:P=[]})=>P.map(({drawId:U})=>U))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(U=>U.drawId===T).sort(Mi);if(!y?.find(({roundPosition:U})=>!U)){let U=y?.find(({tournamentId:E})=>E),{drawDefinition:A}=ze({tournamentRecord:e[U?.tournamentId],drawId:T});A&&$i({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function Se(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Pa({matchUpStatus:t}){return Gh.includes(t)}function ev({matchUpStatus:t}){return zm.includes(t)}function sg({matchUpStatus:t}){return Vh.includes(t)}function ag({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(ag)?.length;return Se({score:o})||s||e&&i||t&&ev({matchUpStatus:t})&&![Rt,Ct,Fn].includes(t)}function Da(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=as({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let A=at({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(ur({structure:i}))return{structure:i,isAdHoc:!0,error:Rs};let{matchUps:u}=ae({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||c.includes(A.structureId)),{matchUpDependencies:m}=on({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let A of u??[]){if(A.structureId===n||c.includes(A.structureId)){l.push(...A.drawPositions??[]);let E=A.roundNumber;for(let N of(A.drawPositions??[]).filter(Boolean))(!f[N]||E&&f[N]>E)&&(f[N]=E)}ag(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=ut(l.filter(Boolean)).sort(le),h=ut(d),S=ut(p?.map(({matchUpId:A,drawPositions:E})=>h.includes(A)?E:[]).flat().filter(Boolean)).sort(le),{positionAssignments:T}=bt({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),P=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),U=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:P,inactiveDrawPositions:U,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function fs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(le)[0]}}var Na={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",brightred:"\x1B[91m",green:"\x1B[32m",brightgreen:"\x1B[92m",yellow:"\x1B[33m",brightyellow:"\x1B[93m",blue:"\x1B[34m",brightblue:"\x1B[94m",lightblue:"\x1B[105m",magenta:"\x1B[35m",brightmagenta:"\x1B[95m",cyan:"\x1B[36m",brightcyan:"\x1B[96m",white:"\x1B[37m",brightwhite:"\x1B[97m"};var SS=[];function Cn(t,e){Vt(t)&&(t={method:t}),(e||Pr())&&SS.push(t)}function Rk(t){let e=SS.slice();return t&&(SS.length=0),e}function rv(t){let r=Rk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Na).includes(o)?Na[o]:Na.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Na[i[d]]?Na[i[d]]:Na.brightwhite;return`${Na.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
1
+ var iL=Object.defineProperty;var Zt=(t,e)=>{for(var r in e)iL(t,r,{get:e[r],enumerable:!0})};function Ba(){return"2.2.16"}var SA={};Zt(SA,{competitionGovernor:()=>NU,drawsGovernor:()=>CN,entriesGovernor:()=>LN,eventGovernor:()=>zN,generationGovernor:()=>eM,matchUpFormatGovernor:()=>_y,matchUpGovernor:()=>EM,mocksGovernor:()=>II,participantGovernor:()=>JM,policyGovernor:()=>iN,publishingGovernor:()=>aR,queryGovernor:()=>MN,reportGovernor:()=>cR,scheduleGovernor:()=>yR,scoreGovernor:()=>jg,tieFormatGovernor:()=>bR,tournamentGovernor:()=>HR,venueGovernor:()=>JR});var NU={};Zt(NU,{getLinkedTournamentIds:()=>su,getTournamentIds:()=>hp,linkTournaments:()=>AU,mutate:()=>PU,query:()=>DU,unlinkTournament:()=>UU,unlinkTournaments:()=>EU});var PU={};Zt(PU,{linkTournaments:()=>AU,unlinkTournament:()=>UU,unlinkTournaments:()=>EU});var ca="SINGLES",kt="SINGLES",Oi="DOUBLES",xt="DOUBLES",xr="TEAM",Yt="TEAM",aC={SINGLES_MATCHUP:ca,SINGLES:kt,DOUBLES_MATCHUP:Oi,DOUBLES:xt,TEAM_MATCHUP:xr,TEAM:Yt};var PI={[kt]:[kt,"S"],[xt]:[xt,"D"],[Yt]:[Yt,"T"],S:[kt,"S"],D:[xt,"D"],T:[Yt,"T"]};function le(t,e){return(t??0)-(e??0)}function mt(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function On(t){return isNaN(t)?!1:t&&(t&t-1)===0}function EA(t){if(!t.length)return;let e=[...t].sort(le),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function cC(t){if(!On(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Sm(t){return isNaN(t)?0:t%2&&t+1||t}function Tm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function te(t){return!isNaN(parseFloat(t))}function DI(t){let e=mt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function es(t){if(isNaN(t))return!1;for(;!On(t);)t++;return t}function po(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function It(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function uC(t=1,e=3,r=!0){let n=0;for(let o=0;o<e;o++)n+=Math.random()*(t/e);return r&&t>1?Math.round(n):n}function sL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function UA(t,e,r,n,o=2){let i=1-Math.random(),s=1-Math.random(),a=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s);return a=a/10+.5,a>1||a<0?a=UA(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=sL(a,n)),parseFloat(a.toFixed(o))}function wl(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function ut(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function pC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function hr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Ha(t){return It(t)?t:1/0}function Tr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function mC(t){return PA(Tr(t))}function PA(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function aL(t,e,r){return r.indexOf(t)===e}function NI(t){return t.filter(aL)}function Zr(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function yn(t){let e=Math.floor(Math.random()*t.length);return t[e]}function tt(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function mo(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function qt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function DA(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Fe(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function dC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function lC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function Ee(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function NA(t,[e,...r]){return t.length?[t.slice(0,e),...NA(t.slice(e),[...r,e])]:[]}function fC(t){return t.reduce((e,r)=>{let n=e[e.length-1];return(!n||n[n.length-1]!==r-1)&&e.push([]),e[e.length-1].push(r),e},[])}function MI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function RI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Ll(t,e,r){return Array.isArray(t)?t.reduce((n,o,i)=>{let s=r?!!(Math.floor(i/e)%2):!1,a=i%e,c=s?e-1-a:a;return n[c]||(n[c]=[]),n[c].push(o),n},[]):[]}function gC(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return tt(r,n+1).filter(o=>!t.includes(o))}function Wr(t){return typeof t=="function"}function Vt(t){return typeof t=="string"}function ht(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function IC(t,e){if(!ht(t)||!ht(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o of r)if(t[o]!==e[o])return!1;return!0}function bI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var hC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function CI(t,e){if(t===void 0)return null;if(!ht(t)||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>CI(i))}:{[o]:e?n(t[o]):CI(t[o])}))}function MA(t){return Array.isArray(t)?t.length+t.map(MA).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>MA(t[e])).reduce((e,r)=>e+r,0):0}function SC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=MA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function Fc(t,e){return!Array.isArray(t)||!Vt(e)?!1:qt(t,PI[e]).length}var C={success:!0},RA="error",TC={SUCCESS:C,ERROR:RA};function vI({collectionValueProfiles:t,matchUpCount:e}){let r=[];if(!Array.isArray(t))return r.push(`collectionValueProfiles is not an array: ${t}`),{errors:r};if(t.length&&t.length!==e)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(let o of t){if(typeof o!="object")return r.push(`valueProfile is not type object: ${o}`),{errors:r};let{matchUpValue:i,collectionPosition:s}=o;if(typeof i!="number"||typeof s!="number"||s>e||s<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}let n=t.map(o=>o.collectionPosition);return n.length!==ut(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...C}}var vC={};Zt(vC,{addNotice:()=>dt,callListener:()=>Dm,createInstanceState:()=>LE,cycleMutationStatus:()=>pf,deepCopyEnabled:()=>uf,deleteNotice:()=>$I,deleteNotices:()=>ki,disableNotifications:()=>FE,enableNotifications:()=>cf,getDevContext:()=>Pr,getMethods:()=>mf,getNotices:()=>qI,getProvider:()=>KI,getTopics:()=>Lr,getTournamentId:()=>ns,getTournamentRecord:()=>df,getTournamentRecords:()=>Fo,globalLog:()=>VE,handleCaughtError:()=>ip,hasTopic:()=>np,removeTournamentRecord:()=>GE,setDeepCopy:()=>Wc,setDevContext:()=>Hc,setGlobalLog:()=>RC,setGlobalMethods:()=>CC,setGlobalSubscriptions:()=>FL,setMethods:()=>bC,setStateMethods:()=>BE,setStateProvider:()=>wL,setSubscriptions:()=>kL,setTournamentId:()=>op,setTournamentRecord:()=>kE,setTournamentRecords:()=>Nm,timeKeeper:()=>LL});var OI={message:"Chronological error; time violation.",code:"ANACHRONISM"},ym={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},CA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},_I={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},Lt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},q={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Wa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ua={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},pa={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},bA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},br={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Xo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},Fl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},kl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},ja={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},vA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},OA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},cL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Gl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ya={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},qu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},yC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Rs={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Cs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Am={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},$u={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},xI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},qa={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},sn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},_A={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},xA={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},wA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},LA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},FA={message:"Invalid action",code:"ERR_INVALID_ACTION"},wI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},kA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},GA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},VA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},Vl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},BA={message:"Existing round",code:"ERR_EXISTING_ROUND"},uL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Ur={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},wt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Bl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},mi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},HA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Wn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Ot={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},jr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},WA={message:"Event exists",code:"ERR_EXISTING_EVENT"},jA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},YA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Hl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},qA={message:"Missing stage",code:"ERR_MISSING_STAGE"},_i={message:"Invalid stage",code:"ERR_INVALID_STAGE"},$A={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},KA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},zA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},LI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},$a={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Wl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},ma={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Lo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},jl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Yl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},QA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},bs={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},ar={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},rs={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},xe={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Jn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Sr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},dr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},FI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Ku={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},pL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},XA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},kI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},JA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},GI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},mL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},kc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},dL={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},ql={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},lL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},$l={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},fL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},gL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},xi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},it={message:"Missing value",code:"ERR_MISSING_VALUE"},ZA={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},tE={message:"Missing date",code:"ERR_MISSING_DATE"},eE={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Em={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Kl={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},rE={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},je={message:"Invalid Date",code:"ERR_INVALID_DATE"},Eo={message:"Invalid time",code:"ERR_INVALID_TIME"},nE={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var VI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},oE={message:"Invalid score",code:"ERR_INVALID_SCORE"},Um={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var AC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},zl={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},iE={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},zu={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},BI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Pm={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},wi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},dn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},wr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},sE={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},An={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},aE={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Li={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Ka={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},ie={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},re={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},cE={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},IL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},uE={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Uo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},pE={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},mE={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},dE={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},vs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Qu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Ql={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Xl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},HI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},EC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},UC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},lE={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},fE={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},WI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},gE={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Jl={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},IE={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Zl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Gc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},hE={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Os={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},SE={message:"Court exists",code:"ERR_EXISTING_COURT"},TE={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Fi={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Jo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},yE={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},jI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},AE={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},EE={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},PC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},tf={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},UE={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},ef={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},rf={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Vc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},PE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},za={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},DE={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},_s={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},NE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Xu={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},ME={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},RE={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},lo={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Ju={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Bc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},V={message:"Invalid values",code:"ERR_INVALID_VALUES"},CE={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},nf={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},bE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Zu={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},of={message:"Value unchanged",code:"ABORT_UNCHANGED"},Ce={message:"Not found",code:"ERR_NOT_FOUND"},tp={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},vE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},sf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},OE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},_E={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},YI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},af={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Qa={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},xE={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},ep={message:"Scores present",code:"ERR_SCORES_PRESENT"},DC={ANACHRONISM:OI,CANNOT_CHANGE_WINNING_SIDE:Pm,CANNOT_MODIFY_TIEFORMAT:zl,CANNOT_MODIFY_PARTICIPANT_TYPE:iE,CANNOT_REMOVE_MAIN_STRUCTURE:CA,CANNOT_REMOVE_PARTICIPANTS:zu,CATEGORY_MISMATCH:BI,COURT_EXISTS:SE,COURT_NOT_FOUND:Os,DRAW_DEFINITION_NOT_FOUND:br,DRAW_ID_EXISTS:_A,DRAW_POSITION_ACTIVE:qu,DRAW_POSITION_ASSIGNED:ja,DRAW_POSITION_NOT_CLEARED:OA,DRAW_POSITION_NOT_FOUND:cL,DRAW_SIZE_MISMATCH:xI,DUPLICATE_ENTRY:ym,DUPLICATE_VALUE:CE,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:fE,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:lE,EVENT_EXISTS:WA,EVENT_NOT_FOUND:jr,EXISTING_DRAW_DEFINITIONS:bA,EXISTING_END_TIME:jI,EXISTING_FLIGHT:vE,EXISTING_MATCHUP_ID:_E,EXISTING_OUTCOME:OE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:vs,EXISTING_PARTICIPANT:Qu,EXISTING_POLICY_TYPE:GI,EXISTING_PROFILE:sf,EXISTING_ROUND:BA,EXISTING_STAGE:YI,EXISTING_STRUCTURE:af,INCOMPATIBLE_MATCHUP_STATUS:Wl,INCOMPLETE_SOURCE_STRUCTURE:Fl,INSUFFICIENT_DRAW_POSITIONS:Jl,INVALID_ACTION:FA,INVALID_ASSIGNMENT:wI,INVALID_BOOKINGS:Em,INVALID_CATEGORY:Bc,INVALID_COLLECTION_DEFINITION:RE,INVALID_CONFIGURATION:ME,INVALID_DATE_AVAILABILITY:Kl,INVALID_DATE:je,INVALID_DRAW_DEFINITION:pa,INVALID_DRAW_POSITION_FOR_SEEDING:kl,INVALID_DRAW_POSITION:Rs,INVALID_DRAW_SIZE:$u,INVALID_END_TIME:yE,INVALID_ENTRIES:YA,INVALID_EVENT_TYPE:Wn,INVALID_GAME_SCORES:VI,INVALID_GENDER:Ju,INVALID_MATCHUP_FORMAT:jl,INVALID_MATCHUP_STATUS:ma,INVALID_MATCHUP_STATUS_BYE:zA,INVALID_MATCHUP:dr,INVALID_OBJECT:lo,INVALID_PARTICIPANT_ID:dn,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:sE,INVALID_PARTICIPANT_SEEDING:xA,INVALID_PARTICIPANT_TYPE:An,INVALID_PARTICIPANT:wi,INVALID_POLICY_DEFINITION:JA,INVALID_RECORDS:_I,INVALID_SCALE_ITEM:za,INVALID_SEED_NUMBER:GA,INVALID_SEED_POSITION:VA,INVALID_SET_NUMBER:lL,INVALID_SIDE_NUMBER:ql,INVALID_SCORE:oE,INVALID_STAGE:_i,INVALID_START_TIME:EE,INVALID_STRUCTURE:Xo,INVALID_STOP_TIME:AE,INVALID_TIE_FORMAT:Lo,INVALID_TIME:Eo,INVALID_TIME_ITEM:tf,INVALID_TOURNAMENT_DATES:nE,INVALID_TOURNAMENT_RECORD:Wa,INVALID_VALUES:V,INVALID_WINNING_SIDE:Um,MATCHUP_NOT_FOUND:xe,METHOD_NOT_FOUND:Qa,MISSING_ASSIGNMENTS:Hl,MISSING_ASYNC_STATE_PROVIDER:UE,MISSING_AVOIDANCE_POLICY:XA,MISSING_BIRTH_DATE:ZA,MISSING_COLLECTION_DEFINITION:QA,MISSING_COURT_ID:xi,MISSING_COURTS_INFO:hE,MISSING_DATE_AVAILABILITY:rE,MISSING_DATE:tE,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:sn,MISSING_DRAW_POSITION:Cs,MISSING_DRAW_POSITIONS:Ya,MISSING_DRAW_SIZE:qa,MISSING_ENTRIES:jA,MISSING_EVENT:Ot,MISSING_MATCHUP_FORMAT:Yl,MISSING_MATCHUP_ID:ar,MISSING_MATCHUP_IDS:rs,MISSING_MATCHUP:Sr,MISSING_MATCHUPS:Jn,MISSING_PARTICIPANT_COUNT:pE,MISSING_PARTICIPANT_ID:ie,MISSING_PARTICIPANT_IDS:Uo,MISSING_PARTICIPANT_ROLE:aE,MISSING_PARTICIPANT:Li,MISSING_PARTICIPANTS:Ka,MISSING_PENALTY_ID:Zl,MISSING_PENALTY_TYPE:IE,MISSING_PERSON_DETAILS:dE,MISSING_POLICY_ATTRIBUTES:kI,MISSING_POLICY_DEFINITION:Ku,MISSING_POLICY_TYPE:FI,MISSING_POSITION_ASSIGNMENTS:KA,MISSING_ROUND_NUMBER:uL,MISSING_SCHEDULE:PE,MISSING_SCORING_POLICY:dL,MISSING_SEED_ASSIGNMENTS:kA,MISSING_SEEDCOUNT_THRESHOLDS:LA,MISSING_SEEDING_POLICY:pL,MISSING_SET_NUMBER:fL,MISSING_SET_OBJECT:$l,MISSING_SIDE_NUMBER:gL,MISSING_STAGE:qA,MISSING_STRUCTURE_ID:Ur,MISSING_STRUCTURE:mi,MISSING_STRUCTURES:Bl,MISSING_TARGET_LINK:Vl,MISSING_TIE_FORMAT:bs,MISSING_TIME_ITEM:ef,MISSING_TIME_ITEMS:rf,MISSING_TOURNAMENT_ID:ua,MISSING_TOURNAMENT_RECORD:q,MISSING_TOURNAMENT_RECORDS:Lt,MISSING_VALUE:it,MISSING_VENUE_ID:Jo,MODIFICATIONS_FAILED:DE,NO_CANDIDATES:Xu,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:gE,NO_MODIFICATIONS_APPLIED:_s,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:WI,NO_PARTICIPANT_REMOVED:uE,NO_VALID_ACTIONS:bE,NO_VALID_ATTRIBUTES:Zu,NO_VALID_DATES:eE,NOT_FOUND:Ce,NOT_IMPLEMENTED:tp,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Ql,PARTICIPANT_ID_EXISTS:cE,PARTICIPANT_NOT_CHECKED_IN:mE,PARTICIPANT_NOT_FOUND:re,PARTICIPANT_PAIR_EXISTS:IL,PENALTY_NOT_FOUND:Gc,POLICY_NOT_ATTACHED:mL,POLICY_NOT_FOUND:kc,SCHEDULE_NOT_CLEARED:vA,SCHEDULED_MATCHUPS:xE,SCORES_PRESENT:ep,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:wA,STAGE_SEQUENCE_LIMIT:$A,STRUCTURE_NOT_FOUND:wt,TEAM_NOT_FOUND:nf,UNABLE_TO_ASSIGN_COURT:NE,UNLINKED_STRUCTURES:HA,UNRECOGNIZED_DRAW_TYPE:Gl,UNRECOGNIZED_MATCHUP_FORMAT:$a,UNRECOGNIZED_MATCHUP_STATUS:LI,VALUE_UNCHANGED:of,VENUE_EXISTS:TE};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},wE={addNotice:RL,callListener:_L,cycleMutationStatus:ML,deleteNotice:vL,deleteNotices:bL,disableNotifications:hL,enableNotifications:SL,getMethods:rp,getNotices:CL,getTopics:OL,getTournamentId:NC,getTournamentRecord:TL,getTournamentRecords:yL,removeTournamentRecord:PL,setMethods:NL,setSubscriptions:DL,setTournamentId:EL,setTournamentRecord:AL,setTournamentRecords:UL,handleCaughtError:xL};function hL(){Ze.disableNotifications=!0}function SL(){Ze.disableNotifications=!1}function NC(){return Ze.tournamentId}function TL(t){return Ze.tournamentRecords[t]}function yL(){return Ze.tournamentRecords}function AL(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Wa}}function EL(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:q}:(Ze.tournamentId=void 0,{success:!0})}function UL(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function PL(t){if(typeof t!="string")return{error:V};if(!Ze.tournamentRecords[t])return{error:Ce};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function DL(t){return typeof t.subscriptions!="object"?{error:V}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ze.subscriptions[e]=t.subscriptions[e]:delete Ze.subscriptions[e]}),{...C})}function NL(t){return typeof t!="object"?{error:V}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...C})}function ML(){let t=Ze.modified;return Ze.modified=!1,t}function RL({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...C}}function rp(){return Ze.methods??{}}function CL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function bL(){Ze.notices=[]}function vL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function OL(){return{topics:Object.keys(Ze.subscriptions)}}function _L({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function xL({engineName:t,methodName:e,params:r,err:n}){let o;return typeof n=="string"?o=n.toUpperCase():n instanceof Error&&(o=n.message),console.log("ERROR",{tournamentId:NC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var be={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},an=wE,MC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function wL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(qt(Object.keys(t),MC).length!==MC.length)throw new Error("Global state provider is missing required methods");return an=t,{success:!0}}function LE(){if(an.createInstanceState){try{an.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:UE}}function Pr(t){return!t||typeof t!="object"?be.devContext??!1:typeof be.devContext!="object"?!1:Object.keys(t).every(e=>be.devContext?.[e]===t[e])&&be.devContext}function LL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(be.timers).filter(o=>o!=="default"||be.timers[o].startTime).map(o=>{let i=be.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:be.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=be.timers[e].state==="stopped"?0:(r-(be.timers[e]?.startTime??0))/1e3,o=be.timers[e].elapsedTime+n;return{state:be.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!be.timers[e]||t==="reset"){if(e==="allTimers")return be.timers={default:{elapsedTime:0}},!0;be.timers[e]={startTime:r,state:"active",elapsedTime:0}}return be.timers[e].elapsedTime||(be.timers[e].elapsedTime=0),t==="stop"&&be.timers[e].state!=="stopped"&&(be.timers[e].state="stopped")&&(be.timers[e].elapsedTime+=(r-(be.timers[e]?.startTime??0))/1e3),t==="start"&&(be.timers[e].startTime=r)&&(be.timers[e].state="active"),be.timers[e]}function RC(t){Wr(t)?be.globalLog=t:delete be.globalLog}function Hc(t){be.devContext=t}function FE(){an.disableNotifications()}function cf(){an.enableNotifications()}function Wc(t,e){typeof t=="boolean"&&(be.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(be.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(be.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(be.deepCopyAttributes.stringify=e.stringify),e.threshold&&(be.deepCopyAttributes.threshold=e.threshold))}function uf(){return{enabled:be.deepCopy,...be.deepCopyAttributes}}function FL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{be.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:it,info:"missing subscriptions"}}function kL(t){return t?.subscriptions?an.setSubscriptions({subscriptions:t.subscriptions}):{error:it,info:"missing subscriptions"}}function CC(t){return t?typeof t!="object"?{error:V}:(Object.keys(t).forEach(e=>{Wr(t[e])&&(be.globalMethods[e]=t[e])}),{...C}):{error:it,info:"missing method declarations"}}function bC(t){return t?typeof t!="object"?{error:V}:an.setMethods(t):{error:it,info:"missing method declarations"}}function pf(){return an.cycleMutationStatus()}function dt(t){if(typeof t?.topic!="string")return;let e=be.globalSubscriptions[t.topic];return an.addNotice(t,e)}function mf(){return{...be.globalMethods,...an.getMethods()}}function qI(t){return an.getNotices(t)}function $I({key:t,topic:e}){return an.deleteNotice({key:t,topic:e})}function ki(){return an.deleteNotices()}function Lr(){return an.getTopics()}function np(t){return Lr()?.topics?.includes(t)}async function Dm(t){return an.callListener(t,be.globalSubscriptions)}function ns(){return an.getTournamentId()}function df(t){return an.getTournamentRecord(t)}function Fo(){return an.getTournamentRecords()}function kE(t){return an.setTournamentRecord(t)}function Nm(t){return an.setTournamentRecords(t)}function op(t){return an.setTournamentId(t)}function GE(t){return an.removeTournamentRecord(t)}function KI(){return an}function ip({engineName:t,methodName:e,params:r,err:n}){let o=Wr(an.handleCaughtError)&&an.handleCaughtError||wE.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function VE(t,e){if(be.globalLog)try{be.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),RC()}else console.log(e,t)}function BE(t,e,r,n){if(!ht(t))return{error:V};te||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Wr(a[u])?i[u]=a[u]:ht(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?CC(i):bC(i),{methods:i}}function GL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function ot(t,e,r,n){if(typeof t!="object"||t===null)return t;uf()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=GL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>ot(c))}:{[a]:n?t[a]:ot(t[a])}))}function x({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,ot(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var Pn="ANY",Qt="MALE",yr="MIXED",os="OTHER",ne="FEMALE",Mm={ANY:Pn,MALE:Qt,FEMALE:ne,MIXED:yr,OTHER:os};var VL="MIXED events can not contain mixed singles or { gender: ANY } collections",BL="events with { gender: ANY } can not contain MIXED singles collections";function Rm(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[Qt,ne].includes(r)&&r!==o?x({result:{valid:!1,error:Ju},context:{gender:o},stack:e}):r===yr&&(o===Pn||o===yr&&n!==xt)?x({result:{error:Ju,valid:!1},info:VL,stack:e}):r===Pn&&o===yr&&n!==xt?x({result:{error:Ju,valid:!1},info:BL,stack:e}):{valid:!0}}var HL="normal",HE="timed",WL="final",lf="NOAD",Cm="SET",OC={S:HL,F:WL};function sp(t,e){if(ht(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return jL(t,e)}function ff(t){return!isNaN(Number(t))&&Number(t)}function wC(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function jL(t,e){let r=ff(t.bestOf)||void 0,n=ff(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return wC(t.setFormat);let i=o&&`${Cm}${o}`||"",s=_C(t.setFormat,e),a=s&&`S:${s}`||"",c=_C(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function _C(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return wC(t);if(t.tiebreakSet)return xC(t.tiebreakSet);let r=ff(t.setTo);if(r){let n=t.NoAD&&lf||"",o=xC(t.tiebreakFormat),i=o&&`/${o}`||"",s=ff(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function xC(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&ff(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?lf:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ye(t){if(Vt(t)){let e=t.startsWith("T")&&HE||t.startsWith(Cm)&&Cm||"";if(e===HE){let r=GC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===Cm)return YL(t)}}function YL(t){let e=t.split("-"),r=gf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&LC(e[1]),s=e&&LC(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=ot({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function LC(t){if(t?.[1]===":"){let e=t.split(":"),r=OC[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=FC(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return GC(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&VC(s[2])||!1,c=!s?.[2]||a,u=s?gf(s[1]):void 0,p=kC(n),m=p!==!1,d=m&&p||u,l=FC(n.split("/")[1]),f=l!==!1,g={setTo:u};return a&&(g.NoAD=!0),l?(g.tiebreakFormat=l,g.tiebreakAt=d):g.noTiebreak=!0,u&&c&&f&&m&&g||!1}}}function kC(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?gf(r[1]):r[1])||!1}function FC(t){if(t)if(t.startsWith("TB")){let e=kC(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&VC(r[2]),i=!r?.[2]||o,s=gf(n);if(s&&i){let a={tiebreakTo:s};return e&&typeof e=="string"&&!It(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}else return!1}else return!1}function GC(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=gf(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2],s=[void 0,"P","G"].includes(i);if(i&&!s){let a=e.match(/^(\d+)(@)([A-Za-z]+)$/)?.[3];return a?(o.modifier=a,o):void 0}return i&&(o.based=r[2]),o}function VC(t){return t&&t.indexOf(lf)>=0}function gf(t){return isNaN(Number(t))?0:Number(t)}function Dr({matchUpFormat:t}){if(!Vt(t)||t==="")return!1;let e=Ye(t),r=t.match(/-S:([1-9])+\/TB(\d{1,2})@?([1-9]?)*/),n=r?.[1],o=r?.[2],i=r?.[3],s=t.match(/-F:([1-9])+\/TB(\d{1,2})@?([1-9]?)*/),a=s?.[1],c=s?.[2],u=s?.[3];return sp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var bm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,zI=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Po=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))([ T](0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/,xs=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))?([ T]?(0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/;function vm(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Et(t.scheduledTime)),!e)return;let r=Xt(t.scheduledTime),n=Et(e);return n&&r&&(n+=`T${r}`),n}function BC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function jc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||xs.test(Ja(t,!0,!0)))}function Nr(t){return Xa(t)||bm.test(t)}function qL(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return $L(r,{displaySeconds:!1})}function $L(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(Zn).join(":")}var Sf=t=>{let e=If(t)||Xa(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${Zn(n)}-${Zn(e.getUTCDate())}`};function KL(t){let e=If(t)||Xa(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function jn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function QI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function zL(t){return QI(t).getTime()}function If(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function ws(t,e){if(!Nr(t)||!Nr(e))return[];let r=Et(t)+"T00:00",n=Et(e)+"T00:00",o=new Date(r),i=new Date(n),s=If(i)&&If(o)&&u(o,i),a=[],c=0;if(s){let p=o,m=p.getTime();for(;m<=i.getTime()&&c<300;)c+=1,a.push(new Date(p)),m=p.setDate(p.getDate()+1)}return a.map(p=>jn(p));function u(p,m){return p<=m}}var QL=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function Xa(t){return typeof t!="string"?!1:QL.test(t)}function JI(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function $t(t){let e=Xt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function HC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[Zn(e),Zn(r)].join(":")}function hf(t){return JI(t)?t.split(":").slice(0,2).map(Zn).join(":"):void 0}function Xt(t){return Xa(t)&&t.indexOf("T")>0?hf(t.split("T").reverse()[0]):hf(t)}function Et(t){return Xa(t)||Po.test(t)?t.split("T")[0]:void 0}function ap(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Et(r.toISOString())}function XI(t){t=typeof t!="string"?"00:00":t;let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:r.hours,1:r.minutes}=e.time.split(":")||[],r.ampm=e.ampm,isNaN(r.hours)||isNaN(r.minutes)||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function XL(t){let e=XI(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(Zn).join(":")}function JL(t){let e=XI(t);if(!(typeof e=="object"&&!Object.keys(e).length))return e.ampm?t:(e.hours>12?(e.hours-=12,e.ampm="PM"):e.hours==="12"?e.ampm="PM":(e.hours==="00"&&(e.hours="12"),e.ampm="AM"),e.hours?.[0]==="0"&&(e.hours=e.hours.slice(1)),`${e.hours||"12"}:${e.minutes||"00"} ${e.ampm}`)}function Ja(t,e,r){let n=Et(t),o=Xt(t),i=n?o:t;return t?e&&(n&&r&&t||XL(i))||JL(i):void 0}function ZI(t,e){let r=XI(t),n=XI(e);if(parseInt(r.hours)<parseInt(n.hours))return-1;if(parseInt(r.hours)>parseInt(n.hours))return 1;if(r.hours===n.hours){if(parseInt(r.minutes)<parseInt(n.minutes))return-1;if(parseInt(r.minutes)>parseInt(n.minutes))return 1}return 0}function th(t,e=7){let r=Et(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return jn(o)}function ZL(t){return th(t)}function tF(t,e,r,n=!1){let o=new Date(e,0,1+(t-1)*7),i=n?0:1;return o.setDate(o.getDate()+(i-o.getDay())),jn(o,r)}function WC(t,e,r){let n=new Date(t,0);return jn(new Date(n.setDate(e)),r)}function ke(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(Zn),o=QI(e).setHours(r,n,0,0);return QI(o)}function da(t,e,r=!0){let n=new Date(t),i=(new Date(e).getTime()-n.getTime())/1e3/60;return r?Math.abs(Math.round(i)):Math.round(i)}function Yr(t,e){let r=Xt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return Xt(Tf(ke(r),n).toISOString())}function Tf(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function Zn(t){return t.toString()[1]?t:"0"+t}function Yn(t,e){let r=new Date(t),n=new Date(e);return r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()&&r.getDate()===n.getDate()}var eh={addDays:th,addWeek:ZL,addMinutesToTimeString:Yr,convertTime:Ja,getIsoDateString:vm,getUTCdateString:Sf,DateHHMM:qL,extractDate:Et,extractTime:Xt,formatDate:jn,getDateByWeek:tF,isISODateString:Xa,isDate:If,isTimeString:JI,offsetDate:QI,offsetTime:zL,sameDay:Yn,timeStringMinutes:$t,timeToDate:ke,timeUTC:KL,validTimeValue:jc,validDateString:bm,timeValidation:xs,dateValidation:Po};var eF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),rF=t=>t.filter(Boolean).every(te);function Ls(t){let e=t.category;if(typeof e!="object")return{error:Bc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(eF([r,n,o,a],"string")&&rF([i,s])&&[n,o].filter(Boolean).every(Nr)))return{error:Bc};let p=t.consideredDate??Et(new Date().toLocaleDateString("sv"));if(!Nr(p))return{error:je};let[m]=p.split("-").slice(0,3).map(G=>parseInt(G)),d=ap(p,-1),[l,f]=d.split("-").slice(1,3).map(G=>parseInt(G)),g=`${Zn(l)}-${Zn(f)}`,I=ap(p,1),[h,S]=I.split("-").slice(1,3).map(G=>parseInt(G)),T=`${Zn(h)}-${Zn(S)}`,y=s&&ap(p,-1*365*s),P=i&&ap(p,-1*365*i),U=[],A=G=>!U.includes(G)&&U.push(G);r=r??a;let E=/^([UO]?)(\d{1,2})([UO]?)$/,N=/^C(\d{1,2})-(\d{1,2})$/,D=r?.includes("-"),M=D&&r?.match(N),R=r?.match(E),b=(G,k)=>`${G}-${k}`,v=G=>{let k=m-G,H=b(k,T);e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==G-1&&(A(`Invalid submitted ageMax: ${i}`),P=void 0),i=G-1)},O=G=>{let k=m-G-1,H=b(k,T);e.ageMin&&e.ageMin>G&&A(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>G&&A(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==G&&(A(`Invalid submitted ageMax: ${i}`),y=void 0),i=G)},_=G=>{let k=m-G,H=b(k,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==G+1&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=G+1)},F=G=>{let k=m-G-1,H=b(k,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==G&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=G)},w=G=>{let[k,H,W]=(G.match(E)||[]).slice(1),Y=parseInt(H);k==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(Y)):k==="O"&&_(Y),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),O(Y)):W==="O"&&F(Y),n=n??y,o=o??P};if(M){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=m-e.ageMin;n=b(H,g)}if(e.ageMax){let H=m-e.ageMax-1;o=b(H,T)}let[G,k]=(r?.match(N)??[]).slice(1).map(H=>parseInt(H));G<=k?(s=G,i=k,c=!0):A(`Invalid combined age range ${r}`)}else D?r?.split("-").forEach(w):R?w(r):(s&&_(s),i&&O(i));i&&e.ageMin&&e.ageMin>i&&(A(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=ot({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return U.length&&(L.errors=U),L}function Yc({category:t}){if(!ht(t))return{error:V};let e=Ls({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!te(r)?x({result:{error:V},context:{ratingMax:r}}):n&&!te(n)?x({result:{error:V},context:{ratingMin:n}}):{...e}}function qc({childCategory:t,withDetails:e,category:r}){let n=Yc({category:r}),o=Yc({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=ot({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function $c({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:n=!0,referenceCategory:o,referenceGender:i,event:s}){i=i??s?.gender;let a="validateCollectionDefinition",c=[];if(typeof e!="object")return c.push(`collectionDefinition must be an object: ${e}`),x({result:{errors:c,error:lo},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Fc([kt,xt],I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`),[!!u?.length].concat([g,m,h,S].map(It)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let U=vI({collectionValueProfiles:u,matchUpCount:l});U.errors&&c.push(...U.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Dr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let U=Rm({referenceGender:i,matchUpType:I,gender:y});if(U.error)return x({context:{referenceGender:i,gender:y},result:U,stack:a})}if(t&&o&&T){let U=qc({category:o,childCategory:T});if(!U.valid)return x({result:{error:Bc},context:U,stack:a})}return c.length?x({result:{errors:c,error:RE},stack:a}):{valid:!0}}function cr(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=nF({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:h,scoreValue:S,collectionValue:T}=I;(h||S)&&!T&&(u=!0);let{valid:y,errors:P}=$c({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(P)&&a.push(...P),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),x({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:Lo},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===ut(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:x({result:{error:Lo},context:{tieFormat:o,errors:a},stack:s})}function nF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?x({result:{error:Lo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:x({result:{error:Lo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):x({result:{error:Lo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var Za="resourceSubType",tc="resourceType",ec="identifier",jC={RESOURCE_SUB_TYPE:Za,RESOURCE_TYPE:tc,IDENTIFIER:ec};function J(t,e,r,n,o=0){if(KI().makeDeepCopy)return KI().makeDeepCopy(t,e,r,n);let i=uf(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Wr(t)||t===null||typeof i?.threshold=="number"&&o>=i.threshold)return t;let p=Array.isArray(t)?[]:{},m=Object.keys(t).filter(l=>!r||!c||Array.isArray(c)&&!c.includes(l)||Wr(c)&&!c(l)),d=(l,f)=>{p[l]=Wr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Wr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=yf(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?d(l,f):Array.isArray(a)&&a.includes(l)&&Wr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:BC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function yf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function rh(t=1,e){return tt(0,t).map(()=>Dt(e))}function Dt(t){let e=[];for(let a=0;a<256;a++)e[a]=(a<16?"0":"")+a.toString(16);let r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0,i=Math.random()*4294967295|0,s=e[r&255]+e[r>>8&255]+e[r>>16&255]+e[r>>24&255]+"-"+e[n&255]+e[n>>8&255]+"-"+e[n>>16&15|64]+e[n>>24&255]+"-"+e[o&63|128]+e[o>>8&255]+"-"+e[o>>16&255]+e[o>>24&255]+e[i&255]+e[i>>8&255]+e[i>>16&255]+e[i>>24&255];return typeof t=="string"?`${t}_${s.replace(/-/g,"")}`:s}var nh={collectionDefinitions:[{collectionName:"Male Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpCount:4,matchUpValue:1,gender:"MALE"},{collectionName:"Female Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:4,matchUpValue:1},{collectionName:"Male Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:2,matchUpValue:1,gender:"MALE"},{collectionName:"Female Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:2,matchUpValue:1},{collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:4,matchUpValue:1,gender:"MIXED"}],tieFormatName:"USTA_GOLD_TEAM_CHALLENGE",winCriteria:{valueGoal:9}};var oh={collectionDefinitions:[{collectionName:"Round 1",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 2",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 3",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"Doubles Shuffle",unrestrictedSelections:!0,winCriteria:{aggregateValue:!0}};var ih={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_SOUTHERN_LEVEL_5",winCriteria:{valueGoal:8}};var sh={collectionDefinitions:[{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Tiebreak Doubles",matchUpCount:1,matchUpFormat:"SET1-S:TB10",matchUpType:"DOUBLES",matchUpValue:1,processCodes:["RANKING.IGNORE"]}],tieFormatName:"USTA_SECTION_BATTLE",winCriteria:{valueGoal:9}};var ah={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_INTERSECTIONAL",winCriteria:{valueGoal:8}};var ch={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Pro Circuit",winCriteria:{aggregateValue:!0}};var uh={collectionDefinitions:[{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO_MIXED",winCriteria:{valueGoal:2}};var ph={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:3},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:3},{scoreValue:1,matchUpType:"DOUBLES",collectionName:"Men's Doubles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Women's Doubles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Dual",winCriteria:{aggregateValue:!0}};var mh={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"USTA_BREWER_CUP",winCriteria:{valueGoal:4}};var dh={winCriteria:{valueGoal:23},tieFormatName:"USTA_OZAKI_CUP",collectionDefinitions:[{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},collectionName:"18U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},collectionName:"16U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},collectionName:"14U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},collectionName:"12U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1}]};var Dn="SET3-S:6/TB7",fF="SET3-S:6NOAD",WE="SET3-S:6/TB7-F:TB10",gF="SET3-S:4/TB7",IF="SET3-S:4/TB5@3",hF="SET1-S:T20",SF="SET1-S:8/TB7",TF="SET1-S:8/TB7@7",YC={FORMAT_STANDARD:Dn,FORMAT_STANDARD_NOAD:fF,FORMAT_ATP_DOUBLES:WE,FORMAT_SHORT_SETS:gF,FORMAT_FAST4:IF,FORMAT_PRO_SET:SF,FORMAT_COLLEGE_PRO_SET:TF,TIMED20:hF};var lh={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO",winCriteria:{valueGoal:2}};var fh={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA_COLLEGE",winCriteria:{valueGoal:4}};var gh={collectionDefinitions:[{collectionName:"Male Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_LEVEL_1",winCriteria:{valueGoal:10}};var Ih={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_WTT_ITT",winCriteria:{aggregateValue:!0}};var hh={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_ZONAL",winCriteria:{valueGoal:10}};var Sh={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}};var Th={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var Om="COLLEGE_DEFAULT",yh="COLLEGE_JUCO",Ah="COLLEGE_D3",jE="DOMINANT_DUO",YE="DOMINANT_DUO_MIXED",qE="LAVER_CUP",$E="TEAM_DOUBLES_3_AGGREGATION",KE="TIME_TENNIS_DUAL",zE="TIME_TENNIS_PRO_CIRCUIT",QE="USTA_BREWER_CUP",XE="USTA_OZAKI_CUP",JE="USTA_COLLEGE",ZE="USTA_GOLD_TEAM_CHALLENGE",tU="USTA_LEVEL_1",eU="USTA_INTERSECTIONAL",rU="USTA_SECTION_BATTLE",nU="USTA_SOUTHERN_LEVEL_5",oU="USTA_TOC",iU="USTA_WTT_ITT",sU="USTA_ZONAL",qC={COLLEGE_D3:Ah,COLLEGE_DEFAULT:Om,COLLEGE_JUCO:yh,DOMINANT_DUO:jE,DOMINANT_DUO_MIXED:YE,LAVER_CUP:qE,TEAM_DOUBLES_3_AGGREGATION:$E,TIME_TENNIS_DUAL:KE,TIME_TENNIS_PRO_CIRCUIT:zE,USTA_BREWER_CUP:QE,USTA_OZAKI_CUP:XE,USTA_COLLEGE:JE,USTA_GOLD_TEAM_CHALLENGE:ZE,USTA_INTERSECTIONAL:eU,USTA_LEVEL_1:tU,USTA_SECTION_BATTLE:rU,USTA_SOUTHERN_LEVEL_5:nU,USTA_TOC:oU,USTA_WTT_ITT:iU,USTA_ZONAL:sU};var KC="STANDARD",$C={[KC]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Ah]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Ah,valueGoal:5},[Om]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Om,valueGoal:4},[yh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:yh,valueGoal:5},[qE]:Sh,[jE]:lh,[YE]:uh,[$E]:oh,[KE]:ph,[zE]:ch,[QE]:mh,[XE]:dh,[JE]:fh,[ZE]:nh,[eU]:ah,[tU]:gh,[rU]:sh,[nU]:ih,[iU]:Ih,[oU]:Th,[sU]:hh},MF=t=>{let e=t?.namedFormat&&Object.keys($C).includes(t.namedFormat)?t.namedFormat:KC,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J($C[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Dt();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:WE,collectionName:"Doubles",matchUpType:xt,...s.doubles},{collectionId:a(1),matchUpFormat:Dn,collectionName:"Singles",matchUpType:kt,...s.singles}]},s.tieFormatName&&(n.tieFormatName=s.tieFormatName)):(s.collectionDefinitions.forEach((c,u)=>c.collectionId=a(u)),n=s),t?.hydrateCollections&&n.collectionDefinitions.forEach(c=>{o&&!c.category&&(c.category=o),i&&!c.gender&&(c.gender=i)}),n},to=MF;var qn="SINGLES",Fs="SINGLES",qr="DOUBLES",ko="DOUBLES",ve="TEAM",vr="TEAM",RF="AGE",CF="RATING",bF="BOTH",zC={AGE:RF,BOTH:bF,DOUBLES:qr,DOUBLES_EVENT:ko,RATING:CF,SINGLES:qn,SINGLES_EVENT:Fs,TEAM_EVENT:vr,TEAM:ve};var rt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",fe="PLAY_OFF",Kc=[rt,ct,qe,fe,$e],ks={[ct]:1,[rt]:2,[fe]:3,[qe]:3,[$e]:4},aU="finishingPositions",cU="aggregateEventStructures",uU={[rt]:1,[fe]:2,[qe]:3,[ct]:4,[$e]:5},QC={[fe]:1,[rt]:2,[qe]:3,[ct]:4,[$e]:5},zc="CLUSTER",XC="SEPARATE",di="WATERFALL",cp="ITEM",Ge="CONTAINER",ln="DRAW",up="RANDOM",En="TOP_DOWN",li="BOTTOM_UP",eo="POSITION",fo="WINNER",ro="LOSER",_n="FIRST_MATCHUP",$r="AD_HOC",vF="AD_HOC",la="FEED_IN",Qc="COMPASS",Xc="OLYMPIC",OF="SINGLE_ELIMINATION";var go="SINGLE_ELIMINATION",Jc="DOUBLE_ELIMINATION",Zc="FIRST_MATCH_LOSER_CONSOLATION",pp="FIRST_ROUND_LOSER_CONSOLATION",Gi="LUCKY_DRAW",Af="CURTIS_CONSOLATION",JC="CURTIS_CONSOLATION",Eh="FEED_IN_CHAMPIONSHIP_TO_SF",_m="FEED_IN_CHAMPIONSHIP_TO_SF",Uh="FEED_IN_CHAMPIONSHIP_TO_QF",xm="FEED_IN_CHAMPIONSHIP_TO_QF",Ph="FEED_IN_CHAMPIONSHIP_TO_R16",wm="FEED_IN_CHAMPIONSHIP_TO_R16",pU="MODIFIED_FEED_IN_CHAMPIONSHIP",Lm="MODIFIED_FEED_IN_CHAMPIONSHIP",mp="FEED_IN_CHAMPIONSHIP",ZC="DOUBLE_ROUND_ROBIN",Nn="ROUND_ROBIN",Io="ROUND_ROBIN_WITH_PLAYOFF",mU="DECIDER",dU="BACKDRAW",Ef={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-3":{name:"Northeast",abbreviation:"NE"},"0-1-1":{name:"South",abbreviation:"S"},"0-1-2":{name:"Southwest",abbreviation:"SW"},"0-2-1":{name:"Northwest",abbreviation:"NW"},"0-1-1-1":{name:"Southeast",abbreviation:"SE"}},Uf={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},fi="WIN_RATIO",Vi="ROUND_OUTCOME",lU=[Qc,Af,xm,wm,_m,mp,Uh,Ph,Eh,Zc,pp,Gi,Lm,Xc,fe,Io],_F=[$r,Qc,Af,Jc,xm,wm,_m,mp,la,Zc,pp,Gi,Lm,Xc,fe,Nn,Io,go],fU={MAIN:rt,QUALIFYING:ct,CONSOLATION:qe,ITEM:cp,CONTAINER:Ge,FIRST_MATCHUP:_n,WINNER:fo,LOSER:ro,AD_HOC:$r,FEED_IN:la,FLEX_ROUNDS:vF,COMPASS:Qc,PLAY_OFF:fe,OLYMPIC:Xc,KNOCKOUT:OF,SINGLE_ELIMINATION:go,DOUBLE_ELIMINATION:Jc,CURTIS:Af,FICSF:Eh,FICQF:Uh,FICR16:Ph,MFIC:pU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:Zc,FIRST_ROUND_LOSER_CONSOLATION:pp,MODIFIED_FEED_IN_CHAMPIONSHIP:Lm,FEED_IN_CHAMPIONSHIP_TO_R16:wm,FEED_IN_CHAMPIONSHIP_TO_QF:xm,FEED_IN_CHAMPIONSHIP_TO_SF:_m,FEED_IN_CHAMPIONSHIP:mp,LUCKY_DRAW:Gi,ROUND_ROBIN_WITH_PLAYOFF:Io,ROUND_ROBIN:Nn,DECIDER:mU,BACKDRAW:dU,COMPASS_ATTRIBUTES:Ef,OLYMPIC_ATTRIBUTES:Uf,DRAW:ln,RANDOM:up,TOP_DOWN:En,BOTTOM_UP:li,WATERFALL:di,WIN_RATIO:fi,ROUND_OUTCOME:Vi,MULTI_STRUCTURE_DRAWS:lU,generatedDrawTypes:_F,stageOrder:ks,finishOrder:uU,AGGREGATE_EVENT_STRUCTURES:cU,FINISHING_POSITIONS:aU},tb=fU;var Ne="tournamentRecords",Pf="policyDefinitions",se="tournamentRecord",Dh="onlineResource",Ve="drawDefinition",Nh="tieFormatName",Fm="matchUpFormat",no="participantId",Mh="scheduleDates",eb="tournamentId",rb="scheduleDate",nb="roundNumber",tu="structureId",Df="participant",rc="matchUpIds",Rh="entryStage",ob="policyType",gU="structures",Nf="eventType",fn="matchUpId",km="tieFormat",eu="inContext",dp="structure",lp="courtIds",ib="personId",fp="venueIds",Mf="matchUps",Ch="courtId",bh="eventId",xn="matchUp",vh="drawId",gn="error",Do="event",is="param",Rf="uuids",sb="averageMatchUpMinutes",ab="recoveryMinutes",cb="periodLength",ub="number";var Kr="object",Be="array";var tr="_validate",Oh="_message",Fr="_invalid",He="_ofType",Gm="_anyOf",Gs="_oneOf";var pb={[Dh]:t=>qt(Object.keys(t),[Za,tc,ec]).length===3,[Nh]:t=>t&&to({namedFormat:t}),[Rf]:t=>!t||Array.isArray(t)&&t.every(Vt),[km]:t=>!cr({tieFormat:t}).error,[Nf]:t=>[qn,qr,ve].includes(t),[Rh]:t=>Kc.includes(t)},xF={[Ne]:Lt,[se]:q,[Pf]:Ku,[Ve]:Z,[no]:ie,[Fm]:Yl,[eb]:ua,[tu]:Ur,[rc]:rs,[Df]:Li,[Dh]:lo,[Nf]:Wn,[gU]:Bl,[fn]:ar,[km]:Lo,[dp]:mi,[Ch]:xi,[Mf]:Jn,[bh]:jr,[xn]:Sr,[lp]:it,[fp]:it,[vh]:sn,[Do]:Ot},wF={[Ne]:Kr,[Pf]:Kr,[se]:Kr,[Ve]:Kr,[Dh]:Kr,[Mh]:Be,[Df]:Kr,[rc]:Be,[gU]:Be,[km]:Kr,[dp]:Kr,[lp]:Be,[fp]:Be,[Mf]:Be,[xn]:Kr,[Do]:Kr,[Rf]:Be};function et(t,e,r){if(!t&&!ht(t))return{error:V};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:V};let{paramError:n,errorParam:o}=kF(t,e);if(!n)return{valid:!0};let i=n[tr]&&(n[gn]||n[Fr])||t?.[o]===void 0&&(n[gn]||n[Fr]||xF[o]||V)||V,s=o??(n[Gs]&&Object.keys(n[Gs]).join(", "));return x({info:{param:s,message:n[Oh]},result:{error:i},stack:r})}function mb(t,e){let r=Object.keys(t),n=Object.keys(e);return qt(r,n)}function LF(t,e){if(!e)return;let r=mb(t,e);return r.length!==1?{error:V}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function FF(t,e){if(!e)return;let r=mb(t,e).filter(n=>t[n]);return r.length<1?{error:V}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function kF(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&LF(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&FF(t,a);if(d?.error)return d.error;d&&Object.assign(p,d);let l=Object.keys(p).filter(g=>typeof p[g]=="boolean"),f=l.find(g=>{let I=c&&!Wr(c),h=t[g]!==void 0&&!c&&GF(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!VF(t[g],c)||pb[g]&&!pb[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function GF(t,e,r){return r=r||wF[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function VF(t,e){return Wr(e)?e(t):!0}var Vm="DYNAMIC",gi="RANKING",Ii="RATING",hi="SCALE",ho="SEEDING",db={RANKING:gi,RATING:Ii,SCALE:hi,SEEDING:ho};function fa(t){let e=et(t,[{[Df]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(hi)&&[gi,Ii,ho].includes(o.split(".")[1])),n={ratings:{},rankings:{},seedings:{}};if(r?.length){let o=s=>r.filter(a=>a?.itemType===s).sort((a,c)=>new Date(a.createdAt||void 0).getTime()-new Date(c.createdAt||void 0).getTime()).pop(),i=ut(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===ho&&"seedings"||c===gi&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Bi(t){if(t===null)return{};let{source:e,template:r}=t||{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let h=I.map(S=>{let T={};return o(S,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=h}else I&&(a[l]={},o(I,g,a[l]));else{let h=i[l];if(Array.isArray(g)&&!g.includes(h))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=h)}}}}var _h="voluntaryConsolation",Si="competitiveBands",Cf="roundRobinTally",So="positionActions",er="matchUpActions",bf="rankingPoints",ga="roundNaming",Vs="participant",ru="progression",No="scheduling",nu="avoidance",BF="participant",HF="display",tn="scoring",wn="seeding",nc="feedIn",WF="audit",Bm="draws",lb={POLICY_TYPE_VOLUNTARY_CONSOLATION:_h,POLICY_TYPE_COMPETITIVE_BANDS:Si,POLICY_TYPE_ROUND_ROBIN_TALLY:Cf,POLICY_TYPE_POSITION_ACTIONS:So,POLICY_TYPE_MATCHUP_ACTIONS:er,POLICY_TYPE_RANKING_POINTS:bf,POLICY_TYPE_ROUND_NAMING:ga,POLICY_TYPE_PARTICIPANT:Vs,POLICY_TYPE_PROGRESSION:ru,POLICY_TYPE_SCHEDULING:No,POLICY_TYPE_AVOIDANCE:nu,POLICY_TYPE_DISPLAY:HF,POLICY_TYPE_PRIVACY:BF,POLICY_TYPE_FEED_IN:nc,POLICY_TYPE_SCORING:tn,POLICY_TYPE_SEEDING:wn,POLICY_TYPE_AUDIT:WF,POLICY_TYPE_DRAWS:Bm};function Go({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[Vs];if(r?.withScaleValues){let{ratings:u,rankings:p}=fa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Bi({template:c.participant,source:a})}return a}var fb="element required",gb="missing name";function fr(t){if(!t||typeof t!="object")return{error:it};if(t.element&&typeof t?.element!="object")return{error:V};if(!t?.name)return{error:it,info:gb};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=fr({element:r,name:t.name});if(n.error)return x({result:n,stack:"removeExtension"})}return{...C}}return{error:it,info:fb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:Ce}}function Ln({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function At(t){if(typeof t!="object")return{error:it};let e="addExtension";if(t?.element&&typeof t.element!="object")return x({result:{error:V},stack:e});if(!Ln({extension:t.extension}))return x({result:{error:V,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=At({extension:t.extension,element:o});if(i.error)return x({result:i,stack:e})}return{...C}}else return x({result:{error:it},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...C}}function vf(t){return!t||typeof t!="object"?{error:it}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:q}}function gp(t){return!t||typeof t!="object"?{error:it}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:br}}function Mo(t){return!t||typeof t!="object"?{error:it}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:jr}}function IU(t){if(!t||typeof t!="object")return{error:it};if(!t.participantId)return{error:ie};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:re}}function Of(t){return!t||typeof t!="object"?{error:it}:t.tournamentRecord?fr({element:t.tournamentRecord,name:t.name}):{error:q}}function hU(t){return!t||typeof t!="object"?{error:it}:t.drawDefinition?fr({element:t.drawDefinition,name:t.name}):{error:br}}function Ip(t){return!t||typeof t!="object"?{error:it}:t?.event?fr({element:t.event,name:t.name}):{error:jr}}function SU(t){if(!t||typeof t!="object")return{error:it};if(!t.participantId)return{error:ie};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?fr({element:r,name:t.name}):{error:re}}function hp({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var jF="extensionQueries";function lt({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:Ce}}return x({result:{error:it},stack:jF})}if(!Array.isArray(e.extensions))return{info:"no extensions"};let o=e.extensions.find(s=>s?.name===r);return{extension:o,info:o?void 0:Ce}}var YF="activeSuspension",ou="appliedPolicies",TU="context",Hm="delegatedOutcome",oo="disabled",Ia="disableAutoCalc",Wm="disableLinks",jm="display",ha="drawDeletions",qF="drawProfile",Ym="entryProfile",$F="eventProfile",KF="eventWithdrawalRequests",zF="factory",cn="flightProfile",xh="groupingAttribute",Ro="lineUps",Bs="linkedTournamentsIds",qm="matchUpHistory",wh="participantRepresentatives",Sa="personRequests",oc="positionActions",QF="rankingPoints",XF="registration",Mn="roundTarget",iu="scheduleLimits",Vo="scheduleTiming",Ta="schedulingProfile",JF="statusDetail",ic="subOrder",Zo="tally",$m="tieFormatModification",Lh={ACTIVE_SUSPENSION:YF,APPLIED_POLICIES:ou,CONTEXT:TU,DELEGATED_OUTCOME:Hm,DISABLED:oo,DISABLE_LINKS:Wm,DISABLE_AUTO_CALC:Ia,DISPLAY:jm,DRAW_DELETIONS:ha,DRAW_PROFILE:qF,ENTRY_PROFILE:Ym,EVENT_PROFILE:$F,EVENT_WITHDRAWAL_REQUESTS:KF,FLIGHT_PROFILE:cn,GROUPING_ATTRIBUTE:xh,LINEUPS:Ro,LINKED_TOURNAMENTS:Bs,MATCHUP_HISTORY:qm,PARTICIPANT_REPRESENTATIVES:wh,PERSON_REQUESTS:Sa,POSITION_ACTIONS:oc,RANKING_POINTS:QF,REGISTRATION:XF,ROUND_TARGET:Mn,SCHEDULE_LIMITS:iu,SCHEDULE_TIMING:Vo,SCHEDULING_PROFILE:Ta,STATUS_DETAIL:JF,SUB_ORDER:ic,TALLY:Zo,TIE_FORMAT_MODIFICATIONS:$m,FACTORY:zF},yU=[Hm,oo,Ia,Wm,cn,Ro,Bs,qm,wh,Sa,Mn,iu,Vo,Ta,ic,Zo,$m];function AU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let e=hp({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:Bs,value:{tournamentIds:r}}}):{...C}}function EU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Lt};let e=fr({name:Bs,tournamentRecords:t,discover:!0});return x({result:e,stack:"unlinkTournaments"})}function UU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:V};if(!e)return{error:ua};let r=hp({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ua};let o;return n.every(i=>{let s=t[i],{extension:a}=lt({element:s,name:Bs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=Of({name:Bs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=vf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var DU={};Zt(DU,{getLinkedTournamentIds:()=>su,getTournamentIds:()=>hp});function su({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:Lt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=lt({element:n,name:Bs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var CN={};Zt(CN,{adHocPositionSwap:()=>FP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Ag,addFinishingRounds:()=>Ua,addGoesTo:()=>$i,addPlayoffStructures:()=>Gp,addQualifyingStructure:()=>LP,addVoluntaryConsolationStage:()=>bP,addVoluntaryConsolationStructure:()=>dg,allPlayoffPositionsFilled:()=>xS,alternateDrawPositionAssignment:()=>TP,assignDrawPosition:()=>XP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>$P,attachPlayoffStructures:()=>vg,attachQualifyingStructure:()=>yg,attachStructures:()=>Og,autoSeeding:()=>J_,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Tc,checkValidEntries:()=>_d,deleteAdHocMatchUps:()=>JP,drawMatic:()=>qd,findDrawDefinition:()=>sT,generateAdHocMatchUps:()=>xu,generateAdHocRounds:()=>Yd,generateAndPopulatePlayoffStructures:()=>Cd,generateDrawDefinition:()=>wa,generateDrawMaticRound:()=>Fd,generateDrawStructuresAndLinks:()=>xd,generateDrawTypeAndModifyDrawDefinition:()=>wd,generateQualifyingStructure:()=>Pd,generateVoluntaryConsolation:()=>NT,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Nu,getDrawDefinitionTimeItem:()=>Xh,getDrawParticipantRepresentativeIds:()=>oT,getDrawStructures:()=>In,getDrawTypeCoercion:()=>Ou,getEligibleVoluntaryConsolationParticipants:()=>nT,getMatchUpsMap:()=>De,getParticipantIdFinishingPositions:()=>iT,getPositionAssignments:()=>Vp,getPositionsPlayedOff:()=>Ac,getSeedingThresholds:()=>PS,getSeedsCount:()=>_u,getStructureSeedAssignments:()=>nn,getTeamLineUp:()=>ms,getValidGroupSizes:()=>bp,isAdHoc:()=>ur,isCompletedStructure:()=>ai,isValidForQualifying:()=>TT,luckyLoserDrawPositionAssignment:()=>fP,modifyDrawDefinition:()=>KP,modifyDrawName:()=>_g,modifySeedAssignment:()=>yP,mutate:()=>eD,positionActions:()=>ST,pruneDrawDefinition:()=>QP,qualifierDrawPositionAssignment:()=>SP,query:()=>dD,removeDrawPositionAssignment:()=>Uu,removeRoundMatchUps:()=>ZP,removeSeededParticipant:()=>wP,removeStructure:()=>CP,renameStructures:()=>RP,resetDrawDefinition:()=>zP,resetQualifyingStructure:()=>vP,resetVoluntaryConsolationStructure:()=>LU,setDrawParticipantRepresentativeIds:()=>RU,setPositionAssignments:()=>IP,setStructureOrder:()=>MP,setSubOrder:()=>tD,shiftAdHocRounds:()=>gP,swapAdHocRounds:()=>hP,swapDrawPositionAssignments:()=>xP,updateTeamLineUp:()=>zi,withdrawParticipantAtDrawPosition:()=>dP});var eD={};Zt(eD,{adHocPositionSwap:()=>FP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Ag,addPlayoffStructures:()=>Gp,addQualifyingStructure:()=>LP,addVoluntaryConsolationStage:()=>bP,addVoluntaryConsolationStructure:()=>dg,alternateDrawPositionAssignment:()=>TP,assignDrawPosition:()=>XP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>$P,attachPlayoffStructures:()=>vg,attachQualifyingStructure:()=>yg,attachStructures:()=>Og,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Tc,deleteAdHocMatchUps:()=>JP,luckyLoserDrawPositionAssignment:()=>fP,modifyDrawDefinition:()=>KP,modifyDrawName:()=>_g,modifySeedAssignment:()=>yP,pruneDrawDefinition:()=>QP,qualifierDrawPositionAssignment:()=>SP,removeDrawPositionAssignment:()=>Uu,removeRoundMatchUps:()=>ZP,removeSeededParticipant:()=>wP,removeStructure:()=>CP,renameStructures:()=>RP,resetDrawDefinition:()=>zP,resetQualifyingStructure:()=>vP,resetVoluntaryConsolationStructure:()=>LU,setDrawParticipantRepresentativeIds:()=>RU,setPositionAssignments:()=>IP,setStructureOrder:()=>MP,setSubOrder:()=>tD,shiftAdHocRounds:()=>gP,swapAdHocRounds:()=>hP,swapDrawPositionAssignments:()=>xP,updateTeamLineUp:()=>zi,withdrawParticipantAtDrawPosition:()=>dP});var MU=t=>e=>t[e],Km=(t=[])=>t.map(Ue).filter(Boolean),_f=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>MU(t)("participantId");var Ue=(t={})=>MU(t)("matchUpId"),au=(t={})=>MU(t)("drawId");function RU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:br};if(!Array.isArray(t))return{error:V};let r=_f(e?.entries||[]);return t.length&&qt(t,r).length<t.length?{error:V}:gp({drawDefinition:e,extension:{name:wh,value:t}})}var Or="ABANDONED",sc="AWAITING_RESULT",Nt="BYE",io="CANCELLED",ge="COMPLETED",cu="DEAD_RUBBER",Rt="DEFAULTED",Me="DOUBLE_DEFAULT",Te="DOUBLE_WALKOVER",Fn="IN_PROGRESS",un="INCOMPLETE",CU="NOT_PLAYED",rr="RETIRED",ss="SUSPENDED",Jt="TO_BE_PLAYED",Ct="WALKOVER",Ib=[sc,ge,Rt,Fn,un,rr,ss],Fh=[sc,ge,Rt,Te,Me,Fn,un,rr,ss,Ct],kh=[Or,sc,Nt,io,ge,cu,Rt,Te,Me,Fn,un,CU,rr,ss,Jt,Ct],Gh=[Nt,Te,Me,ge,Rt,rr,Ct],Vh=[Or,sc,io,cu,Fn,un,CU,ss,Jt,void 0],pe=[io,Or,ge,cu,Rt,Te,Me,rr,Ct],zm=[Or,ge,Rt,Te,Me,Fn,rr,Ct],Bh=[Fn,un,ss,Jt],Hh={ABANDONED:Or,AWAITING_RESULT:sc,BYE:Nt,CANCELLED:io,COMPLETED:ge,DEAD_RUBBER:cu,DEFAULTED:Rt,DOUBLE_WALKOVER:Te,DOUBLE_DEFAULT:Me,IN_PROGRESS:Fn,INCOMPLETE:un,NOT_PLAYED:CU,RETIRED:rr,SUSPENDED:ss,TO_BE_PLAYED:Jt,WALKOVER:Ct};function Ti(t,e,r){let n=m=>lt({element:m,name:Mn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===cU&&QC,s=r?.mode===aU&&uU,a=s||i||ks,c=m=>m?.stage===rt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>pe.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(xf(t)||0)-(xf(e)||0)}function xf(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function at(t){let e=et(t,[{[Ve]:!0,[tu]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=In({drawDefinition:r}),i=o?.map(c=>c.structures?[...c.structures].concat(c):c).flat(),s=i?.find(c=>c.structureId===n);if(!s)return{error:wt};let a=s.structureType===cp?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function In({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&Z||!e?.structures&&Bl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=lt({element:f,name:Mn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Ti(f,g,i))??[],m=t?Object.assign({},...Kc.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:m};function d(f){return!a&&!Array.isArray(s)||a&&f.stage===a||Array.isArray(s)&&s.includes(f.stage)}function l(f){return!n&&!Array.isArray(r)||n&&f.stageSequence===n||Array.isArray(r)&&r.includes(f.stageSequence)}}function Wh({drawDefinition:t}){if(!t)return{error:Z};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=bt({structure:n}),s=i?.map(St).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function bt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:Z};if({structure:r,error:n}=at({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>bt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=KA,{positionAssignments:o,error:n}}function ye({drawDefinition:t,structureId:e,structure:r}){let n=bt({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var wf="addDrawDefinition",Sp="addMatchUps",ti="addParticipants",Lf="addScaleItems",bU="addEvent",jh="addVenue",yi="audit",Yh="dataIssue",Ff="deleteParticipants",kf="deleteVenue",Gf="deletedDrawIds",Vf="deletedMatchUpIds",Bf="modifyDrawDefinition",vU="modifyDrawEntries",OU="modifyEventEntries",Hf="modifyMatchUp",nr="modifyParticipants",Wf="modifyPositionAssignments",jf="modifySeedAssignments",Hi="modifyTournamentDetail",Ai="modifyVenue",Qm="mutations",qh="publishEvent",_U="publishEventSeeding",xU="publishOrderOfPlay",wU="publishParticipants",Yf="unPublishEvent",qf="unPublishEventSeeding",$f="unPublishOrderOfPlay",hb="unPublishParticipants",Tp="updateInContextMatchUp",Sb={ADD_DRAW_DEFINITION:wf,ADD_MATCHUPS:Sp,ADD_PARTICIPANTS:ti,ADD_SCALE_ITEMS:Lf,ADD_EVENT:bU,ADD_VENUE:jh,AUDIT:yi,DATA_ISSUE:Yh,DELETE_PARTICIPANTS:Ff,DELETE_VENUE:kf,DELETED_DRAW_IDS:Gf,DELETED_MATCHUP_IDS:Vf,MODIFY_DRAW_DEFINITION:Bf,MODIFY_DRAW_ENTRIES:vU,MODIFY_EVENT_ENTRIES:OU,MODIFY_MATCHUP:Hf,MODIFY_PARTICIPANTS:nr,MODIFY_POSITION_ASSIGNMENTS:Wf,MODIFY_SEED_ASSIGNMENTS:jf,MODIFY_TOURNAMENT_DETAIL:Hi,MODIFY_VENUE:Ai,MUTATIONS:Qm,PUBLISH_EVENT_SEEDING:_U,PUBLISH_EVENT:qh,PUBLISH_ORDER_OF_PLAY:xU,PUBLISH_PARTICIPANTS:wU,UNPUBLISH_EVENT_SEEDING:qf,UNPUBLISH_EVENT:Yf,UNPUBLISH_ORDER_OF_PLAY:$f,UPDATE_INCONTEXT_MATCHUP:Tp};function $h(t,e){if(!t)return{error:Z};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...C}}function Co({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&$h(t),dt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Sp}),{...C}}function Rn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&$h(t),dt({topic:Vf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)$I({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&vt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),dt({topic:Hf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(Sr),{error:Sr})}function Tb({tournamentId:t,inContextMatchUp:e}){return e?(dt({payload:{inContextMatchUp:e,tournamentId:t},topic:Tp,key:e.matchUpId}),{...C}):{error:Sr}}function ya({tournamentId:t,eventId:e,drawDefinition:r}){return r?($h(r),dt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:wf,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function yb({tournamentId:t,eventId:e,drawId:r}){return dt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Gf,key:r}),$I({key:r}),{...C}}function vt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?($h(t,r),dt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Bf,key:t.drawId}),{...C}):{error:Z}}function Kh({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:mi};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return dt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:jf,key:t.drawId}),vt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function bo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:mi};let o=bt({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return dt({topic:Wf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),vt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function LU({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:Z};let o=e.structures?.find(s=>s.stage===$e);if(!o)return{error:wt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Rn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),vt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function Xm({drawPositions:t,structure:e}){if([ct,rt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=bt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,extension:{name:Wm,value:!0}})})}function uu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[oc]===!1)return;let{extension:o}=lt({name:oc,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===rt);if(a){let c=bt({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:oc};At({element:n,extension:s})}function as({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function pu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===xt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===xt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Mr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var ac="SIGN_IN_STATUS",FU="SIGNED_OUT",mu="SIGNED_IN",Ar="TEAM",Tt="INDIVIDUAL",zr="GROUP",ft="PAIR",Ft="TEAM",du={TEAM_PARTICIPANT:Ar,INDIVIDUAL:Tt,GROUP:zr,TEAM:Ft,PAIR:ft},Ab={INDIVIDUAL:Tt,GROUP:zr,PAIR:ft,TEAM:Ft,SIGN_IN_STATUS:ac,SIGNED_OUT:FU,SIGNED_IN:mu};function lu({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===Ft),s=o.filter(c=>c.participantType===zr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===Tt){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function kU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function Eb(t){let e=Object.assign({},...ei.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return kU(e[t])}var ei=[{ioc:"",iso2:"",iso:"",label:"NONE",phone:""},{ioc:"AND",iso2:"AD",iso:"AND",label:"Andorra",phone:"376"},{ioc:"UAE",iso2:"AE",iso:"ARE",label:"United Arab Emirates",phone:"971"},{ioc:"AFG",iso2:"AF",iso:"AFG",label:"Afghanistan",phone:"93"},{ioc:"ANT",iso2:"AG",iso:"ATG",label:"Antigua and Barbuda",phone:"1-268"},{ioc:"AIA",iso2:"AI",iso:"AIA",label:"Anguilla",phone:"1-264"},{ioc:"ALB",iso2:"AL",iso:"ALB",label:"Albania",phone:"355"},{ioc:"ARM",iso2:"AM",iso:"ARM",label:"Armenia",phone:"374"},{ioc:"ANG",iso2:"AO",iso:"AGO",label:"Angola",phone:"244"},{ioc:"",iso2:"AQ",iso:"ATA",label:"Antarctica",phone:"672"},{ioc:"ARG",iso2:"AR",iso:"ARG",label:"Argentina",phone:"54"},{ioc:"ASA",iso2:"AS",iso:"ASM",label:"American Samoa",phone:"1-684"},{ioc:"AUT",iso2:"AT",iso:"AUT",label:"Austria",phone:"43"},{ioc:"AUS",iso2:"AU",iso:"AUS",label:"Australia",phone:"61",suggested:!0},{ioc:"ARU",iso2:"AW",iso:"ABW",label:"Aruba",phone:"297"},{ioc:"AZE",iso2:"AZ",iso:"AZE",label:"Azerbaijan",phone:"994"},{ioc:"BIH",iso2:"BA",iso:"BIH",label:"Bosnia and Herzegovina",phone:"387"},{ioc:"BAR",iso2:"BB",iso:"BRB",label:"Barbados",phone:"1-246"},{ioc:"BAN",iso2:"BD",iso:"BGD",label:"Bangladesh",phone:"880"},{ioc:"BEL",iso2:"BE",iso:"BEL",label:"Belgium",phone:"32"},{ioc:"BUR",iso2:"BF",iso:"BFA",label:"Burkina Faso",phone:"226"},{ioc:"BUL",iso2:"BG",iso:"BGR",label:"Bulgaria",phone:"359"},{ioc:"BRN",iso2:"BH",iso:"BHR",label:"Bahrain",phone:"973"},{ioc:"BDI",iso2:"BI",iso:"BDI",label:"Burundi",phone:"257"},{ioc:"BEN",iso2:"BJ",iso:"BEN",label:"Benin",phone:"229"},{ioc:"",iso2:"BL",iso:"BLM",label:"Saint Barthelemy",phone:"590"},{ioc:"BER",iso2:"BM",iso:"BMU",label:"Bermuda",phone:"1-441"},{ioc:"BRU",iso2:"BN",iso:"BRN",label:"Brunei Darussalam",phone:"673"},{ioc:"BOL",iso2:"BO",iso:"BOL",label:"Bolivia",phone:"591"},{ioc:"BRA",iso2:"BR",iso:"BRA",label:"Brazil",phone:"55"},{ioc:"BAH",iso2:"BS",iso:"BHS",label:"Bahamas",phone:"1-242"},{ioc:"BHU",iso2:"BT",iso:"BTN",label:"Bhutan",phone:"975"},{ioc:"",iso2:"BV",iso:"BVT",label:"Bouvet Island",phone:"47"},{ioc:"BOT",iso2:"BW",iso:"BWA",label:"Botswana",phone:"267"},{ioc:"BLR",iso2:"BY",iso:"BLR",label:"Belarus",phone:"375"},{ioc:"BIZ",iso2:"BZ",iso:"BLZ",label:"Belize",phone:"501"},{ioc:"CAN",iso2:"CA",iso:"CAN",label:"Canada",phone:"1",suggested:!0},{ioc:"",iso2:"CC",iso:"CCK",label:"Cocos (Keeling) Islands",phone:"61"},{ioc:"CGO",iso2:"CD",iso:"COG",label:"Congo, Republic of the",phone:"242"},{ioc:"CAF",iso2:"CF",iso:"CAF",label:"Central African Republic",phone:"236"},{ioc:"COD",iso2:"CG",iso:"CGD",label:"Congo, Democratic Republic of the",phone:"243"},{ioc:"SUI",iso2:"CH",iso:"CHE",label:"Switzerland",phone:"41"},{ioc:"CIV",iso2:"CI",iso:"CIV",label:"Cote d'Ivoire",phone:"225"},{ioc:"COK",iso2:"CK",iso:"COK",label:"Cook Islands",phone:"682"},{ioc:"CHI",iso2:"CL",iso:"CHL",label:"Chile",phone:"56"},{ioc:"CMR",iso2:"CM",iso:"CMR",label:"Cameroon",phone:"237"},{ioc:"CHN",iso2:"CN",iso:"CHN",label:"China",phone:"86"},{ioc:"COL",iso2:"CO",iso:"COL",label:"Colombia",phone:"57"},{ioc:"CRC",iso2:"CR",iso:"CRI",label:"Costa Rica",phone:"506"},{ioc:"CUB",iso2:"CU",iso:"CUB",label:"Cuba",phone:"53"},{ioc:"CPV",iso2:"CV",iso:"CPV",label:"Cape Verde",phone:"238"},{ioc:"CUW",iso2:"CW",iso:"CUW",label:"Curacao",phone:"599"},{ioc:"CXR",iso2:"CX",iso:"CXR",label:"Christmas Island",phone:"61"},{ioc:"CYP",iso2:"CY",iso:"CYP",label:"Cyprus",phone:"357"},{ioc:"CZE",iso2:"CZ",iso:"CZE",label:"Czech Republic",phone:"420"},{ioc:"GER",iso2:"DE",iso:"DEU",label:"Germany",phone:"49",suggested:!0},{ioc:"DJI",iso2:"DJ",iso:"DJI",label:"Djibouti",phone:"253"},{ioc:"DEN",iso2:"DK",iso:"DNK",label:"Denmark",phone:"45"},{ioc:"DMA",iso2:"DM",iso:"DMA",label:"Dominica",phone:"1-767"},{ioc:"DOM",iso2:"DO",iso:"DOM",label:"Dominican Republic",phone:"1-809"},{ioc:"ALG",iso2:"DZ",iso:"DZA",label:"Algeria",phone:"213"},{ioc:"ECU",iso2:"EC",iso:"ECU",label:"Ecuador",phone:"593"},{ioc:"EST",iso2:"EE",iso:"ESE",label:"Estonia",phone:"372"},{ioc:"EGY",iso2:"EG",iso:"EGY",label:"Egypt",phone:"20"},{ioc:"",iso2:"EH",iso:"ESH",label:"Western Sahara",phone:"212"},{ioc:"ERI",iso2:"ER",iso:"ERI",label:"Eritrea",phone:"291"},{ioc:"ESP",iso2:"ES",iso:"ESP",label:"Spain",phone:"34"},{ioc:"ETH",iso2:"ET",iso:"ETH",label:"Ethiopia",phone:"251"},{ioc:"FIN",iso2:"FI",iso:"FIN",label:"Finland",phone:"358"},{ioc:"FIJ",iso2:"FJ",iso:"FJI",label:"Fiji",phone:"679"},{ioc:"FLK",iso2:"FK",iso:"FLK",label:"Falkland Islands (Malvinas)",phone:"500"},{ioc:"FSM",iso2:"FM",iso:"FSM",label:"Micronesia, Federated States of",phone:"691"},{ioc:"FAR",iso2:"FO",iso:"FRO",label:"Faroe Islands",phone:"298"},{ioc:"FRA",iso2:"FR",iso:"FRA",label:"France",phone:"33",suggested:!0},{ioc:"GAB",iso2:"GA",iso:"GAB",label:"Gabon",phone:"241"},{ioc:"GBR",iso2:"GB",iso:"GBR",label:"United Kingdom",phone:"44"},{ioc:"GRN",iso2:"GD",iso:"GRD",label:"Grenada",phone:"1-473"},{ioc:"GEO",iso2:"GE",iso:"GEO",label:"Georgia",phone:"995"},{ioc:"FGU",iso2:"GF",iso:"GUF",label:"French Guiana",phone:"594"},{ioc:"",iso2:"GG",iso:"GGY",label:"Guernsey",phone:"44"},{ioc:"",iso2:"GH",iso:"GHA",label:"Ghana",phone:"233"},{ioc:"GIB",iso2:"GI",iso:"GIB",label:"Gibraltar",phone:"350"},{ioc:"GRL",iso2:"GL",iso:"GRL",label:"Greenland",phone:"299"},{ioc:"GAM",iso2:"GM",iso:"GMB",label:"Gambia",phone:"220"},{ioc:"GUI",iso2:"GN",iso:"GIN",label:"Guinea",phone:"224"},{ioc:"GUD",iso2:"GP",iso:"GLP",label:"Guadeloupe",phone:"590"},{ioc:"GEQ",iso2:"GQ",iso:"GNQ",label:"Equatorial Guinea",phone:"240"},{ioc:"GRE",iso2:"GR",iso:"GRC",label:"Greece",phone:"30"},{ioc:"",iso2:"GS",iso:"SGS",label:"South Georgia and the South Sandwich Islands",phone:"500"},{ioc:"GUA",iso2:"GT",iso:"GTM",label:"Guatemala",phone:"502"},{ioc:"GUM",iso2:"GU",iso:"GUM",label:"Guam",phone:"1-671"},{ioc:"GBS",iso2:"GW",iso:"GNB",label:"Guinea-Bissau",phone:"245"},{ioc:"GUY",iso2:"GY",iso:"GUY",label:"Guyana",phone:"592"},{ioc:"HKG",iso2:"HK",iso:"HKG",label:"Hong Kong",phone:"852"},{ioc:"",iso2:"HM",iso:"HMD",label:"Heard Island and McDonald Islands",phone:"672"},{ioc:"HON",iso2:"HN",iso:"HND",label:"Honduras",phone:"504"},{ioc:"CRO",iso2:"HR",iso:"HRV",label:"Croatia",phone:"385"},{ioc:"HAI",iso2:"HT",iso:"HTI",label:"Haiti",phone:"509"},{ioc:"HUN",iso2:"HU",iso:"HUN",label:"Hungary",phone:"36"},{ioc:"INA",iso2:"ID",iso:"IDN",label:"Indonesia",phone:"62"},{ioc:"IRL",iso2:"IE",iso:"IRL",label:"Ireland",phone:"353"},{ioc:"ISR",iso2:"IL",iso:"ISR",label:"Israel",phone:"972"},{ioc:"",iso2:"IM",iso:"IMN",label:"Isle of Man",phone:"44"},{ioc:"IND",iso2:"IN",iso:"IND",label:"India",phone:"91"},{ioc:"",iso2:"IO",iso:"IOT",label:"British Indian Ocean Territory",phone:"246"},{ioc:"IRQ",iso2:"IQ",iso:"IRQ",label:"Iraq",phone:"964"},{ioc:"IRI",iso2:"IR",iso:"IRN",label:"Iran, Islamic Republic of",phone:"98"},{ioc:"ISL",iso2:"IS",iso:"ISL",label:"Iceland",phone:"354"},{ioc:"ITA",iso2:"IT",iso:"ITA",label:"Italy",phone:"39"},{ioc:"",iso2:"JE",iso:"JEY",label:"Jersey",phone:"44"},{ioc:"JAM",iso2:"JM",iso:"JAM",label:"Jamaica",phone:"1-876"},{ioc:"JOR",iso2:"JO",iso:"JOR",label:"Jordan",phone:"962"},{ioc:"JPN",iso2:"JP",iso:"JPN",label:"Japan",phone:"81",suggested:!0},{ioc:"KEN",iso2:"KE",iso:"KEN",label:"Kenya",phone:"254"},{ioc:"KGZ",iso2:"KG",iso:"KGZ",label:"Kyrgyzstan",phone:"996"},{ioc:"CAM",iso2:"KH",iso:"KHM",label:"Cambodia",phone:"855"},{ioc:"KIR",iso2:"KI",iso:"KIR",label:"Kiribati",phone:"686"},{ioc:"COM",iso2:"KM",iso:"COM",label:"Comoros",phone:"269"},{ioc:"SKN",iso2:"KN",iso:"KNA",label:"Saint Kitts and Nevis",phone:"1-869"},{ioc:"KOR",iso2:"KP",iso:"KOR",label:"Korea, Democratic People's Republic of",phone:"850"},{ioc:"PRK",iso2:"KR",iso:"PRK",label:"Korea, Republic of",phone:"82"},{ioc:"KUW",iso2:"KW",iso:"KWT",label:"Kuwait",phone:"965"},{ioc:"CAY",iso2:"KY",iso:"CYM",label:"Cayman Islands",phone:"1-345"},{ioc:"KAZ",iso2:"KZ",iso:"KAZ",label:"Kazakhstan",phone:"7"},{ioc:"LAO",iso2:"LA",iso:"LAO",label:"Lao People's Democratic Republic",phone:"856"},{ioc:"LIB",iso2:"LB",iso:"LBN",label:"Lebanon",phone:"961"},{ioc:"LCA",iso2:"LC",iso:"LCA",label:"Saint Lucia",phone:"1-758"},{ioc:"LIE",iso2:"LI",iso:"LIE",label:"Liechtenstein",phone:"423"},{ioc:"SRI",iso2:"LK",iso:"LKA",label:"Sri Lanka",phone:"94"},{ioc:"LBR",iso2:"LR",iso:"LBR",label:"Liberia",phone:"231"},{ioc:"LES",iso2:"LS",iso:"LSO",label:"Lesotho",phone:"266"},{ioc:"LTU",iso2:"LT",iso:"LTU",label:"Lithuania",phone:"370"},{ioc:"LUX",iso2:"LU",iso:"LUX",label:"Luxembourg",phone:"352"},{ioc:"LAT",iso2:"LV",iso:"LVA",label:"Latvia",phone:"371"},{ioc:"LBA",iso2:"LY",iso:"LBY",label:"Libya",phone:"218"},{ioc:"MAR",iso2:"MA",iso:"MAR",label:"Morocco",phone:"212"},{ioc:"MON",iso2:"MC",iso:"MCO",label:"Monaco",phone:"377"},{ioc:"MDA",iso2:"MD",iso:"MDA",label:"Moldova, Republic of",phone:"373"},{ioc:"MNE",iso2:"ME",iso:"MNE",label:"Montenegro",phone:"382"},{ioc:"",iso2:"MF",iso:"MAF",label:"Saint Martin (French part)",phone:"590"},{ioc:"MAD",iso2:"MG",iso:"MDG",label:"Madagascar",phone:"261"},{ioc:"MSH",iso2:"MH",iso:"MHL",label:"Marshall Islands",phone:"692"},{ioc:"MKD",iso2:"MK",iso:"MKD",label:"Macedonia, the Former Yugoslav Republic of",phone:"389"},{ioc:"MLI",iso2:"ML",iso:"MLI",label:"Mali",phone:"223"},{ioc:"MYA",iso2:"MM",iso:"MMR",label:"Myanmar",phone:"95"},{ioc:"MGL",iso2:"MN",iso:"MNG",label:"Mongolia",phone:"976"},{ioc:"MAC",iso2:"MO",iso:"MAC",label:"Macao",phone:"853"},{ioc:"NMA",iso2:"MP",iso:"NMP",label:"Northern Mariana Islands",phone:"1-670"},{ioc:"MRT",iso2:"MQ",iso:"MTQ",label:"Martinique",phone:"596"},{ioc:"MTN",iso2:"MR",iso:"MRT",label:"Mauritania",phone:"222"},{ioc:"MNT",iso2:"MS",iso:"MSR",label:"Montserrat",phone:"1-664"},{ioc:"MLT",iso2:"MT",iso:"MLT",label:"Malta",phone:"356"},{ioc:"MRI",iso2:"MU",iso:"MUS",label:"Mauritius",phone:"230"},{ioc:"MDV",iso2:"MV",iso:"MDV",label:"Maldives",phone:"960"},{ioc:"MAW",iso2:"MW",iso:"MWI",label:"Malawi",phone:"265"},{ioc:"MEX",iso2:"MX",iso:"MEX",label:"Mexico",phone:"52"},{ioc:"MAS",iso2:"MY",iso:"MYS",label:"Malaysia",phone:"60"},{ioc:"MOZ",iso2:"MZ",iso:"MOZ",label:"Mozambique",phone:"258"},{ioc:"NAM",iso2:"NA",iso:"NAM",label:"Namibia",phone:"264"},{ioc:"NCL",iso2:"NC",iso:"NCL",label:"New Caledonia",phone:"687"},{ioc:"NIG",iso2:"NE",iso:"NER",label:"Niger",phone:"227"},{ioc:"NFI",iso2:"NF",iso:"NFK",label:"Norfolk Island",phone:"672"},{ioc:"NGR",iso2:"NG",iso:"NGA",label:"Nigeria",phone:"234"},{ioc:"NCA",iso2:"NI",iso:"NIC",label:"Nicaragua",phone:"505"},{ioc:"NED",iso2:"NL",iso:"NLD",label:"Netherlands",phone:"31"},{ioc:"NOR",iso2:"NO",iso:"NOR",label:"Norway",phone:"47"},{ioc:"NEP",iso2:"NP",iso:"NPL",label:"Nepal",phone:"977"},{ioc:"NRU",iso2:"NR",iso:"NRU",label:"Nauru",phone:"674"},{ioc:"NIU",iso2:"NU",iso:"NIU",label:"Niue",phone:"683"},{ioc:"NZL",iso2:"NZ",iso:"NZL",label:"New Zealand",phone:"64"},{ioc:"OMA",iso2:"OM",iso:"OMN",label:"Oman",phone:"968"},{ioc:"PAN",iso2:"PA",iso:"PAN",label:"Panama",phone:"507"},{ioc:"PER",iso2:"PE",iso:"PER",label:"Peru",phone:"51"},{ioc:"FPO",iso2:"PF",iso:"PYF",label:"French Polynesia",phone:"689"},{ioc:"PNG",iso2:"PG",iso:"PNG",label:"Papua New Guinea",phone:"675"},{ioc:"PHI",iso2:"PH",iso:"PHL",label:"Philippines",phone:"63"},{ioc:"PAK",iso2:"PK",iso:"PAK",label:"Pakistan",phone:"92"},{ioc:"POL",iso2:"PL",iso:"POL",label:"Poland",phone:"48"},{ioc:"SPM",iso2:"PM",iso:"SPM",label:"Saint Pierre and Miquelon",phone:"508"},{ioc:"",iso2:"PN",iso:"PCN",label:"Pitcairn",phone:"870"},{ioc:"PUR",iso2:"PR",iso:"PRI",label:"Puerto Rico",phone:"1"},{ioc:"PLE",iso2:"PS",iso:"PSE",label:"Palestine, State of",phone:"970"},{ioc:"POR",iso2:"PT",iso:"PRT",label:"Portugal",phone:"351"},{ioc:"PLW",iso2:"PW",iso:"PLW",label:"Palau",phone:"680"},{ioc:"PAR",iso2:"PY",iso:"PRY",label:"Paraguay",phone:"595"},{ioc:"QAT",iso2:"QA",iso:"QAT",label:"Qatar",phone:"974"},{ioc:"REU",iso2:"RE",iso:"REU",label:"Reunion",phone:"262"},{ioc:"ROU",iso2:"RO",iso:"ROU",label:"Romania",phone:"40"},{ioc:"SRB",iso2:"RS",iso:"SRB",label:"Serbia",phone:"381"},{ioc:"RUS",iso2:"RU",iso:"RUS",label:"Russia",phone:"7"},{ioc:"RWA",iso2:"RW",iso:"RWA",label:"Rwanda",phone:"250"},{ioc:"KSA",iso2:"SA",iso:"SAU",label:"Saudi Arabia",phone:"966"},{ioc:"SOL",iso2:"SB",iso:"SLB",label:"Solomon Islands",phone:"677"},{ioc:"SEY",iso2:"SC",iso:"SYC",label:"Seychelles",phone:"248"},{ioc:"SUD",iso2:"SD",iso:"SDN",label:"Sudan",phone:"249"},{ioc:"SWE",iso2:"SE",iso:"SWE",label:"Sweden",phone:"46"},{ioc:"SIN",iso2:"SG",iso:"SGP",label:"Singapore",phone:"65"},{ioc:"HEL",iso2:"SH",iso:"SHN",label:"Saint Helena",phone:"290"},{ioc:"SLO",iso2:"SI",iso:"SVN",label:"Slovenia",phone:"386"},{ioc:"",iso2:"SJ",iso:"SJM",label:"Svalbard and Jan Mayen",phone:"47"},{ioc:"SVK",iso2:"SK",iso:"SVK",label:"Slovakia",phone:"421"},{ioc:"SLE",iso2:"SL",iso:"SLE",label:"Sierra Leone",phone:"232"},{ioc:"SMR",iso2:"SM",iso:"SMR",label:"San Marino",phone:"378"},{ioc:"SEN",iso2:"SN",iso:"SEN",label:"Senegal",phone:"221"},{ioc:"SOM",iso2:"SO",iso:"SOM",label:"Somalia",phone:"252"},{ioc:"SUR",iso2:"SR",iso:"SUR",label:"Suriname",phone:"597"},{ioc:"",iso2:"SS",iso:"SSD",label:"South Sudan",phone:"211"},{ioc:"STP",iso2:"ST",iso:"STP",label:"Sao Tome and Principe",phone:"239"},{ioc:"ESA",iso2:"SV",iso:"SLV",label:"El Salvador",phone:"503"},{ioc:"",iso2:"SX",iso:"SMX",label:"Sint Maarten",phone:"1-721"},{ioc:"SYR",iso2:"SY",iso:"SYR",label:"Syria",phone:"963"},{ioc:"",iso2:"SZ",iso:"SWZ",label:"Swaziland",phone:"268"},{ioc:"TKS",iso2:"TC",iso:"TCA",label:"Turks and Caicos Islands",phone:"1-649"},{ioc:"CHA",iso2:"TD",iso:"TCD",label:"Chad",phone:"235"},{ioc:"",iso2:"TF",iso:"ATF",label:"French Southern Territories",phone:"262"},{ioc:"TOG",iso2:"TG",iso:"TGO",label:"Togo",phone:"228"},{ioc:"THA",iso2:"TH",iso:"THA",label:"Thailand",phone:"66"},{ioc:"TJK",iso2:"TJ",iso:"TJK",label:"Tajikistan",phone:"992"},{ioc:"",iso2:"TK",iso:"TKL",label:"Tokelau",phone:"690"},{ioc:"TLS",iso2:"TL",iso:"TLS",label:"Timor-Leste",phone:"670"},{ioc:"TKM",iso2:"TM",iso:"TKM",label:"Turkmenistan",phone:"993"},{ioc:"TUN",iso2:"TN",iso:"TUN",label:"Tunisia",phone:"216"},{ioc:"TGA",iso2:"TO",iso:"TON",label:"Tonga",phone:"676"},{ioc:"TUR",iso2:"TR",iso:"TUR",label:"Turkey",phone:"90"},{ioc:"TTO",iso2:"TT",iso:"TTO",label:"Trinidad and Tobago",phone:"1-868"},{ioc:"TUV",iso2:"TV",iso:"TUV",label:"Tuvalu",phone:"688"},{ioc:"TPE",iso2:"TW",iso:"TWN",label:"Taiwan",phone:"886"},{ioc:"TAN",iso2:"TZ",iso:"TZA",label:"United Republic of Tanzania",phone:"255"},{ioc:"UKR",iso2:"UA",iso:"UKR",label:"Ukraine",phone:"380"},{ioc:"UGA",iso2:"UG",iso:"UGA",label:"Uganda",phone:"256"},{ioc:"USA",iso2:"US",label:"United States",phone:"1",suggested:!0,iso:"USA"},{ioc:"URU",iso2:"UY",iso:"URY",label:"Uruguay",phone:"598"},{ioc:"UZB",iso2:"UZ",iso:"UZB",label:"Uzbekistan",phone:"998"},{ioc:"",iso2:"VA",iso:"VAT",label:"Holy See (Vatican City State)",phone:"379"},{ioc:"VIN",iso2:"VC",iso:"VCT",label:"Saint Vincent and the Grenadines",phone:"1-784"},{ioc:"VEN",iso2:"VE",iso:"VEN",label:"Venezuela",phone:"58"},{ioc:"IVB",iso2:"VG",iso:"VGB",label:"British Virgin Islands",phone:"1-284"},{ioc:"ISV",iso2:"VI",iso:"VIR",label:"US Virgin Islands",phone:"1-340"},{ioc:"VIE",iso2:"VN",iso:"VNM",label:"Vietnam",phone:"84"},{ioc:"VAN",iso2:"VU",iso:"VUT",label:"Vanuatu",phone:"678"},{ioc:"WAF",iso2:"WF",iso:"WLF",label:"Wallis and Futuna",phone:"681"},{ioc:"SAM",iso2:"WS",iso:"WSM",label:"Samoa",phone:"685"},{ioc:"KOS",iso2:"XK",iso:"KOS",label:"Kosovo",phone:"383"},{ioc:"YEM",iso2:"YE",iso:"YEM",label:"Yemen",phone:"967"},{ioc:"MAY",iso2:"YT",iso:"MYT",label:"Mayotte",phone:"262"},{ioc:"RSA",iso2:"ZA",iso:"ZAF",label:"South Africa",phone:"27"},{ioc:"ZAM",iso2:"ZM",iso:"ZMB",label:"Zambia",phone:"260"},{ioc:"ZIM",iso2:"ZW",iso:"ZWE",label:"Zimbabwe",phone:"263"}];function zh({participant:t,withISO2:e,withIOC:r}){let{person:n,individualParticipants:o}=t,i=[n,o?.map(({person:a})=>a)].flat().filter(Boolean);function s(a){let{nationalityCode:c}=a||{};if(c){let u=ei.find(({iso:p})=>p===c);r&&u?.ioc&&!a.iocNationalityCode&&(a.iocNationalityCode=u.ioc),e&&u?.iso2&&!a.iso2NationalityCode&&(a.iso2NationalityCode=u.iso2),u?.label&&!a.countryName&&(a.countryName=u.label)}}i.forEach(s)}function Ub({participantMap:t,template:e}){let r=Object.values(t);for(let n of r){let o=n.participant;if(o.individualParticipantIds?.length){o.individualParticipants=[];for(let i of o.individualParticipantIds){let s=t[i].participant;o.individualParticipants.push(e?Bi({template:e,source:s}):s)}}}}function To(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:re}}function Qh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=To({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:it}}function en(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=Qh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:V,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:rf};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=J(i.pop(),!1,!0);if(s){let a={timeItem:s,...C};return e&&Object.assign(a,{previousItems:i}),a}else return{info:Ce}}function Xh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:sn};if(!e.timeItems)return{info:Ce};let{timeItem:o,previousItems:i,info:s}=en({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function fu({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Ot};if(!n.timeItems)return{info:Ce};let{timeItem:o,previousItems:i,info:s}=en({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function Jm({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:q};if(!e.timeItems)return{info:Ce};let{timeItem:o,previousItems:i,info:s}=en({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Jh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:q};if(!r)return{error:ie};let i=To({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Ce};let{timeItem:a,previousItems:c,info:u}=en({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var ZF={[zr]:"groupParticipantIds",[ft]:"pairParticipantIds",[Ft]:"teamParticipantIds"},tk={[zr]:"groups",[Ft]:"teams"};function Zh({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,withGroupings:i,internalUse:s,withISO2:a,withIOC:c}){let u=[],p={};for(let d of r.participants??[]){let l=d?.participantId;l&&nk({participantMap:p,participantId:l})}for(let d of r.participants??[]){let l=J(d,e,s),{participantId:f,individualParticipantIds:g,participantType:I}=l;if(!p[f]){u.push(f);continue}if(Object.assign(p[f].participant,l),g){let h=rk({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=ek(l)),o){let{ratings:h,rankings:S,seedings:T}=fa({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&zh({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=ht(t)?t:void 0;Ub({participantMap:p,template:d})}let m;return i&&(m=lu({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function ek(t){let{timeItem:e}=en({itemType:ac,element:t});return e?.itemValue===mu}function rk({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){let i=[];for(let s of t){let a=r[s]?.participant;if(!a){i.push(s);continue}if(a[ZF[n]].push(o),[Ft,zr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=tk[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===ft){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function nk({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[kt]:{...r},[xt]:{...r},[Ft]:{...r},...r}}}function Bo({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return Zh({...t,...n,tournamentRecord:r});let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>zh({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=lu({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=fa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function yt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:FI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...C};function a(c){let p=c?.extensions?.find(m=>m.name===ou)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function vo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:FI};let{appliedPolicies:i}=yt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),s={};for(let a of t){let c=i?.[a];c&&(s[a]=c)}return Object.keys(s).length?{policyDefinitions:s}:{info:kc.message}}var tS="WALKOVER",GU="RETIRED",Zm="COMPETITIVE",cc="ROUTINE",uc="DECISIVE",td="winRatio";var ok={[Si]:{policyName:"Competitive Bands Default",profileBands:{[uc]:20,[cc]:50}}},ed=ok;function $n({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=vo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[Si]??s?.[Si]??ed[Si];i.policies[Si]=a}return i}function ri({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:q};let{appliedPolicies:i}=yt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:kc?.message}}function Aa({tournamentRecord:t,categoryName:e,categoryType:r,event:n}){e=e??n?.category?.categoryName??n?.category?.ageCategoryCode,r=r??n?.category?.categoryType??n?.category?.subType;let{policy:o}=ri({policyType:No,tournamentRecord:t,event:n}),s=(t?lt({element:t,name:Vo}).extension:void 0)?.value,c=(n&&lt({name:Vo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function Kf({drawDefinition:t,attributes:e}){let{extension:r}=lt({element:t,name:Ym}),n=r?.value||{};return e.forEach(o=>{Object.keys(o).forEach(i=>{n[i]?Object.assign(n[i],o[i]):n[i]=o[i]})}),r={name:Ym,value:n},gp({drawDefinition:t,extension:r}),{entryProfile:n}}function gu({drawDefinition:t}){let{extension:e}=lt({element:t,name:Ym});return{entryProfile:e?.value||{}}}var rn="ALTERNATE",zf="CONFIRMED",kr="DIRECT_ACCEPTANCE",rd="FEED_IN",Qf="JUNIOR_EXEMPT",cs="LUCKY_LOSER",Xf="ORGANISER_ACCEPTANCE",nd="QUALIFIER",ik="REGISTERED",Jf="SPECIAL_EXEMPT",Gr="UNGROUPED",Ei="UNPAIRED",Iu="WILDCARD",so="WITHDRAWN",Zf=[zf,kr,Qf,Xf,Jf],VU=[rd,cs,nd],ni=[zf,kr,rd,Qf,Xf,Jf,Iu],Qr=[zf,kr,Qf,cs,nd,Xf,Jf,Iu],BU=[rn,zf,kr,rd,Qf,cs,Xf,nd,ik,Jf,Gr,Ei,Iu,so],Pb={ALTERNATE:rn,CONFIRMED:zf,DIRECT_ACCEPTANCE:kr,DIRECT_ENTRY_STATUSES:ni,DRAW_SPECIFIC_STATUSES:VU,EQUIVALENT_ACCEPTANCE_STATUSES:Zf,FEED_IN:rd,JUNIOR_EXEMPT:Qf,LUCKY_LOSER:cs,ORGANISER_ACCEPTANCE:Xf,QUALIFIER:nd,SPECIAL_EXEMPT:Jf,STRUCTURE_SELECTED_STATUSES:Qr,UNGROUPED:Gr,UNPAIRED:Ei,VALID_ENTRY_STATUSES:BU,WILDCARD:Iu,WITHDRAWN:so};function tg({stage:t,drawDefinition:e}){let{entryProfile:r}=gu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&Kc.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return Kf({drawDefinition:e,attributes:o}),!0}return n}function Db({stage:t,drawDefinition:e}){let{entryProfile:r}=gu({drawDefinition:e});return r[t]?.alternates||0}function Nb({stage:t,drawDefinition:e}){let{entryProfile:r}=gu({drawDefinition:e});return r[t]?.wildcardsCount||0}function eS({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Ui({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=lt({name:Mn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===fe){let{playoffEntries:p,error:m}=sk({provisionalPositioning:t,drawDefinition:r,structureId:i});return m&&console.log("playoff entries error"),(p?.length?p:u).filter(d=>!e||d.placementGroup===e)}return u}function sk({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===eo&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===Ge&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=lt({element:h,name:Zo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],y=T.groupOrder||t&&T.provisionalOrder;return h.includes(y)||h.push(y),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:y,GEMscore:P}=S,U=T||t&&y,A=[...i??[]].sort(le).indexOf(U)+1;n.push({entryStage:fe,entryStatus:rd,placementGroup:A,groupingValue:d,participantId:h,GEMscore:P})})})}return{playoffEntries:n}}function Mb({stage:t,drawDefinition:e}){return ni.reduce((r,n)=>(eS({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function nn({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=bt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:wt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===fe&&r&&Ui({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let h=I+1;return{participantId:g.participantId,seedValue:h,seedProxy:!0,seedNumber:h}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=kA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function oi(t){if(!t)return;let{tieFormatId:e,tieFormats:r}=t;if(t.tieFormat)return t.tieFormat;if(e&&Array.isArray(r))return r.find(n=>n.tieFormatId===e)}function yp({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r.tieFormat)return r.tieFormat;if(r.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function We({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:yp({item:r,drawDefinition:t,structure:e,event:n})||yp({item:e,drawDefinition:t,structure:e,event:n})||oi(t)||oi(n)}}function Rb({matchUps:t}){let e=t.reduce((n,o)=>!o.collectionPosition||n.includes(o.collectionPosition)?n:n.concat(o.collectionPosition),[]).map(n=>({[n]:t.filter(o=>o.collectionPosition===n)}));return{collectionPositionMatchUps:Object.assign({},...e)}}function De({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function ii({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}function rS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ee(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(le);return n.map(i=>o.indexOf(i)+1)}function eg(t){if(!ht(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>It(i)||i===void 0||i===null);return n&&o}function Vr(t){return Array.isArray(t)?t.every(eg):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Vr(t))return{roundMatchUps:[],error:V};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?mt(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(le).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Yt)?l.filter(({matchUpType:h})=>h===Yt):l,I=h=>h.sort((S,T)=>le(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?mt(l.roundNumber):l.roundNumber;return d[f]||(d[f]=ot({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>mt(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&On(l)){let f=d+1,g=f+l/2;tt(f,g).forEach((h,S)=>{o[h]=tt(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!pe.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>mt(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(le),I=Ee(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ee(I,h),T=l.map(y=>{let{roundPosition:P}=y,U=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!P)return U;let A=U?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return U?.slice().sort(le);let E=qt(I,A).length!==A?.length;if(A?.length&&E)return A?.length===1?[A[0],void 0]:U?.slice().sort(le);let N=(P-1)*2;return S.slice(N,N+2).map(M=>A?.find(R=>M.includes(R)))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]&&s[d+1].matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).find(({matchUpsCount:d})=>!On(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function od(t){if(!Array.isArray(t))return"";let e=t.filter(te);return e.length?ut([Math.min(...e),Math.max(...e)]).join("-"):""}function Cb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:Z};if(!e)return{error:Ur};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==qe)return{error:_i,info:"Structure is not CONSOLATION stage"};let{links:o}=t,i=o?.filter(m=>m.target.structureId===e)||[],s=i?.reduce((m,d)=>{let{structureId:l}=d.source;return m.includes(l)?m:m.concat(l)},[])||[],a=Object.assign({},...s.map(m=>{let d=ii({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=ii({matchUpsMap:r,structureId:e}),{roundProfile:u}=Ke({matchUps:c}),p={};return i?.forEach(m=>{let{structureId:d,roundNumber:l}=m.source,{feedProfile:f,groupedOrder:g,positionInterleave:I,roundNumber:h}=m.target,S=a[d],T=S[1]?.drawPositions,P=S[l]?.matchUpsCount;if(!P)return;let U=P?T.length/P:0,A=T.length/U,E=T.slice(),N=rS({roundPositionsCount:A,groupedOrder:g}),D=N?.length||1;if(D<=A){let v=T.length/D,O=Ee(E,v);f===li&&O.forEach(_=>_.reverse()),E=N?.length&&N?.map(_=>O[_-1]).flat()||E}let M=Ee(E,U);if(I){let v=tt(0,I.interleave).map(()=>{}),O=tt(0,I.offset).map(()=>{});M=M.map(F=>[F,...v]),M.unshift(O),M=M.flat(1);let _=M.length-I.offset;M=M.slice(0,_)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;M.forEach((v,O)=>{let _=1+O*b;p[h][_]||(p[h][_]=od(v))})}),{sourceDrawPositionRanges:p}}function nS({drawDefinition:t}){if(typeof t!="object")return{error:pa};let e={},{structures:r=[],links:n=[]}=t||{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[qe,fe].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,h=r.find(T=>T.structureId===I).stage,S=[h,I,g,f].join("|");if(p[S])return;p[S]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:h})}}}function bb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Ur};if(!e){let c=ii({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ke({matchUps:c}),!e)return{error:it}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ee(p,p.length/u),d=m.map(od),l=m.map(S=>S.map(T=>T-i)).map(od),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ee(T,T.length/u)}).filter(Boolean),g=tt(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(le)).map(S=>ut(S)),I=g.map(S=>fC(S).map(od).join(", ")),h=Object.assign({},...tt(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function id({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Ke({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Gi)&&!r?.structures&&t&&o}function ur({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var rg={[ga]:{policyName:"Round Naming Default",namingConventions:{round:"Round",pre:"Pre"},qualifyingFinishMap:{1:"Final"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q",preQualifying:"P"},stageConstants:{[rt]:"",[fe]:"P",[ct]:"Q",[qe]:"C"}}},vb=rg;function Ob({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=ur({structure:r}),u=id({structure:r}),p=r.structures,m={},d=rg[ga],l=r.stage===ct,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===ct).map(({stageSequence:b})=>b??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,U=(t?.namingConventions||d.namingConventions).round,A=a&&a!==rt?a[0]:"",E=t?.stageConstants||d.stageConstants,N=a&&E?.[a]||A,D=`${I}${N}${g}`,M=o?Object.keys(o):[],R=l&&E?.[ct]?`${E?.[ct]}-`:"";if(p||c||u)Object.assign(m,...M.map(b=>{let v=`${R}${U} ${b}`,O=`${y}${b}`;return{[b]:{roundName:v,abbreviatedRoundName:O}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...M.map(v=>{if(!o?.[v])return;let{matchUpsCount:O,preFeedRound:_}=o[v],F=O*2,w=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,L=_?`-${T}`:"",G=`${w}${L}`,k=[D,s,G].filter(Boolean).join("-"),W=`${S[O]||`${y}${F}`}${L}`,Y=[D,s,W].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:Y,roundName:k}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var ak=(t,e)=>(t||0)+(e||0);function oS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&tS||r<=e[uc]&&uc||r<=e[cc]&&cc||Zm}function iS({score:t}){let e=t?.sets||[],r=e.reduce((o,i)=>(o[0]+=i.side1Score||0,o[1]+=i.side2Score||0,o),[0,0]),n=e.reduce((o,i)=>(o[0]+=i.side1TiebreakScore||0,o[1]+=i.side2TiebreakScore||0,o),[0,0]);return n.reduce(ak)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function ck(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function sS(t){return t.map(ck).sort().map(e=>parseFloat(e.toFixed(2)))}function hu({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:Sr};let{score:n,winningSide:o}=r;if(!o)return{error:V};let i=!e&&t&&ri({policyType:Si,tournamentRecord:t}).policy,s=e||i?.profileBands||ed[Si].profileBands,a=iS({score:n}),c=sS([a]),u=oS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function aS({matchUp:t}){if(!t)return{error:Sr};if(t&&!t.sides)return{error:dr};if(t&&!t.hasContext)return{error:Vc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Tt).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=ut(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...C}}var sd="CHECK_IN",ad="CHECK_OUT",uk="SCHEDULE",Wi="SCHEDULE.ASSIGNMENT.VENUE",ao="SCHEDULE.ALLOCATION.COURTS",Ho="SCHEDULE.ASSIGNMENT.COURT",Ap="SCHEDULE.COURT.ORDER",ji="SCHEDULE.DATE",pk="COMPLETED.DATE",cd="HOME_PARTICIPANT_ID",ng="SCHEDULE.ASSIGN.OFFICIAL",Yi="SCHEDULE.TIME.SCHEDULED",Oo="SCHEDULE.TIME.START",qi="SCHEDULE.TIME.STOP",Pi="SCHEDULE.TIME.RESUME",Di="SCHEDULE.TIME.END",Ep="SCHEDULE.TIME.MODIFIERS",_b="TO_BE_ANNOUNCED",xb="NEXT_AVAILABLE",wb="FOLLOWED_BY",Lb="AFTER_REST",Fb="RAIN_DELAY",mk="NOT_BEFORE",cS=[_b,xb,wb,Lb,Fb],dk="ELIGIBILITY",lk="REGISTRATION",fk="SUSPENSION",gk="MEDICAL",Ik="PENALTY",HU="SCALE",WU="RATING",jU="RANKING",og="SEEDING",_o="PUBLISH",Rr="PUBLIC",xo="STATUS",hk="MODIFICATION",Sk="RETRIEVAL",Tk="other",kb={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:cS,AFTER_REST:Lb,ALLOCATE_COURTS:ao,ASSIGN_COURT:Ho,ASSIGN_OFFICIAL:ng,ASSIGN_VENUE:Wi,CHECK_IN:sd,CHECK_OUT:ad,COMPLETED_DATE:pk,COURT_ORDER:Ap,ELIGIBILITY:dk,END_TIME:Di,FOLLOWED_BY:wb,MEDICAL:gk,MODIFICATION:hk,NEXT_AVAILABLE:xb,NOT_BEFORE:mk,OTHER:Tk,PENALTY:Ik,PUBLIC:Rr,PUBLISH:_o,RANKING:jU,RATING:WU,RAIN_DELAY:Fb,REGISTRATION:lk,RESUME_TIME:Pi,RETRIEVAL:Sk,SCALE:HU,SCHEDULE:uk,SCHEDULED_DATE:ji,SCHEDULED_TIME:Yi,SEEDING:og,START_TIME:Oo,STATUS:xo,STOP_TIME:qi,SUSPENSION:fk,TIME_MODIFIERS:Ep,TO_BE_ANNOUNCED:_b};function us({matchUp:t}){if(!t)return{error:Sr};if(!t.hasContext)return{error:Vc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:dr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=aS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[sd,ad].includes(u.itemType)).sort((u,p)=>(u.createdAt?new Date(u.createdAt).getTime():0)-(p.createdAt?new Date(p.createdAt).getTime():0)),a=i.map(u=>u.itemValue).filter(u=>i.filter(p=>p?.itemValue===u).reverse()[0].itemType===sd);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...C}}var me=t=>e=>{let r=ht(e)&&e?.matchUpType||Vt(e)&&e;return r&&PI[t].includes(r)};function Up(t){let{matchUpAverageTimes:e,matchUpFormat:r}=t||{},n=e?.map(({matchUpFormatCodes:a})=>a?.filter(c=>c===r)).flat().filter(Boolean).sort((a,c)=>(a?.length||0)-(c?.length||0))||[],i=n.includes(r)?r:n[0];return e?.find(({matchUpFormatCodes:a,averageTimes:c})=>a?.find(u=>i===u)&&c)?.averageTimes}function Pp(t){let{matchUpRecoveryTimes:e,averageMinutes:r,matchUpFormat:n}=t||{};return e?.find(({matchUpFormatCodes:o,averageTimes:i,recoveryTimes:s})=>{if(i&&r){let{greaterThan:a=0,lessThan:c=360}=i;if(r>a&&r<c)return!0}return o?.find(a=>a===n)&&s})?.recoveryTimes}function uS({timesBlockArray:t,categoryName:e,categoryType:r}){return t.filter(n=>Array.isArray(n)).map(n=>n.sort((o,i)=>(i.categoryNames?.length||0)-(o.categoryNames?.length||0)).find(({categoryTypes:o,categoryNames:i})=>!i?.length&&!o?.length||i?.includes(e)||o?.includes(r))).find(Boolean)}function Gb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Pp({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Pp({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Pp({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return uS({categoryName:i,categoryType:s,timesBlockArray:m})}function Vb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Up({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Up({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Up({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return uS({categoryName:e,categoryType:r,timesBlockArray:p})}var YU="DOUBLES_SINGLES",qU="SINGLES_DOUBLES",co="total",pS="participantConflict",Ea="matchUpConflict",$U="ISSUE_IDS",pc="CONFLICT",mc="WARNING",mS="ERROR",dS="ISSUE",ig="STATE",Bb={SINGLES_DOUBLES:qU,DOUBLES_SINGLES:YU,TOTAL:co,CONFLICT_MATCHUP_ORDER:Ea,CONFLICT_PARTICIPANTS:pS,SCHEDULE_ISSUE_IDS:$U,SCHEDULE_CONFLICT:pc,SCHEDULE_WARNING:mc,SCHEDULE_ERROR:mS,SCHEDULE_ISSUE:dS,SCHEDULE_STATE:ig};function Su({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:q};s=s??a?.eventType??Fs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Aa({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return Dp({eventType:s,timingDetails:p})}function Dp({timingDetails:t,eventType:e}){let r=Vb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Gb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=me(Fs)(e)?qU:YU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function KU(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Wo({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>KU(o)-KU(i)).pop(),n=r&&KU(r);return{itemValue:r?.itemValue,timeStamp:n}}function lS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Yi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Hs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function Np(t){if(zI.test(t)){let e=Sf();return new Date(`${e}T${t}`)}else return new Date(t)}function Hb({matchUp:t}){if(!t)return{error:Sr};if(!t.timeItems)return{error:rf};let e=t.timeItems.filter(n=>[Oo,qi,Pi,Di].includes(n?.itemType)).sort((n,o)=>Np(n.itemValue).getTime()-Np(o.itemValue).getTime()),r=e.reduce((n,o)=>{let i,s=o?.itemType?.split("."),c=`SCHEDULE.TIME.${o?.itemType?.startsWith("SCHEDULE.TIME")&&s[2]}`;switch(c){case Oo:i=0;break;case Di:if(n.lastValue&&[Oo,Pi].includes(n.lastType)){let u=Np(o.itemValue).getTime()-Np(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case qi:if([Oo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=Np(o.itemValue).getTime()-Np(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;default:i=n.milliseconds;break}return{milliseconds:i,lastType:c,lastValue:o.itemValue}},{milliseconds:0,lastType:void 0,lastValue:void 0});if([Oo,Pi].includes(r.lastType)){let n=new Date().getTime()-Np(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:yk(r.milliseconds),relevantTimeItems:e}}function yk(t){let e=(r,n=2)=>("00"+r).slice(-n);return e(t/36e5|0)+":"+e(t%36e5/6e4|0)+":"+e(t%6e4/1e3|0)}function Wb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{startTime:e.reduce((i,s)=>{let a=s.itemType===Oo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function dc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:V};let o=Mr(t);r.venueId||(r.venueId=Dt());let i;for(let s of Object.values(o)){let a=Ak({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||dt({topic:jh,payload:{venue:r}}),ot({...C,venue:i})}function Ak({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Dt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:TE}:(r&&At({element:n,extension:{value:r,name:TU}}),t.venues.push(n),e||dt({payload:{venue:n,tournamentId:t.tournamentId},topic:jh}),{...C,venue:J(n)})):{error:it,info:"missing venue"}:{error:q}}function jo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:q};if(!r)return{error:Jo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(su({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=jo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return dc({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:Fi}}function fS({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=jo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ps({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:q};if(!r)return{error:xi};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...C,court:o,venue:i};if(t){let a=(su({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ps({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&dc({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return x({result:{error:Os},stack:n})}function gS(t){return J(ps(t),!1,!0)}function ud({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:q};if(!r)return{error:xi};let n=ps({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...C,courtInfo:J(o,!1,e)}}function lc(t){let e=et(t,[{[se]:!0},{venueId:!0,[gn]:Jo}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=jo({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(ud({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:m})=>({venueAbbreviation:m,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...C,venueData:J(c,!1,!0)}}function jb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{endTime:e.reduce((i,s)=>{let a=s.itemType===Di&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:Ot};let n=lt({name:cn,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function ze(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Ht({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,...x({result:{error:jr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,...x({result:{error:br},context:{drawId:n,eventId:r},stack:o})}}function pd(t){let e=t.event,r=t.matchUpType,{scheduleVisibilityFilters:n,afterRecoveryTimes:o,tournamentRecord:i,usePublishState:s,scheduleTiming:a,matchUpFormat:c,publishStatus:u,matchUp:p}=t;if(!p)return{error:Sr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let U=t.drawDefinition||e?.drawDefinitions?.find(E=>E.drawId===p.drawId);!U&&i&&({drawDefinition:U,event:e}=ze({drawId:p.drawId,tournamentRecord:i}));let A=p.structureId&&U?.structures?.find(({structureId:E})=>E===p.structureId);r=t.matchUpType||A?.matchUpType||U?.matchUpType||e?.eventType!==ve&&e?.eventType}let{milliseconds:m,time:d}=Hb({matchUp:p}),{startTime:l}=Wb({matchUp:p}),{endTime:f}=jb({matchUp:p}),g,{eventIds:I,drawIds:h}=n??{};if((!I||I.includes(p.eventId))&&(!h||h.includes(p.drawId))){let U=Q=>Q.createdAt?new Date(Q.createdAt).getTime():0,A=new Map,E=p.timeItems?.toSorted((Q,pt)=>U(Q)-U(pt))??[];for(let Q of E)A.set(Q.itemType,Q.itemValue);let N=A.get(cd),D=A.get(ao),M=A.get(Yi),R=A.get(Ep),b=A.get(ji),v=A.get(ng),O=A.get(Ap),_=A.get(Wi),F=A.get(Ho),w,L,G,k,H,W=p.matchUpType??r;if(a&&M&&o&&W){let Q={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:L=0,recoveryMinutes:G=0,typeChangeRecoveryMinutes:k=0}=Dp({timingDetails:Q,eventType:W})),(L||G)&&(w=f?Yr(Xt(f),G):Yr(M,L+G)),k&&(H=f?Yr(Xt(f),k):Yr(M,L+k))}!b&&M&&(b=Et(M));let Y=vm({scheduledDate:b,scheduledTime:M}),$={},B=(i&&_&&lc({tournamentRecord:i,venueId:_}))?.venueData||{};_&&($[_]=B);let{venueName:K,venueAbbreviation:X,courtsInfo:j}=B,z=(F&&j?.find(Q=>Q.courtId===F))?.courtName;for(let Q of D||[]){if(!i)break;Q.venueId&&!$[Q.venueid]&&($[Q.venueId]=lc({venueId:Q.venueId,tournamentRecord:i})?.venueData);let pt=$[Q.venueId];Q.venueName=pt?.venueName;let st=pt?.courtsInfo?.find(Mt=>Mt.courtId===Q.courtId);Q.courtName=st?.courtName}g=ot({typeChangeTimeAfterRecovery:H,timeAfterRecovery:w,scheduledDate:b,scheduledTime:M,isoDateString:Y,homeParticipantId:N,venueAbbreviation:X,allocatedCourts:D,timeModifiers:R,venueName:K,venueId:_,courtOrder:O,courtName:z,courtId:F,official:v,typeChangeRecoveryMinutes:k,recoveryMinutes:G,averageMinutes:L,milliseconds:m,startTime:l,endTime:f,time:d})}else g=ot({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Hs({matchUp:p}),{scheduledTime:T}=lS({matchUp:p});if(s&&u?.displaySettings?.draws){let U=u.displaySettings.draws,A=(U?.[p.drawId]??U?.default)?.scheduleDetails;if(A){let E=(A.find(N=>S&&N.dates?.includes(S))??A.find(N=>!N.dates?.length))?.attributes;if(E){let N=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),E);g=Bi({source:g,template:N})}}}let P=p.matchUpStatus&&pe.includes(p.matchUpStatus)&&(Et(f)||Et(S)||Et(T))||void 0;return{schedule:g,endDate:P}}function Yb({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(RI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Fe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(MI(t)){let c=[...t].sort(le);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(mt(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Mp({collectionPosition:t,collectionId:e,lineUp:r}){let n=[],o=[];if(r){let i=a=>a===void 0?-1:a,s=r.map(a=>{let{collectionAssignments:c,participantId:u}=a,p=c?.find(m=>m.collectionPosition===t&&m.collectionId===e);return p&&{participantId:u,...p}}).filter(Boolean).sort((a,c)=>i(a.substitutionOrder)-i(c.substitutionOrder));for(let a of s){let{participantId:c,previousParticipantId:u,substitutionOrder:p}=a;n.includes(c)||(u&&o.push({previousParticipantId:u,substitutionOrder:p,participantId:c}),n=n.filter(m=>m!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function hn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:q};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return x({result:{error:Uo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===ft&&qt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return x({result:{error:re},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function ms({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:ie};let{extension:r}=lt({element:t,name:Ro});return{lineUp:(r?.value||{})[e]}}function qb({tournamentParticipants:t,positionAssignments:e,collectionPosition:r,drawPositions:n=[],participantMap:o,drawDefinition:i,collectionId:s,sideLineUps:a,matchUpType:c}){if(!s||!r)return{};let u=({attribute:m,lineUp:d,teamParticipant:l})=>{let{assignedParticipantIds:f,substitutions:g}=Mp({collectionPosition:r,collectionId:s,lineUp:d});if(c===xt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||hn({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[m]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[m]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[m]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let m=a?.map(d=>{let{teamParticipant:l,sideNumber:f}=d,g=d.lineUp||ms({participantId:l.teamParticipantId,drawDefinition:i})?.lineUp;return u({attribute:f,lineUp:g,teamParticipant:l})}).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...m)}}let p=n?.map(m=>{let d=e.find(I=>I.drawPosition===m)?.participantId,l=a?.find(I=>I?.drawPosition===m),f=l?.teamParticipant||d&&o?.[d]?.participant||t?.find(({participantId:I})=>I===d),g=l?.lineUp||ms({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function md(t){let e=et(t,[{[xn]:!0}]);if(e.error)return e;let r=t?.matchUp,n=r?.matchUpType;if(!n&&r?.sides?.length){let s=r.sides.find(({participant:a})=>a)?.participant?.participantType;n=s===Tt&&kt||s===ft&&xt||s===Ft&&Ft||void 0}return{matchUpType:n}}function $b({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:r,displaySideNumber:n,seedAssignments:o,drawPosition:i,isFeedRound:s,sideNumber:a}){let c=r.find(l=>l.drawPosition&&l.drawPosition===i),u=i&&t,p=a&&e,m=u?u[i]?.participantId:c?.participantId,d=c?Ek({displaySideNumber:n,seedAssignments:o,participantId:m,assignment:c,sideNumber:a}):{...p?.[a]};if(s&&(a===1?Object.assign(d,{participantFed:!0}):Object.assign(d,{participantAdvanced:!0})),i&&u){let l=u[i]?.teamParticipant,f=u[i]?.participant,g=u[i]?.substitutions;f&&(d.participant=f),g&&(d.substitutions=g),l&&(d.teamParticipant=l)}return d}function Ek({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Uk({seedAssignments:e,participantId:r});Object.assign(i,s,{participantId:r}),s?.seedNumber&&s?.seedValue===""&&(i.seedValue="~")}else n.bye&&Object.assign(i,{bye:!0});return n.qualifier&&Object.assign(i,{qualifier:!0}),i}function Uk({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function zU({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:m,appliedPolicies:d,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,publishStatus:P,scoringActive:U,matchUpTieId:A,isRoundRobin:E,roundProfile:N,sideLineUps:D,structure:M,context:R,matchUp:b,event:v}){c=c??{};let O=We({drawDefinition:y,structure:M,matchUp:b,event:v})?.tieFormat,{roundOffset:_,structureId:F,structureName:w,stage:L,stageSequence:G}=M,{drawId:k,drawName:H,drawType:W}=y??{},Y=O?.collectionDefinitions,$=b.collectionId&&Y?.find(jt=>jt.collectionId===b.collectionId),B=b.collectionId?$?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,K=b.matchUpType||$?.matchUpType||M?.matchUpType||y?.matchUpType||!me(ve)(v?.eventType)&&v?.eventType,X=l?Nt:b.matchUpStatus,{schedule:j,endDate:nt}=pd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:B,publishStatus:P,matchUpType:K,matchUp:b,event:v}),z=m??b.drawPositions??[],{collectionPosition:Q,collectionId:pt,roundPosition:st}=b,Mt=b.roundNumber??c.roundNumber,_t=pt?qb({tournamentParticipants:r,positionAssignments:n,collectionPosition:Q,participantMap:I,drawDefinition:y,drawPositions:z,collectionId:pt,sideLineUps:D,matchUpType:K}):void 0,Re=u?.[Mt]?.roundName||c.roundName,Kt=u?.[Mt]?.abbreviatedRoundName||c.abbreviatedRoundName,Ie=N?.[Mt]?.feedRound,_r=N?.[Mt]?.preFeedRound,pn=N?.[Mt]?.roundFactor,gr=o?.[Mt],Xe=st?gr?.[st]:void 0,ee=e?.[Mt],Ut=$?.category?{...R?.category||{},...$.category}:R?.category??v?.category,ce=b.processCodes?.length&&b.processCodes||$?.processCodes?.length&&$?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||v?.processCodes?.length&&v?.processCodes||p?.processCodes,ue=T?.withCompetitiveness&&hu({...h,matchUp:b}),we=b.finishingPositionRange??c.finishingPositionRange,zt=jt=>ot(jt,void 0,!0),Wt={...zt(R),...zt({matchUpFormat:b.matchUpType===ve?void 0:B,tieFormat:b.matchUpType!==ve?void 0:O,gender:$?.gender??v?.gender,roundOfPlay:L!==ct&&It(a)&&a+(Mt||0),endDate:b.endDate??nt,discipline:v?.discipline,category:Ut,finishingPositionRange:we,abbreviatedRoundName:Kt,drawPositionsRange:Xe,competitiveProfile:ue,structureName:w,stageSequence:G,drawPositions:z,matchUpStatus:X,processCodes:ce,isRoundRobin:E,matchUpTieId:A,preFeedRound:_r,matchUpType:K,roundFactor:pn,roundOffset:_,structureId:F,roundNumber:Mt,feedRound:Ie,roundName:Re,drawName:H,drawType:W,schedule:j,drawId:k,stage:L}),...J(zt(b),!0,!0)};if(B&&b.score?.scoreStringSide1){let jt=Ye(B),{bestOf:Pe,finalSetFormat:lr,setFormat:he}=jt??{};(lr?.tiebreakSet||he?.tiebreakSet||he?.timed)&&(Wt.score.sets=Wt.score.sets.sort((oe,Le)=>oe.setNumber-Le.setNumber).map((oe,Le)=>(Le+1===Pe?(lr?.tiebreakSet||lr?.timed)&&(oe.tiebreakSet=!0):(he?.tiebreakSet||he?.timed)&&(oe.tiebreakSet=!0),oe)))}if(Array.isArray(z)){let{orderedDrawPositions:jt,displayOrder:Pe}=Yb({drawPositions:z,roundProfile:N,roundNumber:Mt}),lr=N?.[Mt]?.feedRound,he=Pe[0]!==jt[0],Le=jt.concat(void 0,void 0).slice(0,2).map((Cr,Je)=>{let Hn=Je+1,de=he?3-Hn:Hn,Er=$b({..._t,positionAssignments:n,displaySideNumber:de,seedAssignments:f,drawPosition:Cr,isFeedRound:lr,sideNumber:Hn}),ts=b.sides?.find(aa=>aa.sideNumber===Hn),mn=st?(st-1)*2+Je+1:void 0,vi=mn?ee?.[mn]:void 0;return zt({sourceDrawPositionRange:vi,...ts,...Er})});Object.assign(Wt,J({sides:Le},!0,!0))}if(r&&Wt.sides){let jt=d?.[Vs],Pe=he=>{let oe=I?.[he]?.participant;return oe&&Bi({template:jt?.participant,source:oe})};if(Wt.sides.filter(Boolean).forEach(he=>{if(he.participantId){let oe=J(Pe(he.participantId)||(r?Go({policyDefinitions:d,participantId:he.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(oe){let Le,Cr;if(y?.entries){let Je=y.entries.find(de=>de.participantId===he.participantId),Hn=v?.entries?.find(de=>de.participantId===he.participantId);Le=Je?.entryStatus||Hn?.entryStatus,oe.entryStatus=Le,Je?.entryStage&&(Cr=Je.entryStage,oe.entryStage=Cr)}i!==!1?Object.assign(he,{participant:oe}):Object.assign(he,{participant:{entryStage:Cr,entryStatus:Le}})}}if(he?.participant?.individualParticipantIds?.length&&!he.participant.individualParticipants?.length){let oe=he.participant.individualParticipantIds.map(Le=>Pe(Le)||(r?Go({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:Le}):void 0));i!==!1&&Object.assign(he.participant,{individualParticipants:oe})}}),!Wt.matchUpType){let{matchUpType:he}=md({matchUp:Wt});he&&Object.assign(Wt,{matchUpType:he})}if(T?.inferGender&&(!Wt.gender||Wt.gender===yr)&&Wt.sides?.length===2&&Wt.matchUpType!==ve){let he=Wt.sides.map(oe=>{if(me(kt)(Wt.matchUpType))return oe.participant?.person?.sex;if(oe.participant?.individualParticipants?.length===2){let Le=ut(oe.participant.individualParticipants.map(Cr=>Cr.person?.sex)).filter(Boolean);if(Le.length===1)return Le[0]}});if(he.filter(Boolean).length===2&&ut(he).length===1){let oe=he[0];Wt.inferredGender=oe}}}if(Wt.tieMatchUps){let jt=Wt.matchUpStatus===Nt,Pe=Wt.sides?.map(({participant:lr,drawPosition:he,sideNumber:oe,lineUp:Le})=>{let Cr=lr?.participantType===ve&&lr;return{teamParticipant:Cr&&ot({participantRoleResponsibilities:Cr.participantRoleResponsibilities,participantOtherName:Cr.participanOthertName,participantName:Cr.participantName,participantId:Cr.participantId,teamId:Cr.teamId}),drawPosition:he,sideNumber:oe,lineUp:Le}});Wt.tieMatchUps=Wt.tieMatchUps.map(lr=>{let he=Wt.matchUpId,Le={finishingPositionRange:Wt.finishingPositionRange,abbreviatedRoundName:Kt,roundNumber:Mt,roundName:Re};return zU({tieDrawPositions:z,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:Pe,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:Le,appliedPolicies:d,isCollectionBye:jt,usePublishState:g,publishStatus:P,matchUpTieId:he,isRoundRobin:E,roundProfile:N,matchUp:lr,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:U,structure:M,context:R})})}let Ir=Wt.sides&&Wt.sides.filter(jt=>jt?.participantId).length===2,mr=!Wt.winningSide;if(Object.assign(Wt,{readyToScore:U&&Ir&&mr,hasContext:!0}),Ir){let{allParticipantsCheckedIn:jt,checkedInParticipantIds:Pe}=us({matchUp:Wt});Object.assign(Wt,{allParticipantsCheckedIn:jt,checkedInParticipantIds:Pe})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(jt=>delete Wt[jt]),Wt}function Kb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:ao});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function zb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Ho});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function Qb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Wo({timeItems:r?.timeItems||[],itemType:Wi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function Ni(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:P,tournamentIds:U,matchUpTypes:A,structureIds:E,readyToScore:N,courtIds:D,eventIds:M,venueIds:R,drawIds:b,stages:v}=t,O=Array.isArray(y)?y.filter(Boolean):[],_=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],w=Array.isArray(v)?v.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],G=Array.isArray(p)?p.filter(Boolean):[],k=Array.isArray(f)?f.filter(Boolean):[],H=Array.isArray(d)?d.filter(Boolean):[],W=Array.isArray(c)?c.filter(Boolean):[],Y=Array.isArray(l)&&I?l.filter(Boolean):[],$=Array.isArray(A)&&g?A.filter(Boolean):[],B=Array.isArray(D)?D.filter(Boolean):[],K=Array.isArray(R)?R.filter(Boolean):[],X=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],j=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],nt=Array.isArray(U)?U.filter(Boolean):[],z=Array.isArray(M)?M.filter(Boolean):[],Q=Array.isArray(b)?b.filter(Boolean):[],pt=Array.isArray(E)?E.filter(Boolean):[];return e.filter(st=>{if(N&&!me(xr)(st)&&!st.readyToScore||st.winningSide&&s&&![1,2].includes(st.winningSide)||m!==void 0&&(m&&!st.tieMatchUps||!m&&st.tieMatchUps)||o!==void 0&&(o&&!st.collectionId||!o&&st.collectionId)||w.length&&!w.includes(st.stage)||L.length&&!L.includes(st.stageSequence)||G.length&&(!st.collectionId||!G.includes(st.collectionId))||k.length&&(!st.roundName||!k.includes(st.roundName))||H.length&&(!st.roundNumber||!H.includes(st.roundNumber))||W.length&&(!st.roundPosition||!W.includes(st.roundPosition))||_.length&&(!st.matchUpStatus||!_.includes(st.matchUpStatus))||F.length&&st.matchUpStatus&&F.includes(st.matchUpStatus)||Y.length&&!Y.includes(st.matchUpId)||$.length&&(!st.matchUpType||!Fc($,st.matchUpType))||X.length&&(!st.matchUpFormat||!X.includes(st.matchUpFormat)))return!1;if(j?.length){let{scheduledTime:Mt}=lS({matchUp:st}),{scheduledDate:_t}=Hs({matchUp:st}),Kt=Et(Mt)||_t;if(!j.find(Ie=>Yn(Ie,Kt)))return!1}if(B.length){let{courtId:Mt}=zb({matchUp:st}),{allocatedCourts:_t}=Kb({matchUp:st}),Re=_t?.map(({courtId:Kt})=>Kt);if(!B.filter(Boolean).includes(Mt)||Re?.includes(Mt))return!1}if(K.length){let{venueId:Mt}=Qb({matchUp:st});if(!K.filter(Boolean).includes(Mt))return!1}if(P){if(nt.length&&!nt.includes(st.tournamentId)||z.length&&!z.includes(st.eventId)||Q.length&&!Q.includes(st.drawId)||pt.length&&!pt.includes(st.structureId))return!1;let Mt=st.sides?.map(({participantId:_t})=>_t).filter(Boolean)??[];if(n&&Mt.length<n||O.length&&!O.some(Re=>Mt.includes(Re)))return!1}return!0})}function Pt(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:m,contextContent:d,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:mi,roundMatchUps:I,matchUps:[]};let h=Array.isArray(o?.eventIds)?o?.eventIds.filter(Boolean):[],S=Array.isArray(o?.structureIds)?o?.structureIds.filter(Boolean):[],T=Array.isArray(o?.drawIds)?o?.drawIds.filter(Boolean):[],y=!a?.eventId||!h?.length&&!n?.eventIds?.filter(Boolean).length||h?.includes(a.eventId)||n?.eventIds?.includes(a.eventId),P=!S?.length||S.includes(c.structureId),U=!s||!T?.length||T.includes(s.drawId);if(!y||!P||!U)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=$n({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:A}=yt({drawDefinition:s}),E={...t.tournamentAppliedPolicies,...A,...t.policyDefinitions},N=E?.scoring?.structures,D=c.stage&&N?.stage?.[c.stage],M=c.stageSequence&&D?.stageSequence?.[c.stageSequence],R=E?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned;f||(f=De({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:v}=ye({structure:c}),O=!R||v,{seedAssignments:_}=nn({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??_;let{structureId:F}=c;l=l||s&&nS({drawDefinition:s}).exitProfiles;let w=l?.[F],L=w?.length&&(w[0].split("-").map(B=>parseInt(B)).reduce((B,K)=>B+K)||0),G=!!c.structures,k=ii({matchUpsMap:f,structureId:F,inContext:u}),H=E?.[ga],W=Ob({roundNamingPolicy:H,drawDefinition:s,structure:c,matchUps:k}),{roundNamingProfile:Y,roundProfile:$}=W;if(I=W?.roundMatchUps??[],o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:B}=Cb({drawDefinition:s,matchUpsMap:f,structureId:F}),K=s?bb({drawDefinition:s,roundProfile:$,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0,X=t.tournamentParticipants,j=t.participantMap;!X?.length&&!j&&r&&({participants:X=[],participantMap:j}=Bo({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:r,contextProfile:i,inContext:u})),k=k.map(z=>zU({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:B,tournamentParticipants:X,positionAssignments:b,drawPositionsRanges:K,initialRoundOfPlay:L,roundNamingProfile:Y,tournamentRecord:r,appliedPolicies:E,seedAssignments:m,contextContent:d,participantMap:j,contextProfile:i,drawDefinition:s,scoringActive:O,isRoundRobin:G,roundProfile:$,structure:c,context:a,matchUp:z,event:p})),(k?.filter(z=>Array.isArray(z.tieMatchUps))).forEach(z=>{let Q=z.tieMatchUps;k=k.concat(...Q)}),n&&(k=Ni({processContext:!0,...n,matchUps:k}))}else(k?.filter(K=>Array.isArray(K.tieMatchUps))).forEach(K=>{let X=K.tieMatchUps;k=k.concat(...X)});return o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(k=Ni({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:k})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ke({matchUps:k}).roundMatchUps??[]),We({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=Rb({matchUps:k})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:G,roundProfile:$,matchUpsMap:f,matchUps:k}}function ds({matchUp:t}){return t?pe.includes(t?.matchUpStatus)||t?.winningSide:!1}function Tu({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structureId:T,inContext:y,structure:P,context:U,event:A}){!P&&T&&({structure:P}=at({drawDefinition:I,structureId:T}));let E=Pt({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structure:P,inContext:y,context:U,event:A}),N=[],D=[],M=[],R=[],b=[];if(E.error)return E;let{matchUps:v}=E,{assignedPositions:O}=ye({structure:P}),_=O?.filter(w=>w.participantId).map(w=>w.drawPosition),F;return v.filter(w=>{let L=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===Yt;return!(w.matchUpType!==Yt&&L)}).forEach(w=>{if(w.matchUpStatus===Or){N.push(w);return}w.matchUpType===Yt&&(F=!0);let L=w.collectionId,G=L&&w.sides?.every(K=>K.participantId),k=!L&&w.drawPositions?.filter(Boolean).length===2,H=!L&&w.drawPositions?.every(K=>_?.includes(K)),W=O?.filter(K=>K.bye).map(K=>K.drawPosition),Y=!L&&w.drawPositions?.find(K=>W?.includes(K)),B=Bh.includes(w.matchUpStatus)&&(G||k&&(!t||H));return Y?b.push(w):ds({matchUp:w})?D.push(w):B?M.push(w):R.push(w)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:P}}function Xb({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Ur};let{links:n}=Ws({drawDefinition:t,structureId:r}),o=n.source.reduce((s,a)=>!a.source.roundNumber||a.source.roundNumber===e?s.concat(a):s,[]),i=n.target.reduce((s,a)=>!a.target.roundNumber||a.target.roundNumber===e?s.concat(a):s,[]);return{links:{source:o,target:i}}}function IS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Fe(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[fo,ro].includes(o?.linkType)&&!o?.source?.roundNumber?x({result:{error:V},stack:"getTargetLink",context:o}):o}function Ws({drawDefinition:t,structureId:e,roundNumber:r}){return t?e?{links:(t.links||[]).filter(Boolean).reduce((i,s)=>(s.source?.structureId===e&&(!r||s.source.roundNumber===r)&&(i.source=i.source.concat(s)),s.target?.structureId===e&&(!r||s.target.roundNumber===r)&&(i.target=i.target.concat(s)),i),{source:[],target:[]})}:{error:Ur}:{error:Z}}function Jb({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function hS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:Vl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({drawDefinition:n,structureId:i}),{positionAssignments:m}=bt({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=tt(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let D=u.offset+(r-1)*u.interleave,M=r+D;h=Math.ceil(M/2),S=1-M%2}let T=g,y=g[h-1],P=rS({roundPositionsCount:g.length,groupedOrder:a}),U=P?.length||1;if(U<=g.length){let D=f/U,M=Ee(g,D);s===li&&M.forEach(R=>R.reverse()),T=P?.length&&P?.map(R=>M[R-1]).flat()||T}s===En?y=T[h-1]:s===li?((!P?.length||U>g.length)&&(h=l.length+1-h),y=T[h-1]):s===up&&Pr()&&console.log(tp,{feedProfile:s});let A=y&&l.reduce((D,M)=>M.roundPosition===y?M:D,void 0),E;A?.feedRound?(S=0,E=Math.min(...(A.drawPositions||[]).filter(Boolean))):E=A?.drawPositions?.length===2&&A?.drawPositions[S];let N=m?.find(({drawPosition:D})=>D===E);if(N){let{extension:D}=lt({element:N,name:Wm});if(D?.value)return{disabledDrawPosition:E}}return{matchUp:A,targetDrawPosition:E,matchUpDrawPositionIndex:S}}function pr({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Vi?Pk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Dk({matchUp:i})}function Pk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=Xb({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=IS({source:c,linkType:fo}),p=IS({linkCondition:_n,linkType:ro,source:c}),m=IS({source:c,linkType:ro}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,P,U,A,E,N;if(e&&(i||s)&&(U=i&&l!==ln&&t.find(({matchUpId:R})=>R===i),T=s&&f!==ln&&t.find(({matchUpId:R})=>R===s),U||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:U}};let{roundPosition:D}=o;N=N||t.filter(R=>R.structureId===n.structureId);let M=N.reduce((R,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?R+1:R,0);return m&&!T&&f!==ln&&({matchUpDrawPositionIndex:P,targetDrawPosition:y,matchUp:T}=hS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==ln&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=hS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!U&&l!==ln&&({matchUpDrawPositionIndex:E,targetDrawPosition:A,matchUp:U}=hS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),U||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:U}=Jb({structureMatchUps:N,matchUp:o})),ot({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:E,loserMatchUpDrawPositionIndex:P,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:U,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function Dk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Zb({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=at({drawDefinition:t,structureId:i});if(a?.finishingPosition===fi){let{roundNumber:c}=n,u=c&&mt(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Ke({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(le).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=pr({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=QU({upcomingMatchUp:u}),d=QU({upcomingMatchUp:p});if(n.matchUpStatus!==Nt&&p?.matchUpStatus===Nt){let{matchUp:f}=tv({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&QU({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&$t(m.schedule.scheduledTime)<$t(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&$t(d.schedule.scheduledTime)<$t(l)&&(r[d.matchUpId]=n.matchUpId,d.schedule.scheduleConflict=n.matchUpId)),Object.assign(n,{winnerTo:m,loserTo:d}),n.drawPositions?.filter(Boolean).length){let g=c.targetLinks?.loserTargetLink?.linkCondition===_n,I=Nk(n);if(I.length){let h=_f(u?.sides),S=_f(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,U=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&U.length<2&&U.push({bye:!0,tbd:!0}),y?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:A})=>A===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(y)),U?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(U))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function Nk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function tv({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Jt)return{matchUp:t};if(o===Nt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=pr({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},tv({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function QU(t){if(t?.upcomingMatchUp)return(({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s})=>({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s}))(t.upcomingMatchUp)}function ae(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=js(t);if(r.error)return x({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function js(t){if(!t?.drawDefinition)return{error:Z};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:y,context:P,event:U}=t,A=[],E=[],N=[],D=[],M=[];h&&!r&&(r=$n({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:U}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=lu({participants:e,participantsProfile:a})));let{structures:b}=In({drawDefinition:S});if(!b)return{error:wt};n||(n=De({drawDefinition:S}));let v=S&&nS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:w=[],pendingMatchUps:L=[],upcomingMatchUps:G=[],completedMatchUps:k=[],abandonedMatchUps:H=[]}=Tu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||T||d,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:v,matchUpsMap:n,structure:F,context:P,event:U});A=A.concat(...H),E=E.concat(...k),N=N.concat(...G),D=D.concat(...L),M=M.concat(...w)});let O=F=>(!l&&!T&&!d||(l&&(F=Ni({matchUps:F,...l})),d&&(F=Ni({matchUps:F,...d,processContext:!0}))),F),_={abandonedMatchUps:O(A),completedMatchUps:O(E),upcomingMatchUps:O(N),pendingMatchUps:O(D),byeMatchUps:O(M),matchUpsMap:n,...C,groupInfo:R};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:w,completed:L,upcoming:G,pending:k,bye:H}=F,W=[].concat(...w&&A||[],...L&&E||[],...G&&N||[],...k&&D||[],...H&&M||[]);Zb({inContextDrawMatchUps:W,drawDefinition:S})}return _}function Kn(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:h,event:S}=t;if(!S)return{error:Ot};let{eventId:T,eventName:y,endDate:P,eventType:U,category:A,gender:E,matchUpFormat:N}=S??{},D={...h,...ot({indoorOutDoor:S.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:S.surfaceCategory??p?.surfaceCategory,endDate:S.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:N,eventName:y,eventType:U,category:A,eventId:T,gender:E})};P&&(D.endDate=P),f&&!r&&(r=$n({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:S}));let M;if(!e?.length&&!n&&p){let O=Bo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=O.participantMap,e=O.participants??[],M=O.groupInfo}let R=S.drawDefinitions??[],b=Aa({tournamentRecord:p,event:S}).scheduleTiming;return{matchUps:R.flatMap(O=>{let{matchUps:_}=ae({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:D,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:O,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:b,nextMatchUps:g,inContext:I,event:S});return _??[]}),groupInfo:M}}function Ae(t){let e=et(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:q};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:m,contextProfile:d,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,h=t.tournamentId??u.tournamentId,S=u?.events??[];n||({participants:n,participantMap:r}=Bo({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:d,inContext:p}));let{appliedPolicies:T}=yt({tournamentRecord:u}),y={...I,tournamentId:h,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},P=$n({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:S.flatMap(A=>(y.eventDrawsCount=A.drawDefinitions?.length??0,Kn({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:m,contextContent:P,contextFilters:f,contextProfile:d,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:A}).matchUps??[])).concat(...u.matchUps??[])}}function Un({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}){if(typeof n!="object"||!Object.keys(n).length)return{error:Lt};let m=Object.keys(n).map(d=>{let l=n[d];return Ae({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...C,matchUps:m}}function Mi(t,e){return Mk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Mk(t,e){return(ks[t?.stage]||0)-(ks[e?.stage]||0)}function or(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:y,endDate:P,eventType:U,category:A,gender:E,matchUpFormat:N}=S??{},D={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:N,eventType:U,eventName:y,category:A,eventId:T,endDate:P,gender:E},M;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:M}=Bo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=$n({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...ae({context:D,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:d,contextProfile:l,matchUpFilters:m,participantMap:r,nextMatchUps:g,inContext:I,event:S}),groupInfo:M}}function ls({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=J(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}var XU=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:ls({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:ls({element:e,accessor:r})?.value}))||(typeof t=="string"&&ls({element:e,accessor:t}))?.value,Br=XU;function Ua({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Vr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Ke({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,m=p&&c?.[n-p]?.matchUpsCount,d=c&&Object.values(c).map(Br("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},y=d?.slice(I-1).reduce((R,b)=>R+(b||0),0),P=a&&I!==1,U=1+t+(P?r??0:0),A=1,E=tt(U,s?U+S*2:y+U+A),N=y+A-S,D=l(E.slice(N)),M=l(E.slice(0,N),!0);return T.finishingPositionRange={loser:D,winner:M},{[I]:T}})),g=Pr({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let h=I.roundNumber&&f[I.roundNumber];g&&!h&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=h?.finishingRound,I.finishingPositionRange=h?.finishingPositionRange}),i}function $i({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=ae({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Ua({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=pr({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=ii({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function on(t){let e=Mr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Jn};if(!Array.isArray(n))return{error:sn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:rs};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(P=>(P.drawDefinitions||[]).map(U=>U.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===eo),g=r;if(f.length){g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,P)=>{let U=P.source?.structureId,A=P.target?.structureId;return U&&A&&(p[A]=U),U&&!y.includes(U)&&y.push(U),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let P=y.containerStructureId||y.structureId;T.includes(P)&&c[P].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(U=>{u[y].matchUpIds.push(U)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(U=>u[y].participantIds.push(U))},S=T=>{let y=Object.keys(c).length;for(let P of T||[]){let{matchUpId:U,winnerMatchUpId:A,loserMatchUpId:E}=P;if(!a.length||a.includes(U)){if(I(U),o){let{individualParticipantIds:M}=pu(P);u[U].participantIds=M}A&&(I(A),h(U,A),m[A].push(U)),E&&(I(E),h(U,E),m[E].push(U)),u[U].sources.push(m[U]);let N=m[U].map(M=>u[M].sources[0]).flat(),D=m[U].map(M=>u[M].sources[1]).flat();if(u[U].sources.push(N,D),y){let M=P.containerStructureId||P.structureId,R=p[M];if(c[R])for(let b of c[R])I(b),h(b,U),m[b].push(U)}}}};if(s)$i({drawDefinition:s}),g?.length||(g=or({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:P=[]})=>P.map(({drawId:U})=>U))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(U=>U.drawId===T).sort(Mi);if(!y?.find(({roundPosition:U})=>!U)){let U=y?.find(({tournamentId:E})=>E),{drawDefinition:A}=ze({tournamentRecord:e[U?.tournamentId],drawId:T});A&&$i({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function Se(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Pa({matchUpStatus:t}){return Gh.includes(t)}function ev({matchUpStatus:t}){return zm.includes(t)}function sg({matchUpStatus:t}){return Vh.includes(t)}function ag({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(ag)?.length;return Se({score:o})||s||e&&i||t&&ev({matchUpStatus:t})&&![Rt,Ct,Fn].includes(t)}function Da(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=as({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let A=at({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(ur({structure:i}))return{structure:i,isAdHoc:!0,error:Rs};let{matchUps:u}=ae({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||c.includes(A.structureId)),{matchUpDependencies:m}=on({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let A of u??[]){if(A.structureId===n||c.includes(A.structureId)){l.push(...A.drawPositions??[]);let E=A.roundNumber;for(let N of(A.drawPositions??[]).filter(Boolean))(!f[N]||E&&f[N]>E)&&(f[N]=E)}ag(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=ut(l.filter(Boolean)).sort(le),h=ut(d),S=ut(p?.map(({matchUpId:A,drawPositions:E})=>h.includes(A)?E:[]).flat().filter(Boolean)).sort(le),{positionAssignments:T}=bt({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),P=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),U=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:P,inactiveDrawPositions:U,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function fs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(le)[0]}}var Na={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",brightred:"\x1B[91m",green:"\x1B[32m",brightgreen:"\x1B[92m",yellow:"\x1B[33m",brightyellow:"\x1B[93m",blue:"\x1B[34m",brightblue:"\x1B[94m",lightblue:"\x1B[105m",magenta:"\x1B[35m",brightmagenta:"\x1B[95m",cyan:"\x1B[36m",brightcyan:"\x1B[96m",white:"\x1B[37m",brightwhite:"\x1B[97m"};var SS=[];function Cn(t,e){Vt(t)&&(t={method:t}),(e||Pr())&&SS.push(t)}function Rk(t){let e=SS.slice();return t&&(SS.length=0),e}function rv(t){let r=Rk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Na).includes(o)?Na[o]:Na.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Na[i[d]]?Na[i[d]]:Na.brightwhite;return`${Na.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
2
2
  `:"",c,s,m,Na.white,p,Na.reset,`
3
3
  `].join("")});r?.length&&console.log(...r)}function nv(){SS.length=0}function Hr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUpsMap:i,structureId:s,structure:a,event:c}){if(!n)return{error:Z};if(a||({structure:a}=at({drawDefinition:n,structureId:s})),!a)return{error:wt};s||({structureId:s}=a);let u="assignDrawPositionBye";Cn({method:u,color:"cyan",drawPosition:o}),i||(i=De({drawDefinition:n}));let{positionAssignments:p}=bt({structure:a}),{activeDrawPositions:m}=Da({drawDefinition:n,structureId:s});if(p?.find(R=>R.drawPosition===o)?.bye)return{...C};if(m?.includes(o))return{error:qu};let f=p?.find(R=>R.drawPosition===o);if(!f)return{error:Rs};let{filled:g,containsBye:I,assignedParticipantId:h}=Ck(f);if(I)return{...C};if(g&&!I)return x({result:{error:ja},stack:u});let S=yt({tournamentRecord:r,drawDefinition:n,event:c}).appliedPolicies??{},T=ae({inContext:!0,drawDefinition:n,matchUpsMap:i}).matchUps??[],y={isCollectionMatchUp:!1},{matchUps:P}=Pt({provisionalPositioning:t,drawDefinition:n,matchUpFilters:y,matchUpsMap:i,structure:a});if(p?.forEach(R=>{R.drawPosition===o&&(R.bye=!0)}),a.structureType===Ge)return bk({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:P}),bo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),ov({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u});let{roundProfile:U,roundMatchUps:A}=Ke({matchUps:P}),N=(U&&Object.keys(U).map(R=>parseInt(R)).reverse())?.find(R=>U?.[R].drawPositions?.includes(o)),D=N?A?.[N].find(({drawPositions:R})=>R?.includes(o)):void 0;D&&iv({tournamentRecord:r,drawDefinition:n,matchUp:D,event:c});let M=D?.drawPositions?.find(R=>R!==o);if(D&&M){let R=TS({sourceDrawPositions:D.drawPositions,matchUpId:D.matchUpId,inContextDrawMatchUps:T,drawPositionToAdvance:M,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});if(R.error)return R}return bo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),ov({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u})}function ov({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&uu({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),x({result:{...C},stack:s})}function Ck(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function iv({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:Nt,score:void 0,winningSide:void 0}),gt({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function bk({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&iv({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function TS({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Cn({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(P=>P.matchUpId===s),m=e.find(P=>P.matchUpId===s)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=bt({structure:d}),f=l?.filter(P=>P.bye).map(P=>P.drawPosition),g=u?.drawPositions?.find(P=>P!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserTargetDrawPosition:y}}=pr({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s});if(T&&T.structureId===d?.structureId&&vk({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),S&&I&&S.structureId!==d?.structureId){let{roundNumber:P}=S;if(P===1){let U=Hr({structureId:h.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(U.error)return U}else sv({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...C}}function vk({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(w=>w.matchUpId===i.matchUpId),m=e.find(w=>w.matchUpId===i.matchUpId)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=bt({structure:d}),g=l?.find(({drawPosition:w})=>w===t)?.bye,I=u.drawPositions?.filter(Boolean),h=l?.filter(w=>I?.includes(w.drawPosition)),S=l?.find(({drawPosition:w})=>w===t),T=r?.find(w=>w!==t),P=(T&&h?.find(({drawPosition:w})=>w===T))?.bye,U=g&&P;if(U&&console.log({isByeAdvancedBye:U}),I?.length>1&&g&&!P)return x({result:{error:ja},stack:c});let A=I?.find(w=>w!==t),E=U,N=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),D=N.map(w=>!w&&!E||w===t?(E=!0,t):w).sort(le);if(!E)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),x({result:{error:ja},stack:c});let M=l?.find(({drawPosition:w})=>w===A)?.bye,R=l?.find(({drawPosition:w})=>w===t)?.bye;Object.assign(u,{matchUpStatus:R||M?Nt:Jt,score:void 0,winningSide:void 0,drawPositions:D});let v=u.drawPositions.find(w=>!N.includes(w));Cn({method:c,color:"brightyellow",changedDrawPosition:v,pairedDrawPositionIsBye:M,drawPositionIsBye:R}),gt({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:O},targetMatchUps:{loserMatchUp:_,loserTargetDrawPosition:F}}=pr({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(M||R){let w=M?t:A;if(w)TS({drawPositionToAdvance:w,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(R&&O&&_)if(_.feedRound)sv({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:O,drawDefinition:o,loserMatchUp:_,matchUpsMap:s});else{let G=1-i.roundPosition%2,k=_.drawPositions[G],H=Hr({structureId:O.target.structureId,drawPosition:k,tournamentRecord:n,drawDefinition:o,event:a});if(H.error)return H}}}function sv({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Cn({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=fs({drawPosition:t,matchUps:p});if(m===a){let d=Hr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function yS({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=Pt({drawDefinition:r,matchUpsMap:n,structure:o,event:i});s.forEach(a=>{let u=t.filter(({drawPosition:p})=>a.drawPositions?.includes(p)).filter(p=>p.bye).length;a.winningSide||(Object.assign(a,{matchUpStatus:u?Nt:Jt}),gt({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function fc(t){let{inContextDrawMatchUps:e,participantId:r,drawPosition:n}=t,{tournamentRecord:o,drawDefinition:i,structureId:s,matchUpsMap:a,event:c}=t,{structure:u}=at({drawDefinition:i,structureId:s}),m=(ye({drawDefinition:i,structure:u}).positionAssignments||[]).find(g=>r&&g.participantId===r||n&&g.drawPosition===n);if(m&&r&&!n&&(n=m?.drawPosition),!n)return{error:Cs};r||(r=m?.participantId);let{activeDrawPositions:d}=Da({drawDefinition:i,structureId:s});return d.includes(n)?{error:qu}:(e||({matchUps:e}=ae({inContext:!0,drawDefinition:i,matchUpsMap:a})),JU({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(bo({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...C,participantId:r}):{error:OA})}function JU({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:i,event:s}){let{structure:a}=at({drawDefinition:r,structureId:i});if(!a)return{error:wt};let c=ye({drawDefinition:r,structure:a}).positionAssignments||[],u=c.some(T=>{if(T.drawPosition===n)return delete T.participantId,delete T.qualifier,delete T.bye,!0});if(a.structureType===Ge)return yS({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...C};let p={isCollectionMatchUp:!1},{matchUps:m}=Pt({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=Ke({matchUps:m}),g=(d&&Object.keys(d))?.map(T=>mt(T)),I=n,S=g?.map(T=>{let P=d?.[T]?.pairedDrawPositions?.find(v=>v.includes(I)),U=P?.find(v=>v!==I),A=c.find(v=>v.drawPosition===U),E=d?.[T+1],N=A?.bye,D=E?.pairedDrawPositions?.find(v=>v.includes(U)),M=N&&D&&E&&E.drawPositions?.includes(U),b=P&&{pairedDrawPositionByeAdvancedPair:!M&&D,pairedDrawPosition:U,targetDrawPosition:I,relevantPair:P,roundNumber:T};return M&&(I=U),b}).filter(T=>T?.targetDrawPosition)?.reduce((T,y)=>{let{roundNumber:P,relevantPair:U,targetDrawPosition:A,pairedDrawPosition:E,pairedDrawPositionByeAdvancedPair:N}=y,D={roundNumber:P,targetDrawPosition:A,relevantPair:U},M=N&&{roundNumber:P+1,targetDrawPosition:E,relevantPair:N,subsequentRoundRemoval:!0},R=[D,M].filter(Boolean);return T.concat(...R)},[]);return S?.forEach(({roundNumber:T,targetDrawPosition:y,relevantPair:P})=>{let U=l?.[T].find(A=>Fe(A.drawPositions?.filter(Boolean),P.filter(Boolean)));U&&(Ok({inContextDrawMatchUps:t,targetDrawPosition:y,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),av({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:U,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function Ok({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,roundNumber:i,structureId:s}){let{structure:a}=at({drawDefinition:n,structureId:s});if(!a)return{error:wt};if(a.structureType===Ge)return;o=o||De({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=fs({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=bt({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>av({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...C}}function av({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u="removeDrawPosition",p=o.drawPositions?.slice(),m=o.matchUpStatus,d=o.winningSide;s=s??De({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=fs({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let D=(o.drawPositions??[]).map(M=>M===i?void 0:M);o.drawPositions=D}if(o.matchUpType===Yt){let R=(t?.find(b=>b.matchUpId===o.matchUpId)?.sides??[]).reduce((b,v,O)=>v.drawPosition===i?O:b,void 0);R!==void 0&&o.sides?.[R]?.lineUp&&(delete o.sides?.[R].lineUp,gt({tournamentId:r?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:o,drawDefinition:n}))}let I=pr({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,U=e.filter(({drawPosition:D})=>o.drawPositions?.includes(D)).filter(D=>D.bye).length,A=U&&Nt||o.matchUpStatus&&[Rt,Ct].includes(o.matchUpStatus)&&o.matcHUpStatus||Jt;o.matchUpStatus=A,o.matchUpStatus&&[Ct,Rt].includes(o.matchUpStatus)&&(o.winningSide=void 0);let E=p?.find(D=>!o.drawPositions?.includes(D));if(p?.includes(i)&&m===o.matchUpStatus&&d===o.winningSide||(E&&Cn({method:u,color:"brightyellow",removedDrawPosition:E}),gt({tournamentId:r?.tournamentId,context:`${u}-${i}`,eventId:c?.eventId,matchUp:o,drawDefinition:n})),S&&S.structureId!==I.matchUp.structureId&&!U){let{drawPositions:D,roundNumber:M}=S;if(M===1){let R=D[y];JU({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let R=Math.min(...D.filter(Boolean)),b=_k({loserMatchUpDrawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:S,matchUpsMap:s,event:c});if(b.error)return x({result:b,stack:u});let O=(s?.mappedMatchUps||{})[S.structureId].matchUps,{initialRoundNumber:_}=fs({drawPosition:R,matchUps:O});_===1&&(Cn({method:u,color:"brightyellow",loserMatchUpDrawPosition:R}),JU({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,ln),{...C}}function _k({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=at({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=bt({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=fc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...C}}function Ri({drawDefinition:t,stages:e}){if(!t)return{error:Z};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=ut(r.map(o=>{let{positionAssignments:i}=bt({structure:o});return i?i.map(St):[]}).flat().filter(Boolean));return{...C,assignedParticipantIds:n}}function zn(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||rt}${s||""}`;return n[a]||(n[a]=[]),n[a].push(o),n},{}),r=n=>isNaN(n)?1/0:n;return Object.keys(e).map(n=>e[n].sort((o,i)=>r(o.entryPosition)-r(i.entryPosition)).map((o,i)=>{let s=i+1;return{...o,entryPosition:s}})).flat()}function Ys(t){return[Ei,Gr].includes(t)}function dd({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:r,drawDefinition:n,participantIds:o,entryStatus:i,entryStage:s,extension:a,eventSync:c,drawId:u,stage:p,event:m}){if(!o||!Array.isArray(o))return{error:dn,method:"modifyEntriesStatus",participantIds:o};if(!n&&!m)return{error:Ot};if(i&&!BU.includes(i))return{error:Xl};if(s&&!Kc.includes(s))return{error:_i};let d="modifyEntriesStatus",l=[];if(!i&&!a)return x({result:{error:it},info:"Missing entryStatus",stack:d});if(a&&!Ln({extension:a,requiredAttributes:["name"]}))return x({result:{error:V},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(D=>{let M=Ri({stages:p&&[p],drawDefinition:D}).assignedParticipantIds??[];f.push(...M)});let g=r?.participants??[];if(!o.every(D=>{let M=Go({tournamentParticipants:g,participantId:D})?.participantType;return!(M&&[ft,Ar].includes(M)&&Ys(i))&&!(i&&m?.eventType&&M===Tt&&[qr,vr].includes(m.eventType)&&[rn,...Zf].includes(i))}))return{error:Xl};let h=m&&Ht({event:m}).flightProfile,S=h?.flights?.find(D=>D.drawId===u),T=D=>{let M=(D||[]).filter(v=>!p||!v.entryStage||p===v.entryStage).filter(({participantId:v})=>o.includes(v)),R=v=>i&&f.includes(v.participantId)&&!(Zf.includes(v.entryStatus)&&Zf.includes(i));return M.every(v=>R(v)&&!e?!1:(i&&(v.entryStatus=i,delete v.entryPosition),s&&(v.entryStage=s,delete v.entryPosition),a&&(a.value?At({element:v,extension:a}):fr({element:v,name:a.name})),!0))?{...C}:{error:vs}},y=({flight:D,drawDefinition:M})=>{m&&(m.entries=zn({entries:m.entries??[]})),D&&(D.drawEntries=zn({entries:D.drawEntries})),M&&(M.entries=zn({entries:M.entries}))},P=D=>{let{flight:M,drawDefinition:R}=D,b="updateDrawEntries";if(M){let v=T(M.drawEntries);if(v.error)return x({result:v,stack:b})}if(R){let v=T(R.entries);if(v.error)return x({result:v,stack:b});l.includes(R.drawId)||l.push(R.drawId)}return{...C}},U=m?.entries?.find(({entryPosition:D})=>D)??(S?.drawEntries?.find(({entryPosition:D})=>D)||n?.entries?.find(({entryPosition:D})=>D));if(t&&!U&&y({flight:S,drawDefinition:n}),S||n){let D=P({flight:S,drawDefinition:n});if(D.error)return x({result:D,stack:d})}let A=m?.drawDefinitions?.map(({drawId:D})=>D)??[],E=h?.flights?.filter(D=>!A.includes(D.drawId))||[];for(let D of E){let M=D&&P({flight:D});if(M?.error)return x({result:M,stack:d})}let N=h?.flights?.length===1&&(m?.drawDefinitions?.length??0)<=h?.flights?.length;if(!S&&!n&&i&&VU.includes(i))return{error:fE};if(!S&&!n||i===so||c&&N){let D=T(m?.entries);if(D?.error)return x({result:D,stack:d});let M;if(i===so&&(h?.flights?.every(R=>{let b=T(R.drawEntries);return b.error?(M=b.error,!1):(R.drawEntries=R.drawEntries.filter(({participantId:v})=>!o.includes(v)),!0)}),m?.drawDefinitions?.every(R=>{let b=T(R.entries);return b.error?(M=b.error,!1):(R.entries=R.entries?.filter(({participantId:v})=>!o.includes(v)),!0)})),M)return x({result:{error:M},stack:d})}t&&y({flight:S,drawDefinition:n});for(let D of m?.drawDefinitions??[])l.length&&!l.includes(D.drawId)||vt({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:D});return{...C}}function yo({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Li};if(!ht(e))return{error:V};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[hi,o,i,s].join("."),u=r.timeItems.filter(p=>p?.itemType===a).filter(p=>!t||p?.itemDate).sort((p,m)=>(p.createdAt?new Date(p.createdAt).getTime():0)-(m.createdAt?new Date(m.createdAt).getTime():0)).pop();if(u){let[p,m,d,l]=u.itemType?.split(".")??[];if(p!==hi)return{error:za};let g=(n&&ls({element:u.itemValue,accessor:n}))?.value||u.itemValue,I={eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...C,scaleItem:I}}}return{...C,scaleItem:void 0}}function cv({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[hi,ho,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems||[]).filter(({itemType:m})=>m.split(".")[1]===ho).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=qt(Object.keys(a),c);if(!!(!e||!Object.keys(a).length&&!t?.drawIds?.length||u.length)&&u.length){if(t?.stageSeedingScaleNames){let m=Object.keys(t.stageSeedingScaleNames).map(l=>{let f=s(t.stageSeedingScaleNames[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else if(u){let m=u.map(d=>a[d]);i.seedValue=m.pop()}}else if(!e&&typeof r=="object"){let m=Object.keys(r).map(l=>{let f=s(r[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else{let{categoryName:m,ageCategoryCode:d}=o.category||{},l=[d,o.eventId,m].filter(Boolean),f;for(let g of l){let I={eventType:o.eventType,scaleType:ho,scaleName:g},h=yo({scaleAttributes:I,participant:n});if(h.scaleItem){f=h.scaleItem;break}}if(f&&(!e||t?.published&&!t?.published?.drawIds?.length)){let I=f.scaleValue;i.seedValue=I}}return i}function uv({convertExtensions:t,seedAssignments:e,participant:r,withSeeding:n,seedValue:o,eventId:i,ranking:s,entry:a}){let{entryStatus:c,entryStage:u,entryPosition:p,extensions:m}=a,d=m?.length&&t?Object.assign({},...yf(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=ot(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function yu(t){let e=et(t,[{[se]:!0}]);if(e.error)return e;let{tournamentRecord:r,status:n=Rr}=t,o=`${_o}.${xo}`;return J(Jm({tournamentRecord:r,itemType:o})?.timeItem?.itemValue?.[n],!1,!0)}function pv(t){let{tournamentId:e}=t??{};return!!e}function Xr({event:t,status:e=Rr}){let r=`${_o}.${xo}`;return fu({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function ld({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function gs(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!pv(e))return{error:V};if(o&&!a)return{error:jr};if(Array.isArray(n)&&n?.length){let m={};for(let d of n){if(!Vt(d))return{error:V};let l=ze({tournamentRecord:e,eventId:d})?.event;if(!l)return{error:jr};let f=ZU({event:l});m[d]=f}return{...C,publishState:m}}if(a){let m=ZU({event:a}),d={};if(s)return r?{publishState:{status:{published:!!m.status.publishedDrawIds?.includes(s),drawDetail:m.status.drawDetails?.[s]},...C}}:{error:br};if(Array.isArray(i)&&i?.length){let l=a.drawDefinitions?.map(au)??[];for(let f of i){if(!Vt(f))return{error:V};if(!l.includes(f))return{error:br};d[f]={status:{published:!!m.status.publishedDrawIds.includes(f),drawDetail:m.status.drawDetails?.[f]}}}}else d=m;return{...C,publishState:d}}let c=[],u=!1,p={};for(let m of e?.events??[]){let d=ZU({event:m});p[m.eventId]=d,d.status.published&&(c.push(m.eventId),u=!0);for(let{drawId:l}of m.drawDefinitions??[]){let f=d.status?.publishedDrawIds?.includes(l);f&&(p[l]={status:{published:f}})}}if(e){let m=yu({tournamentRecord:e});p.tournament=m??{},(m?.orderOfPlay?.published||m?.participants?.published)&&(u=!0),p.tournament.status={published:u,publishedEventIds:c}}return{...C,publishState:p}}function ZU({event:t}){let e=Xr({event:t});if(!e)return{status:{published:!1}};let r={published:void 0,seedingScaleNames:[],drawIds:[]};e.seeding&&Object.assign(r,e.seeding);let n=e.drawDetails??{};for(let a of t.drawDefinitions?.map(au)||[])n[a]||(n[a]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(a=>ld({drawDetails:n,drawId:a})),i=o?.length?o:e.drawIds??[];if(i?.length&&!o?.length)for(let a of i)n[a]={publishingDetail:{published:!0}};let s=i?.length>0;return{status:{publishedDrawIds:i,publishedSeeding:r,drawDetails:n,published:s}}}function AS(t){let{participantMap:e,participantId:r,matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,schedule:p,drawId:m,score:d}=t;if(!p||!Object.keys(p).length)return;n===Nt||e[r].scheduleItems.push({...p,scheduledDate:Et(p?.scheduledDate),scheduledTime:Xt(p?.scheduledTime),checkScoreHasValue:Se({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function mv({finishingPositionRange:t={},participantMap:e,finishingRound:r,participantWon:n,matchUpStatus:o,participantId:i,stageSequence:s,roundNumber:a,structureId:c,matchUpId:u,drawId:p,stage:m}){let d=e[i],l=S=>Math.abs(S[0]-S[1]);d.structureParticipation[c]||(d.structureParticipation[c]={rankingStage:m,walkoverWinCount:0,defaultWinCount:0,stageSequence:s,winCount:0,structureId:c,drawId:p});let f=d.structureParticipation[c],{winner:g,loser:I}=t,h=n?g:I;n&&(f.winCount+=1,o===Ct&&(f.walkoverWinCount+=1),o===Rt&&(f.defaultWinCount+=1)),h&&(!f.finishingPositionRange||l(h)<l(f.finishingPositionRange))&&(f.finishingPositionRange=h),r&&((!f.finishingRound||r<f.finishingRound)&&(f.finishingMatchUpId=u,f.finishingRound=r,f.roundNumber=a),r===1&&(f.participantWon=n))}function tP(t){let{withScheduleItems:e,scheduleAnalysis:r,withTeamMatchUps:n,participantMap:o,withOpponents:i,withMatchUps:s,withEvents:a,withDraws:c,finishingPositionRange:u,finishingRound:p,matchUpStatus:m,stageSequence:d,roundNumber:l,structureId:f,score:g,stage:I,withRankingProfile:h,tieWinningSide:S,roundPosition:T,matchUpTieId:y,matchUpSides:P,collectionId:U,matchUpType:A,winningSide:E,matchUpId:N,schedule:D,eventId:M,drawId:R,sides:b}=t,v=i&&b?.length===2&&Object.assign({},...b.map(({sideNumber:O},_)=>{let F=b[1-_].participantId;return O&&{[O]:F}}).filter(Boolean));for(let O of b){let{participantId:_,sideNumber:F,bye:w}=O;if(w)continue;let L=E===F,G=W=>{let Y=o[W]?.participant,$=Y?.participantType,B=[{participantId:W,participantType:$}];if($!==Ar)for(let K of Y?.individualParticipantIds||[]){let X=o[K]?.participant;B.push({participantType:X?.participantType,participantId:K})}return B},k=(W,Y)=>{if(s){if(o[W].matchUps[N]={participantWon:L,matchUpType:A,structureId:f,sideNumber:F,matchUpId:N,eventId:M,drawId:R,stage:I},i){let $=G(Y);o[W].matchUps[N].opponentParticipantInfo=$}U&&(o[W].matchUps[N].collectionId=U)}i&&Y&&(o[W].opponents[Y]={participantId:Y,matchUpId:N,eventId:M,drawId:R}),h&&mv({finishingPositionRange:u,participantMap:o,participantWon:L,finishingRound:p,matchUpStatus:m,participantId:W,stageSequence:d,roundNumber:l,structureId:f,matchUpId:N,drawId:R,stage:I}),(r||e)&&AS({participantMap:o,participantId:W,matchUpStatus:m,roundPosition:T,matchUpType:A,roundNumber:l,structureId:f,matchUpId:N,schedule:D,drawId:R,score:g})},H=({participant:W,partnerParticipantId:Y})=>{let $=(B,K)=>{B&&(B.partnerParticipantIds||(B.partnerParticipantIds=[]),B.partnerParticipantIds.includes(K)||B.partnerParticipantIds.push(K))};c&&$(W?.draws?.[R],Y),a&&$(W?.events?.[M],Y),s&&$(W?.matchUps?.[N],Y)};if(_&&o[_]){let W=v?.[F];k(_,W);let Y=o[_]?.participant.participantType===ft,$=o[_]?.participant.individualParticipantIds||[];if(y){if(n){let B=K=>o[K].matchUps[y]={participantWon:S===F,matchUpId:y,matchUpType:Yt,sideNumber:F};B(_),$.forEach(B)}if(c&&!o[_].draws[R]){let B=P.find(j=>j.sideNumber===F)?.participant?.participantId,K=o[B]?.draws?.[R]?.entryStatus,X=j=>o[j].draws[R]={entryStatus:K,eventId:M,drawId:R};X(_),$.forEach(X)}}if(Y&&($.forEach(B=>o[B]&&k(B,W)),$.forEach((B,K)=>{let X=$[1-K],j=o[B];j&&H({participant:j,partnerParticipantId:X})}),a&&P)){let B=P.find(K=>K.sideNumber===F)?.participant?.participantId;if(B){let K=o[B]?.events[M];K?(o[_].events[M]={...K},$.forEach(X=>o[X].events[M]={...K})):console.log("Missing teamEntry",{eventId:M,teamParticipantId:B})}}if(E){let B=K=>{L?(o[K].counters[A].wins+=1,o[K].counters.wins+=1,m===Ct&&(o[K].counters[A].walkoverWins+=1,o[K].counters.walkoverWins+=1),m===Rt&&(o[K].counters[A].defaultWins+=1,o[K].counters.defaultWins+=1)):(o[K].counters[A].losses+=1,o[K].counters.losses+=1,m===Ct&&(o[K].counters[A].walkovers+=1,o[K].counters.walkovers+=1),m===Rt&&(o[K].counters[A].defaults+=1,o[K].counters.defaults+=1))};B(_),$.forEach(B)}}}}function Au(t,e){return(t||"").localeCompare(e||"")}function dv(t){let{participantFilters:e,convertExtensions:r,policyDefinitions:n,tournamentRecord:o,usePublishState:i,contextFilters:s,matchUpFilters:a,participantMap:c,contextProfile:u,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,withOpponents:I,withMatchUps:h,withSeeding:S,withEvents:T,withDraws:y}=t,P=e?.participantIds,U=O=>{let _=[O];return c[O]?.participant.individualParticipantIds?.forEach(F=>_.push(F)),_.some(F=>!P?.length||P.includes(F))?_:[]},A={withMatchUps:h||m,withEvents:T||m,withDraws:y||m,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,participantMap:c,withOpponents:I,withSeeding:S},E=[],N={},D=[],M={},R={},b={},v=({eventType:O,scaleNames:_,participantId:F})=>c[F]?.participant?.rankings?.[O]?.find(w=>_.includes(w.scaleName))?.scaleValue;for(let O of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(O.eventId))continue;let{drawDefinitions:_=[],extensions:F=[],eventType:w,eventName:L,category:G,entries:k,eventId:H,gender:W}=O,{flightProfile:Y}=Ht({event:O}),$=Y?.flights??[],B=gs({event:O}).publishState;B&&(M[H]=B);let K=B?.status?.publishedSeeding;if(T||S||m){let j=r?Object.assign({},...yf(F??[])):{};R[H]={...j,eventName:L,eventType:w,category:G,eventId:H,gender:W};let nt=[G?.categoryName,G?.ageCategoryCode].filter(Boolean);for(let z of k){let{participantId:Q}=z;if(!Q||!c[Q])continue;let pt=v({eventType:w,scaleNames:nt,participantId:Q}),st,Mt;if(S){let Kt=c[Q].participant;({seedAssignments:st,seedValue:Mt}=cv({publishedSeeding:K,usePublishState:i,withSeeding:S,participant:Kt,event:O}))}let _t=Kt=>{if(c[Kt]?.events?.[H])return;let Ie=c[Kt];uv({convertExtensions:r,seedAssignments:st,participant:Ie,withSeeding:S,seedValue:Mt,eventId:H,ranking:pt,entry:z})};_t(Q),(c[Q].participant.individualParticipantIds||[]).forEach(_t)}}let X=M?.[H]?.publishedSeeding;if(y||m||S){let j=z=>z?Object.assign({},...z.map(({participantId:Q,seedValue:pt,seedNumber:st})=>({[Q]:{seedValue:pt,seedNumber:st}}))):void 0,nt=ut([..._.map(au),...$.map(au)]);for(let z of nt){let Q=_.find(jt=>jt.drawId===z),pt=[G?.categoryName,G?.ageCategoryCode].filter(Boolean),{structures:st=[],drawOrder:Mt,drawName:_t,drawType:Re}=Q??{},Kt=$?.find(jt=>jt.drawId===z),Ie=Q?.entries||Kt?.drawEntries,_r=Kt?.flightNumber,pn=(Q?.structures||[]).sort((jt,Pe)=>Ti(jt,Pe)).map(({structureId:jt,structures:Pe})=>[jt,...(Pe||[]).map(({structureId:lr})=>lr)]).flat(1/0),gr,Xe,ee,Ut,ce=0,ue=st.filter(({stage:jt,stageSequence:Pe})=>jt===rt&&Pe===1||jt===ct).flatMap(jt=>{let{positionAssignments:Pe}=bt({structure:jt}),{seedAssignments:lr,stageSequence:he,stage:oe}=jt;return oe===rt?(ce=Pe?.length??0,ee=Pe,Ut=lr):he===1&&(gr=Pe,Xe=lr),Pe}).map(({participantId:jt})=>jt).filter(Boolean),we=j(Ut),zt=j(Xe),Wt=Q?Ie.filter(({participantId:jt})=>ue.includes(jt)):Ie,Ir=!i||X?.published&&(X?.drawIds?.length===0||X?.drawIds?.includes(z));for(let jt of Wt){if(!c[jt.participantId])continue;let{entryStatus:Pe,entryStage:lr,entryPosition:he,participantId:oe}=jt,Le=v({participantId:oe,scaleNames:pt,eventType:w}),Cr=Je=>{if(!c[Je]||c[Je].draws?.[z])return;let Hn=S&&Ir,de=Hn?{}:void 0,Er=Hn?we?.[oe]?.seedValue||we?.[oe]?.seedNumber:void 0,ts=Er?we?.[oe]:void 0,mn=Hn?zt?.[oe]?.seedValue||zt?.[oe]?.seedNumber:void 0,vi=mn?zt?.[oe]:void 0;de&&Er&&(de[rt]=ts),de&&mn&&(de[ct]=vi);let aa=Er||mn;aa&&(c[Je].participant.seedings[w]||(c[Je].participant.seedings[w]=[]),ts&&c[Je].participant.seedings[w].push({...ts,scaleName:z}),vi&&c[Je].participant.seedings[w].push({...vi,scaleName:z}),de&&(c[Je].events[H].seedAssignments||(c[Je].events[H].seedAssignments={}),Object.keys(de).forEach(xl=>c[Je].events[H].seedAssignments[xl]=de[xl]))),(y||m)&&(c[Je].draws[z]=ot({seedAssignments:de,entryPosition:he,entryStatus:Pe,entryStage:lr,seedValue:aa,eventId:H,ranking:Le,drawId:z},!1,!1,!0))};[Gr,Ei].includes(Pe)||(Cr(oe),(c[oe].participant.individualParticipantIds||[])?.forEach(Cr))}let mr=(Q?.structures??[]).reduce((jt,Pe)=>(jt.includes(Pe.stage)||jt.push(Pe.stage),jt),[]),sr=(Q?.links??[]).length;b[z]={qualifyingPositionAssignments:gr,qualifyingSeedAssignments:Xe,mainPositionAssignments:ee,qualifyingSeedingMap:zt,mainSeedAssignments:Ut,orderedStructureIds:pn,mainSeedingMap:we,flightNumber:_r,linksCount:sr,drawOrder:Mt,drawName:_t,drawType:Re,drawSize:ce,drawId:z,stages:mr}}}if(m||l||f||g||I||h||y){let j=!!l||p,nt=Kn({afterRecoveryTimes:!!l,policyDefinitions:n,tournamentRecord:o,inContext:!0,participantMap:c,contextFilters:s,matchUpFilters:a,contextProfile:u,nextMatchUps:j,event:O})?.matchUps??[];for(let z of nt){let{finishingPositionRange:Q,potentialParticipants:pt,tieMatchUps:st=[],sides:Mt=[],winningSide:_t,matchUpType:Re,matchUpId:Kt,eventId:Ie,drawId:_r,collectionId:pn,stageSequence:gr,finishingRound:Xe,matchUpStatus:ee,roundPosition:Ut,roundNumber:ce,structureId:ue,schedule:we,score:zt,stage:Wt}=z;N[Kt]=z;let Ir={finishingPositionRange:Q,finishingRound:Xe,stageSequence:gr,roundPosition:Ut,collectionId:pn,roundNumber:ce,structureId:ue,schedule:we,eventId:Ie,drawId:_r,score:zt,stage:Wt};tP({...Ir,...A,matchUpStatus:ee,winningSide:_t,matchUpType:Re,matchUpId:Kt,sides:Mt});for(let mr of st){let{winningSide:sr,sides:jt=[],matchUpId:Pe,matchUpStatus:lr,matchUpType:he}=mr;tP({...Ir,...A,winningSide:sr,tieWinningSide:_t,matchUpTieId:Kt,matchUpId:Pe,sides:jt,matchUpSides:Mt,matchUpStatus:lr,matchUpType:he})}Array.isArray(pt)&&(j||l||d)&&pt.flat().map(St).filter(Boolean)?.forEach(sr=>{U(sr)?.forEach(Pe=>{c[Pe]&&(c[Pe].potentialMatchUps[Kt]=ot({tournamentId:o?.tournamentId,matchUpId:Kt,eventId:Ie,drawId:_r}))}),(l||d)&&AS({potential:!0,participantMap:c,participantId:sr,matchUpStatus:ee,roundPosition:Ut,structureId:ue,matchUpType:Re,roundNumber:ce,matchUpId:Kt,schedule:we,drawId:_r,score:zt})})}D.push(...nt)}}if(g||m||l){let O=Object.values(c);for(let _ of O){let{wins:F,losses:w,[kt]:{wins:L,losses:G},[xt]:{wins:k,losses:H}}=_.counters,W=(Y,$,B)=>{let K=$+B,X=$,j=K&&X/K;_.statistics[Y]={denominator:K,numerator:X,statValue:j,statCode:Y}};if(g&&(W(td,F,w),W(`${td}.${kt}`,L,G),W(`${td}.${xt}`,k,H)),m){let Y=($=[])=>Math.abs($[0]-$[1]);for(let $ of Object.keys(_.draws)){let{orderedStructureIds:B=[],flightNumber:K}=b[$]||{};if(_.structureParticipation&&B.length){let X,j=0,nt=B.map(z=>{let Q=_.structureParticipation[z];if(!Q)return;X||(X=Q?.finishingPositionRange),Y(X)>Y(Q?.finishingPositionRange)&&(X=Q?.finishingPositionRange);let pt=Q.stage!==ct;return pt&&(j+=1),ot({...Q,participationOrder:pt?j:void 0,flightNumber:K})}).filter(Boolean);_.draws[$]&&(_.draws[$].finishingPositionRange=X,_.draws[$].structureParticipation=nt)}}}if(l){let Y=ht(l)?l.scheduledMinutesDifference:0,$=_.scheduleItems||[],B=_.potentialMatchUps||{},K=$.reduce((j,nt)=>{let{scheduledDate:z,scheduledTime:Q}=nt;return j[z]||(j[z]=[]),Q&&j[z].push(nt),j},{});Object.values(K).forEach(j=>j.sort(ZI));for(let j of $){let{typeChangeTimeAfterRecovery:nt,timeAfterRecovery:z,scheduledDate:Q,scheduledTime:pt}=j,st=K[Q],Mt=$t(pt);for(let _t of st){if(_t.matchUpId===j.matchUpId||[Ct,Rt].includes(_t.matchUpStatus)&&!_t.checkScoreHasValue)continue;let Ie=j.matchUpType!==_t.matchUpType&&nt||z,_r=j.drawId===_t.drawId,pn=B[j.matchUpId]&&B[_t.matchUpId],gr=$t(_t.scheduledTime),Xe=Math.abs(gr-Mt),ee=gr>=Mt;if((Y&&!isNaN(Y)?Xe<=Y:ee&&$t(_t.scheduledTime)<$t(Ie))&&!(pn&&_r)&&ee){let ce=[j.matchUpId,_t.matchUpId].sort(Au).join("|");_.scheduleConflicts[ce]={priorScheduledMatchUpId:j.matchUpId,matchUpIdWithConflict:_t.matchUpId}}}}let X=_.participant.participantId;Object.keys(_.scheduleConflicts).length&&E.push(X),c[X].scheduleConflicts=_.scheduleConflicts}}}return{participantIdsWithConflicts:E,eventsPublishStatuses:M,derivedEventInfo:R,derivedDrawInfo:b,mappedMatchUps:N,participantMap:c,matchUps:D}}function Eu({participantFilters:t={},tournamentRecord:e,participants:r=[]}){if(!Object.keys(t).length)return r;let{accessorValues:n,drawEntryStatuses:o,positionedParticipants:i,eventEntryStatuses:s,participantRoles:a,participantRoleResponsibilities:c,participantTypes:u,participantIds:p,signInStatus:m,enableOrFiltering:d,eventIds:l,genders:f}=t,g=qs(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&xk({drawEntryStatuses:o,tournamentEvents:g}),h=s&&wk({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,P)=>y.concat(...(P.drawDefinitions||[]).map(U=>Wh({drawDefinition:U}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((P,U)=>{let{accessor:A,value:E}=U,{values:N}=ls({element:y,accessor:A});return P&&N?.includes(E)},!0);if(r=r?.filter(y=>{let P=en({element:y,itemType:ac})?.timeItem?.itemValue,{participantRoleResponsibilities:U,participantType:A,participantRole:E,participantId:N,person:D}=y,M=Array.isArray(f)&&f?.length&&D?.sex&&f.includes(D.sex);return d?f&&M||i&&S.includes(N)||i===!1&&!S.includes(N)||I?.includes(N)||h?.includes(N)||p?.includes(N)||m&&P===m||u&&A&&qs(u)&&u.includes(A)||a&&E&&qs(a)&&a.includes(E)||c&&qs(U)&&qs(c)&&c.find(R=>U?.includes(R))||n?.length&&qs(n)&&T(y):(!f||M)&&(i===void 0||i&&S.includes(N)||i===!1&&!S.includes(N))&&(!I||I.includes(N))&&(!h||h.includes(N))&&(!p||p.includes(N))&&(!m||P===m)&&(!u||A&&qs(u)&&u.includes(A))&&(!a||E&&qs(a)&&a.includes(E))&&(!c||qs(U)&&qs(c)&&c.find(R=>U?.includes(R)))&&(!n?.length||qs(n)&&T(y))}),g.length&&l){let y=g.filter(P=>l.includes(P.eventId)).map(P=>{let U=(P.entries||[]).map(E=>E.participantId);if(me(qn)(P.eventType))return U;let A=(e?.participants??[]).filter(E=>U.includes(E.participantId)).map(E=>E.individualParticipantIds).flat(1);return U.concat(...A)}).flat(1);r=r?.filter(P=>y.includes(P.participantId))}return r}function qs(t){return t&&Array.isArray(t)&&t.length}function xk({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return ut(e.reduce((n,o)=>{let{flightProfile:i}=Ht({event:o}),s=i?.flights?.map(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(St):[]).flat()||[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(St):[])||[];return n.concat(...s,...a)},[]))}function wk({eventEntryStatuses:t,tournamentEvents:e}){return ut(e.reduce((r,n)=>{let o=(n.entries||[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(St);return r.concat(...o)},[]))}function Gt(t){let{withIndividualParticipants:e,participantFilters:r={},withPotentialMatchUps:n,withRankingProfile:o,convertExtensions:i,policyDefinitions:s,withScheduleItems:a,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:p,withTeamMatchUps:m,withScaleValues:d,usePublishState:l,withStatistics:f,contextFilters:g,matchUpFilters:I,contextProfile:h,withOpponents:S,withMatchUps:T,internalUse:y,withSeeding:P,withEvents:U,withDraws:A,withISO2:E,withIOC:N}=t;if(!c)return{error:q};(T||o)&&on({tournamentRecord:c});let D=Zh({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:y,withISO2:E,withIOC:N}),{participantMap:M}=D,R=dv({withMatchUps:T??o,withEvents:U??o,withDraws:A??o,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:o,convertExtensions:i,withScheduleItems:a,policyDefinitions:s,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:m,usePublishState:l,withStatistics:f,contextFilters:g,matchUpFilters:I,participantMap:M,withOpponents:S,contextProfile:h,withSeeding:P}),{participantIdsWithConflicts:b,eventsPublishStatuses:v,derivedEventInfo:O,derivedDrawInfo:_,mappedMatchUps:F}=R,w=R.matchUps;M=R.participantMap;let L=u??n,G=({potentialMatchUps:K,scheduleConflicts:X,scheduleItems:j,participant:nt,statistics:z,opponents:Q,matchUps:pt,events:st,draws:Mt})=>{let _t=Object.values(Mt),Re=Object.values(Q);return S&&_t?.forEach(Kt=>{Kt.opponents=Re.filter(Ie=>Ie.drawId===Kt.drawId)}),ot({...nt,scheduleConflicts:u?Object.values(X):void 0,draws:A||o?_t:void 0,events:U||o?Object.values(st):void 0,matchUps:T||o?Object.values(pt):void 0,opponents:S?Re:void 0,potentialMatchUps:L?Object.values(K):void 0,statistics:f?Object.values(z):void 0,scheduleItems:a?j:void 0},!1,!1,!0)},k=new Map;for(let K of Object.keys(M))k.set(K,G(M[K]));let H=[...k.values()],Y=s?.[Vs]?.participant,$=Eu({participants:H,participantFilters:r,tournamentRecord:c});if(e){let K=ht(e)?e:void 0;for(let X of $)for(let j of X.individualParticipantIds??[]){X.individualParticipants||(X.individualParticipants=[]);let nt=k.get(j),z=K?Bi({template:K,source:nt}):nt;X.individualParticipants.push(z)}}let B=Y?$.map(K=>Bi({source:K,template:Y})):$;return{participantMap:t.returnParticipantMap!==!1?M:void 0,mappedMatchUps:t.returnMatchUps!==!1?F:void 0,matchUps:t.returnMatchUps!==!1?w:void 0,missingParticipantIds:D.missingParticipantIds,participantIdsWithConflicts:b,eventsPublishStatuses:v,derivedEventInfo:O,derivedDrawInfo:_,participants:B,...C}}function gc({participantId:t,drawDefinition:e,entryStatus:r,entryStage:n}){if(!e)return{error:Z};let o=e.entries?.find(i=>i.participantId===t&&(!r||r===i.entryStatus)&&(!n||n===i.entryStage));return t&&o}function Is(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:Z};let{entryProfile:s}=gu({drawDefinition:r}),a=i&&n&&s?.[i]?.stageSequence?.[n]?.qualifiersCount||i&&s?.[i]?.qualifiersCount||0,c={};if(!o)return{qualifiersCount:a,roundQualifiersCounts:c};let{structure:u}=at({drawDefinition:r,structureId:o}),p=r.links?.filter(l=>l?.target?.structureId===u?.structureId),m=0;if(p?.length)for(let l of p){let f=at({structureId:l.source.structureId,drawDefinition:r})?.structure;if(f?.stage===ct){let g=l.source.roundNumber,I=l.target.roundNumber,h=0;if(f.structureType===Ge){let S=f.structures?.length??0,T=l.source.finishingPositions?.length??0;h=S*T}else h=Pt({matchUpFilters:{roundNumbers:[g]},structure:f,afterRecoveryTimes:!1,provisionalPositioning:e,inContext:!1}).matchUps?.length||0;c[I]||(c[I]=0),c[I]+=h,m+=h}}let d=Object.keys(c);if(d.length<=1){let l=d[0]||1;c[l]=Math.max(c[l]||0,a)}return m=Math.max(m,a),{qualifiersCount:m,roundQualifiersCounts:c}}function Rp({stage:t,drawDefinition:e}){let{entryProfile:r}=gu({drawDefinition:e});return r?.[t]?.drawSize||0}function lv(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=Rp({stage:o,drawDefinition:r}),{qualifiersCount:s}=Is({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function eP({stage:t,drawDefinition:e}){return!!(t===$e||tg({stage:t,drawDefinition:e})&&Rp({stage:t,drawDefinition:e}))}function rP({entryStatus:t=kr,drawDefinition:e,stageSequence:r,stage:n}){if(t===rn)return Db({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...C}:{error:lE};let o=lv({drawDefinition:e,stageSequence:r,stage:n}),i=Nb({drawDefinition:e,stage:n}),s=eS({entryStatus:Iu,drawDefinition:e,stage:n}),a=eS({entryStatus:kr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==$e&&u?{error:WI}:t===Iu?s<i?{...C}:{error:WI}:{positionsAvailable:p,...C}}function fd(t){let e=et(t,[{[Ve]:!0,[Rh]:!0}]);if(e.error)return e;let{suppressDuplicateEntries:r=!0,entryStatus:n=kr,entryStageSequence:o,entryStage:i=rt,ignoreStageSpace:s,drawDefinition:a,entryPosition:c,participant:u,roundTarget:p,extensions:m,extension:d,drawType:l,event:f}=t,g="addDrawEntry";if(l!==$r&&!eP({stage:i,drawDefinition:a}))return x({result:{error:_i},stack:g});let I=rP({stageSequence:o,stage:i,drawDefinition:a,entryStatus:n});if(!s&&!I.success&&(!l||l!==$r))return{error:I.error};if(d&&!Ln({extension:d}))return x({result:{error:V},info:"Invalid extension",context:{extension:d},stack:g});let h=t.participantId||u?.participantId;if(!h)return x({result:{error:ie},stack:g});let S=n===cs&&gc({participantId:h,drawDefinition:a,entryStatus:n}),T=i===$e&&gc({participantId:h,drawDefinition:a,entryStage:i}),y=gc({participantId:h,drawDefinition:a}),P=n!==cs&&i!==$e&&y;if(P)return r?(dt({payload:{drawId:a.drawId,eventId:f?.eventId,error:ym,participantId:h},topic:Yh}),{...C}):x({result:{error:ym},context:{participantId:h},stack:g});if(S||T)return x({context:{invalidEntry:P,invalidLuckyLoser:S,invalidVoluntaryConsolation:T},result:{error:Qu},stack:g});let U=ot({entryStageSequence:o,participantId:h,entryPosition:c,entryStatus:n,entryStage:i,extensions:m});return d&&At({element:U,extension:d}),p&&At({extension:{name:"roundEntry",value:p},element:U}),a.entries||(a.entries=[]),a.entries.push(U),vt({drawDefinition:a}),{...C}}function fv(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=kr,autoEntryPositions:o=!0,ignoreStageSpace:i,participantIds:s,drawDefinition:a,stageSequence:c,stage:u=rt,roundTarget:p,extension:m,event:d}=t;if(!u)return{error:qA};if(!a)return{error:Z};if(!Array.isArray(s))return{error:wr};if(!eP({stage:u,drawDefinition:a}))return{error:_i};if(m&&!Ln({extension:m}))return x({result:{error:V},info:"Invalid extension",context:{extension:m},stack:e});let l=rP({drawDefinition:a,stageSequence:c,entryStatus:n,stage:u});if(!i&&!l.success)return{error:l.error};let f=l.positionsAvailable??0;if(!i&&u!==$e&&f<s.length)return{error:Ql};let g=[],I=a.drawId,h=d?.eventId,S=s.reduce((T,y)=>{let P=n===cs&&gc({participantId:y,drawDefinition:a,entryStatus:n}),U=u===$e&&gc({entryStage:u,drawDefinition:a,participantId:y}),A=gc({participantId:y,drawDefinition:a});return n!==cs&&u!==$e&&A&&(g.push(y),r&&dt({payload:{error:ym,participantId:y,eventId:h,drawId:I},topic:Yh})),P||U?T.concat(y):T},[]);return g.length&&!r?x({context:{eventId:h,drawId:I,duplicateEntries:g},result:{error:ym},stack:e}):(s.filter(T=>T&&!S.includes(T)).forEach(T=>{let y={entryStageSequence:c,entryStage:u,participantId:T,entryStatus:n};m&&At({element:y,extension:m}),p&&At({extension:{name:Mn,value:p},element:y}),a.entries||(a.entries=[]),a.entries.push(y)}),o&&(a.entries=zn({entries:a.entries})),vt({drawDefinition:a}),S?.length||g?.length?{info:"some participantIds could not be added",participantIdsNotAdded:S,duplicateEntries:g,...C}:{...C})}function cg({suppressDuplicateEntries:t=!0,autoEntryPositions:e=!0,entryStageSequence:r,ignoreStageSpace:n,participantIds:o,drawDefinition:i,entryStatus:s,roundTarget:a,entryStage:c,extension:u,drawId:p,event:m}){if(!o?.length)return{error:Uo};if(!m)return{error:jr};if(!p)return{error:sn};let d=(m.entries||[]).map(St);if(o.filter(I=>!d.includes(I)).length)return{error:jA};if(i){let I=fv({stageSequence:r,suppressDuplicateEntries:t,autoEntryPositions:e,stage:c,ignoreStageSpace:n,participantIds:o,drawDefinition:i,entryStatus:s,roundTarget:a,extension:u});if(I.error)return I}let{flightProfile:f}=Ht({event:m}),g=f?.flights.find(I=>I.drawId===p);return g?.drawEntries&&(o.forEach(I=>{let h=s===cs&&nP({participantId:I,entryStatus:s,flight:g}),S=c===$e&&nP({participantId:I,entryStage:c,flight:g});!(s!==cs&&c!==$e&&nP({flight:g,participantId:I}))&&!h&&!S&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=zn({entries:g.drawEntries}))),{...C}}function nP({participantId:t,entryStatus:e,entryStage:r,flight:n}){let o=n.drawEntries?.find(i=>i.participantId===t&&(!e||e===i.entryStatus)&&(!r||r===i.entryStage));return t&&o}function Ic({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:Ot};if(!Array.isArray(e)||e.some(m=>!Vt(m)))return x({result:{error:dn},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>Ri({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(St).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(St).filter(m=>!s.includes(m));if(e.length?e=e.filter(m=>(!r?.length||a.includes(m))&&(!n||c.includes(m))):a.length&&c.length?e=qt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return x({result:{error:vs},stack:i});if(!e?.length)return{...C,participantIdsRemoved:[]};let u=[];o.entries=(o.entries??[]).filter(m=>{let d=!e.includes(m?.participantId);return d||u.push(m.participantId),d}),t&&(o.entries=zn({entries:o.entries}));let{flightProfile:p}=Ht({event:o});return p?.flights?.forEach(m=>{m.drawEntries=(m.drawEntries||[]).filter(d=>!e.includes(d.participantId))}),o.drawDefinitions?.forEach(m=>{m.entries=(m.entries??[]).filter(d=>!e.includes(d.participantId))}),{...C,participantIdsRemoved:u}}var oP={[er]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},hs=oP;function kn(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=kr,autoEntryPositions:n=!0,enforceGender:o=!0,entryStageSequence:i,policyDefinitions:s,entryStage:a=rt,tournamentRecord:c,ignoreStageSpace:u,drawDefinition:p,roundTarget:m,extensions:d,extension:l,drawId:f,event:g}=t,I="addEventEntries";if(!Array.isArray(t.participantIds))return x({result:{error:wr},stack:I});let h=ut(t.participantIds??[]);if(!g)return{error:Ot};if(!h?.length)return x({result:{error:Uo},stack:I});if(!g?.eventId)return{error:jr};let S=yt({tournamentRecord:c,event:g}).appliedPolicies??{},T=s?.[er]??S?.[er]??hs[er],y=(o??T?.participants?.enforceGender)!==!1,P=[],U=[];if(d&&(!Array.isArray(d)||!d.every(_=>Ln({extension:_})))||l&&!Ln({extension:l}))return x({context:ot({extension:l,extensions:d}),result:{error:V},info:"Invalid extension(s)",stack:I});let A=!!c,E=[],N,D=c?.participants?.filter(_=>{if(!h.includes(_.participantId))return!1;let F=me(kt)(g.eventType)&&_.participantType===Tt&&!Ys(r),w=g.eventType===xt&&_.participantType===ft;return F&&(!g.gender||!y||[yr,Pn].includes(g.gender)||g.gender===_.person?.sex)||w&&!Ys(r)||g.eventType===xt&&_.participantType===Tt&&Ys(r)?!0:F&&g.gender&&y&&![yr,Pn].includes(g.gender)&&g.gender!==_.person?.sex?(E.push({participantId:_.participantId,sex:_.person?.sex}),!1):g.eventType===Ft&&(_.participantType===Ft||Ys(r)&&_.participantType===Tt)}).map(_=>_.participantId)??[],M=h.filter(_=>!A||D.includes(_));g.entries||(g.entries=[]);let R=g.entries.map(_=>_.participantId||_.participant?.participantId);if(M.forEach(_=>{if(!R.includes(_)){let F=ot({participantId:_,entryStatus:r,entryStage:a,extensions:d});l&&At({element:F,extension:l}),m&&At({extension:{name:Mn,value:m},element:F}),i&&(F.entryStageSequence=i),P.push(F.participantId),g.entries?.push(F)}}),f&&!Ys(a)){let _=cg({participantIds:M,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:i,ignoreStageSpace:u,drawDefinition:p,entryStatus:r,roundTarget:m,entryStage:a,extension:l,drawId:f,event:g});_.error&&(N=_.error)}if(g.eventType&&[ko,vr].includes(g.eventType)){let _=(g.entries||[]).map(k=>k.participantId),F=(g.entries||[]).filter(k=>Ys(k.entryStatus)).map(k=>k.participantId),L=(c?.participants??[]).filter(k=>_.includes(k.participantId)&&k.participantType&&[ft,Ft].includes(k.participantType)).map(k=>k.individualParticipantIds).flat(1/0),G=F.filter(k=>L.includes(k));G.length&&(U.push(...G),Ic({participantIds:G,autoEntryPositions:!1,event:g}))}if(M.length!==h.length)return x({context:{mismatchedGender:E,gender:g.gender},result:{error:wr},stack:I});n&&(g.entries=zn({entries:g.entries||[]}));let v=P.length,O=U.length;return x({result:{...C,addedEntriesCount:v,removedEntriesCount:O},stack:I,info:N})}var iP="ADMINISTRATION",Lk="CAPTAIN",Fk="COACH",Oe="COMPETITOR",sP="MEDIA",aP="MEDICAL",ug="OFFICIAL",cP="OTHER",uP="SECURITY",gd={ADMINISTRATION:iP,CAPTAIN:Lk,COACH:Fk,COMPETITOR:Oe,MEDIA:sP,MEDICAL:aP,OFFICIAL:ug,OTHER:cP,SECURITY:uP};function pg({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return x({result:{error:q},stack:i});if(!r||!e)return x({result:{error:it},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return x({result:{error:re},stack:i});if(![Ft,zr].includes(a.participantType))return x({result:{participantType:a.participantType,error:An},stack:i});let c=gv({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:n,suppressErrors:o}),{removed:u,error:p}=c;if(p)return x({result:c,stack:i});if(t)for(let m of n.events??[]){let d=(m.entries??[]).map(({participantId:l})=>l).filter(Boolean);if(d.includes(r)){let l=u?.filter(f=>!d.includes(f));kn({participantIds:l,entryStatus:Gr,tournamentRecord:n,event:m})}}return u&&dt({topic:nr,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...C,...c}}function gv({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:r,suppressErrors:n,mappedMatchUps:o,participants:i}){let s=[];if(!e)return{removed:s};let a=[],c=[];i||({participants:i,mappedMatchUps:o}=Gt({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));let p=i?.find(({participantId:l})=>l===e.participantId)?.events?.map(({eventId:l})=>l),m=(e.individualParticipantIds??[]).filter(l=>{let f=t?.includes(l),g=f&&i?.find(h=>h.participantId===l)?.matchUps.filter(({eventId:h})=>p.includes(h)).map(({matchUpId:h})=>o?.[h]).filter(({winningSide:h,score:S})=>h||Se({score:S})),I=f&&!g?.length;if(f&&!I&&c.push(l),I){s.push(l);for(let h of r.events??[])for(let S of h.drawDefinitions??[]){let{extension:T}=lt({element:S,name:Ro}),y=T?.value[e.participantId];T&&y&&(T.value[e.participantId]=y.filter(U=>U.participantId!==l),At({element:S,extension:T}),ya({drawDefinition:S}));let P=or({drawDefinition:S,inContext:!1}).matchUps??[];for(let U of P){let A=U.sides??[];for(let E of A){let N=E.lineUp??[];N.find(M=>M.participantId===l)&&(E.lineUp=N.filter(M=>M.participantId!==l),gt({tournamentId:r?.tournamentId,drawDefinition:S,matchUp:U}))}}}}else a.push(l);return!I});e.individualParticipantIds=m;let d={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:a,removed:s};return c.length&&!n&&{...d,cannotRemove:c,error:zu}||d}function Cp({participantRole:t=Oe,individualParticipantIds:e=[],groupingTypes:r=[Ar,zr],tournamentRecord:n}){if(!n)return{error:q};let o=n.participants??[],{participants:i,mappedMatchUps:s}=Gt({withMatchUps:!0,tournamentRecord:n,withEvents:!0}),a=0;return o.filter(c=>(c.participantRole===t||!c.participantRole)&&c.participantType&&r.includes(c.participantType)).forEach(c=>{let{removed:u}=gv({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?C:{error:uE}}function Ki(t){let e=et(t,[{[se]:!0},{participantIds:!0,[He]:Be,[gn]:Uo}]);if(e.error)return e;let{addIndividualParticipantsToEvents:r,tournamentRecord:n,participantIds:o}=t,i=n.participants?.length||0;if(!i)return{...C};let s=(n.events||[])?.filter(({eventType:f})=>f===ve).map(f=>f?.drawDefinitions?.map(({drawId:g})=>g)).flat(1/0),a=Gt({participantFilters:{participantIds:o},tournamentRecord:n,withDraws:!0}).participants??[],c=f=>{let I=(Ae({matchUpFilters:{drawIds:f,matchUpTypes:[xt]},tournamentRecord:n}).matchUps??[]).flatMap(({sides:h})=>h?.map(({participantId:S})=>S||[])).filter(Boolean);return qt(I,o)},u=s?.length?c(s):[],p=a.filter(f=>f.draws?.filter(g=>(!s?.length||!s?.includes(g.drawId))&&g.positionAssignments).length);if(u?.length||p.length)return{error:vs};let m={},d={};for(let f of n.events||[]){let g=Ic({participantIds:o,event:f});if(g.error)return g;m[f.eventId]=g.participantIdsRemoved}n.participants=(n.participants??[]).filter(f=>{let g=o.includes(f.participantId)||f.participantType===ft&&f.individualParticipantIds?.some(I=>o.includes(I));if(!g&&f.participantType===ve&&f.individualParticipantIds?.some(I=>o.includes(I))&&(f.individualParticipantIds=f.individualParticipantIds.filter(I=>!o.includes(I))),g&&r&&f.participantType&&[ft,Ft].includes(f.participantType))for(let I of f.individualParticipantIds||[])o.includes(I)||(d[f.participantId]||(d[f.participantId]=[]),d[f.participantId].push(I));return!g});let l=i-n.participants.length;if(Cp({individualParticipantIds:o,tournamentRecord:n}),r)for(let f of n.events||[]){let I=m[f.eventId].map(h=>d[h]||[]).flat();kn({participantIds:I,entryStatus:Gr,tournamentRecord:n,event:f})}return l&&dt({payload:{participantIds:o,tournamentId:n.tournamentId},topic:Ff}),l?{...C,participantsRemovedCount:l}:{error:zu}}function ES({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Ht({event:o}),u=c?.flights?.find(p=>p.drawId===n);u?s=u.drawEntries:e.entries&&(s=e?.entries)}let a=s.filter(c=>(!r?.length||!c.entryStatus||r.includes(c.entryStatus))&&(!i||!c.entryStage||c.entryStage===i)&&(!t||c.entryStatus&&Qr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function pP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry";if(!e)return{error:q};if(!n)return x({result:{error:ie},stack:a});if(!s)return{error:Ot};if(!s.eventType||![ko,vr].includes(s.eventType))return x({result:{error:Wn},stack:a});let c=e.participants??[],u=c.find(S=>S.participantId===n);if(!u)return x({result:{error:re},stack:a});if(!u.participantType||![ft,Ar].includes(u.participantType)||u.participantType===Ar&&s.eventType!==vr||u.participantType===ft&&s.eventType!==ko)return{error:An};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:HI};let{stageEntries:d}=ES({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),l=d.map(St),f=c.filter(({participantId:S})=>l.includes(S)).map(({individualParticipantIds:S})=>S).flat().filter(Boolean),g=u.individualParticipantIds?.filter(S=>mo(S,f).length===1),I=Ic({participantIds:[n],event:s});if(I.error||g?.length&&(I=kn({participantIds:g,entryStatus:Gr,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&Ki({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...C,participantRemoved:h}}function mg({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return pP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function mP(t){if(!t.tournamentRecord)return{error:q};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=pP({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...C}:{error:o}}function Uu(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=fc(t);if(u.error)return x({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t,f=yt({tournamentRecord:e,drawDefinition:n,event:d}).appliedPolicies??{};if([rn,so].includes(i)&&p){let{tournamentRecord:h}=t,{participant:S}=To({tournamentRecord:h,participantId:p}),{participantType:T,individualParticipantIds:y}=S??{};if(o&&T===ft){let P=mg({tournamentRecord:h,drawDefinition:n,participantId:p,event:d});if(P.error)return x({result:P,stack:c});y&&dd({participantIds:y,tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else dd({participantIds:[p],tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let h=Hr({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(h.error)return x({result:h,stack:c})}let{structure:g}=at({drawDefinition:n,structureId:l});return Xm({structure:g,drawPositions:[m]}),uu({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function dP(t){return Object.assign(t,{entryStatus:so}),Uu(t)}function US(t){return Vt(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function Qe(t){return Vt(t)?US(t.replace(/_/g," ")):""}var Ss=({finishingPosition:t=Vi,qualifyingRoundNumber:e,structureAbbreviation:r,seedAssignments:n=[],stageSequence:o=1,structureOrder:i,seedingProfile:s,matchUpFormat:a,structureType:c,structureName:u,matchUpType:p,matchUps:m=[],structureId:d,roundOffset:l,roundLimit:f,stageOrder:g,structures:I,stage:h})=>{let S={structureId:d??Dt(),structureAbbreviation:r,finishingPosition:t,seedAssignments:n,matchUpFormat:a,stageSequence:o,structureName:u};i&&(S.structureOrder=i),c&&(S.structureType=c),s&&(typeof s=="string"?S.seedingProfile=s:typeof s=="object"&&typeof s.positioning=="string"&&(S.seedingProfile=s.positioning)),p&&(S.matchUpType=p),l&&(S.roundOffset=l),g&&(S.stageOrder=g),f&&(S.roundLimit=f),h&&(S.stage=h),e&&(S.qualifyingRoundNumber=e);let T=m.flatMap(({drawPositions:y})=>y).filter(Boolean);return I?S.structures=I:(S.matchUps=m,S.positionAssignments=ut(T).sort((y,P)=>y-P).map(y=>({drawPosition:y}))),S},Sn=Ss;function dg({structureName:t=Qe($e),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:Z};let i=Sn({stage:$e,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(i),vt({drawDefinition:r,structureIds:[i.structureId]}),{...C}}function lg({drawPositions:t}){if(!t?.length)return{error:Ya};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=ut(r.map(fg)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function fg(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(le).join("|")}function lP({groupSize:t,drawPositionOffset:e}){if(!t)return[];let r=m=>[...Array(m)].map((d,l)=>l),n=r(2*Math.round(t/2)+1).slice(1),o=r(n.length-1).map(()=>[]),i=n.slice(0,n.length/2),s=n.slice(n.length/2);n.slice(1).forEach((m,d)=>{i.forEach((I,h)=>{o[d].push([i[h],s[h]])});let l=i.shift(),f=i.pop(),g=s.shift();i=[l,g,...i].filter(Boolean),s=[...s,f].filter(Boolean)});let a=i.shift(),c=i.pop(),u=s.shift();i=[a,u,...i].filter(Boolean),s=[...s,c].filter(Boolean);let p=m=>m[0].reduce((d,l)=>d+l);return[...o].reverse().sort((m,d)=>p(m)-p(d)).map(m=>m.filter(d=>d.every(l=>l<=t)).map(d=>{let l=d.map(f=>f+e);return fg(l)}))}function kk({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:it}}var Iv={getRoundRobinGroupMatchUps:lg,determineRoundNumber:kk,drawPositionsHash:fg,groupRounds:lP};function Ma(t){let{groupNameBase:e="Group",playoffAttributes:r,stageSequence:n=1,structureOptions:o,appliedPolicies:i,seedingProfile:s,stage:a=rt,matchUpType:c,roundTarget:u,structureId:p,groupNames:m,drawSize:d,idPrefix:l,isMock:f,uuids:g}=t,I=t.structureName??r?.["0"]?.name??Qe(rt),{groupCount:h,groupSize:S}=Gk({structureOptions:o,appliedPolicies:i,drawSize:d}),T=fi,y,P=tt(1,h+1).map(A=>{let E=Vk({groupSize:S,structureOrder:A,matchUpType:c,drawSize:d,idPrefix:l,isMock:f});y=Array.isArray(E)?Math.max(...E.map(({roundNumber:D})=>D??0)):0;let N=m?.[A-1]??`${e} ${A}`;return Ss({structureId:g?.pop(),structureType:cp,finishingPosition:T,structureOrder:A,structureName:N,matchUps:E})}),U=Ss({structureId:p??g?.pop(),structureType:Ge,finishingPosition:T,seedingProfile:s,structureName:I,stageSequence:n,structures:P,stage:a});return u&&At({extension:{name:Mn,value:u},element:U}),{structures:[U],maxRoundNumber:y,groupCount:h,links:[],groupSize:S,...C}}function Gk({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=bp({groupSizeLimit:o,drawSize:r}),s=i&&Math.max(...i);n&&i?.includes(n)||(n&&n>4||!i?.includes(4)?n=s:n=4);let c=Math.ceil(r/n);return{groupSize:n,groupCount:c}}function bp(t){let{groupSizeLimit:e=10,drawSize:r=0}=t??{},n=tt(3,e+1).filter(o=>{let i=Math.ceil(r/o),s=i*o-r,a=Math.ceil(r/i),c=Math.ceil(s/i);return(!s||s<o)&&a===o&&a>=3&&c<2});return{...C,validGroupSizes:n}}function Vk({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=tt(1+a,r+1+a),u=lg({drawPositions:c}).uniqueMatchUpGroupings??[],p=lP({groupSize:r,drawPositionOffset:a});return u.map(l).sort((f,g)=>(f.roundNumber??1/0)-(g.roundNumber??1/0));function d(f){return p.reduce((g,I,h)=>I.includes(f)?h+1:g,void 0)}function l(f){let g=fg(f),I=d(g),h=[1,n],S=Bk({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?Jt:Nt,matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function Bk({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Dt()}function gg(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!It(r))return{seedBlocks:void 0,...x({result:{error:V},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=es(r);if(e){let l=Math.min(e,o),f=[],g=1;for(tt(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=tt(g,g+l);g+=l,f.push(I)}return{...C,seedBlocks:f}}let i=tt(1,o+1),s=[],a=o/2;for(;a>1;){let l=Ee(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,y=g[0],P=g[g.length-1];n&&f>4?f===8?h=S?P:y:h=T?y:P:h=S?y:P,Fe(g,s)||s.push(h)}),a=a/2}let c=i.filter(l=>!s.includes(l));for(;c.length;)c.length%2===0?s.push(c.pop()):s.push(c.shift());let u=tt(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),m=0,d=[];return tt(0,p).forEach(l=>{d.push(s.slice(m,m+u[l])),m+=u[l]}),{...C,seedBlocks:d}}function Ig({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!It(e))return{seedGroups:void 0,...x({result:{error:V},context:{drawSize:e},stack:r})};if(t){if(!It(t))return{seedGroups:void 0,...x({context:{roundRobinGroupsCount:t},result:{error:V},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:tt(0,o).map(()=>{let s=tt(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=gg({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function PS({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=bp({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return x({context:{roundRobinGroupsCount:t},result:{error:V}})}let{seedGroups:r}=Ig({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...C,seedingThresholds:n}}function hc(t){if(!t)return 1/0;if(It(t))return mt(t);let e=t.split("-")[0];return It(e)?mt(e):1/0}function Hk({size:t}){let e=[t],r=t;for(;r/2===Math.floor(r/2);)r=r/2,e.push(r);return e.includes(1)||e.push(1),e.sort(le),e.reverse(),e}function hv({blockPattern:t,index:e}){let r=0;for(let n of t){if(r===e)return n;let o=0;for(;o<n.length;){if(r===e)return n;r+=1,o++}}}function Sv({positioning:t,size:e}){let r=Hk({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[zc,di].includes(t)&&l%2?s(d):i(d))||i(d),c=(d,l)=>{if(d.every(f=>!o.includes(f))){let f=a(d,l);return o.push(f),f}},u=d=>{let l=d.filter(f=>!o.includes(f));if(l.length)return o.push(...l),l},p=(d,l)=>{let f=a(d,l);if(!o.includes(f))return o.push(f),f},m=tt(1,e+1);for(let d of r)if(d===1){let l=Ee(m,2),f=l.map(c).filter(Boolean);f.length&&n.push(f);let g=l.flatMap(u).filter(Boolean);g.length&&n.push(g)}else{let f=Ee(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function Ts({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:mi};let{matchUps:c,roundMatchUps:u}=Pt({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=nn({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:m}=ye({structure:s}),d=m?.length,l=p?.length??0,f=[],I=Object.keys(u).map(w=>parseInt(w)).sort((w,L)=>w-L).map(w=>{let L=u[w].map(k=>k.drawPositions).flat(1/0).filter(Boolean),G=L.filter(k=>!f.includes(k));return f=f.concat(...L),G}).filter(w=>w.length).reverse(),h=I.pop()??[],S=h&&Math.min(...h)-1||0;n=n??r?.seeding?.seedingProfile;let T=h?.length||0,y=I.filter(w=>w.filter(L=>L<=l).length),{stage:P,structureType:U,roundLimit:A}=s,E=U===Ge,N=!E&&I?.length,D=!E&&P===ct&&A,M=y.flat(1/0),R=N?M?.length:0,b=i?d:l,v=id({drawDefinition:o,structure:s,matchUps:c}),O=v?0:!N&&b||b&&M.length<b&&b-M.length||0;if(D){let w=s?.matchUps?s.matchUps.filter(({roundNumber:G})=>G===s.roundLimit).length:0,L=h.length/w;if(!N){let G=Op(n),k=Ee(h,L),H=1,W=tt(0,k[0].length).map(()=>{let Y=tt(H,H+k.length);return H+=k.length,Y});({validSeedBlocks:a}=Tv({drawPositionBlocks:k,nonRandom:n?.nonRandom,positioning:G,seedGroups:W}))}}else E?{validSeedBlocks:a}=Wk({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):N?a=y.map(w=>({seedNumbers:w,drawPositions:w})):v&&Ee(h,2).map((L,G)=>({drawPositions:[L[0]],seedNumbers:[G+1]})).forEach(L=>a.push(L));if(!E&&!v&&!D){let{blocks:w}=jk({drawPositionOffset:S,seedNumberOffset:R,seedCountGoal:O,seedingProfile:n,baseDrawSize:T});w.forEach(L=>a.push(L))}let F=a.flatMap(w=>w.drawPositions).reduce((w,L)=>h?.includes(L)&&w,!0);return!v&&!N&&!E&&!F?{error:VA,validSeedBlocks:[],isContainer:E,isFeedIn:N}:{isLuckyStructure:v,validSeedBlocks:a,isContainer:E,isFeedIn:N}}function Wk({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=bt({structure:e})?.positionAssignments,s=Op(t),a=i?.length??0,{seedGroups:c}=Ig({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>bt({structure:p}).positionAssignments?.map(m=>m.drawPosition));return Tv({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function Tv({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=Sv({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=hv({blockPattern:i,index:c});a.forEach((p,m)=>{let d=c%2?t.length-m-1:m,f=t[d].slice().filter((I,h)=>u.includes(h+1)&&I);e!==di?f=n?f:hr(f):c%2&&f.reverse();let g=f.find(I=>!s.includes(I));g&&(s.push(g),o.push({drawPositions:[g],seedNumbers:[p]}))})}),{validSeedBlocks:o}}function jk(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=gg({cluster:Op(o)===zc,participantsCount:s,roundRobinGroupsCount:r});a=0;for(let m of u){if(a+1>i)break;let d=m.map(f=>f+e),l=p(a+1,m.length).map(f=>+f+n);a+=m.length,c.push({drawPositions:d,seedNumbers:l})}return{blocks:c};function p(m,d){return Array.from(new Array(d),(l,f)=>f+m)}}function vp({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=at({drawDefinition:e,structureId:o});t||(t=yt({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=Ts({appliedPolicies:t,drawDefinition:e,structure:s})?.validSeedBlocks),t?.seeding?.validSeedPositions?.ignore?!0:t?.seeding?.validSeedPositions?.strict?(a.find(m=>m.seedNumbers.includes(i))?.drawPositions||[]).includes(n):[].concat(...a.map(u=>u.drawPositions)).includes(n)}function DS(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=at({drawDefinition:r,structureId:i}),{seedAssignments:c}=nn({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:a}),{positionAssignments:u}=ye({structure:a}),m=u?.filter(L=>L.participantId??L.bye??L.qualifier)?.map(L=>L.drawPosition).filter(Boolean),{appliedPolicies:d}=yt({drawDefinition:r}),g=(o?.validSeedBlocks||a&&Ts({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(L=>L.drawPositions.filter(k=>!m?.includes(k)).length)[0],I=c?.map(L=>L.participantId).filter(Boolean),h=u?.map(L=>L.participantId).filter(Boolean),S=I?.filter(L=>h?.includes(L)),T=I?.filter(L=>!h?.includes(L)),y=c?.filter(L=>T?.includes(L.participantId)),P=c?.filter(L=>!L.participantId),A=(y?.length&&y.length>0?y.length:P?.length??0)&&g?.drawPositions.filter(L=>!m?.includes(L))||[],E=s?hr(A):A,N=[],D=E.map(()=>{let G=w(y,N)?.participantId;return G&&N.push(G),G}).filter(Boolean),M=c?.filter(L=>S?.includes(L.participantId)).map(L=>L.seedNumber),b=(g?.seedNumbers||[]).filter(L=>!M?.includes(L)),v=c?.filter(L=>b.includes(L.seedNumber)).map(L=>L.participantId),O=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(O!==void 0?O:!0)?D:v,unplacedSeedNumbers:b,unfilledPositions:E,unplacedSeedAssignments:y};function w(L,G){let k=L.filter($=>!G.includes($.participantId)),H=Math.min(...k.map($=>hc($.seedValue))),W=k.filter($=>hc($.seedValue)===H);return hr(W).pop()}}function Op(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function $s({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,seedBlockInfo:i,structureId:s,seedNumber:a,seedValue:c,eventId:u,event:p}){let m="assignSeed",{structure:d}=at({drawDefinition:r,structureId:s}),{positionAssignments:l}=ye({structure:d}),f=nn({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(U=>U.seedNumber),I=gc({drawDefinition:r,participantId:o});if(o&&!I)return x({result:{error:dn},context:{participantId:o},stack:m});let h=p?Ht({event:p}).flightProfile?.flights?.length:0,S=h&&h>1,y=l?.find(U=>U.participantId===o)?.drawPosition;if(y&&!vp({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return x({result:{error:kl},context:{assignedDrawPosition:y},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let P;return f.forEach(U=>{U.participantId===o&&U.seedNumber!==a&&(U.participantId=void 0),U.seedNumber===a&&(U.participantId=o,!n?.groupSeedingThreshold&&!S&&(U.seedValue=c??a),P=!0)}),P?(Kh({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...C}):x({result:{error:GA},stack:m})}function Id({inContextTargetMatchUp:t,drawPositionSideIndex:e,teamParticipantId:r,tournamentRecord:n,drawDefinition:o,matchUp:i,event:s}){let a=t?.sides?.[e]?.sideNumber,c=a&&i.sides?.find(d=>d.sideNumber===a),{extension:u}=lt({element:o,name:Ro}),p=u?.value||{},m=J(p[r],!1,!0);if(c)i?.sides?.forEach(d=>{d.sideNumber===a&&(d.lineUp=m)});else{i.sides=[1,2].map(l=>({...i.sides?.find(g=>g.sideNumber===l)??{},sideNumber:l}));let d=i.sides.find(l=>l.sideNumber===a);d&&(d.lineUp=m)}gt({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function NS(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=ii({structureId:n.structureId,matchUpsMap:o});!e&&i&&(e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)));let c=e?.roundPosition,u=c%2?1:-1,p=c+u,m=s&&a.find(({roundNumber:f,roundPosition:g})=>f===s&&g===p),d=m?.matchUpStatus,l=[Te,Me].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function yv({drawPosition:t,drawPositions:e}){let r=!1,n=!!e?.includes(t);return{updatedDrawPositions:n?e||[]:[...e,void 0,void 0].slice(0,2).map(s=>!s&&!n?(n=!0,r=!0,t):s).sort(le).filter(Boolean),positionAdded:r,positionAssigned:n}}function MS({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:ii({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function RS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=MS({structureId:i?.structureId,matchUp:i,matchUpsMap:n});if(i&&s){let a=s?.matchUpId,c=t.find(p=>p.matchUpId===a),u=i?.structureId===c?.structureId?i?.roundPosition<c?.roundPosition&&1||2:i.structureId===c?.structureId&&2||1;o.matchUpStatusCodes=(o.matchUpStatusCodes??[]).map(p=>{let m=Vt(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function hd({inContextDrawMatchUps:t,drawPosition:e,matchUpId:r}){let n=t.filter(({winnerMatchUpId:s,loserMatchUpId:a})=>a===r||s===r).sort((s,a)=>s.roundPosition-a.roundPosition);return t.find(s=>s.matchUpId===r).feedRound?1:n.reduce((s,a,c)=>a.drawPositions?.includes(e)?c+1:s,void 0)}function Sc({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:r,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,event:u}){let p="assignMatchUpDrawPosition";a||(a=De({drawDefinition:o})),t||(t=ae({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[]);let m=t.find(b=>b.matchUpId===c),d=m?.structureId,l=o?.structures?.find(b=>b.structureId===d);if(!l)return{error:wt};let f=a?.drawMatchUps?.find(b=>b.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=yv({drawPositions:g,drawPosition:s}),{positionAssignments:T}=bt({drawDefinition:o,structure:l}),P=T?.filter(b=>S.includes(b.drawPosition))?.find(({bye:b})=>b),U=f?.matchUpStatus&&[Ct,Rt].includes(f.matchUpStatus)&&S.filter(Boolean).length<2;if(i=P&&Nt||i||U&&f.matchUpStatus||f?.matchUpStatus&&[Te,Me].includes(f.matchUpStatus)&&f.matchUpStatus||Jt,f&&I){t=ae({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let b=U&&hd({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||void 0;f?.matchUpStatusCodes&&RS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:a,matchUp:f}),Object.assign(f,{drawPositions:S,winningSide:b,matchUpStatus:i}),gt({tournamentId:r?.tournamentId,eventId:m?.eventId,context:p,drawDefinition:o,matchUp:f})}let A=pr({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:E,loserMatchUp:N,loserTargetDrawPosition:D},targetLinks:{loserTargetLink:M}}=A,R=ii({structureId:l.structureId,matchUpsMap:a});if(h&&P){if(E)if([Nt,Te,Me].includes(i)){let b=Sc({matchUpId:E.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(b.error)return b}else{let{structureId:b}=E;b!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(E&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:b}=NS({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(b){let v=Sc({matchUpId:E.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(v.error)return v}}if(f?.matchUpType===Yt){let b=t?.find(({matchUpId:F})=>F===f.matchUpId),O=(b?.sides??[]).reduce((F,w,L)=>w.drawPosition===s?L:F,void 0),_=T?.find(F=>F.drawPosition===s)?.participantId;_&&O!==void 0&&Id({inContextTargetMatchUp:b,drawPositionSideIndex:O,teamParticipantId:_,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(M?.linkCondition===_n&&S.filter(Boolean).length===2&&!P&&R.filter(({drawPositions:O,roundNumber:_})=>_===1&&Fe(O,S)).every(({matchUpStatus:O})=>[ge,rr].includes(O))&&N){let{structureId:O}=N,_=Hr({drawPosition:D,tournamentRecord:r,drawDefinition:o,structureId:O,matchUpsMap:a,event:u});if(_.error)return _}return h?{...C}:x({result:{error:ja},context:{drawPosition:s},stack:p})}function CS({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=as({drawDefinition:e})?.containedStructures?.[o.structureId]?.map(({structureId:m})=>m)||[];s.push(o?.structureId);let a=r?.map(({drawPosition:m})=>m)||[],c=t?.filter(m=>s.includes(m.structureId)&&qt(m.drawPositions??[],a).length)??[],u=c.map(({matchUpId:m})=>m),p=n?.drawMatchUps?.filter(m=>u.includes(m.matchUpId))??[];return{drawPositions:a,matchUps:p,targetMatchUps:c}}function Sd({lineUp:t}){if(!Array.isArray(t))return;let e={};return ut(t.flatMap(({collectionAssignments:n})=>n?.map(({collectionId:o,collectionPosition:i})=>[o,i].join("|"))).filter(Boolean)).forEach(n=>{let[o,i]=n.split("|"),s=parseInt(i),{assignedParticipantIds:a}=Mp({collectionPosition:s,collectionId:o,lineUp:t});a.forEach(c=>{e[c]||(e[c]=[]),e[c].push({collectionId:o,collectionPosition:s})})}),Object.keys(e).map(n=>({participantId:n,collectionAssignments:e[n]}))}function si(t){return`${t} must be an array`}function Td({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(si("lineUp")),{valid:!1,errors:r,error:V};let n=t.every(s=>{if(typeof s!="object")return r.push("lineUp entries must be objects"),!1;let{participantId:a,collectionAssignments:c}=s;return a?typeof a!="string"?(r.push("participantIds must be strings"),!1):Array.isArray(c)?c.every(u=>{if(typeof u!="object")return r.push("collectionAssignments must be objects"),!1;let{collectionPosition:p}=u;return typeof p!="number"?(r.push("collectionPosition must be a number"),!1):!0}):(r.push(si("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=ut(t.map(St)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?V:void 0}}function zi({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:ie};let o=Td({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=lt({element:t,name:Ro}),s=i?.value||{};return s[e]=Sd({lineUp:n}),At({element:t,extension:{name:Ro,value:s}}),ya({drawDefinition:t}),{...C}}function hg({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,assignments:i,structure:s,event:a}){if(!n)return{error:Z};let{drawPositions:c,matchUps:u,targetMatchUps:p}=CS({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===xr&&(m.sides??[]).forEach((d,l)=>{if(d?.drawPosition&&c?.includes(d.drawPosition)){let f=u.find(({matchUpId:g})=>g===m.matchUpId);if(f?.sides?.[l]){if(delete f.sides[l].lineUp,e===!1){let g=m.tieFormat,I=d.participantId;g&&I&&zi({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}gt({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...C}}function Gn({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:r,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,seedBlockInfo:c,drawPosition:u,matchUpsMap:p,structureId:m,event:d}){let l="assignDrawPosition";if(!a&&!r)return x({result:{error:ie},stack:l});p=p??De({drawDefinition:i}),e||({matchUps:e}=ae({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=at({drawDefinition:i,structureId:m});if(f.error)return x({result:f,stack:l});let{structure:g}=f;if(!g)return{error:wt};if(ur({structure:g}))return x({result:{error:dr},stack:l});let{seedAssignments:I}=nn({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(v=>v.participantId===a)?.seedNumber,{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!vp({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return x({result:{error:kl},context:{drawPosition:u},stack:l});let P=ye({structure:g}).positionAssignments||[],U=P?.find(v=>v.drawPosition===u);if(!U)return x({result:{error:Rs},context:{drawPosition:u},stack:l});if(P?.map(St).includes(a))return x({result:{error:vs},context:{drawPosition:u},stack:l});let{containsParticipant:E,containsBye:N}=b(U);if(N){let v=fc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(v.error)return x({result:v,stack:l})}if(E&&U.participantId!==a){let{activeDrawPositions:v}=Da({drawDefinition:i,structureId:m});if(v.includes(u))return x({result:{error:qu},stack:l});hg({assignments:[U],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}if(U.participantId=a,r&&(U.qualifier=!0),g.stage===rt&&(!g.stageSequence||g.stageSequence>1)||g.stage&&[qe,fe].includes(g.stage)){let v=g.stage===ct?ct:rt,F=(i.structures?.find(w=>w?.stage===v&&w?.stageSequence===1)?.seedAssignments??[]).find(w=>w.participantId===a);if(F?.participantId){let{participantId:w,seedNumber:L,seedValue:G}=F;$s({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:w,seedNumber:L,seedValue:G,structureId:m,event:d})}}if(g.structureType!==Ge)Yk({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{yS({positionAssignments:P,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:v,matchUps:O,targetMatchUps:_}=CS({assignments:[U],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(v&&O?.length===1&&O[0].matchUpType===Yt){let w=(_?.[0].sides??[]).reduce((L,G,k)=>v?.includes(G.drawPosition)?k:L,void 0);Id({inContextTargetMatchUp:_[0],teamParticipantId:a,matchUp:O[0],drawPositionSideIndex:w,tournamentRecord:o,drawDefinition:i})}}let M=i.entries?.find(v=>v.participantId===a),R=d?.entries?.find(v=>v.participantId===a);return!M&&R&&fd({entryStatus:R.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:i,participantId:a,event:d}),bo({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:P,...C};function b(v){let O=v.bye,_=v.qualifier,F=v.participantId;return{containsBye:O,containsQualifier:_,containsParticipant:F,filled:O||_||F}}}function Yk({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=Pt({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=Ke({matchUps:p}),{initialRoundNumber:d}=fs({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=Sc({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return x({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...C}}function yd(t){let{participantIdAttributeName:e="participantId",isQualifierPosition:r,positionActionName:n,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,event:u}=t,p="positionParticipantAction";if(!i)return{error:Z};let m=yt({tournamentRecord:o,drawDefinition:i,event:u}).appliedPolicies??{},{inContextDrawMatchUps:d,matchUpsMap:l}=t;l||(l=De({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),d||({matchUps:d}=ae({inContext:!0,drawDefinition:i,matchUpsMap:l}),Object.assign(t,{inContextDrawMatchUps:d}));let{positionAssignments:f}=bt({drawDefinition:i,structureId:c}),g=f?.find(y=>y.drawPosition===a);if(g?.participantId){let y=g.participantId,P=Gn({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return P.success?T({appliedPolicies:m,removedParticipantId:y}):x({result:P,stack:p})}let I=fc({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(I.error)return x({result:I,stack:p});let h=I.participantId,S=Gn({inContextDrawMatchUps:d,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(!S.success)return x({result:S,stack:p});return T({appliedPolicies:m,removedParticipantId:h});function T({appliedPolicies:y,removedParticipantId:P}){let{structure:U}=at({drawDefinition:i,structureId:c});Xm({drawPositions:[a],structure:U});let A={[e]:s,name:n,drawPosition:a,structureId:c};return uu({appliedPolicies:y,drawDefinition:i,positionAction:A}),x({context:{removedParticipantId:P},result:{...C},stack:p})}}function Av({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return yd({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function fP(t){return Av(t)}function bS({params:t,modMap:e,structure:r}){let{tournamentRecord:n,drawDefinition:o,event:i}=t;for(let s of r.matchUps)e[s.matchUpId]&&(s.roundNumber=e[s.matchUpId],gt({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:o,matchUp:s}))}function vS(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=et(t,r);if(n.error)return n;let o=at(t);if(o.error)return o;let i=o.structure;if(!ur({structure:i}))return x({result:{error:Xo,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=Ke({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:Jn}}function gP(t){let e=vS(t,[{targetRoundNumber:!0,roundNumber:!0,[He]:ub}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e,{targetRoundNumber:i,roundNumber:s}=t;if(!o?.includes(s)||!o?.includes(i))return x({result:{error:V},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?tt(s+1,i+1):tt(i,s),u={};return c.forEach(p=>(n?.[p]??[]).forEach(({matchUpId:m})=>{u[m]=p-(a?1:-1)})),n?.[s]?.forEach(({matchUpId:p})=>u[p]=i),bS({params:t,modMap:u,structure:r}),{...C}}function IP({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:Z};if(!Array.isArray(t))return{error:V};let i="setPositionAssignments";for(let a of t){let{structureId:c,positionAssignments:u}=a;if(!u)continue;let p=at({drawDefinition:n,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:wt};let d=bt({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(qt(d,l).length!==d?.length)return x({result:{error:V},info:"drawPositions do not match",stack:i});let f=De({drawDefinition:n}),{matchUps:g}=ae({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u||[]){let{drawPosition:h,participantId:S,bye:T,qualifier:y}=I;if(T){let P=Hr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:m,event:o});if(P?.error)return P}else if(y)u.forEach(P=>{P.drawPosition===h&&(P.qualifier=!0,delete P.participantId,delete P.bye)});else if(S){let P=Gn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(P?.error)return P}}bo({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return vt({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...C}}function hP(t){let e=vS(t,[{roundNumbers:!0,[He]:Be,[tr]:s=>s.length===2&&s.every(te)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return x({result:{error:V,message:"roundNumbers must be valid rounds"}});let i={};return t.roundNumbers.forEach((s,a)=>(n?.[s]??[]).forEach(({matchUpId:c})=>{i[c]=t.roundNumbers[1-a]})),bS({params:t,modMap:i,structure:r}),{...C}}function Ev({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return yd({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function SP(t){return Ev(t)}function TP({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i}){return yd({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i})}function yP({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:Z};if(!o)return{error:Ur};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:dn};let{structure:c}=at({drawDefinition:r,structureId:o});if(!c)return{error:wt};if(!(!t||te(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>te(l)&&mt(l)>0)))return{error:V};let{seedAssignments:p}=nn({drawDefinition:r,structure:c}),m=p?.map(l=>l.seedNumber),d=p?.find(l=>l.participantId===n);if(d){let l=typeof i=="string"?i.includes("-")&&i.split("-").map(f=>parseInt(f)).join("-")||parseInt(i)>0&&parseInt(i)||"":i&&i>0&&i||"";d.seedValue=l}else{let f={seedNumber:Math.max(0,...m||[])+1,participantId:n};i&&(f.seedValue=i),c.seedAssignments||(c.seedAssignments=[]),c.seedAssignments.push(f)}return Kh({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...C}}function OS({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{structure:r}=at({drawDefinition:t,structureId:e}),n=(t?.links||[]).filter(i=>i.source?.structureId===e).map(i=>i.target?.structureId);return{playoffStructures:(t?.structures||[]).filter(i=>n.includes(i.structureId)),structure:r}}function Sg({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:Ot};let a={},c=[];for(let u of i.drawDefinitions||[]){let{structures:p,stageStructures:m}=In({withStageGrouping:t,stageSequences:e,drawDefinition:u,stageSequence:r,roundTarget:n,stages:o,stage:s});if(c.push(...p),m)for(let d of Object.keys(m))a[d]||(a[d]=[]),a[d].push(...m[d])}return{structures:c,stageStructures:a}}function _S({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:q};let a={},c=[];for(let u of e.events||[]){let{structures:p,stageStructures:m}=Sg({withStageGrouping:t,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,event:u,stage:s});if(p&&c.push(...p),m)for(let d of Object.keys(m))a[d]||(a[d]=[]),a[d].push(...m[d])}return{structures:c,stageStructures:a}}function ai(t){if(!t?.drawDefinition)return!1;let e=Tu(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e||{};return r&&(n=n?.filter(({matchUpType:a})=>a===Yt),o=o?.filter(({matchUpType:a})=>a===Yt),i=i?.filter(({matchUpType:a})=>a===Yt)),!!(n?.length&&!o?.length&&!i?.length)}function xS(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:Z};let{playoffStructures:n}=OS({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&Qr.includes(c.entryStatus))?.length??0,i=0;return(n||[]).reduce((c,u)=>!!((bt({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}function wS({significantCharacters:t,accessors:e=[],value:r}){let n=[],o=e[0];if(r?.[o]){let s=e.slice(1);if(Array.isArray(r[o]))r[o].forEach(c=>{let u=wS({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=wS({accessors:s,significantCharacters:t,value:r});n.push(...a)}else i({value:r})}function i({value:s}){if(s&&["string","number"].includes(typeof s)){let a=t?s.slice(0,t):s;n.push(a)}}return n}function Uv({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:kI};if(!Array.isArray(n))return{error:Ka};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=AP({policyAttributes:e,idCollections:r,participants:n,participant:s});a&&a.forEach(c=>{o[c]||(o[c]=[]),o[c].includes(i)||o[c].push(i)})}),o}function AP({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:kI};if(!n)return{error:Li};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(...wS({significantCharacters:p,value:n,accessors:m}))}else if(a){let m=s?.includeIds,d=(e?.[a]||[]).filter(l=>!m||m.includes(l));d?.length&&r?.length&&d.forEach(l=>{let f=r.find(g=>g.participantId===l);if(f?.individualParticipantIds?.includes(n.participantId)){let g=f?.participantId;o.push(g)}})}else c&&Object.keys(c).forEach(m=>{c[m].includes(n.participantId)&&o.push(m)})}),{values:ut(o)}}function EP({candidatePositionAssignments:t,participantsWithGroupings:e,policyAttributes:r,idCollections:n}){let o=Object.assign({},...e.map(i=>({[i.participantId]:i})));return t.map(i=>{let s=o[i.participantId],{values:a}=AP({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function Dv({participantIdGroups:t,positionAssignments:e,groupsToAvoid:r}){return Object.assign({},...e.filter(n=>n?.participantId).map(n=>{let{drawPosition:o,participantId:i}=n,s=t?t[i]||[]:[],a=!!r.some(c=>s.includes(c));return{[o]:{participantGroups:s,includesGroupsToAvoid:a}}}))}function Nv(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=Dv(t);return r.map(s=>{let a=e.filter(m=>s.includes(m)),c=i(a),p=a.filter(m=>!c.includes(m)).filter(m=>{let d=Pv(m);return!n[d]?.includesGroupsToAvoid});return{unassigned:a,unpaired:c,pairedNoConflict:p}});function i(s){return s.filter(c=>!a(c));function a(c){let u=Pv(c);return!s.includes(u)}}}function Mv(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=Dv(t);return r.map(o=>{let i=e.filter(u=>o.includes(u)),s=i.length===o.length?i:[],a=o.filter(u=>n[u]?.includesGroupsToAvoid).length;return{unassigned:i,unpaired:s,pairedNoConflict:a?[]:i,conflictsCount:a}})}function Pv(t){return Number(t%2?t+1:t-1)}function Rv({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function Cv({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?Mv({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):Nv({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}));if(i){let a=s.map(p=>p.map(m=>m.unassigned).filter(m=>m?.length)).filter(p=>p?.length).sort((p,m)=>(m.length||0)-(p.length||0)),c=s.map(p=>p.map(m=>m.unpaired).filter(m=>m?.length)).filter(p=>p?.length),u=s.map(p=>p.map(m=>m.pairedNoConflict).filter(m=>m?.length)).filter(p=>p?.length).sort((p,m)=>(m.length||0)-(p.length||0));return{unassigned:a,unpaired:c,pairedNoConflict:u}}else{let a=s.map(p=>p.map(m=>m.unassigned).filter(m=>m?.length)).filter(p=>p?.length),c=s.map(p=>p.map(m=>m.unpaired).filter(m=>m?.length)).filter(p=>p?.length),u=s.map(p=>p.map(m=>m.pairedNoConflict).filter(m=>m?.length)).filter(p=>p?.length);return{unassigned:a,unpaired:c,pairedNoConflict:u}}}function LS({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function bv({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:r=!0,allGroups:n,groupKey:o}){let i=Object.assign({},...Object.keys(n).map(p=>[p,n[p].filter(m=>e.includes(m))]).filter(p=>p[1].length).map(([p,m])=>({[p]:m}))),s=Object.keys(i).reduce((p,m)=>i[m].length>p?i[m].length:p,0),a=Object.keys(i).filter(p=>i[p].length===s),c=r?yn(a):yn(Object.keys(i));return o=t&&i[o]?.length?o:c,{participantId:o&&i[o]?yn(i[o]):yn(e),groupKey:o}}function vv({drawPositionGroups:t,positionAssignments:e}){let r=Object.assign({},...e.map(n=>({[n.drawPosition]:n})));return t.map(n=>n.filter(Boolean).map(o=>r[o]).filter(Boolean).filter(o=>!o.participantId&&!o.bye).map(o=>o.drawPosition)).flat().filter(Boolean)}function Ov({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a}){let u=o.reduce((N,D)=>D.length>N?D.length:N,0)<=2,p=LS({positionAssignments:t,participantIds:e}),m=vv({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=bv({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=Rv({participantId:d,allGroups:s}),g=Cv({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:f,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:m}),{unassigned:I,unpaired:h,pairedNoConflict:S}=g,T=S?.length&&S[0],y=h?.length&&h[0],P=i&&T?T:y,U=i?y:T,A=P?.length&&P||U?.length&&U,E;if(A?.length){let N=Zr(A);E=Zr(N)}else{let N=Zr(I[0]);E=Zr(N)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:E}}function Ad({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=lg({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{Fe(s[a[0]].values||[],s[a[1]].values||[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{Fe(n[0]?.values||[],n[1]?.values||[])&&(r.push(n),n.conflict=!0)}),r}function _v({positionedParticipants:t,potentialDrawPositions:e,drawPositionGroups:r,avoidanceConflicts:n,isRoundRobin:o}){return n.map(i=>{let s=i.map(c=>c.drawPosition);return i.filter(c=>e.includes(c.drawPosition)).map(c=>{let p=e.filter(m=>!s?.includes(m)).filter(m=>{let d=r.find(T=>T.includes(m)).find(T=>T!==m),l=t.find(T=>T.drawPosition===d),g=Ad({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=Ad({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function UP(t){let{initialPositionAssignments:e,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:o,drawPositionGroups:i,policyAttributes:s,idCollections:a,allGroups:c}=t,u=[],p,m=Math.min(...(i||[]).map(T=>T?.length).filter(Boolean)),d=m>2,l=J(e,!1,!0).filter(T=>!T.qualifier),f=e.filter(T=>!T.participantId&&(!T.bye||o?.includes(T.drawPosition))).map(T=>T.drawPosition);tt(0,n).forEach(()=>{let{newGroupKey:T,selectedParticipantId:y,targetDrawPosition:P}=Ov({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(U=>{U.drawPosition===P&&(U.participantId=y)})});let g=EP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ee(g,m),h=Ad({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=_v({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let y=qk({candidatePositionAssignments:l,swapOptions:T});y.error&&console.log({result:y}),g=EP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ee(g,m),h=Ad({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let y=wI;u.push(y)}if(T.qualifier&&T.participantId){let y=wI;u.push(y)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function qk({candidatePositionAssignments:t,swapOptions:e}){let r=Zr(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=Zr(r.possibleDrawPositions),i=t.find(u=>u.drawPosition===n),s=t.find(u=>u.drawPosition===o)??{},a={participantId:s?.participantId,qualifier:s?.qualifier,bye:s?.bye},c={participantId:i.participantId,qualifier:i.qualifier,bye:i.bye};return Object.assign(i,a),Object.assign(s,c),{...C}}function xv({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unseededByePositions:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:p,drawSize:m,event:d}){if(!p)return{error:XA};let{candidatesCount:l=1,policyAttributes:f,targetDivisions:g}=p,{roundsToSeparate:I}=p,h="randomUnseededSeparation",{structure:S}=at({drawDefinition:i,structureId:u}),{matchUps:T}=Pt({provisionalPositioning:t,matchUpsMap:c,structure:S,event:d});if(g&&On(g)&&!I){let k=cC(g)||0,H=T.reduce((W,Y)=>Y.roundNumber>W?Y.roundNumber:W,0);I=H<k?1:H-k+1}let{positionAssignments:y}=ye({structure:S}),P=lu({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,U=y?.filter(k=>!k.participantId),A=y?.map(k=>k.drawPosition),E=S?.structureType===Ge,N=E?{structure:S,matchUps:T,allDrawPositions:A,roundsToSeparate:I}:{matchUps:T,allDrawPositions:A,roundsToSeparate:I},{drawPositionGroups:D,drawPositionChunks:M}=E?$k(N):Kk(N),R={groupParticipants:a.filter(k=>k.participantType===zr).map(k=>k.participantId),teamParticipants:a.filter(k=>k.participantType===Ft).map(k=>k.participantId),pairParticipants:a.filter(k=>k.participantType===ft).map(k=>k.participantId)},b=Uv({targetParticipantIds:e,policyAttributes:f,idCollections:R,participants:a});if(b.error)return x({result:b,stack:h});let v=Object.assign({},...e.map(k=>{let H=Object.keys(b).filter(W=>(b[W]??[]).includes(k));return{[k]:H}})),O=LS({participantIds:e,positionAssignments:y});if(O.length>(U?.length||0))return{error:Jl};let _,F=O.length,w=tt(0,l).map(()=>UP({initialPositionAssignments:y,participantsWithGroupings:P,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));if(_=w.reduce((k,H)=>!k||(H.conflicts||0)<(k.conflicts||0)?H:k,void 0),!_||_.conflicts){let k=tt(0,l).map(()=>UP({initialPositionAssignments:y,participantsWithGroupings:P,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));_=w.concat(...k).filter(W=>!W.errors?.length).reduce((W,Y)=>!W||(Y.conflicts||0)<(W.conflicts||0)?Y:W,void 0)}if(!_)return{error:Xu};let L=(bt({structure:S})?.positionAssignments??[]).filter(k=>k.participantId).map(k=>k.participantId),G=_.positionAssignments.filter(k=>!L.includes(k.participantId));for(let k of G)if(k.bye){let H=Hr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...k});if(H.error)return x({result:H,stack:h})}else if(k.participantId){let H=Gn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...k});if(H.error)return x({result:H,stack:h,context:{assignment:k}})}return{...C}}function $k(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function Kk({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(le),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=tt(a===2?1:2,a).filter(d=>d===Tm(d)),m=u.slice(0,e||u.length).reverse().map(d=>Ee(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function wv({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:r,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,structure:p,drawSize:m,event:d}){let l="positionUnseededParticipants";p||({structure:p}=at({drawDefinition:i,structureId:u})),u||({structureId:u}=p);let{positionAssignments:f}=ye({structure:p}),{seedAssignments:g}=nn({provisionalPositioning:t,drawDefinition:i,structure:p}),I=g?.map(M=>M.participantId).filter(Boolean),{stage:h,stageSequence:S}=p,T=h===ct?lt({element:p,name:Mn})?.extension?.value:void 0,P=Ui({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:ni,structureId:u,roundTarget:T,stage:h}),A=P.filter(M=>!I?.includes(M.participantId)).map(M=>M.participantId),E=f?.filter(M=>!M.participantId&&!M.bye&&!M.qualifier).map(M=>M.drawPosition);if(!n&&A.length>(E?.length||0))return x({result:{error:Jl},context:{unseededParticipantsCount:A.length,unfilledDrawPositionsCount:E?.length},stack:l});let{appliedPolicies:N}=yt({tournamentRecord:o,drawDefinition:i,event:d}),D=N?.[nu];if(p.stage===fe){let M=P.reduce((R,b)=>(R[b.groupingValue]||(R[b.groupingValue]=[]),R[b.groupingValue].push(b.participantId),R),{});Object.keys(M).length&&(D||(D={policyName:"Playoff Avoidance"}),D.policyAttributes||(D.policyAttributes=[]),D.policyAttributes.push({groupings:M}))}return D&&a?xv({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:D,drawSize:m,entries:P}):zk({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unfilledDrawPositions:E,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d})}function zk({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unfilledDrawPositions:n,multipleStructures:o,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,matchUpsMap:c,structureId:u,drawSize:p,event:m}){let d=p>2?hr(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=Gn({provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,participantId:l,drawPosition:f,matchUpsMap:c,structureId:u,event:m});if(g?.error&&console.log("!!!!!",{result:g}),g?.error)return x({result:g,stack:"randomUnseededDistribution"})}}return{...C}}function Lv(t){let e=t.structure??at(t).structure,r="positionQualifiers",n=[];if(e.stage===qe)return x({result:{error:_i},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=Qk(t);for(let a of Object.keys(o)){let c=i?.filter(u=>s[a].includes(u.drawPosition)&&!u.participantId&&!u.qualifier&&!u.bye).map(u=>u.drawPosition);if(o[a]>(c||0))return x({result:{error:gE},context:{unfilledDrawPositions:c},stack:r});tt(0,o[a]).forEach(()=>{let u=Zr(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...C,qualifierDrawPositions:n}}function Qk({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=at({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:n}=ye({structure:e}),{stage:o,stageSequence:i}=e,{qualifiersCount:s,roundQualifiersCounts:a}=Is({drawDefinition:t,stageSequence:i,structureId:r,stage:o}),u=(a?Object.keys(a):[]).map(h=>mt(h)),{matchUps:p}=Pt({structure:e}),{roundProfile:m}=Ke({matchUps:p}),d=Object.assign({},...u.filter(h=>m?.[h]).map(h=>({[h]:m?.[h]?.drawPositions?.filter(Boolean)??[]}))),l=n?.filter(h=>h.qualifier).map(h=>h.drawPosition),f=s-(l?.length??0),g=l?.length;return{unplacedRoundQualifierCounts:Object.assign({},...u.map(h=>{let S=n?.filter(T=>T.qualifier&&d[h]?.drawPositions?.includes(T.drawPosition)).map(T=>T.drawPosition);return{[h]:(a?.[h]??0)-(S?.length??0)}})),unplacedQualifiersCount:f,placedQualifiersCount:g,roundQualifiersCounts:a,positionAssignments:n,roundDrawPositions:d,qualifiersCount:s}}function PP({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,groupsCount:u,structureId:p,matchUpsMap:m,structure:d,event:l}){let f=[],g=[],I=0;if(d||({structure:d}=at({drawDefinition:i,structureId:p})),p||(p=d?.structureId),n||(n=yt({drawDefinition:i}).appliedPolicies),!o){let h=d&&Ts({provisionalPositioning:t,appliedPolicies:n,drawDefinition:i,seedingProfile:s,structure:d});h?.error&&g.push(h.error),o=h?.validSeedBlocks}return u=u??o?.length??0,tt(0,u).forEach(()=>{if(I<(u||0)){let h=Xk({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,structureId:p,matchUpsMap:m,event:l});h?.success&&(I++,f.push(...h.seedPositions??[])),h.error&&g.push({seedPositionError:h.error})}}),g.length?{error:g}:{...C,seedPositions:f}}function Xk({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,participants:s,structureId:a,matchUpsMap:c,event:u}){let{unplacedSeedParticipantIds:p,unfilledPositions:m}=DS({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,event:u}),{appliedPolicies:d}=yt({drawDefinition:n}),{avoidance:l}=d??{};l&&s&&p?.length>2;let f=[];for(let g of p){let I=m.pop();if(!I)return{error:Cs};f.push(I);let h=Gn({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,participantId:g,seedBlockInfo:i,drawPosition:I,matchUpsMap:c,structureId:a,event:u});if(!h.success)return h}return{...C,seedPositions:f}}function Fv({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=ye({structure:r}),{seedAssignments:o}=nn({provisionalPositioning:t,drawDefinition:e,structure:r}),i=Object.assign({},...(o||[]).filter(s=>s.participantId).map(s=>({[s.participantId]:s})));return n?.map(s=>i[s.participantId]?{...s,seedNumber:i[s.participantId].seedNumber,seedValue:i[s.participantId].seedValue}:"").filter(Boolean)}function kv({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:r}){let n=[];e.forEach(i=>{if(r-n.length>i.drawPositions.length)n.push(...i.drawPositions);else{let a=DP(Ee(i.drawPositions,2)),c,u=t[n.length];for(;c=Tg(a,u);)n.push(c),u=t[n.length]}});let o=n.map(i=>Array.isArray(i)?hr(i):i).flat(1/0);return DI(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function Tg(t,e){if(Array.isArray(t)&&t.length!==2)return t.pop();if(!Array.isArray(t[0]))return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(Math.random())?t.pop():t.shift();let r=t[0].flat(1/0).length,n=t[1].flat(1/0).length;if(r===n){let o=t[0].flat(1/0).includes(e)?t[0]:t[1];return Tg(e?o:t[Math.round(Math.random())],e)}return r<n?Tg(t[1],e):Tg(t[0],e)}function DP(t){let e=Math.floor(t.length/2);return t.length>2?[DP(t.slice(0,e)),DP(t.slice(e))]:t}function Vv({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=Ts({provisionalPositioning:t,appliedPolicies:r,drawDefinition:n,seedingProfile:o,structure:a}));let{isFeedIn:c,isLuckyStructure:u,isContainer:p}=i,{validSeedBlocks:m}=i;r?.seeding?.containerByesIgnoreSeeding&&(m=[]);let d=Fv({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=ut([].concat(...e.map(P=>P.drawPositions))),f=d.filter(P=>l.includes(P.drawPosition)),g=(P,U)=>hc(P.seedValue)-hc(U.seedValue),h=m.reduce((P,U)=>{let A=f.filter(E=>U.drawPositions?.includes(E.drawPosition)).sort(g);return P.concat(...A)},[]).map(P=>P.drawPosition),S=kv({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=Gv({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),y=Gv({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function Gv({orderedSeedDrawPositions:t,relevantMatchUps:e}){let n=e.map(i=>i.drawPositions).map(i=>i?.sort((s,a)=>s-a)).filter(i=>i?.[0]+1===i?.[1]);return t.map(i=>n.find(s=>s?.includes(i))).filter(Boolean).map(i=>i?.reduce((s,a)=>t.includes(a)?s:a,void 0)).filter(Boolean)}function Bv({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:r,appliedPolicies:n,drawDefinition:o,seedLimit:i,structure:s,isFeedIn:a}){let c=n?.seeding?.seedingProfile,u=s.stage===ct,{positionAssignments:p}=ye({structure:s}),m=p?.filter(O=>O.participantId).map(O=>O.drawPosition),d={isCollectionMatchUp:!1},{matchUps:l,roundMatchUps:f}=Pt({provisionalPositioning:t,matchUpFilters:d,structure:s}),g=f?.[1]||[],I=s.structureType===Ge?l:g,h=ut([].concat(...I.map(O=>O.drawPositions))),S=Math.min(...h)-1,T=m?.filter(O=>h.includes(O)),y=O=>{let _=Math.ceil(O.length/2),F=[O.slice(0,_),O.slice(_)],w=F.map(B=>[].concat(...B.flat(1/0)).length),L=Math.min(...w.flat(1/0)),G=Math.max(...w.flat(1/0)),k=w.indexOf(G),H=L!==G,W=hr(F),[Y,$]=!L||H?[F[k],F[1-k]]:[W[0],W[1]];return{greaterHalf:Y,lesserHalf:$}},P=O=>{let{greaterHalf:_,lesserHalf:F}=y(O),{greaterHalf:w,lesserHalf:L}=y(_),k=hr(w.flat(1/0)).pop(),H=w.flat().filter(Y=>Y!==k);return{newlyFilteredChunks:[...F,...L,H],drawPosition:k}},U=O=>!e.includes(O),A=O=>!T?.includes(O),E=O=>{let F=Ee(O.sort(le),Math.ceil(O.length/4)).map(G=>G.filter(A)),w=[].concat(...F.flat(1/0)).length,L=[];for(let G=0;G<w;G++){let{newlyFilteredChunks:k,drawPosition:H}=P(F);L.push(H),F=k}return L},{validSeedBlocks:N}=Ts({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),D=N?.map(O=>O.drawPositions?.map(_=>_+S)),M;if(a){let O=h.length,{seedBlocks:_}=gg({cluster:Op(c)===zc,participantsCount:O});M=_.map(w=>w.map(L=>L+S)).map(E).filter(w=>w.length)}else u?M=D?.map(O=>O.filter(A)):M=D?.map(E).filter(O=>O.length);let R=I.map(O=>O.drawPositions).map(O=>O?.sort((_,F)=>_-F)).filter(O=>O?.[0]+1===O?.[1]),b=O=>R.reduce((_,F)=>F.includes(O)?F.reduce((w,L)=>L!==O?L:w,void 0):_,void 0),v=M.map(O=>O.map(b)).flat(1/0).filter(A).filter(U).filter(Boolean);if(u&&!s.structures){let O=i%4,_=v.slice(0,O),F=f[s.roundLimit]?.length,w=Ee(v.slice(O),F).map(hr).flat();v=_.concat(w)}return{unseededByePositions:v}}function Hv({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=Pt({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]||[],u=n?.structureType===Ge,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=Ui({entryStatuses:Qr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=Is({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=ye({structure:n}),y=T?.map(D=>D.drawPosition),P=S?.filter(D=>D.bye).length,U=S?.filter(D=>D.bye).map(D=>D.drawPosition),A=p.map(D=>D.drawPositions).filter(D=>D?.reduce((M,R)=>!U?.includes(R)&&M,!0)).flat(1/0).filter(D=>y?.includes(D)),E=S?.length,N=E?E-h:0;return N>m&&n.stageSequence===1&&n.stage!==qe&&(N=m),{placedByes:P,byesCount:N,relevantMatchUps:p,placedByePositions:U,roundMatchUps:a,positionsToAvoidDoubleBye:A}}function NP({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,seedBlockInfo:o,seedingProfile:i,matchUpsMap:s,structureId:a,structure:c,seedLimit:u,seedsOnly:p,event:m}){c||({structure:c}=at({drawDefinition:n,structureId:a})),a||(a=c?.structureId);let d=!(c?.structures??c?.stage===ct),{byesCount:l,placedByes:f,relevantMatchUps:g}=Hv({provisionalPositioning:t,drawDefinition:n,matchUpsMap:s,structure:c,event:m}),I=l-(f||0);if(I<=0)return{...C};let{strictSeedOrderByePositions:h,blockSeedOrderByePositions:S,isLuckyStructure:T,isFeedIn:y}=Vv({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),P=c?.structureType&&[Ge,cp].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,U=d&&S?.length?S:h,{unseededByePositions:A}=Bv({provisionalPositioning:t,seedOrderByePositions:U,isLuckyStructure:T,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:y}),E=R=>R%2,N=(R,b)=>(R||[]).every(v=>E(v)?b!==v+1:b!==v-1),D=[].concat(...U);if(!p)for(;A.length;){let R=A.find(b=>N(D,b));R?(D.push(R),A=A.filter(b=>b!==R)):(D.push(...A),A=[])}P&&(D=hr(D),Pr({ignoreSeededByes:P})&&console.log({byePositions:D}));let M=D.slice(0,I);for(let R of M){let b=Hr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:R,matchUpsMap:s,structureId:a,structure:c,event:m});if(b?.error)return b}return{...C,unseededByePositions:A,byeDrawPositions:M}}function Tc(t){let{drawDefinition:e}=t,{applyPositioning:r=!0,provisionalPositioning:n,multipleStructures:o,placeByes:i=!0,tournamentRecord:s,placementGroup:a,seedingProfile:c,structureId:u,seedLimit:p,seedsOnly:m,drawType:d,drawSize:l,event:f}=t,g=[];r||(FE(),e=J(e,!1,!0));let I=_=>(r||cf(),x({result:_,stack:"automatedPositioning"})),h=_=>(r||cf(),_),S=at({drawDefinition:e,structureId:u});if(S.error)return I(S);let T=S.structure;if(!T)return{error:wt};let y=t.appliedPolicies||yt({drawDefinition:e,structure:T,event:f})?.appliedPolicies,{qualifiersCount:P}=Is({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,drawDefinition:e,structureId:u}),U=ni;if(!Ui({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,placementGroup:a,drawDefinition:e,entryStatuses:U,structureId:u})?.length&&!P)return h({...C});let E=t.matchUpsMap??De({drawDefinition:e}),N=t.inContextDrawMatchUps??ae({inContext:!0,drawDefinition:e,matchUpsMap:E})?.matchUps,D=[],M=Ts({provisionalPositioning:n,appliedPolicies:y,drawDefinition:e,seedingProfile:c,structure:T});if(M.error)return M;let{validSeedBlocks:R}=M;g.push({validSeedBlocks:R});let b=t.participants||(s?Gt({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]);if(Op(T.seedingProfile||c)===di){let _=i?NP({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:M,matchUpsMap:E,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(_?.error)return I(_);D=_.unseededByePositions,g.push({action:"positionByes",unseededByePositions:D});let F=T.seedingProfile?{positioning:T.seedingProfile}:c;if(_=PP({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:E,structure:T,event:f}),_.error)return I(_);g.push({seedPositions:_.seedPositions,action:"positionSeedBlocks"})}else{if(d!==Gi){let F=T.seedingProfile?{positioning:T.seedingProfile}:c,w=PP({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:E,structure:T,event:f});if(w.error)return I(w);g.push({action:"positionSeedBlocks",seedPositions:w.seedPositions})}let _=i?NP({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:M,matchUpsMap:E,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(_?.error)return I(_);D=_?.unseededByePositions,g.push({action:"positionByes",byeDrawPositions:_?.byeDrawPositions,unseededByePositions:D})}let v={};if(!m){let _=Lv({inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:E,structure:T});if(_.error||(_.conflicts&&(v.qualifierConflicts=_.conflicts),g.push({action:"positionQualifiers",qualifierDrawPositions:_.qualifierDrawPositions}),_=wv({provisionalPositioning:n,inContextDrawMatchUps:N,unseededByePositions:D,multipleStructures:o,tournamentRecord:s,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:E,structureId:u,structure:T,drawSize:l,event:f}),_.error))return I(_);_.conflicts&&(v.unseededConflicts=_.conflicts),g.push({action:"positionUnseededParticipants"})}let{positionAssignments:O}=bt({drawDefinition:e,structure:T});return vt({drawDefinition:e,structureIds:[u]}),r||cf(),{positionAssignments:O,conflicts:v,...C,positioningReport:g}}function Ks(t){let{applyPositioning:e=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,placeByes:a,seedsOnly:c}=t;if(!o)return{error:br};if(!ai({drawDefinition:o,structureId:s})&&!r)return{error:Fl};let p=OS({drawDefinition:o,structureId:s}).playoffStructures?.sort((l,f)=>xf(l)-xf(f)),m=[],d=[];if(p)for(let l of p){let{structureId:f}=l,g=Tc({structureId:f,provisionalPositioning:r,applyPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,placeByes:a,seedsOnly:c});if(g.error)return g;g.positionAssignments&&m.push({positionAssignments:g.positionAssignments,structureId:f}),g.positioningReport&&d.push(g.positioningReport)}return{...C,structurePositionAssignments:m,positioningReports:d}}function MP({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>It(r)))&&x({result:{error:V},context:{orderMap:e}}),t.structures||(t.structures=[]),t.structures.forEach(r=>{let n=e[r.structureId];n&&(r.structureOrder=n)}),t.structures.sort((r,n)=>Ha(r.structureOrder)-Ha(n.structureOrder)),{...C}):{error:Z}}function Pu({drawDefinition:t}){let e=t.structures??[],r=t.links??[],n=new Map,o=I=>{let h=n.get(I)||n.set(I,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&n.get(I);if(h&&!h?.stage){let S=e.find(T=>T.structureId===I);h.stage=S?.stage}return h},i={},s={},a=r.map(I=>{let h=I.source.structureId,S=I.target.structureId,T=o(h),y=o(S);return[li,En,up,di].includes(I.target.feedProfile)?(T?.targets.push(S),y?.sources.push(h)):I.target.feedProfile===ln&&(y?.drawSources.push(h),T?.drawTargets.push(S)),s[S]=s[S]||I.target.feedProfile===ln,i[S]=ut([...i[S]||[],h]).filter(Boolean),[I.source.structureId,I.target.structureId]});for(let I of n.keys()){let h=n.get(I);if(h){let S=h.targets??[];for(;S.length;){let T=S.pop(),y=T&&n[T];y?.targets?.length?S.push(...y.targets):y&&(h.rootStage=y.stage)}if(h.rootStage||(h.rootStage=h.stage),!h.targets?.length){let T=h.sources??[];for(;T.length;){let y=T.pop(),P=y&&n[y];if(P?.sources?.length){for(let U of P.sources)h.progeny?.includes(U)||h.progeny?.push(U);T.push(...P.sources)}}}}}let c=0;for(let I of n.keys()){let h=n.get(I);if(h&&h.rootStage===ct){let S=[h.drawTargets?.[0]],T=0;for(;S.length;){T+=1;let y=S.pop(),P=y?n.get(y):void 0;P?.drawTargets?.length&&S.push(P.drawTargets[0])}h.distanceFromMain=T,T>c&&(c=T)}}let u=a.length;tt(0,Math.ceil(u/2)).forEach(()=>{a=tt(0,u).map(I=>{let h=a[I],S=a.reduce((T,y)=>Fe(h,y)?T.concat(...y):T,[])||[];return ut(h.concat(...S))})});let p=a[0],m=(I,h)=>qt(I,h).length===I.length,d=a.slice(1).reduce((I,h)=>I&&m(h,p),!0),l=[p].filter(Boolean),f=[p].filter(Boolean);e.forEach(I=>{let{structureId:h,stage:S}=I;l.find(y=>y.includes(h))||(l.push([h]),S!==$e&&f.push([h]))});let g=d&&f.length===1;return!r?.length&&e.length===1&&o(e[0].structureId),{structureProfiles:Object.fromEntries(n),allStructuresLinked:g,maxQualifyingDepth:c,sourceStructureIds:i,hasDrawFeedProfile:s,structureGroups:l}}function FS({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=Pu({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...C}}function yg(t){let e=et(t,[{[se]:!0,[Ve]:!0}]);if(e.error)return e;let{tournamentRecord:r,drawDefinition:n,structure:o,link:i}=t;return Jk({tournamentId:r.tournamentId,drawDefinition:n,structure:o,link:i})}function Jk(t){let e=et(t,[{[Ve]:!0,[dp]:!0},{link:!0,[He]:Kr,[RA]:Vl}]);if(e.error)return e;let{drawDefinition:r,tournamentId:n,structure:o,eventId:i,link:s}=t,a=s.target.structureId,c=at({drawDefinition:r,structureId:a});if(c.error)return x({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:c});r.structures||(r.structures=[]),r.links||(r.links=[]),r.structures.push(o),r.links.push(s),FS({drawDefinition:r});let u=Pt({structure:o})?.matchUps||[];return Co({drawDefinition:r,tournamentId:n,matchUps:u,eventId:i}),vt({drawDefinition:r,structureIds:[o.structureId]}),{...C}}function RP({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:V};if(!t)return{error:Z};let r=Object.assign({},...e.map(n=>{if(!ht(n))return;let{structureId:o,structureName:i}=n||{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:it};for(let n of t.structures||[]){let o=r[n.structureId];if(o&&(n.structureName=o),n.structures)for(let i of n.structures){let s=r[i.structureId];s&&(i.structureName=s)}}return{...C}}function Ag({drawDefinition:t,timeItem:e}){if(!t)return{error:br};if(!e)return{error:ef};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:tf};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),ya({drawDefinition:t}),{...C}}function CP(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=et(t,[{drawDefinition:!0,structureId:!0}]);if(i.error)return i;let s=r.structures??[],a=s.find(h=>h.structureId===n);if(!a)return{error:wt};let c=s.find(({stage:h,stageSequence:S})=>h===rt&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===ct).map(Br("structureId"));if(u&&!p.length)return{error:CA};let m=p.includes(n),d=Zk({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=eG({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=rG({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(tG({removedMatchUpIds:g,drawDefinition:r}),u){let h=(c.matchUps??[])?.map(Br("matchUpId"));g.push(...h),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&FS({drawDefinition:r}),Rn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),vt({drawDefinition:r,eventId:o?.eventId}),{...C,removedMatchUpIds:g,removedStructureIds:I}}function Zk({isQualifyingStructure:t,tournamentRecord:e,drawDefinition:r,structureId:n,structure:o,event:i,force:s}){let a=[n];if(t){let p=d=>r.links?.find(l=>l.target.structureId===d),m=p(n)?.source.structureId;for(;m;)a.push(m),m=p(m)?.source.structureId}if(ae({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>Se({score:p}))){let p=yt({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[tn]?.allowDeletionWithScoresPresent?.structures))return{error:ep}}return{...C}}function tG({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=ae({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function eG({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Br("structureId")),c=d=>o.links?.map(l=>l.source.structureId===d&&l.target.structureId!==n?.structureId&&l.target.structureId).filter(Boolean)??[],u=d=>o.links?.map(l=>t.includes(l.source.structureId)&&l.target.structureId===d&&l.source.structureId).filter(Boolean)??[],p=new Map;return a.forEach(d=>p.set(d,e?u(d):c(d))),{structureIdsToRemove:r?p.get(i):[i],relatedStructureIdsMap:p}}function rG({relatedStructureIdsMap:t,qualifyingStructureIds:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureIdsToRemove:i,structureId:s}){let a=[],c=[];for(;i?.length;){let u=i.pop();c.push(...iG({idBeingRemoved:u,drawDefinition:o}));let p=oG({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=nG({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function nG({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function oG({qualifyingStructureIds:t,isMainStageSequence1:e,idBeingRemoved:r,drawDefinition:n,structureId:o}){let i=[];return n.links=n.links?.filter(s=>s.source.structureId!==r&&s.target.structureId!==r)??[],(!e||e&&t.length||r!==o)&&(n.structures=(n.structures??[]).filter(s=>(r&&r===s.structureId&&i.push(r),s.structureId!==r))),{removedStructureIds:i}}function iG({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=at({structureId:t,drawDefinition:e}),n=Pt({structure:r}).matchUps;return Km(n)}function _p({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:Z};if(!tg({drawDefinition:e,stage:n}))return{error:_i};let o=Mb({drawDefinition:e,stage:n}),{qualifiersCount:i}=Is({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:xI};let{entryProfile:a}=Kf({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return vt({drawDefinition:e}),{...C,entryProfile:a}}function kS({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?tg({drawDefinition:e,stage:r})?r!==rt?{error:xI,info:"qualifiersCount can only be set for main stage"}:(Kf({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),vt({drawDefinition:e}),{...C}):{error:_i}:{error:Z}}function Wv({drawDefinition:t,drawSize:e}){if(!t)return{error:Z};let r=_p({stage:$e,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(vt({drawDefinition:t}),{...C})}function bP(t){return Wv(t)}function vP({tournamentRecord:t,drawDefinition:e,event:r,structureId:n}){if(!e)return{error:Z};let o=e.structures?.find(s=>s.stage===ct&&s.structureId===n);if(!o)return{error:wt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Rn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),vt({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}var jv="qualifierDrawPositionAssignment",Yv="withdrawParticipantAtDrawPosition",qv="alternateDrawPositionAssignment",$v="luckyLoserDrawPositionAssignment",OP="removeDrawPositionAssignment",GS="swapDrawPositionAssignments",Kv="modifyPairAssignment",zv="adHocPositionSwap",Qv="modifyParticipantOtherName",_P="assignDrawPosition",Xv="removeSeededParticipant",Jv="assignDrawPositionBye",Zv="modifySeedAssignment",VS="addPenalty",Eg="MODIFY_PAIR",xp="QUALIFIER",Ug="ALTERNATE",Pg="WITHDRAW",ys="ASSIGN",BS="REMOVE",Dg="LUCKY",wp="REMOVE_SEED",Lp="SWAP",Du="NICKNAME",zs="SEED_VALUE",Qs="PENALTY",Ed="BYE",tO={MODIFY_PAIR_ASSIGNMENT:Eg,QUALIFYING_PARTICIPANT:xp,ALTERNATE_PARTICIPANT:Ug,WITHDRAW_PARTICIPANT:Pg,ASSIGN_PARTICIPANT:ys,LUCKY_PARTICIPANT:Dg,REMOVE_ASSIGNMENT:BS,SWAP_PARTICIPANTS:Lp,ADD_NICKNAME:Du,REMOVE_SEED:wp,ADD_PENALTY:Qs,ASSIGN_BYE:Ed,SEED_VALUE:zs};function xP({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:Z};if(!n)return{error:Ur};if(r?.length!==2)return{error:V,drawPositions:r};let i=De({drawDefinition:e}),{matchUps:s}=ae({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=at({drawDefinition:e,structureId:n});if(!a)return{error:wt};let c=yt({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===Ge?u=cG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=sG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(Xm({structure:a,drawPositions:r}),uu({appliedPolicies:c,drawDefinition:e,positionAction:{name:GS,drawPositions:r,structureId:n}}),bo({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===vr){let m=Pt({matchUpFilters:{matchUpTypes:[xr]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),d=Pt({matchUpFilters:{matchUpTypes:[xr]},structure:a}).matchUps;m.forEach(l=>{(l.sides||[]).forEach(f=>{let g=f?.drawPosition;if(r.includes(g)){let I=f.participantId,h=d.find(({matchUpId:T})=>T===l.matchUpId),S=l?.sides?.reduce((T,y,P)=>y.drawPosition===g?P:T,void 0);Id({inContextTargetMatchUp:l,drawPositionSideIndex:S,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:h,event:o})}})})}return vt({drawDefinition:e,structureIds:[n]}),{...C}}function sG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i?.positionAssignments.filter(p=>n?.includes(p.drawPosition));if(!a)return{error:V,structure:i,info:"Missing positionAssignments"};if(a.filter(({bye:p})=>p).length===2)return{...C};if(a.filter(({qualifier:p})=>p).length===2)return{...C};let c=a.some(({qualifier:p})=>p);return a.some(({bye:p})=>p)&&!c?eO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):aG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function eO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:n,matchUpsMap:o,structure:i,event:s}){let a=n.find(({bye:f})=>f),c=n.find(({participantId:f})=>f),u=a.drawPosition,{participantId:p,drawPosition:m}=c,{structureId:d}=i,l=Uu({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=Uu({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Hr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=Gn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...C}}function aG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:n,matchUpsMap:o,structure:i,event:s}){let a=Object.assign({},...n.map((c,u)=>{let{drawPosition:p}=c,m={...n[1-u],drawPosition:p};return{[p]:m}}));return i.positionAssignments=i.positionAssignments.map(c=>a[c.drawPosition]||c),hg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...C}}function cG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i.structures?.reduce((p,m)=>{let d=m?.positionAssignments.filter(l=>n?.includes(l.drawPosition));return d&&p.push(...d),p},[]);if(a.filter(({bye:p})=>p).length===2)return{...C};if(a.filter(({qualifier:p})=>p).length===2)return{...C};hg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:a,structure:i,event:s});let c=a.some(({qualifier:p})=>p);if(a.some(({bye:p})=>p)&&!c)eO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s});else{let p=J(a,!1,!0);a.forEach((m,d)=>{let l=p[1-d].participantId;m.qualifier=p[1-d].qualifier,m.participantId=l})}return{...C}}function wP({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:q};if(!e)return{error:Z};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![rt,ct].includes(i.stage)||i.stage===rt&&i.stageSequence!==1?x({result:{error:Xo},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...C}:x({info:"participant not seeded",result:{error:Ce},context:{participantId:r}}):x({result:{error:wt},stack:o})}function Ra({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=fo}){return!n||!o?{error:Ur}:{link:ot({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:ln,roundNumber:t,structureId:o}})}}function Ud({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Dt()}function Fp({includeMatchUpType:t,matchUpType:e,roundNumber:r,matchUps:n,idPrefix:o,isMock:i,uuids:s,nodes:a}){let c=0,u=[],p=1,m=r-1,d=a?.length;for(;c<(d||0);){let l=a?.[c],f=a?.[c+1];m&&(l.roundNumber=m),f&&m&&(f.roundNumber=m);let g=Ud({roundPosition:p,roundNumber:r,idPrefix:o,uuids:s}),I={roundPosition:p,children:[l,f],matchUpId:g};u.push(I);let h={drawPositions:I.children.map(S=>S?.drawPosition).filter(Boolean),matchUpStatus:Jt,matchUpId:I.matchUpId,roundPosition:p,roundNumber:r};t&&e&&(h.matchUpType=e),i&&(h.isMock=!0),n.push(h),p++,c+=2}return{roundNodes:u,matchUps:n}}function bn({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:r,qualifyingPositions:n,matchUpType:o,roundLimit:i,idPrefix:s,drawSize:a,isMock:c,uuids:u}){if(isNaN(a)||a<2||n&&a<=n)return{matchUps:[],roundsCount:0};if(n&&(!On(a)||a%n)){let I=n;for(;I<a;)I=2*I;a=I}let p=n&&!(a%2)&&(!isNaN(n)||r&&!isNaN(r))&&(a/n===Math.round(a/n)||r&&a/r===Math.round(a/r));if(!On(a)&&!p)return{matchUps:[],roundsCount:0};let m=tt(1,a+1).map(I=>({drawPosition:I})),d,l=[],f=1;for({roundNodes:d,matchUps:l}=Fp({matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,nodes:m,uuids:u}),f++,i=i??r;d.length>1;)n&&d.length===n&&(i=f-1),{roundNodes:d,matchUps:l}=Fp({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=Ua({finishingPositionOffset:t,finishingPositionLimit:e,roundsCount:g,roundLimit:i,matchUps:l}),i?l=l.filter(I=>i&&(I.roundNumber??0)<=i):i=f-1,{drawSize:a,matchUps:l,roundsCount:g,roundLimit:i}}function Pd(t){let e="generateQualifyingStructure";if(!t.drawDefinition)return x({result:{error:Z},stack:e});if(t.drawSize&&!It(t.drawSize)||t.participantsCount&&!It(t.participantsCount)||t.qualifyingPositions&&!It(t.qualifyingPositions))return x({result:{error:V},stack:e});let r=t.drawSize??Sm(t.participantsCount),{qualifyingRoundNumber:n,qualifyingPositions:o,targetStructureId:i,structureOptions:s,appliedPolicies:a,drawDefinition:c,matchUpFormat:u,structureName:p,structureId:m,roundTarget:d,drawType:l,idPrefix:f,isMock:g,uuids:I}=t;if(!t.drawSize)return x({result:{error:qa},context:{drawSize:r},stack:e});if(o&&o>=t.drawSize)return x({result:{error:V},context:{drawSize:r,qualifyingPositions:o},stack:e});let h,S,T,y,P=0,U,A=1,{structureProfiles:E}=Pu({drawDefinition:c}),N=E[i];if(!N)return x({result:{error:wt},context:{targetStructureId:i},stack:e});let D=c.matchUpType,M=d?`${d}-`:"",R=N.stage===ct,b=a?.[ga]?.namingConventions?.pre??vb[ga]?.namingConventions?.pre,v=R&&b?`${b}-`:"",O=p??(M?`${v}${Qe(ct)} ${M}`:`${v}${Qe(ct)}`);if(l===Nn){let{maxRoundNumber:w,structures:L,groupCount:G}=Ma({structureName:p??O,structureId:m??I?.pop(),stage:ct,structureOptions:s,appliedPolicies:a,stageSequence:A,matchUpType:D,roundTarget:d,idPrefix:f,drawSize:r,isMock:g,uuids:I});P=G,h=w,T=L[0],U=[1]}else({drawSize:r,matchUps:y,roundLimit:h,roundsCount:S}=bn({qualifyingRoundNumber:n,qualifyingPositions:o,matchUpType:D,idPrefix:f,drawSize:r,isMock:g,uuids:I})),h||(h=S),T=Sn({structureName:p??O,structureId:m??I?.pop(),qualifyingRoundNumber:h,stage:ct,matchUpFormat:u,stageSequence:A,matchUpType:D,roundLimit:h,matchUps:y}),d&&At({extension:{name:Mn,value:d},element:T}),P=y?.filter(w=>w.roundNumber===h)?.length;let _=l===Nn?eo:fo,F=T&&h&&Ra({sourceStructureId:T.structureId,sourceRoundNumber:h,targetStructureId:i,finishingPositions:U,linkType:_})?.link;return{qualifyingDrawPositionsCount:r,qualifiersCount:P,...C,structure:T,link:F}}function LP(t){if(!t.tournamentRecord)return{error:q};let r=uG(t);return r.error,r}function uG(t){if(!t.drawDefinition)return{error:Z};if(!t.targetStructureId)return{error:Ur};let e=Pd(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:V}:yg({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function FP(t){let e=et(t,[{[Ve]:!0,[tu]:!0,[fn]:!0},{[nb]:!0,[tr]:m=>Number.isInteger(m)&&m>0},{[tr]:m=>Array.isArray(m)&&m.length===2&&m.every(Vt),[Fr]:wr,participantIds:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n,tournamentRecord:o,event:i}=t,{structure:s}=at({drawDefinition:r,structureId:n});if(!s)return{error:wt};if(!ur({structure:s}))return{error:Xo};let a=m=>m.sides?.map(d=>d.participantId).some(d=>t.participantIds.includes(d)),c=m=>m.roundNumber===t.roundNumber,u=m=>!Se(m),p=(s?.matchUps??[]).filter(c).filter(u).filter(a);if(p.length!==2)return{error:wr};for(let m of p){let d=m?.sides?.find(l=>t.participantIds.includes(l?.participantId));if(d){let l=t.participantIds.find(f=>f!==d?.participantId);d.participantId=l,gt({tournamentId:o?.tournamentId,eventId:i?.eventId,drawDefinition:r,matchUp:m})}}return vt({drawDefinition:r,structureIds:[n]}),{...C}}function rO({includeMatchUpType:t,drawPosition:e,roundNumber:r,matchUpType:n,idPrefix:o,matchUps:i,isMock:s,uuids:a,nodes:c,fed:u}){let p=c.length,m=e?e-p:void 0,d=tt(0,p).map(g=>m?m+g:void 0),l=[];for(let g=0;g<p;g++){let I=d.shift(),h={drawPosition:I,fed:u+1,feed:!0},S=c[g];S.roundNumber=r-1;let T=Ud({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:Jt,roundNumber:r,matchUpId:T};t&&(y.matchUpType=n),s&&(y.isMock=!0),i.push(y);let P={children:[S,h]};l.push(P)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function ci(t){let e=t.drawSize,{feedRoundsProfile:r,feedRounds:n=0,skipRounds:o=0,baseDrawSize:i}=t,{linkFedFinishingRoundNumbers:s,finishingPositionOffset:a,linkFedRoundNumbers:c,feedsFromFinal:u,isConsolation:p,matchUpType:m,idPrefix:d,isMock:l,uuids:f,fmlc:g}=t;i=i??F(e);let I=pG({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((w,L)=>w+L,0);else if(e){let w=e-i;r=I.filter(L=>L<=w?(w-=L,!0):!1),S=r.reduce((L,G)=>L+G,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((w,L)=>u&&!n||n&&L>=o+n||L<o?0:w),S=r.reduce((w,L)=>w+L,0),n=r.length;let T=[...I,...r].sort((w,L)=>L-w),y=T.length,U=[...(c??[]).map(w=>w-1),...(s??[]).map(w=>y-w)].map(w=>T[w]).reduce((w,L)=>w+L,0);S=S-U;let A=0,E=[],N,D=1,R=tt(0,i).map((w,L)=>({drawPosition:L+1+S})),b=S+1;for(let w of I){if({roundNodes:N,matchUps:E}=Fp({matchUpType:m,roundNumber:D,idPrefix:d,matchUps:E,isMock:l,nodes:R,uuids:f}),D++,r.includes(w)){let L=Tr(r)[w],G=tt(0,L),k=y+1-D,H=s?.includes(k)??c?.includes(D);G.forEach(()=>{({roundNodes:N,matchUps:E,drawPosition:b}=rO({drawPosition:!H&&b||void 0,nodes:N,matchUpType:m,roundNumber:D,idPrefix:d,matchUps:E,isMock:l,uuids:f,fed:A})),D++,A+=1})}R=N}y!==D-1&&console.log("ERROR");let v=i-S;E=Ua({finishingPositionOffset:p?v:a,positionsFed:S,roundsCount:y,matchUps:E,fmlc:g});let _=N?.length?N[0]:N;return _&&(_.roundNumber=D-1,_.matchUps=E),{draw:_,matchUps:E,roundsCount:y};function F(w){let L=Tm(w);return L>w?L/2:L}}function pG({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return tt(0,e).reverse().map(n=>Math.pow(2,n))}function yc(t){let{finishingPositionOffset:e=0,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,stageSequence:a=1,exitProfile:c="0",exitProfileLimit:u,roundOffsetLimit:p,roundOffset:m=0,drawDefinition:d,staggeredEntry:l,sequenceLimit:f,stage:g=rt,drawSize:I,idPrefix:h,isMock:S,uuids:T}=t;if(!(!s||!u||s?.[c])||I<2||f&&a>f)return{};let P=[],U=[],A=[],E=t.matchUpType??d?.matchUpType,N=e+1,D=e+I,M=`${N}-${D}`,R=s?.[c],b=n&&`${n} `||"",v=s?.[M]??o?.[M],O=t.structureName||v?.name||R?.name&&(r?`${b}${R?.name}`:R.name)||`${b}${M}`,_=v?.abbreviation??R?.abbreviation,F=t.structureId??R?.structureId??T?.pop(),w={idPrefix:h&&`${h}-${O}-RP`,finishingPositionOffset:e,matchUpType:E,drawSize:I,isMock:S,uuids:T},{matchUps:L}=l?ci(w):bn(w),G=Sn({structureAbbreviation:_,stageSequence:a,structureName:O,matchUpType:E,roundOffset:m,structureId:F,matchUps:L,stage:g});P.push(...L),U.push(G);let k=Math.ceil(Math.log(I)/Math.log(2)),H=p?Math.min(p-m,k):(!i||N<i)&&k||0;return I>2&&tt(1,H+1).forEach(Y=>W(Y)),{structureId:G.structureId,matchUps:P,structureName:O,structures:U,links:A,...C};function W(Y){let $=I/Math.pow(2,Y);if($<2)return;let B=I/Math.pow(2,Y)+e;if(i&&B+1>i)return;let{structures:K,structureId:X,matchUps:j,links:nt}=yc({finishingPositionOffset:B,exitProfile:`${c}-${Y}`,roundOffset:m+Y,stageSequence:a+1,drawSize:$,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:d,sequenceLimit:f,matchUpType:E,idPrefix:h,uuids:T,stage:g});if(G.structureId&&X){let z={linkType:ro,source:{roundNumber:Y,structureId:G.structureId},target:{roundNumber:1,feedProfile:En,structureId:X}};nt&&G&&nt.push(z),nt?.length&&A.push(...nt)}return K?.length&&U.push(...K),j?.length&&P.push(...j),{structureId:X,childLinks:nt,structures:U}}}function Dd({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=at({drawDefinition:t,structureId:r});if(n.error)return x({result:n});let{matchUps:o}=Pt({structure:n.structure,matchUpsMap:e});return{...Ke({matchUps:o}),matchUps:o,matchUpsMap:e}}function kP({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=Dd({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(nO(n?.[s]).forEach(c=>{t.forEach(u=>{mG({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function mG({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return tt(r,(n||r)+1).includes(t)}function nO(t){return[ut(t?.finishingPositionRange?.loser||[]),ut(t?.finishingPositionRange?.winner||[])]}function oO(t){return nO(t).map(e=>tt(e[0],e[1]&&e[1]+1||e[0]+1))}function Ac({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:V,context:{structureIds:e}};if(!t)return{error:Z};e=e??(t.structures??[]).filter(a=>a.stage!==ct).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=Dd({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(oO).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(le).flat();return{positionsNotPlayedOff:ut(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function HS({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){if(!r)return{error:Z};if(!n)return{error:Ur};if(!e)return{error:it,info:"missing playoffPositions"};let o=Ac({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=kP({finishingPositions:s,drawDefinition:r,structureId:n}),u=Object.values(a).reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>mt(S)).filter(S=>!t.includes(S)),p=kP({finishingPositions:i,drawDefinition:r,structureId:n}),m=p?Object.values(p):[],d=p?m.reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>mt(S)):[],l=u.filter(S=>!d.includes(S)).sort(le),{roundProfile:f}=Dd({drawDefinition:r,structureId:n}),g=l.map(S=>{let T=f?.[S].finishingPositionRange.loser,[y,P]=T??[0,0];return tt(y,(P||y)+1)}).flat().sort(le),{playoffRoundsRanges:I}=dG({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function dG({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=tt(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function Nu({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{matchUps:r,matchUpsMap:n}=or({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=Ac({drawDefinition:t,matchUpsMap:n}),{structures:s}=In({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==$e||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=lG({playoffPositions:o,drawDefinition:t,structure:u,matchUps:r}),{error:d,...l}=m;if(d)return m;c[p]={structureId:p,...l}}return e?{positionsPlayedOff:i,...c[e]}:{availablePlayoffProfiles:Object.values(c),availablePlayoffRounds:Object.values(c),positionsPlayedOff:i}}function lG({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=Ws({drawDefinition:e,structureId:o});if(r.structureType===Ge||r.structures){let l=bt({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:D})=>D?.finishingPositions||[])||[],h=tt(1,g+1).filter(D=>!I.includes(D)),S=n.find(D=>D.containerStructureId===o&&D.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:D})=>D.structureId),{positionsPlayedOff:y=[],positionsNotPlayedOff:P=[]}=Ac({structureIds:T,drawDefinition:e}),U=[...y,...P],A=tt(S[0],S[1]+1).filter(D=>!U.includes(D)),E=Ee(A,A.length/h.length),N=h.map((D,M)=>{let R=E[M],b=[Math.min(...R||[]),Math.max(...R||[])].join("-");return{finishingPosition:D,finishingPositions:R,finishingPositionRange:b}});return{positionsNotPlayedOff:A,playoffFinishingPositionRanges:N,finishingPositionsAvailable:h,finishingPositionsPlayedOff:I,positionsPlayedOff:y,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==_n).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===_n).map(l=>l.source?.roundNumber)||[],c=HS({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:e,structureId:o}),u=c?.playoffSourceRounds?[...c?.playoffSourceRounds||[]]:void 0,p=[...c?.playoffRoundsRanges||[]],{roundProfile:m,error:d}=c;for(let l of a){let f=i?.source.find(T=>T.source.roundNumber===l),g=f?.target.roundNumber,I=f?.target.structureId,h=n.filter(({roundNumber:T,structureId:y})=>y===I&&T===g),S=h.filter(({sides:T})=>T.find(y=>y.participantFed&&!y.participantId)).length;if(u&&S===h.length){u.push(l);let T=m?.[l]?.finishingPositionRange?.loser;if(T){let y=Math.min(...T),P=y+S,U=tt(y,P),A={finishingPositionRange:[y,P-1].join("-"),finishingPositions:U,roundNumber:l};p.push(A)}}}return u&&u.sort(le),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function iO({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:Z};if(!Vt(r)||!Array.isArray(t))return{error:V};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Nu({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function WS(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=rt,matchUpType:a,structureId:c,idPrefix:u,drawSize:p,isMock:m,uuids:d}=t,l={finishingPositionOffset:e,matchUpType:a,drawSize:p,idPrefix:u,isMock:m,uuids:d},{matchUps:f}=o?ci(l):bn(l),g=Sn({structureName:i||r?.["0"]?.name||Qe(rt),structureId:c||d?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],h=[];if(p>2){let S=p/2,{matchUps:T}=bn({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:m}),y=Qe(qe),P=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),U=Sn({structureName:P,matchUps:T,structureId:d?.pop(),stage:qe,stageSequence:1,matchUpType:a});I.push(U);let A={linkType:ro,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:En,structureId:U.structureId}};h.push(A)}return{...C,structures:I,links:h}}function jS({consolationStructure:t,roundOffset:e=0,mainStructure:r,roundsCount:n,feedPolicy:o,fmlc:i}){let a=t.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),c=o?.roundGroupedOrder||[],u=o?.roundFeedProfiles;return tt(1+e,n+1+e).map(p=>{let m=u?.[p-1]?u[p-1]:p%2&&En||li,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:ro,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),Pr()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=_n,l.target.feedProfile=En),a.includes(d)?l:void 0}).filter(Boolean)}function YS(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=rt,matchUpType:c,structureId:u,drawSize:p,idPrefix:m,isMock:d,uuids:l}=t,f={finishingPositionOffset:r,matchUpType:c,drawSize:p,idPrefix:m,isMock:d,uuids:l},{matchUps:g,roundsCount:I}=s?ci(f):bn(f),h=t.structureName??o?.["0"]?.name??Qe(rt),S=Ss({structureId:u||l?.pop(),structureName:h,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[S],y=[];if(p>2){let A=[0,2].slice(0,p/16).map((E,N)=>{let D=N+1,{consolationStructure:M}=fG({idPrefix:m&&`${m}-c${N}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:D,roundOffset:E,matchUpType:c,drawSize:p,isMock:d,index:N,uuids:l});T.push(M);let R=jS({consolationStructure:M,roundsCount:2,mainStructure:S,roundOffset:E});return{consolationStructure:M,links:R}}).map(E=>E.links).flat();if(y.push(...A),p>=4&&p<=16||p>32){let{matchUps:E}=bn({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),N=o?.["3-4"]?.name??Qe(fe),D=i?.[N]||N,M=e?`${e} ${D}`:D,R=Ss({structureId:l?.pop(),matchUps:E,stageSequence:2,stage:fe,structureName:M,matchUpType:c}),b={linkType:ro,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:R.structureId,feedProfile:En,roundNumber:1}};T.push(R),y.push(b)}}return{structures:T,links:y,...C}}function fG({playoffStructureNameBase:t,stageSequence:e=1,playoffAttributes:r,structureNameMap:n,roundOffset:o=0,matchUpType:i,structureId:s,idPrefix:a,drawSize:c,isMock:u,index:p,uuids:m}){let d=c/(2*Math.pow(2,o)),{matchUps:l,roundsCount:f}=ci({finishingPositionOffset:d,baseDrawSize:d,isConsolation:!0,feedRounds:1,matchUpType:i,idPrefix:a,isMock:u,uuids:m}),I=p===0&&r?.["0-1"]?.name||p===1&&r?.["0-3"]?.name||`${Qe(qe)} ${p+1}`,h=n?.[I]||I,S=t?`${t} ${h}`:h;return{consolationStructure:Ss({matchUps:l,stage:qe,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function Ec(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=rt,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,h=t.feedPolicy||t.policyDefinitions?.[nc]||t.appliedPolicies?.[nc],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?ci(S):bn(S),y=Sn({structureName:s||n?.["0"]?.name||Qe(rt),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),P=[y],U=[],A=l/2,{matchUps:E,roundsCount:N}=ci({finishingPositionOffset:A,idPrefix:d&&`${d}-c`,isConsolation:!0,feedsFromFinal:o,baseDrawSize:A,matchUpType:u,feedRounds:m,skipRounds:p,isMock:f,uuids:g,fmlc:I});if(l>2){let D=n?.["0-1"]?.name??Qe(qe),M=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${D}`:D,R=Sn({matchUps:E,structureId:g?.pop(),stage:qe,stageSequence:1,structureName:M,matchUpType:u});P.push(R);let b=jS({consolationStructure:R,mainStructure:y,roundsCount:N,feedPolicy:h,fmlc:I});U.push(...b)}return{...C,structures:P,links:U}}function $S({requireSequential:t=!0,playoffMatchUpFormat:e,playoffAttributes:r,sourceStructureId:n,policyDefinitions:o,stageSequence:i,drawDefinition:s,playoffGroups:a,matchUpType:c,feedPolicy:u,groupCount:p,idPrefix:m,isMock:d,uuids:l}){u=u||o?.[nc];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:y}=iO({structureId:n,drawDefinition:s,playoffGroups:a});if(T)return x({result:{error:T},stack:f});if(!(!y||a?.every(U=>{let{finishingPositions:A=[]}=U;if(!A.length)return!1;let E=[...A].sort(le).map((N,D)=>(A[D+1]||N)-N).every(N=>N<2);return(!t||E)&&A.every(N=>y[N])})))return x({context:{validFinishingPositions:Object.values(y)},result:{error:V},stack:f});for(let U of a){let A=U.finishingPositions,E=y&&A.map(F=>y[F]?.finishingPositions).flat(),N=p*A.length,D=es(N),M=D===2&&go||U.drawType||go;E&&(g=Math.min(...E)-1);let R=E&&`${Math.min(...E)}-${Math.max(...E)}`,b=U.structureName||R&&U.playoffAttributes?.[R]?.name||U.playoffAttributes?.["0"]?.name,O={...{addNameBaseToAttributeName:U.addNameBaseToAttributeName,playoffStructureNameBase:U.playoffStructureNameBase,finishingPositionNaming:U.finishingPositionNaming,finishingPositionLimit:U.finishingPositionLimit,structureId:U.structureId??l?.pop(),playoffAttributes:U.playoffAttributes,structureNameMap:U.structureNameMap,sequenceLimit:U.sequenceLimit,structureName:b},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:g,stage:fe,stageSequence:i,matchUpType:c,drawSize:D,isMock:d,uuids:l},_=({playoffStructures:F,playoffLinks:w})=>{let[L]=F,G=qS({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(G),S.push(...w),h.push(...F),I.push({structureId:L.structureId,finishingPositions:A}),g+=N};if(M===go){let{matchUps:F}=bn({finishingPositionLimit:g+N,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:D,isMock:d,uuids:l}),w=Sn({structureId:U.structureId??l?.pop(),matchUpFormat:e,stage:fe,structureName:b,stageSequence:i,matchUps:F});h.push(w);let L=qS({playoffStructureId:w.structureId,finishingPositions:A,sourceStructureId:n});S.push(L),g+=N,I.push({structureId:w.structureId,finishingPositions:A})}else if([Qc,Xc,fe].includes(M)){let F={playoffAttributes:U.playoffAttributes??r,playoffStructureNameBase:U.playoffStructureNameBase,structureId:U.structureId??l?.pop(),structureName:U.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:fe,roundOffset:0,stageSequence:i,drawSize:D,isMock:d,uuids:l};M===Qc?Object.assign(F,{playoffAttributes:U?.playoffAttributes??r??Ef,roundOffsetLimit:3}):M===Xc&&Object.assign(F,{playoffAttributes:U?.playoffAttributes??r??Uf,roundOffsetLimit:2});let w=yc(F);if(w.error)return w;if(w.links?.length&&S.push(...w.links),w.structures?.length&&h.push(...w.structures),h.sort(Ti),w.structureId){let L=qS({playoffStructureId:w.structureId,finishingPositions:A,sourceStructureId:n});S.push(L),I.push({structureId:w.structureId,finishingPositions:A})}g+=N}else if([Zc,mp,wm,xm,_m,Lm].includes(M)){let F=[l?.pop(),l?.pop()],w={playoffStructureNameBase:U.playoffStructureNameBase,structureId:U.structureId??l?.pop(),playoffAttributes:U.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,uuids:F,stage:fe,structureName:b,matchUpType:c,feedPolicy:u,drawSize:D,isMock:d},L={[Zc]:{fmlc:!0,feedRounds:1},[Lm]:{feedRounds:1},[wm]:{feedsFromFinal:3},[xm]:{feedsFromFinal:2},[_m]:{feedsFromFinal:1}};Object.assign(w,L[M]||{});let{structures:G,links:k}=Ec(w),[H]=G,W=qS({playoffStructureId:H.structureId,finishingPositions:A,sourceStructureId:n});S.push(W),S.push(...k),h.push(...G),I.push({structureId:H.structureId,finishingPositions:A}),g+=N}else if([Nn].includes(M)){let{structures:F,links:w}=Ma({...O,structureOptions:U.structureOptions||{groupSize:4}});_({playoffStructures:F,playoffLinks:w})}else if([pp].includes(M)){let{structures:F,links:w}=WS(O);_({playoffStructures:F,playoffLinks:w})}else if([JC].includes(M)){let{structures:F,links:w}=YS(O);_({playoffStructures:F,playoffLinks:w})}else if([$r].includes(M)){let F=Sn({structureId:U.structureId??l?.pop(),structureName:U.structureName,finishingPosition:td,stage:fe,stageSequence:i,matchUps:[]});_({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:h,links:S}}function qS({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:eo,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:ln,roundNumber:1}}}function Ca({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>Mu({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function Mu({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:r,matchUp:n,isMock:o,uuids:i}){let{matchUpCount:s,matchUpType:a,collectionId:c,processCodes:u}=e||{},p=r??s??0,m=d=>{if(!o&&!n?.isMock)return i?.pop()??Dt();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return tt(0,p).map(d=>{let l=t+d+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:m(d),matchUpStatus:Jt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function sO(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return x({result:{error:it},info:"playoffGroups required",stack:e});let{sourceStructureId:r,requireSequential:n,tournamentRecord:o,drawDefinition:i,playoffGroups:s,groupCount:a,groupSize:c,event:u}=t,p=$S({requireSequential:n,sourceStructureId:r,playoffGroups:s,groupCount:a,groupSize:c,...t});if(p.error)return x({result:p,stack:e});let{structures:m=[],links:d=[],finishingPositionTargets:l,positionRangeMap:f}=p,g=l?.map(({finishingPositions:E})=>E).flat().map(E=>f[E].finishingPositions).flat();i.structures.push(...m),i.links.push(...d);let{matchUps:I,matchUpsMap:h}=ae({inContext:!0,drawDefinition:i}),S=m.map(({structureId:E})=>E),T=I?.filter(({structureId:E})=>S.includes(E)).map(Ue),y=h?.drawMatchUps?.filter(({matchUpId:E})=>T?.includes(E));if(y?.length){let E=We({drawDefinition:i,event:u})?.tieFormat;E&&y.forEach(N=>{let{tieMatchUps:D}=Ca({isMock:t.isMock,tieFormat:E,matchUp:N});Object.assign(N,{tieMatchUps:D,matchUpType:xr})})}let{positionAssignments:P}=bt({structureId:r,drawDefinition:i}),U={};P?.forEach(E=>{let M=lt({element:E,name:Zo})?.extension?.value?.groupOrder;M&&(U[M]||(U[M]=[]),U[M].push(E.participantId))});let A=Ks({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return A.error&&A.error?.code!==Fl.code?x({result:A,stack:e}):{structures:m,links:d,positionsPlayedOff:g,drawDefinition:i,...C}}function Ru({value:t,sourceRange:e,targetRange:r}){let n=Math.min(...e),o=Math.max(...e),i=Math.min(...r),s=Math.max(...r);return(t-n)*(s-i)/(o-n)+i}var Qn="ELO",GP="NTRP",gG="TRN",VP="UTR",Ng="WTN",aO={ELO:Qn,NTRP:GP,TRN:gG,UTR:VP,WTN:Ng};var IG={[Qn]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[GP]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[VP]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[Ng]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},_e=IG;function cO({sourceRatingType:t,sourceRating:e}){let r=_e[t].range,n=r[0]>r[1],o=_e[Qn].range;return Ru({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function uO({targetRatingType:t,sourceRating:e}){let r=_e[t].decimalsCount||0,n=_e[t].range,o=n[0]>n[1],i=Math.max(...n),s=_e[Qn].range,a=Ru({targetRange:n,sourceRange:s,value:e}),c=parseFloat(a.toFixed(r));return o?i-c:c}function BP(t){let e=et(t,[{ratings:!0,[He]:Kr}]);if(e.error)return e;let r=t.matchUpType&&[kt,xt].includes(t.matchUpType)?t.matchUpType:kt,n=Object.keys(_e),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:Qn,i=t.ratings[r]?t.ratings[r].reduce((d,l)=>d.includes(l.scaleName)?d:d.concat(l.scaleName),[]):[];if(!i)return{error:Ce};let s=t.ratings[r]?.find(d=>d.scaleName===o)??t.ratings[r][0];if(i[0]===o)return s;let a=s.scaleName,c=_e[s.scaleName].accessor,u=c?s.scaleValue[c]:s.scaleValue,p=cO({sourceRatingType:a,sourceRating:u});return{convertedRating:uO({targetRatingType:o,sourceRating:p}),sourceRating:u}}function pO({participantResults:t,sides:e,score:r}){let n=e.find(({sideNumber:a})=>a===1),o=e.find(({sideNumber:a})=>a===2),i=n?.participant?.ratings,s=o?.participant?.ratings;if(i?.[kt]&&s?.[kt]){let a=Qn,{convertedRating:c}=BP({ratings:i,targetRatingType:a}),{convertedRating:u}=BP({ratings:s,targetRatingType:a}),{side1pressure:p,side2pressure:m}=hG({side1ConvertedRating:c,side2ConvertedRating:u,score:r});p&&t[n?.participantId].pressureScores.push(p),m&&t[o?.participantId].pressureScores.push(m);let d=Math.max(..._e[Qn].range),l=wl((u-c)/d),f=wl((c-u)/d);t[n?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(f)}}function hG({side1ConvertedRating:t,side2ConvertedRating:e,score:r}){let n=t>e?t:e,o=t>e?e:t,i=Math.abs(t-e),s=_e[Qn].range,a=Math.max(...s),c=(a-n)*0,p=(n+c)/a*i,m=r?.sets?.reduce((T,y)=>T+(y?.side1Score??0),0),d=r?.sets?.reduce((T,y)=>T+(y.side2Score??0),0),l=t>e?2:1,f=(m||0)*(o+(l===1?p:0)),g=(d||0)*(o+(l===2?p:0)),I=f+g,h=I?wl(f/I):0,S=I?wl(g/I):0;return{side1pressure:h,side2pressure:S}}function Mg({winningSide:t,matchUpFormat:e=Dn,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=Ye(e),u=HP(c?.bestOf??1);if(typeof a=="number"&&(r===Rt&&n?.setsCreditForDefaults||r===Ct&&n?.setsCreditForWalkovers))i[a]=u;else for(let p of s||[]){let{winningSide:m}=p;m&&(i[m-1]+=1)}return typeof a=="number"&&r===rr&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function KS({matchUpFormat:t=Dn,winningSide:e,matchUpStatus:r,tallyPolicy:n,score:o}){let{sets:i}=o||{};if(!i)return[0,0];let s=typeof e=="number"&&e-1,a=Ye(t),c=a?.bestOf??1,u=HP(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===Rt&&n?.gamesCreditForDefaults||r===Ct&&n?.gamesCreditForWalkovers)){let d=a?.setFormat?.setTo||0,l=u*d;m[s].push(l)}else i.forEach((d,l)=>{let g=(d.setNumber||l+1)>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",I=a?.[g]?.based,h=a?.[g].tiebreakSet,{side1Score:S,side2Score:T}=d;mO(I)&&(m[0].push(mt(S||0)),m[1].push(mt(T||0))),h&&d.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&m[d.winningSide-1].push(1)});if(r===rr&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(mO(l.based)){let f=l?.setTo||0,g=S=>{if(!(!a||S===""))return+S===p-1||+S===p?mt(p||0)+1:+S<p?f:p},I=Mg({winningSide:e,score:{sets:i},matchUpStatus:r,matchUpFormat:t,tallyPolicy:n});if(m.map(S=>S[s]<=S[1-s]).reduce((S,T)=>S+(T?1:0),0)>I[1-s]){let S=m[s].length,T=g(m[1-s][S-1]);T&&(m[s][S-1]=T)}u>m[s].length&&n?.gamesCreditForRetirements&&m[s].push(f)}}return[m[0].reduce((d,l)=>d+l,0),m[1].reduce((d,l)=>d+l,0)]}function zS({matchUpFormat:t,score:e}){let r=t?Ye(t):void 0,n=r?.bestOf??1,o=HP(n),i=[0,0],s=[0,0];return e?.sets?.forEach((a,c)=>{let p=(a.setNumber||c+1)>o&&r?.finalSetFormat?"finalSetFormat":"setFormat",m=r?.[p]?.based;if(dO(m)){let{side1Score:d,side2Score:l}=a;d&&(s[0]+=mt(d||0)),l&&(s[1]+=mt(l||0))}else a.side1TiebreakScore&&(s[0]+=mt(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=mt(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function HP(t){return t&&Math.ceil(t/2)||1}function dO(t){return t==="P"}function mO(t){return!dO(t)}function lO({participantResults:t,matchUpFormat:e,tallyPolicy:r,perPlayer:n,totalSets:o}){let i=e&&Ye(e)||{},s=i.bestOf,a=s&&Math.ceil(s/2)||1,c=i.setFormat?.setTo;Object.keys(t).forEach(u=>{let p=t[u].setsWon,m=t[u].setsLost,d=r?.groupTotalSetsPlayed?o:n*(a||0)||p+m,l=Math.round(p/d*1e3)/1e3;(l===1/0||isNaN(l))&&(l=d);let f=t[u].tieMatchUpsWon,g=t[u].tieMatchUpsLost,I=f+g,h=Math.round(f/I*1e3)/1e3;(h===1/0||isNaN(h))&&(h=f);let S=t[u].matchUpsWon,T=t[u].matchUpsLost,y=S+T,P=Math.round(S/y*1e3)/1e3;(P===1/0||isNaN(P))&&(P=S);let U=t[u].gamesWon||0,A=t[u].gamesLost||0,E=(n||0)*(a||0)*(c||0),N=Math.max(E,U+A),D=Math.round(U/N*1e3)/1e3;(D===1/0||isNaN(D))&&(D=0);let M=t[u].pointsWon+t[u].pointsLost,R=Math.round(t[u].pointsWon/M*1e3)/1e3;(R===1/0||isNaN(R))&&(R=0),t[u].setsWon=p,t[u].setsLost=m,t[u].setsPct=l,t[u].tieMatchUpsWon=f,t[u].tieMatchUpsPct=h,t[u].matchUpsPct=P,t[u].gamesWon=U,t[u].gamesLost=A,t[u].gamesPct=D,t[u].pointsPct=R,t[u].result=`${t[u].matchUpsWon}/${t[u].matchUpsLost}`})}function Cu({participantIds:t,pressureRating:e,matchUpFormat:r,tallyPolicy:n,perPlayer:o,matchUps:i}){let s={},a=n?.excludeMatchUpStatuses||[],c=i?.filter(m=>(m.tieMatchUps||!a.includes(m.matchUpStatus))&&(!t?.length||qt(t,[Nd(m,0),Nd(m,1)]).length===2)),p=c?.flatMap(({score:m,tieMatchUps:d})=>d?d.filter(({matchUpStatus:l})=>!a.includes(l)).flatMap(({score:l})=>l?.sets?.length??0):m?.sets?.length??0)?.reduce((m,d)=>m+d,0);for(let m of c??[]){let{matchUpStatus:d,tieMatchUps:l,tieFormat:f,score:g,winningSide:I,sides:h}=m,S=f&&m._disableAutoCalc&&f.collectionDefinitions.every(({scoreValue:A})=>A),T=I&&SG(m),y=I&&TG(m);if(!T&&!y)if(d&&pe.includes(d)){let A=Nd(m,0),E=Nd(m,1);A&&(Uc(s,A),s[A].matchUpsCancelled+=1),E&&(Uc(s,E),s[E].matchUpsCancelled+=1)}else if(l?.length){o=0;for(let A of l){if(A.winningSide){let E=h?.find(({sideNumber:D})=>D===A.winningSide)?.participantId,N=h?.find(({sideNumber:D})=>D===A.winningSide)?.participantId;E&&N&&(Uc(s,E),Uc(s,N),s[E].tieMatchUpsWon+=1,s[N].tieMatchUpsLost+=1,me(kt)(A.matchUpType)?(s[E].tieSinglesWon+=1,s[N].tieSinglesLost+=1):me(xt)(A.matchUpType)&&(s[E].tieDoublesWon+=1,s[N].tieDoublesLost+=1))}fO({score:A.score,manualGamesOverride:S,participantResults:s,sides:h})}}else fO({manualGamesOverride:S,participantResults:s,score:g,sides:h});else if(Uc(s,T),Uc(s,y),l?.length){o=0;for(let A of l){let{matchUpType:E}=A,N=me(xt)(E),D=me(kt)(E);A.winningSide&&(A.winningSide===I?(T&&(s[T].tieMatchUpsWon+=1,D&&(s[T].tieSinglesWon+=1),N&&(s[T].tieDoublesWon+=1)),y&&(s[y].tieMatchUpsLost+=1,D&&(s[y].tieSinglesLost+=1),N&&(s[y].tieDoublesLost+=1))):A.winningSide!==I&&(y&&(s[y].tieMatchUpsWon+=1,D&&(s[y].tieSinglesWon+=1),N&&(s[y].tieDoublesWon+=1)),T&&(s[T].tieMatchUpsLost+=1,D&&(s[T].tieSinglesLost+=1),N&&(s[T].tieDoublesLost+=1)))),gO({matchUpFormat:A.matchUpFormat,matchUpStatus:A.matchUpStatus,matchUpType:A.matchUpType,score:A.score,sides:A.sides,winningParticipantId:T,losingParticipantId:y,manualGamesOverride:S,participantResults:s,isTieMatchUp:!0,pressureRating:e,tallyPolicy:n,winningSide:I})}IO({winningParticipantId:T,losingParticipantId:y,participantResults:s,matchUpStatus:d})}else gO({matchUpFormat:m.matchUpFormat??r,matchUpType:m.matchUpType,isTieMatchUp:void 0,winningParticipantId:T,manualGamesOverride:S,losingParticipantId:y,participantResults:s,pressureRating:e,matchUpStatus:d,tallyPolicy:n,winningSide:I,score:g,sides:h});let P=g?.sets?.reduce((A,E)=>A+(E?.side1Score??0),0),U=g?.sets?.reduce((A,E)=>A+(E.side2Score??0),0);if(S){let A=h?.find(({sideNumber:N})=>N===1)?.participantId,E=h?.find(({sideNumber:N})=>N===2)?.participantId;Uc(s,A),Uc(s,E),A&&(s[A].gamesWon+=P,s[A].gamesLost+=U),E&&(s[E].gamesWon+=U,s[E].gamesLost+=P)}}return lO({participantResults:s,matchUpFormat:r,tallyPolicy:n,perPlayer:o,totalSets:p}),{participantResults:s}}function SG(t){let e=t.winningSide-1;return Nd(t,e)}function TG(t){let e=1-(t.winningSide-1);return Nd(t,e)}function Nd(t,e){if(!t?.sides)return console.log("no sides:",{matchUp:t}),"foo";let r=t.sides[e];return r?r.participantId:(console.log("No Side",{matchUp:t,index:e}),"foo")}function Uc(t,e){e&&!t[e]&&(t[e]={allDefaults:0,defaults:0,defeats:[],gamesLost:0,gamesWon:0,matchUpsCancelled:0,matchUpsLost:0,matchUpsWon:0,pointsLost:0,pointsWon:0,pressureScores:[],ratingVariation:[],retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function fO({manualGamesOverride:t,participantResults:e,score:r,sides:n}){let{sets:o}=r||{},i=[[],[]],s=[0,0];for(let c of o||[]){let{winningSide:u,side1Score:p,side2Score:m}=c;u&&(s[u-1]+=1),i[0].push(mt(p||0)),i[1].push(mt(m||0))}let a=[i[0].reduce((c,u)=>c+u,0),i[1].reduce((c,u)=>c+u,0)];n.forEach((c,u)=>{let{participantId:p}=c;p&&(Uc(e,p),e[p].setsWon+=s[u],e[p].setsLost+=s[1-u],t||(e[p].gamesWon+=a[u],e[p].gamesLost+=a[1-u]))})}function gO({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,isTieMatchUp:a,matchUpType:c,tallyPolicy:u,winningSide:p,score:m,sides:d}){let l=p&&p-1,f=1-l;o&&c===kt&&pO({participantResults:n,sides:d,score:m}),a||IO({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let g=Mg({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),I=KS({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),{pointsTally:h}=zS({score:m,matchUpFormat:i});t&&(n[t].setsWon+=g[l],n[t].setsLost+=g[f],e||(n[t].gamesWon+=I[l],n[t].gamesLost+=I[f]),n[t].pointsWon+=h[l],n[t].pointsLost+=h[f]),r&&(n[r].setsWon+=g[f],n[r].setsLost+=g[l],e||(n[r].gamesWon+=I[f],n[r].gamesLost+=I[l]),n[r].pointsWon+=h[f],n[r].pointsLost+=h[l])}function IO({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===Ct&&(r[e].walkovers+=1),n===Rt&&(r[e].defaults+=1),n===rr&&(r[e].retirements+=1),[Rt,rr,Ct].includes(n)&&(r[e].allDefaults+=1),r[e].matchUpsLost+=1),t&&(r[t].matchUpsWon+=1),e&&t&&(r[e].defeats.push(t),r[t].victories.push(e))}function hO({matchUps:t,order:e,report:r}){let n={};t.forEach(({sides:i})=>{i.forEach(s=>{s.participantId&&s.participant&&(n[s.participantId]=s.participant.participantName)})});let o=[];return Array.isArray(r)&&r.forEach((i,s)=>{if(i.excludedDirectives?.length){let a=i.excludedDirectives.map(({attribute:p})=>p).join(", "),c=`${a.length} directives were excluded due to participants limit}`;o.push(c);let u=`Excluded: ${a}`;o.push(u)}else{let a=(l,f)=>parseFloat(i.reversed?l:f)-parseFloat(i.reversed?f:l),c=i.groups?Object.values(i.groups).flat(1/0).length:i.participantIds?.length??0,u=l=>{l.groups&&Object.keys(l.groups).sort(a).forEach(f=>{let g=l.groups[f].map(h=>n[h]).join(", "),I=`${f} ${l.attribute}: ${g}`;o.push(I)})},p=i.reversed?" in reverse order":"",m=i.groups?"grouped":"separated",d=`Step ${s+1}: ${c} particiants were ${m}${p} by ${i.attribute}`;if(o.push(d),i.idsFilter){let l=`${i.attribute} was calculated considering ONLY TIED PARTICIPANTS`;o.push(l)}u(i)}o.push("----------------------")}),o.push("Final Order:"),e.forEach(i=>{let{participantId:s,resolved:a}=i,c=i.groupOrder||i.provisionalOrder;o.push(`${c}: ${n[s]} => resolved: ${!!a}`)}),o.join(`\r
4
4
  `)}function WP({participantResults:t,participantIds:e,attribute:r}){return jP({participantResults:t,participantIds:e}).reduce((o,i)=>{let{participantId:s,results:a}=i,c=a?.[r];return!isNaN(c)&&s&&(o[c]?o[c].push(s):o[c]=[s]),o},{})}function jP(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var yG=[{attribute:"matchUpsPct",idsFilter:!1},{attribute:"allDefaults",reversed:!0,idsFilter:!1},{attribute:"defaults",reversed:!0,idsFilter:!1},{attribute:"walkovers",reversed:!0,idsFilter:!1},{attribute:"retirements",reversed:!0,idsFilter:!1},{attribute:"setsPct",idsFilter:!1},{attribute:"gamesPct",idsFilter:!1},{attribute:"pointsPct",idsFilter:!1},{attribute:"matchUpsPct",idsFilter:!0},{attribute:"setsPct",idsFilter:!0},{attribute:"gamesPct",idsFilter:!0},{attribute:"pointsPct",idsFilter:!0}],YP={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function qP(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!AG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=WP({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let p=Object.keys(a).map(S=>parseFloat(S)).sort((S,T)=>T-S).map(S=>a[S]).map(S=>{let T=SO({participantIds:S,...t});return i.push(...T.report??[]),T.order}).map((S,T)=>S.map(y=>y.resolved?y:{...y,subGroup:[T].concat(...y.subGroup??[])})).flat(),m,d=0,l=1,f;p.forEach((S,T)=>{T&&(S.resolved||f&&!S.resolved)&&(l+=1),f=S.resolved;let y=parseInt(S.subGroup?.join("")||0);S.resolved?(S.position=T+1,l=S.position):(m&&y>m&&(l+=d,d=0),S.position=l,d+=1),m=y});let g=p.map(({position:S})=>S),I=Tr(g);return p.forEach(S=>{let{participantId:T,position:y}=S||{},P=r[T];S.GEMscore=h(P);let U=I[y];S?.position!==void 0&&(U>1&&(S.ties=U,n&&(S.subOrder=n[T])),S.rankOrder=y,S.groupOrder=y+(S.subOrder||1)-1)}),{groupOrder:p,report:i.flat(1/0).filter(Boolean)};function h(S){return(Array.isArray(o?.GEMscore)?Object.keys(YP).filter(P=>o.GEMscore.includes(P)):Object.keys(YP)).map(P=>(S[P]||0)*Math.pow(10,YP[P].toFixed(3))).reduce((P,U)=>P+U,0)}}function AG({participantResults:t,participantsCount:e}){let n=jP({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function EG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,tallyPolicy:n,attribute:o,idsFilter:i,matchUps:s,reversed:a}){let{participantResults:c}=Cu({participantIds:i&&e,matchUpFormat:r,tallyPolicy:n,matchUps:s}),u=WP({participantResults:c,participantIds:e,attribute:o}),p=[{attribute:o,reversed:a,groups:u,idsFilter:i}],m;return Object.keys(u).length>1&&e.length&&(m=Object.keys(u).map(f=>parseFloat(f)).sort((f,g)=>a?f-g:g-f).map(f=>u[f]).map(f=>{let g=SO({participantResults:c,disableHeadToHead:t,participantIds:f,matchUpFormat:r,tallyPolicy:n,matchUps:s});return p.push(...g.report??[]),g.order}).map((f,g)=>f.map(I=>I.resolved?I:{...I,subGroup:[g].concat(...I.subGroup??[])})).flat()),{order:m,report:p}}function SO({participantResults:t,disableHeadToHead:e,participantIds:r,matchUpFormat:n,tallyPolicy:o,matchUps:i}){let s=[],a=[],c;if(r?.length===1)return{order:[{resolved:!0,participantId:r[0]}]};if(r?.length===2&&(!o?.headToHead||!o.headToHead.disabled&&!e)){let m=UG({participantIds:r,participantResults:t});if(m){let d=m[0].participantId;return a.push({attribute:"head2Head",participantIds:r,headToHeadWinner:d}),{order:m,headToHeadWinner:d,report:a}}}let p=(o?.tallyDirectives||yG).filter(m=>{let d=!(te(m.maxParticipants)&&r?.length>m.maxParticipants);return d||s.push(m),d});return s.length&&a.push({excludedDirectives:s,participantIds:r}),p.every(({attribute:m,reversed:d,idsFilter:l,disableHeadToHead:f})=>(c=EG({disableHeadToHead:f,participantIds:r,matchUpFormat:n,tallyPolicy:o,attribute:m,idsFilter:l,matchUps:i,reversed:d}),a.push(c.report),!c.order)),c.order?{order:c.order,report:a}:{order:r?.map(m=>({participantId:m})),report:a}}function UG({participantIds:t,participantResults:e}){if(t){if(e[t[0]].victories.includes(t[1]))return t.map(r=>({resolved:!0,participantId:r}));if(e[t[1]].victories.includes(t[0]))return t.reverse().map(r=>({resolved:!0,participantId:r}))}}function ba({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Vr(o))return{error:Jn};let a=ut(o.map(({structureId:y})=>y));if(a.length!==1)return x({result:{error:V,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!==Nt),u=c.length&&ut(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>ds({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:P})=>y===Yt&&P?.every(U=>ds({matchUp:U}))),d=t?.[Cf],l=o.filter(y=>ds({matchUp:y})||y.matchUpType===Yt),{participantResults:f}=Cu({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=qP({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i});if(r&&PG({participantResults:f}),p&&h)g=S,I=h,h.forEach(y=>{let{participantId:P,groupOrder:U,rankOrder:A,subOrder:E,ties:N,GEMscore:D}=y,M=f[P];Object.assign(M,{groupOrder:U,rankOrder:A,GEMscore:D,subOrder:E,ties:N})});else{let{groupOrder:y,report:P}=qP({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=P,I=y,y&&y.forEach(U=>{let{participantId:A,groupOrder:E,GEMscore:N}=U,D=f[A];Object.assign(D,{provisionalOrder:E,GEMscore:N})})}let T={completedTieMatchUps:m,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||m)&&(T.order=I),e||Pr({tally:!0})){let y=hO({matchUps:o,report:g,order:I});Pr({tally:!0})&&console.log(y),T.readableReport=y}return T}function PG({participantResults:t}){let e=o=>o.reduce((i,s)=>i+parseFloat(s),0),r=o=>parseFloat((e(o)/o.length).toFixed(2)),n=Object.keys(t).map(o=>{let i=t[o],{pressureScores:s}=i,a=s?.length?r(s):0;return{participantId:o,averagePressure:a}}).sort((o,i)=>(i.averagePressure||0)-(o.averagePressure||0)).map((o,i)=>({...o,order:i+1}));for(let o of n)t[o.participantId].pressureOrder=o.order}function QS({positionAssignments:t}){let e=(t||[]).filter(Br(no)).map(i=>{let{extension:s}=lt({element:i,name:ic}),a=mt(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=Tr(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function Md({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Vr(o))return{error:V};if(!t)return{error:V};let{policyDefinitions:s}=vo({policyTypes:[Cf],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=QS({positionAssignments:t}),c=o.length?ba({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;if(c?.error)return c;let{participantResults:u={},bracketComplete:p,report:m}=c??{},d=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;if(d.includes(f)){let g={value:u[f],name:Zo};At({element:l,extension:g}),u[f].ties||fr({element:l,name:ic})}else fr({element:l,name:Zo}),fr({element:l,name:ic})}),vt({drawDefinition:r}),{...C,participantResults:u,bracketComplete:p,report:m}}function XS({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Bt(t){let e=et(t,[{[Ve]:!0,[fn]:!0}]);if(e.error)return e;let{tournamentParticipants:r,afterRecoveryTimes:n,contextProfile:o,drawDefinition:i,matchUpsMap:s,matchUpId:a,inContext:c,context:u,event:p}=t,{structures:m=[]}=In({drawDefinition:i}),d=t.contextContent||o&&$n({contextProfile:o,drawDefinition:i});for(let l of m){let{matchUps:f}=Pt({tournamentParticipants:r,afterRecoveryTimes:n,contextContent:d,drawDefinition:i,contextProfile:o,matchUpsMap:s,inContext:c,structure:l,context:u,event:p}),{matchUp:g}=XS({matchUps:f,matchUpId:a});if(g)return{matchUp:g,structure:l}}return{error:xe}}function kp(t){return!ht(t)||!t.notes?{error:it}:ht(t.element)?!Vt(t.notes)&&!t.notes?.testing?{error:V}:(Object.assign(t.element,{notes:t.notes}),{...C}):{error:V}}function Rg(t){return ht(t)?ht(t.element)?(t.element.notes&&delete t.element.notes,{...C}):{error:V}:{error:it}}var bu={matchUpStatus:Jt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Vn(t){let e="modifyMatchUpScore",r=t.matchUpFormat,n=t.matchUp,o,{matchUpStatusCodes:i,tournamentRecord:s,drawDefinition:a,matchUpStatus:c,removeScore:u,winningSide:p,matchUpId:m,event:d,notes:l,score:f}=t,I=t.appliedPolicies&&Object.keys(t.appliedPolicies).length?t.appliedPolicies:yt({policyTypes:[tn],tournamentRecord:s,drawDefinition:a,structure:o,event:d})?.appliedPolicies,h=n.matchUpType===Yt;if(h&&a){if(m&&n.matchUpId!==m){let E=Bt({drawDefinition:a,matchUpId:m,event:d});if(!E.matchUp)return{error:xe};({matchUp:n,structure:o}=E)}}else n.matchUpId!==m&&console.log("!!!!!");c&&[Ct,Te].includes(c)||u?Object.assign(n,{...bu}):f&&(n.score=f);let S=c&&n?.matchUpStatus===Rt&&c!==Rt;c&&(n.matchUpStatus=c),r&&(n.matchUpFormat=r),i&&(n.matchUpStatusCodes=i),p&&(n.winningSide=p),t.removeWinningSide&&(n.winningSide=void 0),!o&&a&&({structure:o}=Bt({drawDefinition:a,matchUpId:m,event:d})),c&&!n.winningSide&&Se(n)&&!pe.includes(c)&&![sc,ss,un].includes(c)&&(n.matchUpStatus=Fn);let T;if((S&&n?.processCodes?.length||c===Rt)&&(T=I?.[tn]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let E=o?.structureType===Ge,N=ur({structure:o});if(id({drawDefinition:a,structure:o})||N||E){let D=b=>{r=h?"SET1-S:T100":r??n.matchUpFormat??b?.matchUpFormat??a?.matchUpFormat??d?.matchUpFormat;let v=h?{matchUpTypes:[Yt]}:void 0,{matchUps:O}=Pt({afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,matchUpFilters:v,drawDefinition:a,structure:b,event:d});return N&&(b.positionAssignments=ut(O.flatMap(_=>(_.sides??[]).map(F=>F.participantId)).filter(Boolean)).map(_=>({participantId:_}))),Md({positionAssignments:b.positionAssignments,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUps:O,event:d})},M=E&&o.structures.find(b=>b?.matchUps.find(v=>v.matchUpId===m)),R=D(M||o);if(R.error)return x({result:R,stack:e})}}if(l){let E=kp({element:n,notes:l});if(E.error)return x({result:E,stack:e})}let y=s?.tournamentId,P=Lr().topics.includes(Tp),U=(P||T)&&De({drawDefinition:a}),A=U&&ae({matchUpFilters:{matchUpIds:[m]},nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:a,matchUpsMap:U}).matchUps?.[0];if(P&&A&&Tb({tournamentId:y,inContextMatchUp:A}),Array.isArray(T)&&A&&!A.sides?.every(({participantId:E})=>E))if(c===Rt)n.processCodes=ut([...n.processCodes??[],...T]);else for(let E of T||[]){let N=E&&n?.processCodes?.lastIndexOf(E);n?.processCodes?.splice(N,1)}return gt({eventId:d?.eventId,context:e,drawDefinition:a,tournamentId:y,matchUp:n}),{...C}}function Rd(t){let{matchUpStatusCodes:e,matchUpStatus:r,structure:n,matchUp:o,dualMatchUp:i,inContextMatchUp:s,autoCalcDisabled:a}=t,c=Pa({matchUpStatus:r})||[io,Or].includes(r)&&i||a,u=o?.sides?.map(I=>I.participantId).filter(Boolean).length||s?.sides?.map(I=>I.participantId).filter(Boolean).length,p="attemptToModifyScore";if(!(ur({structure:n})&&u===1||r===Rt&&u||DG({structure:n,matchUp:o,inContextMatchUp:s})||t.appliedPolicies?.[tn]?.requireParticipantsForScoring===!1))return x({result:{error:Hl},stack:p});let l=[Ct].includes(r),f=c?r:t.winningSide&&ge||un,g=Vn({...t,matchUpStatusCodes:c&&e||[],matchUpStatus:f,context:p,removeScore:l});return x({result:g,stack:p})}function DG({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=ye({structure:t}),i=o?.filter(a=>n?.includes(a.drawPosition)&&a.participantId),s=r?.sides?.every(a=>a.participantId);return i?.length===2||s}function JS({collectionGroups:t=[]}){let e=Object.assign({},...t.filter(n=>It(n?.groupValue)&&n?.groupNumber).map(n=>({[n.groupNumber]:{...n,allGroupMatchUpsCompleted:!0,matchUpsCount:0,sideWins:[0,0],values:[0,0]}}))),r=Object.keys(e).map(n=>mt(n));return{groupValueGroups:e,groupValueNumbers:r}}function TO({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(S=>S.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(S=>pe.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),It(d)?i.forEach(S=>{S.winningSide&&(s[S.winningSide-1]+=d)}):It(g)?i.forEach(S=>{S.score?.sets?.forEach(T=>{T.winningSide&&(s[T.winningSide-1]+=g)})}):It(f)?i.forEach(S=>{S.score?.sets?.forEach(T=>{let{side1TiebreakScore:y=0,side2TiebreakScore:P=0,side1Score:U=0,side2Score:A=0}=T;(S.matchUpStatus===ge||S.winningSide||T.winningSide)&&(U||A?(s[0]+=U,s[1]+=A):(y||P)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,y=NG({collectionDefinition:t,collectionPosition:T});It(y)&&(s[S.winningSide-1]+=y)}}),It(m)){let S;if(l?.aggregateValue)c&&(It(d||g||f)&&s[0]!==s[1]?S=s[0]>s[1]?1:2:h[0]!==h[1]&&(S=h[0]>h[1]?1:2));else if(l?.valueGoal)S=s.reduce((T,y,P)=>y>=l.valueGoal?P+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((y,P,U)=>P>=T?U+1:y,0)}S&&(I?r[p].values[S-1]+=m:a[S-1]+=m)}else I?(r[p].values[0]+=s[0]||0,r[p].values[1]+=s[1]||0):a=s;I?(r[p].sideWins[0]+=h[0]||0,r[p].sideWins[1]+=h[1]||0,r[p].allGroupMatchUpsCompleted=r[p].allGroupMatchUpsCompleted&&c,r[p].matchUpsCount+=i.length):a.forEach((S,T)=>n[T]+=S||0)}function NG({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function Pc(t){let{sideAdjustments:e=[0,0],separator:r="-",drawDefinition:n,matchUpsMap:o,structure:i,matchUp:s,event:a}=t;if(!Array.isArray(e)||e.length!==2||isNaN(e.reduce((y,P)=>y+P)))return{error:V};if(!s)return{error:Sr};let c=We({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:bs};let u=cr({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=JS(c);for(let y of p)TO({collectionDefinition:y,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let y of f){let P=l[y],{allGroupMatchUpsCompleted:U,matchUpCount:A,winCriteria:E,groupValue:N,sideWins:D,values:M}=P,R;if(E?.aggregateValue)U&&M[0]!==M[1]&&(R=M[0]>M[1]?1:2);else if(E?.valueGoal)R=M.reduce((b,v,O)=>v>=E.valueGoal?O+1:b,void 0);else{let b=Math.floor(A/2)+1;R=D.reduce((v,O,_)=>O>=b?_+1:v,void 0)}R&&(d[R-1]+=N||0)}let g=d.map((y,P)=>(y||0)+e[P]),I={side1Score:g[0],side2Score:g[1],winningSide:void 0},h=g.join(r),S=g.slice().reverse().join(r),T;if(c?.winCriteria){let{valueGoal:y,aggregateValue:P,tallyDirectives:U}=c.winCriteria;if(y?T=g.map((E,N)=>({sideNumber:N+1,points:E})).find(({points:E})=>E>=y)?.sideNumber:P&&m.every(E=>E.matchUpStatus&&pe.includes(E.matchUpStatus)||E.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&U){let A=s.matchUpId,E=s.hasContext?s:o?.drawMatchUps?.[A]||n&&Bt({inContext:!0,drawDefinition:n,matchUpId:A})?.matchUp;if(E){let{completedTieMatchUps:N,order:D}=ba({matchUps:[E]});if(N&&D?.length){let M=D[0].participantId;T=E.sides.find(({participantId:R})=>R===M)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function va({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Bt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=lt({element:e,name:Ro}),s=J(i?.value||{},!1,!0),a=({displaySideNumber:c,drawPosition:u,sideNumber:p})=>({drawPosition:u,sideNumber:p,displaySideNumber:c});n.sides=t?.sides?.map(c=>{let u=c.participantId,p=u&&s[u]||void 0,{lineUp:m,...d}=n.sides?.find(({sideNumber:f})=>f===c.sideNumber)??{},l=m?.length?m:p;return{...a(c),...d,lineUp:l}}),gt({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function ir(t){if(t)return J(t,!1,!0)}function Cg(t){let e=et(t,[{[Ne]:!0}]);return e.error?e:Object.keys(t.tournamentRecords).reduce((n,o)=>{n.tournamentIdMap[o]=[];let s=t.tournamentRecords[o].events??[],a=s.map(({eventId:u})=>u),c=s.map(u=>(u.drawDefinitions??[]).map(({drawId:p})=>p)).flat();return n.tournamentIdMap[o].push(...a,...c),n.eventIds.push(...a),n.drawIds.push(...c),n},{eventIds:[],drawIds:[],tournamentIdMap:{}})}function ZS({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=Cg({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function uo(t){let{exitWhenNoValues:e,drawDefinition:r,matchUpStatus:n,removeScore:o,matchUpsMap:i,matchUpId:s,event:a}=t,c=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord?.tournamentId]:t.tournamentRecord}||{},u=t.tournamentId||t.tournamentRecord?.tournamentId;c&&ZS({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:q};let m=Bt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:xe};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:dr};va({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=lt({name:Ia,element:d});if(f?.value)if(o)fr({element:d,name:Ia});else return{...C,score:d.score};let g=We({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=ir(g);let I=Pc({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:y}=I,P=S?.side1Score||S?.side2Score;if(e&&!d.score&&!P)return{...C};let U={scoreStringSide1:T,scoreStringSide2:y,sets:S?[S]:[]},A=h&&[1,2].includes(h),E=A&&ge||ag({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:U})&&Fn||Jt,N=!!(d.winningSide&&!A),D=d.tieMatchUps.find(({score:R,winningSide:b,matchUpStatus:v})=>R?.sets?.length&&(R.sets[0].side1Score||R.sets[0].side2Score)||v&&pe.includes(v)||b),M;if(d.tieFormat&&!A&&!D){let R=We({drawDefinition:r,structure:l,event:a})?.tieFormat;R&&JSON.stringify(g)===JSON.stringify(R)&&(d.tieFormatId=void 0,d.tieFormat=void 0,M=!0)}return Vn({appliedPolicies:t.appliedPolicies,matchUpStatus:E,score:U,removeWinningSide:N,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...C,score:U,removeWinningSide:N,tieFormatRemoved:M,winningSide:h}}function yO({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:r,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}){let l="directWinner";if(s){let f=u.drawPositions||[],g=f[t],I=s.source.structureId,h=at({structureId:I,drawDefinition:c});if(h.error)return h;let{structure:S}=h,{positionAssignments:T}=ye({structureId:I,drawDefinition:c}),P=T?.find(R=>R.drawPosition===o)?.participantId,U=s.target.structureId,{positionAssignments:A}=ye({structureId:U,drawDefinition:c}),N=A?.find(R=>R.participantId===P)?.drawPosition,D=A?.filter(R=>{let b=f.includes(R.drawPosition),v=!R.participantId&&!R.bye&&!R.qualifier;return b&&v}).map(R=>R.drawPosition),M=D?.includes(g);if(P&&s.target.roundNumber===1&&M)Gn({drawPosition:g,participantId:P,structureId:U,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(P&&D?.length){let R=D.pop();R&&Gn({participantId:P,structureId:U,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:R,matchUpsMap:m,event:d})}else if(N){let R=Sc({drawPosition:N,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(R.error)return x({result:R,stack:l})}else if(S?.stage!==ct){let R="winner target position unavaiallble";return console.log(R),{error:R}}if(S?.seedAssignments&&S.structureId!==U){let R=S.seedAssignments.find(({participantId:v})=>v===P),b=R?.participantId;R&&b&&$s({eventId:u?.eventId,structureId:U,...R,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=Sc({matchUpId:u.matchUpId,drawPosition:o,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(f.error)return f}if(p&&r){let f=p.sides?.find(g=>g.sideNumber===r);if(f?.lineUp){let g=p.roundPosition,I=u.roundPosition,h=g===I&&g!==1||Math.floor(g/2)===I?2:1,S=m?.drawMatchUps?.find(({matchUpId:P})=>P===u.matchUpId),T=[1,2].map(P=>({...S.sides?.find(A=>A.sideNumber===P)||{},sideNumber:P}));S.sides=T;let y=S.sides.find(P=>P.sideNumber===h);if(y){let P=f.lineUp?.filter(U=>U?.participantId);y.lineUp=Sd({lineUp:P}),gt({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...C}}function AO(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,sourceMatchUpStatus:o,loserDrawPosition:i,tournamentRecord:s,loserTargetLink:a,drawDefinition:c,loserMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}=t,l="directLoser",f=a.linkCondition,g=u.drawPositions||[],I=f===_n&&u.roundNumber===2&&Math.min(...g.filter(Boolean)),h=I||g[e],S=I||g[1-e],T=a.source.structureId,{structure:y}=at({structureId:T,drawDefinition:c}),{matchUps:P}=Pt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:y,event:d}),A=P.filter(W=>W.drawPositions?.includes(i)).filter(W=>{let Y=W.sides.find(B=>B.drawPosition===i),$=W.matchUpStatus===Ct||W.matchUpStatus===Rt&&!Se(W);return Y?.sideNumber===W.winningSide&&!$}),E=f===_n&&A.length===0,{positionAssignments:N}=ye({structureId:T,drawDefinition:c}),M=N?.find(W=>W.drawPosition===i)?.participantId,R=a.target.structureId,{positionAssignments:b}=ye({structureId:R,drawDefinition:c}),v=b?.filter(({drawPosition:W})=>g.includes(W));if(v?.some(W=>W.participantId===M))return{...C};let _=v?.filter(W=>{let Y=g.includes(W.drawPosition),$=!W.participantId&&!W.bye&&!W.qualifier;return Y&&$}).map(W=>W.drawPosition),F=_?.includes(h),w=a.target.roundNumber>1&&_?.length,L=a.target.roundNumber===1&&F;if(I){let W=G();if(W.error)return x({result:W,stack:l})}else if(L){let W=H();if(W.error)return x({result:W,stack:l})}else if(M&&w){_.sort(le);let W=_[0],Y=Gn({participantId:M,structureId:R,drawPosition:W,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d});if(Y.error)return x({result:Y,stack:l})}else return x({context:{loserDrawPosition:i,loserTargetLink:a,targetDrawPositionIsUnfilled:F},result:{error:F?Rs:yC},stack:l});if(y?.seedAssignments&&y.structureId!==R){let W=y.seedAssignments.find(({participantId:$})=>$===M),Y=W?.participantId;W&&Y&&$s({eventId:u?.eventId,structureId:R,...W,tournamentRecord:s,drawDefinition:c,participantId:Y})}if(p&&n){let W=p.sides?.find(Y=>Y.sideNumber===3-n);if(W?.lineUp){let{roundNumber:Y,eventId:$}=u,{roundPosition:B}=p,K=Y===1?2-B%2:1,X=m?.drawMatchUps?.find(({matchUpId:z})=>z===u.matchUpId),j=[1,2].map(z=>({...X.sides?.find(pt=>pt.sideNumber===z)||{},sideNumber:z}));X.sides=j;let nt=X.sides.find(z=>z.sideNumber===K);nt&&(nt.lineUp=Sd({lineUp:W.lineUp}),gt({tournamentId:s?.tournamentId,matchUp:X,context:l,drawDefinition:c,eventId:$}))}}return{...C};function G(){let W="loserLinkFedFMLC";return E?x({result:H(),stack:W}):x({result:k(),stack:W})}function k(){let W=Hr({drawPosition:S,structureId:R,tournamentRecord:s,drawDefinition:c,event:d});return x({result:W,stack:"assignLoserPositionBye"})}function H(){let W=M?Gn({drawPosition:h,participantId:M,structureId:R,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d}):{error:ie};return x({result:W,stack:"assignLoserDrawPosition"})}}function tT(t){let e="directParticipants",r=Rd(t);if(r.error)return x({result:r,stack:e});let n=Pa({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,projectedWinningSide:i,inContextDrawMatchUps:s,tournamentRecord:a,drawDefinition:c,matchUpStatus:u,dualMatchUp:p,matchUpsMap:m,winningSide:d,targetData:l,matchUpId:f,structure:g,matchUp:I,event:h}=t,S=!!I.collectionId,T=ur({structure:g}),y=I.drawPositions,P;if(S){let{matchUpTieId:U,matchUpsMap:A}=t,E=uo({appliedPolicies:t.appliedPolicies,matchUpId:U,tournamentRecord:a,drawDefinition:c,matchUpsMap:A,event:h});if(P=E&&{tieMatchUpResult:E},y=s.find(({matchUpId:D})=>D===U)?.drawPositions,!o)return x({result:{...C,...P},stack:e})}if(T)return x({result:{...C,...P},stack:e});if(y){let U=i?i-1:d-1,A=1-U,E=y[U],N=y[A],{targetLinks:{loserTargetLink:D,winnerTargetLink:M,byeTargetLink:R},targetMatchUps:{winnerMatchUpDrawPositionIndex:b,loserMatchUpDrawPositionIndex:v,winnerMatchUp:O,loserMatchUp:_,byeMatchUp:F}}=l;if(O){let w=yO({sourceMatchUpStatus:n&&u||ge,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,winningDrawPosition:E,tournamentRecord:a,winnerTargetLink:M,drawDefinition:c,winnerMatchUp:O,dualMatchUp:p,matchUpsMap:m,event:h});if(w.error)return x({result:w,stack:e})}if(_){let w=AO({sourceMatchUpStatus:n&&u||ge,loserMatchUpDrawPositionIndex:v,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,loserDrawPosition:N,tournamentRecord:a,loserTargetLink:D,drawDefinition:c,loserMatchUp:_,winningSide:d,matchUpsMap:m,dualMatchUp:p,event:h});if(w.error)return x({result:w,stack:e})}if(F){let w=F.drawPositions||[],L=Math.min(...w.filter(Boolean)),G=R.target.structureId,k=Hr({drawPosition:L,structureId:G,tournamentRecord:a,drawDefinition:c,event:h});if(k.error)return x({result:k,stack:e})}}else return x({result:{error:Ya},stack:e});return x({result:{...C,...P},stack:e})}function Cd(t){let e="genPlayoffStructure";if(!t.drawDefinition)return x({result:{error:Z},stack:e});let r=Nu(t);if(r.error)return x({result:r,stack:e});let{structureId:n,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:m,exitProfileLimit:d,roundProfiles:l,roundNumbers:f,idPrefix:g,isMock:I,event:h,uuids:S}=t,T=J(t.drawDefinition,!1,!0),{structure:y}=at({structureId:n,drawDefinition:T});if(!y)return x({result:{error:wt},stack:e});if(y.structureType===Ge||y.structures)return sO({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:P,playoffRounds:U}=r,{playoffPositionsReturned:A,error:E,playoffSourceRounds:N,playoffRoundsRanges:D}=HS(t);if(E)return x({result:{error:E},stack:e});let M=l?.length&&Object.assign({},...l),R=f||typeof l=="object"&&l.map(j=>Object.keys(j)).flat(),b=Array.isArray(R)&&R.map(j=>!isNaN(j)&&mt(j)).filter(Boolean);if(b){if(!Array.isArray(b))return x({result:{error:V},context:{validRoundNumbers:b},stack:e});b.forEach(j=>{if(!U?.includes(j))return x({result:{error:V},context:{roundNumber:j},stack:e})})}u&&u.forEach(j=>{if(!A?.includes(j))return x({result:{error:V},context:{playoffPosition:j},stack:e})});let v=b||N,O=b?P:D,_=[],F=[];for(let j of v??[]){let nt=O?.find(Kt=>Kt.roundNumber===j);if(!nt)return x({result:{error:V},context:{roundNumber:j},stack:e});let z=nt.finishingPositions.length,Q=Math.min(...nt.finishingPositions)-1,pt=2,st=j&&M?.[j]&&pt+M[j]-1,Mt=yc({exitProfile:`0-${j}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:Q,playoffAttributes:c,exitProfileLimit:d,stage:fe,roundOffset:0,drawDefinition:T,sequenceLimit:st,stageSequence:pt,drawSize:z,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(Mt.error)return x({result:Mt,stack:e});let{structures:_t,links:Re}=Mt;if(_t?.length&&_.push(..._t),Re?.length&&F.push(...Re),Mt.structureId&&j){let Kt={linkType:ro,source:{structureId:n,roundNumber:j},target:{structureId:Mt.structureId,feedProfile:En,roundNumber:1}};F.push(Kt)}}if(!_.length)return x({result:{error:V},info:"No structures generated",stack:e});T.structures.push(..._),T.links.push(...F);let{matchUps:w,matchUpsMap:L}=ae({inContext:!0,drawDefinition:T}),G=_.map(({structureId:j})=>j),k=w?.filter(({structureId:j})=>G.includes(j)).map(Ue),H=L?.drawMatchUps?.filter(({matchUpId:j})=>k?.includes(j));if(H?.length){let j=We({drawDefinition:T,event:h})?.tieFormat;j&&H.forEach(nt=>{let{tieMatchUps:z}=Ca({matchUp:nt,tieFormat:j,isMock:I});Object.assign(nt,{tieMatchUps:z,matchUpType:Yt})})}w?.filter(j=>ds({matchUp:j})&&j.structureId===n)?.forEach(j=>{let{matchUpId:nt,score:z,winningSide:Q}=j,pt=pr({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:nt}),st=tT({inContextDrawMatchUps:w,tournamentRecord:m,drawDefinition:T,matchUpsMap:L,winningSide:Q,targetData:pt,matchUpId:nt,structure:y,matchUp:j,score:z,event:h});st.error&&console.log(st.error)}),w?.filter(j=>j.matchUpStatus===Nt&&j.structureId===n)?.forEach(j=>{let{matchUpId:nt}=j,z=pr({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:nt}),{targetLinks:{loserTargetLink:Q},targetMatchUps:{loserMatchUpDrawPositionIndex:pt,loserMatchUp:st}}=z;if(Q&&st){let Mt=Q.target.structureId,_t=st.drawPositions[pt],Re=Hr({drawPosition:_t,structureId:Mt,tournamentRecord:m,drawDefinition:T,event:h});Re.error&&console.log(Re.error)}});let $=[],B=$i({inContextDrawMatchUps:w,drawDefinition:T,matchUpsMap:L}).goesToMap,{structure:K}=at({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:X}=Pt({structure:K});return X.forEach(j=>{let nt=B?.loserMatchUpIds[j.matchUpId];if(nt&&j.loserMatchUpId!==nt){j.loserMatchUpId=nt;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:j};$.push(Q)}let z=B?.winnerMatchUpIds[j.matchUpId];if(z&&j.winnerMatchUpId!==z){j.winnerMatchUpId=z;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:j};$.push(Q)}}),{structures:_,matchUpModifications:$,links:F,drawDefinition:T,...C}}function eT({element:t}){if(!t)return{error:V};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:V};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function Xn(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:ef};let i=Qh(t);if(i.error)return i;if(!(ht(o)&&Vt(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:tf};if(!i.timeItems)i.timeItems=[];else if(MG({element:i,duplicateValues:e,timeItem:o}))return{...C};if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let c=new Date().toISOString();Object.assign(o,{createdAt:c})}return n&&(i.timeItems=i.timeItems.filter(({itemType:c})=>o.itemType!==c)),n&&!o.itemValue||i.timeItems.push(o),{...C}}function MG({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&en({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function bg({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:q};if(!o)return{error:ie};let s=To({tournamentRecord:r,participantId:o});return s.error?s:Xn({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function Dc(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:q};let s=Xn({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=eT({element:r});return dt({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:Hi}),s}function Qi(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?Xn({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:jr}}function $P(t){return Og({...t,itemType:"attachConsolationStructures"})}function vg(t){return Og({...t,itemType:"attachPlayoffStructures"})}function Og({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:Z};if(!Array.isArray(o)||!Array.isArray(i))return x({result:{error:V},stack:a});let c=h=>[h.source.structureId,h.source.roundNumber||h.source.finishingPositions?.join("|"),h.target.roundNumber].join("|"),u=n.links?.map(c);if(i.some(h=>{let S=c(h);return u?.includes(S)}))return x({result:{error:af},info:"playoff structure exists",stack:a});i.length&&n.links?.push(...i);let m=o.map(({structureId:h})=>h),d=n.structures?.map(({structureId:h})=>h);n.structures=(n.structures??[]).map(h=>m.includes(h.structureId)?o.find(({structureId:S})=>S===h.structureId):h);let l=o?.filter(({structureId:h})=>!d?.includes(h));l.length&&n.structures.push(...l),$i({drawDefinition:n});let f=o.map(h=>Pt({structure:h})?.matchUps||[]).flat();Co({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(vt({drawDefinition:n,structureIds:g}),e?.length){let h={};e.forEach(T=>{let y=T.matchUp?.matchUpId;y&&(h[y]=T)});let S=T=>{T.matchUps.forEach(y=>{if(h[y.matchUpId]){let{tieMatchUps:P,...U}=h[y.matchUpId].matchUp;if(Object.assign(y,U),P?.length){let A={};P.forEach(E=>h[E.matchUpId]=E),y.tieMatchUps.forEach(E=>Object.assign(E,A[E.matchUpId]))}h[y.matchUpId].matchUp=y,gt(h[y.matchUpId])}})};n.structures.forEach(T=>{if(d?.includes(T.structureId))if(T.structures)for(let y of T.structures)S(y);else S(T)})}let I=l.map(Br("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};Xn({element:r,timeItem:S})}return{...C,addedStructureIds:I}}function Gp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=Cd(t);if(o)return{error:o};let i=t.drawDefinition;return vg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function Xi(t){let e=et(t,[{_anyOf:{[Ne]:!1,[se]:!1,[Ve]:!1,[Do]:!1},[Pf]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=EO(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&vt({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:q};for(let i of o){let s=t.tournamentRecords[i],a=EO(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:q};return r.length?{...C,applied:r}:{error:GI}}function EO(t,e){let r=yt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:Ku};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!ht(s))return{error:V};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!Vt(a))return{error:V};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...At({element:e,extension:{name:ou,value:r}}),applied:n}:{applied:n,error:GI}}function _g({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return x({result:{error:V},context:{drawName:n}});r||(r=Ht({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:cn,value:{...r,flights:r.flights}};Mo({event:i,extension:a})}return e&&(e.drawName=n,vt({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:Z}:{...C,flight:s}}function KP({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!ht(r))return{error:V};let i=Ht({event:o}).flightProfile,s=r.drawName&&_g({drawName:r.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:i,drawId:n,event:o});if(s?.error)return s?.error;let a=s?.flight||i?.flights?.find(c=>c.drawId===n);if(!a&&!e)return{error:Z};if(a){let c={name:cn,value:{...i,flights:i.flights}};Mo({event:o,extension:c})}return e&&(r.policyDefinitions&&Xi({policyDefinitions:r.policyDefinitions,drawDefinition:e}),vt({tournamentId:t?.tournamentId,drawDefinition:e})),{...C}}function zP({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:Z};let n=De({drawDefinition:r}),o=s=>n?.drawMatchUps?.find(a=>a.matchUpId===s);for(let s of r.structures||[]){let{positionAssignments:a,stage:c,stageSequence:u}=s;a&&(u!==1||![ct,rt].includes(c))&&(s.positionAssignments=a.map(d=>(delete d.participantId,d)),s.seedAssignments=[]);let{matchUps:p,isRoundRobin:m}=Pt({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:n,structure:s});for(let d of p){let{matchUpId:l,roundNumber:f}=d,g=d.sides||[],I=o(l);if(I){if(delete I.extensions,delete I.notes,I.matchUpStatus!==Nt&&Object.assign(I,bu),f&&f>1&&I.drawPositions?.length&&!m){let h=g?.map(({drawPosition:T,participantFed:y})=>!y&&T).filter(Boolean),S=I.drawPositions.map(T=>h.includes(T)?void 0:T);I.drawPositions=S}e?delete I.timeItems:I.timeItems?.length&&(I.timeItems=I.timeItems.filter(h=>h.itemType&&![ao,Ho,Wi,ng,ji,Yi].includes(h.itemType))),gt({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}r.extensions=r.extensions.filter(s=>s.name!==oc);let i=(r.structures||[]).map(({structureId:s})=>s);return vt({drawDefinition:r,structureIds:i}),{...C}}function vu({tournamentRecord:t}){if(!t)return{error:q};let e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={};return(t.events?.map(o=>{let i=o.eventId;return r[i]=o,(o?.drawDefinitions||[]).map(s=>({drawDefinition:s,eventId:i}))}).flat().filter(Boolean)).forEach(({drawDefinition:o,eventId:i})=>{let s=0,a=0,c=0,{allStructuresLinked:u}=Pu({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(P=>{let{stage:U,stageSequence:A,structureId:E}=P,N=ks[U],{inContextStructureMatchUps:D}=Da({drawDefinition:o,structure:P,event:p}),M=D?.filter(({winningSide:Y})=>Y),R=M.filter(Boolean).length||0;a+=R,c+=D.length-a;let b=Math.max(M.filter(({roundNumber:Y})=>Y===1).map(({roundPosition:Y})=>Y)),{positionAssignments:v}=bt({structure:P}),O=v?.filter(({participantId:Y})=>Y);s+=O?.length??0;let _=(v?.length??0)-(O?.length??0),{roundMatchUps:F,roundProfile:w,roundNumbers:L,maxMatchUpsCount:G}=Ke({matchUps:D}),k=w&&Object.keys(w).filter(Y=>!w[Y].inactiveRound).map(Y=>parseInt(Y)),H=w&&Object.keys(w).filter(Y=>w[Y].inactiveRound).map(Y=>parseInt(Y)),W=w&&Object.values(w).every(Y=>Y.inactiveRound);return{positionsAssignedCount:O?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:_,inactiveStructure:W,maxMatchUpsCount:G,inactiveRounds:H,roundMatchUps:F,activeRounds:k,roundNumbers:L,roundProfile:w,structureId:E,stageSequence:A,orderNumber:N,stage:U}}),l=d.find(P=>P.orderNumber===2&&P.stageSequence===1),f=d.filter(({inactiveStructure:P})=>!P).length,{links:g}=Ws({structureId:l.structureId,drawDefinition:o}),I=mt(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=d?.every(({inactiveStructure:P})=>P),S=!g.length&&l.activeRounds.length&&(l.roundProfile[1].inactiveCount||l.inactiveRounds.length),T=o.drawId;s&&!a&&e.positionsNoOutcomes.push(T),h&&e.inactive.push(T),I&&e.matchPlay.push(T),S&&e.canBePruned.push(T);let y={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:c,positionsAssignedCount:s,allStructuresLinked:u,structuresData:d,inactiveDraw:h,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=y}),{...C,drawsAnalysis:e}}function QP({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:q};if(!r)return{error:Z};let o=[],{drawsAnalysis:i}=vu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=In({stageSequence:1,drawDefinition:r,stage:rt}),u=a.structuresData.find(({structureId:l})=>c.structureId===l),p=(c.matchUps??[]).sort((l,f)=>l.roundPosition-f.roundPosition);o=p.filter(({roundNumber:l})=>!u.inactiveRounds.includes(l));let m=o.map(Ue),d=p.map(Ue).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Ue),g=m.filter(T=>!f.includes(T));d.push(...g);let h=l.flatMap(T=>T.drawPositions??[]).filter(Boolean).flat(),S=Object.assign({},...h.map((T,y)=>({[T]:y+1})));if(l.forEach(T=>{t?T.drawPositions=T.drawPositions.map(y=>S[y]):delete T.drawPositions}),t){let T=c?.positionAssignments?.filter(y=>h.includes(y.drawPosition)).map(y=>(y.drawPosition=S[y.drawPosition],y));c.positionAssignments=T}else c.positionAssignments=[];c.matchUps=l,o=l}Rn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),vt({drawDefinition:r})}return{...C,matchUps:o}}function XP({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,qualifier:i,event:s,bye:a}){if(!e)return{error:Z};if(!n)return{error:Cs};if(!o)return{error:Ur};if(a){let c=Hr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:tp};{let c=Gn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...C}}function rT(t){let e=t.matchUpIds??[],{drawDefinition:r}=t,n=t.structureId??r?.structures?.find(c=>c.matchUps?.some(({matchUpId:u})=>e.includes(u)))?.structureId??r?.structures?.[0]?.structureId;if(!n)return{error:wt};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:wt};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===Vi)return{error:Xo};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Ue);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function JP(t){let e=et(t,[{[Ve]:!0},{[Gs]:{[rc]:!1,roundNumbers:!1},[Fr]:V,[He]:Be}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=rT(t);if(c.error)return c;let{structure:u,structureId:p,existingMatchUps:m,matchUpIds:d}=c,l=[],f=m?.filter(({matchUpId:h,score:S,winningSide:T})=>{if(T&&!o)return!1;if(T||Se({score:S})){if(!T&&!r)return!1;l.push(h)}else if(!n)return!1;return d?.includes(h)})??[],g=f.map(Ue),I=f.map(({tieMatchUps:h})=>h?.map(Ue)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),Rn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=ut(u.matchUps.map(Br("roundNumber"))),S=gC(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,gt({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=ut(u.matchUps.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,P=c.existingMatchUps.some(N=>N.matchUpType===xr)?{matchUpTypes:[xr]}:void 0,{matchUps:U}=Pt({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:P,structure:u,event:a});ur({structure:u})&&(u.positionAssignments=ut(U.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N})));let E=Md({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:U,event:a});E.error&&console.log(E)}vt({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:ep}:{...C,deletedMatchUpsCount:[...g,...I].length}}function ZP({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:q};if(!r)return{error:Z};if(!o)return x({result:{error:it},info:"roundNumber required"});let s=at({drawDefinition:r,structureId:n});if(s.error)return s;let a=s.structure;return a?.structures?{error:Xo}:ur({structure:a})?RG({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...C})}function RG({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:r,roundNumber:n,structure:o,eventId:i}){let s=o?.matchUps??[],a=[],c=[],u=!1;if(s.reduce((m,d)=>{let l=d?.roundNumber;return l?m.includes(l)?m:m.concat(l):m},[]).sort(le).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!pe.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Ue))),!l});c.length&&(Rn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,gt({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...C}}function bd(t){let{suppressNotifications:e,tournamentRecord:r,drawDefinition:n,matchUps:o,event:i}=t;if(typeof n!="object")return{error:Z};let s=t?.structureId;if(!s&&n.structures?.length===1&&(s=n.structures?.[0]?.structureId),typeof s!="string")return{error:Ur};if(!Vr(o))return{error:V,info:si("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:wt};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===Vi)return{error:Xo};let p=Ae({tournamentRecord:r,inContext:!1})?.matchUps?.map(Ue)??[],m=o.map(Ue);if(Fe(p,m))return{error:_E,info:"One or more matchUpIds already present in tournamentRecord"};a.matchUps.push(...o);let d=o.map(({tieMatchUps:l})=>l).filter(Boolean).flat();return e||(Co({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),vt({drawDefinition:n,structureIds:[s]})),{...C}}function tD({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:Z};if(!n)return{error:Ur};if(!r)return{error:Cs};let{structure:s}=at({drawDefinition:e,structureId:n});if(!s)return{error:wt};let a=s;s.structures&&s.structureType===Ge&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&At({element:u,extension:{name:ic,value:o}});let d=(i?.eventType===Yt||e.matchUpType===Yt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[Yt]},{matchUps:l}=Pt({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return Md({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),vt({drawDefinition:e,structureIds:[n]}),{...C}}var dD={};Zt(dD,{addGoesTo:()=>$i,allPlayoffPositionsFilled:()=>xS,checkValidEntries:()=>_d,findDrawDefinition:()=>sT,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Nu,getDrawDefinitionTimeItem:()=>Xh,getDrawParticipantRepresentativeIds:()=>oT,getDrawStructures:()=>In,getDrawTypeCoercion:()=>Ou,getEligibleVoluntaryConsolationParticipants:()=>nT,getMatchUpsMap:()=>De,getParticipantIdFinishingPositions:()=>iT,getPositionAssignments:()=>Vp,getPositionsPlayedOff:()=>Ac,getSeedingThresholds:()=>PS,getSeedsCount:()=>_u,getStructureSeedAssignments:()=>nn,getTeamLineUp:()=>ms,getValidGroupSizes:()=>bp,isAdHoc:()=>ur,isCompletedStructure:()=>ai,isValidForQualifying:()=>TT,positionActions:()=>ST});function nT({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:r,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:m,winsLimit:d,event:l}){if(!a)return{error:Z};let f=[rt,fe];r&&f.push(ct);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?Kn({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:or({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=Ui({stage:$e,drawDefinition:a}).map(({participantId:L})=>L),y={},P={},U={},A={};o||(o=vo({policyTypes:[_h],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let E=o?.[_h];t=t.length&&t||E?.excludedMatchUpStatuses||[],e=e??E?.includeEventParticipants,m=m??E?.allEntries,n=n??E?.finishingRoundLimit,i=i??E?.roundNumberLimit,c=c??E?.matchUpsLimit,u===void 0&&(u=E?.requirePlay!==void 0?E.requirePlay:!0),p===void 0&&(p=E?.requireLoss!==void 0?E.requireLoss:!0),d=d??E?.winsLimit;for(let L of h){if(u&&L.winningSide&&![1,2].includes(L.winningSide)&&L.matchUpStatus!==Te||L.finishingRound&&n&&L.finishingRound>=n||L.finishingRound&&i&&L.finishingRound<=i)continue;let G=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===3-L.winningSide),k=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===L.winningSide);if(L.sides?.forEach(H=>{let W=H?.participant?.participantId;W&&(U[W]=H.participant,L.matchUpStatus===Te&&!u&&(P[W]=H.participant,y[W]||(y[W]=0),(!L.matchUpStatus||!t.includes(L.matchUpStatus))&&(y[W]+=1)))}),G?.participant){let H=G.participant.participantId;P[H]=G.participant,y[H]||(y[H]=0),L.matchUpStatus&&!t.includes(L.matchUpStatus)&&(y[H]+=1)}if(k?.participant){let H=k.participant.participantId;A[H]||(A[H]=0),A[H]+=1,y[H]||(y[H]=0),L.matchUpStatus&&!t.includes(L.matchUpStatus)&&(y[H]+=1)}}let N=s?.participants&&!u&&!p&&m,D=N?((e&&l?l.entries:a.entries)??[]).filter(L=>![so,Gr].includes(L.entryStatus)).map(({participantId:L})=>L):[],M=Object.keys(P),R=N?(s?.participants??[]).filter(({participantId:L})=>D.includes(L)):p&&Object.values(P)||Object.values(U),b=L=>!p||M.includes(L),v=L=>!u||(y[L]||0)>=0,O=L=>!d||(A[L]||0)<=d,_=L=>!c||y[L]<=c,F=L=>!T.includes(L);return{eligibleParticipants:R.filter(L=>b(L.participantId)&&v(L.participantId)&&O(L.participantId)&&_(L.participantId)&&F(L.participantId)).map(L=>({...L,individualParticipants:L.individualParticipantIds?.map(G=>s?.participants?.find(k=>k.participantId===G))})),losingParticipantIds:M,...C}}function vd(t){let e=et(t,[{drawDefinition:!0}]);if(e.error)return e;let{drawDefinition:r,roundNumber:n}=t,o=t.structureId??(r.structures?.length===1&&r.structures?.[0]?.structureId);if(typeof o!="string")return{error:Ur};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:wt};let s,c=(i.matchUps??[])?.reduce((g,I)=>(I.roundPosition&&(s=!0),(I?.roundNumber||0)>g?I.roundNumber:g),0);if(i.structures||s||i.finishingPosition===Vi)return{error:Xo};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return Qr.includes(I)})??[],p=Math.floor(u?.length/2)||1,m=n??c??1,d=i.matchUps?.filter(g=>g.roundNumber===m)?.length??0,l=p-d,f=l>0?l:0;return{...C,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function oT({drawDefinition:t}){let e=lt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function UO({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:Z};let n=ae({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=J(n.matchUps,!1,!0),i=ut(o.reduce((a,c)=>a.concat(...c.sides.map(u=>u.participantId).filter(Boolean)),[])),s=Object.assign({},...i.map(a=>{let c=o.filter(u=>u.sides.map(m=>m.participantId).filter(Boolean).includes(a));return{[a]:c}}));return{participantIds:i,participantIdMatchUps:s}}function iT({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:Z};let{participantIds:n,participantIdMatchUps:o}=UO({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[ge,Nt].includes(d.matchUpStatus)||d.winningSide),u=c.map(d=>{let l=d.sides.find(I=>I.bye),f=d.sides.find(I=>I.participantId===s).sideNumber;return(d.winningSide||t&&l&&f)===f?d.finishingPositionRange.winner:d.finishingPositionRange.loser}),p=d=>Math.abs(d[0]-d[1]),m=u.reduce((d,l)=>d&&p(d)<p(l)?d:l,void 0);return{[s]:{relevantMatchUps:c,finishingPositionRanges:u,finishingPositionRange:m}}})||[];return Object.assign({},...i)}function wo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:q};if(!n)return{error:sn};if(!e&&t){if(typeof r!="string"&&(r=ZS({tournamentRecords:t,drawId:n}),!r))return{error:ua};if(e=t[r],!e)return{error:q}}let o=e&&ze({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...C}:x({result:{error:br},stack:"findDrawDefinition"})}function sT(t){let{drawDefinition:e,error:r}=wo(t);return r?{error:r}:{drawDefinition:J(e)}}function xg({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=Ws({drawDefinition:r,structureId:n})||{},a=(i?.target||[]).filter(({linkType:u})=>u===o).filter(({target:u})=>!t||t===u.roundNumber).map(u=>{let p=u.source.structureId,{structure:m}=at({structureId:p,drawDefinition:r});if(!(e&&m?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}function PO({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Gr,Ei].includes(a)).map(({participantId:a})=>a)||[];if(s.length){let a=n.individualParticipantIds,c=e?t.filter(({participantId:m})=>s.includes(m)):void 0,u=e?t.filter(({participantId:m})=>a.includes(m)):void 0;return{validModifyAssignedPairAction:ot({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:Kv,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:Eg},!1,!1,!0)}}return{}}function Ci(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===_n&&r?.matchUp?.matchUpStatus===Nt)return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&pr({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,m=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,d=p?.sides[m]?.participant,l=[Rt,Ct].includes(s?.matchUpStatus)&&!d,f=a?.drawPositions?.filter(Boolean).length||0;if(s?.winningSide&&!l||a?.winningSide&&f===2&&(!a.feedRound||![Ct,Rt].includes(a?.matchUpStatus)))return!0;let g=a&&pr({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),I=u&&Ci({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(g&&Ci({targetData:g,inContextDrawMatchUps:e,drawDefinition:n})||I)}var aT={[So]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ct,rt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Du,Qs,xp,zs],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var wg="positionAction",cT="matchUpAction";function uT({actionType:t=wg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===wg&&So||t===cT&&er,i=t===wg&&aT||t===cT&&oP,s=o&&(e?.[o]||i?.[o]),c=r.links?.filter(d=>d?.target?.structureId===n?.structureId)?.map(({target:d})=>d.feedProfile)??[],{enabledStructures:u,disabledStructures:p}=s||{},m=p?.find(d=>{let{stages:l,stageSequences:f,structureTypes:g,feedProfiles:I}=d;return(!I?.length||Array.isArray(I)&&I.some(h=>c.includes(h)))&&(!l?.length||Array.isArray(l)&&l?.includes(n?.stage))&&(!g?.length||Array.isArray(g)&&g?.includes(n?.structureType))&&(!f?.length||Array.isArray(f)&&f.includes(n?.stageSequence))});return{enabledStructures:u,actionsDisabled:m,actionsPolicy:s}}function rD({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function pT({enabledStructures:t,drawDefinition:e,structure:r}){if(t===!1)return{};if(!t?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};let{stage:n,stageSequence:o,structureType:i}=r||{},a=e.links?.filter(u=>u?.target?.structureId===r?.structureId)?.map(({target:u})=>u.feedProfile)||[];return{policyActions:t.find(u=>{let{stages:p,stageSequences:m,structureTypes:d,feedProfiles:l}=u||{},f=!p?.length||Array.isArray(p)&&p.includes(n),g=!m?.length||Array.isArray(m)&&m.includes(o),I=!d?.length||Array.isArray(d)&&d.includes(i),h=!l?.length||Array.isArray(l)&&l.some(S=>a.includes(S));return g&&I&&h&&u&&f})}}function Bn({action:t,policyActions:e}){let r=!e?.enabledActions||e?.disabledActions?.length&&e.disabledActions.includes(t);return r?!1:(e?.enabledActions.length===0||e?.enabledActions.includes(t))&&!r}var nD="replaceTieMatchUpParticipantId",oD="assignTieMatchUpParticipantId",mT="removeTieMatchUpParticipantId",iD="assignMatchUpSideParticipant",DO="removeMatchUpSideParticipant",sD="substituteParticipant",dT="REMOVE_SUBSTITUTION",aD="REPLACE_PARTICIPANT",Lg="REMOVE_PARTICIPANT",lT="setMatchUpStatus",fT="SUBSTITUTION",cD="SCHEDULE",CG="PENALTY",gT="REFEREE",uD="STATUS",IT="START",pD="SCORE",hT="END",NO={REPLACE_TEAM_POSITION_METHOD:nD,ASSIGN_TEAM_POSITION_METHOD:oD,REMOVE_TEAM_POSITION_METHOD:mT,REPLACE_PARTICIPANT:aD,SUBSTITUTION_METHOD:sD,REMOVE_SUBSTITUTION:dT,REMOVE_PARTICIPANT:Lg,SCHEDULE_METHOD:lT,SUBSTITUTION:fT,SCHEDULE:cD,PENALTY:CG,REFEREE:gT,STATUS:uD,SCORE:pD,START:IT,END:hT};function MO({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:m,side:d}){let l=[],f=o.sides?.find(F=>F.participant),g=o.gender===yr&&o.sideNumber&&o.sides?.filter(F=>F.particiapntId).length===1&&f?.participant?.person?.sex,I=o.matchUpType,S=(s??n?.participants?.enforceGender)!==!1?o.gender:void 0,y=o.sides?.flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean)?.map(St),P=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),U=P?.map(St),E=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:w,person:L})=>!U?.includes(w)&&(!S||S===Pn||L.sex===S||S===yr&&!g||g&&L.sex!==g))),N=c?E?.[c-1]:E?.map((F,w)=>({participants:F,sideNumber:w+1})),D=c?E?.[c-1]?.map(St):E?.map((F,w)=>({participants:F?.map(St),sideNumber:w+1})),M=c&&(me(ca)(I)&&!U?.length||me(Oi)(I)&&(U?.length??0)<2)||!c&&(me(ca)(I)&&(U?.length??0)<2||me(Oi)(I)&&(U?.length??0)<4),R=D?.filter(F=>!y?.includes(F)),b=N?.filter(({participantId:F})=>R.includes(F));if(M&&R?.length&&l.push({availableParticipantIds:R,method:oD,availableParticipants:b,type:ys,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),U?.length&&(!Se(p)||d?.substitutions?.length)&&l.push({method:mT,type:Lg,existingParticipantIds:U,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&U?.length||c&&d?.participant)&&l.push({availableParticipantIds:R,method:nD,availableParticipants:b,type:aD,existingParticipantIds:U,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),Bn({policyActions:i,action:dT})&&d?.substitutions?.length){let F=d.participant?.participantType===Tt&&[d.participantId]||d.participant?.participantType===ft&&d.participant.individualParticipantIds||[],w=d.substitutions.map(L=>L.participantId).filter(L=>F.includes(L));(!a||w.includes(a))&&l.push({method:mT,type:dT,substitutedParticipantIds:w,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let v=t?.[er],O=v?.substituteWithoutScore,_=v?.substituteAfterCompleted;if(Bn({policyActions:i,action:fT})&&r.length===2&&(!c&&U?.length||c&&d?.participant)&&(O||Se(p))&&(_||p.matchUpStatus&&!pe.includes(p.matchUpStatus))&&P?.length&&N.length){let F=P.map(St);l.push({info:"list of team players available for substitution",method:sD,availableParticipantIds:D,existingParticipantIds:F,availableParticipants:N,existingParticipants:P,type:fT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function RO({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:r,positionAssignments:n,returnParticipants:o,appliedPolicies:i,drawDefinition:s,drawPosition:a,validActions:c,structureId:u,structure:p,drawId:m,event:d}){if(r.includes(a))return{};let l=c.find(E=>E.type===ys)?.availableParticipantIds,f=i?.[So]?.otherFlightEntries,g=i?.[So]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:E})=>!g||(p.stage===ct?E===ct:E!==ct)).sort((E,N)=>(E.entryPosition??1/0)-(N.entryPosition??1/0)).map(({participantId:E})=>E).filter(Boolean),{allPositionedParticipantIds:h}=Wh({drawDefinition:s}),S=n.map(E=>E.participantId).filter(Boolean),T=I.filter(E=>p.stage&&[ct,rt,fe].includes(p.stage)?!h?.includes(E):!S.includes(E)),P=(d?.entries??[]).filter(E=>E.entryStatus===rn&&mD({restrictQualifyingAlternates:g,structure:p,entry:E})&&(p.stage&&[ct,rt,fe].includes(p.stage)?!h?.includes(E.participantId):!S.includes(E.participantId))).sort((E,N)=>(E.entryPosition??1/0)-(N.entryPosition??1/0)).map(E=>E.participantId),U=ut(T.concat(P));if(f){let N=(d?Ht({event:d}).flightProfile:void 0)?.flights?.filter(D=>D.drawId!==m).map(D=>D.drawEntries.filter(M=>M.participantId&&![so,Gr,Ei].includes(M.entryStatus)&&!I.includes(M.participantId)).map(({participantId:M})=>M)).flat().filter(Boolean);N?.length&&U.push(...N)}l?.length&&(U=U.filter(E=>!l.includes(E)));let A=o?t?.filter(E=>U.includes(E.participantId)):void 0;return A?.forEach(E=>{let N=(s.entries??[]).find(D=>D.participantId===E.participantId);E.entryPosition=N?.entryPosition}),A?.sort((E,N)=>(E.entryPosition||1/0)-(N.entryPosition||1/0)),U.length?{validAlternatesAction:ot({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:qv,availableAlternatesParticipantIds:U,type:Ug,availableAlternates:A})}:{}}function mD({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===ct&&!t||r.entryStage===rt&&n===qe)return!0}function CO({eventEntries:t,structure:e}){let r=o=>o.entryStatus===rn&&mD({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(St)}function bO({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:m}){let d=[],l=c?.matchUps??[],g=u.sides?.find(N=>N.sideNumber===s)?.participantId,I=l.filter(({roundNumber:N})=>N===u.roundNumber),h=o?.entries?.filter(({entryStatus:N})=>N&&ni.includes(N)).map(St)??[],S=I.map(N=>(N.sides??[]).flatMap(St)).flat().filter(Boolean),T=h.filter(N=>!r.includes(N)&&(!t||!S.includes(N))),y=e?.filter(N=>T?.includes(N.participantId)).map(N=>J(N,void 0,!0));y?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),T.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:iD,type:ys,availableParticipantIds:T,participantsAvailable:y});let P=m?.entries??[],U=CO({eventEntries:P,structure:c}),A=ut(h.concat(U));if(n){let D=(m?Ht({event:m}):void 0)?.flights?.filter(M=>M.drawId!==p).flatMap(M=>M.drawEntries.filter(R=>R.participantId&&![so,Gr,Ei].includes(R.entryStatus)).map(({participantId:R})=>R)).filter(Boolean);D?.length&&A.push(...D)}A=A.filter(N=>!r.includes(N)&&!T.includes(N)&&(!t||!S.includes(N)));let E=e?.filter(N=>A.includes(N.participantId)).map(N=>J(N,void 0,!0));if(E?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),E?.sort((N,D)=>(N.entryPosition||1/0)-(D.entryPosition||1/0)),A.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:A,participantsAvailable:E,method:iD,type:rn}),!Se(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:DO,type:Lg});let N=w=>w.sides.map(St),D=({matchUpId:w})=>w!==u.matchUpId,M=w=>!Se(w),R=u.sides?.find(w=>w.sideNumber!==s)?.participantId,v=l.filter(({roundNumber:w})=>w!==u.roundNumber).filter(D).map(N),O=[R,...v.filter(w=>w.includes(g)).flat()].filter(Boolean),_=w=>!O.flat().includes(w),F=I.filter(M).filter(D).map(N).flat().filter(_);if(F.length){let w=e?.filter(L=>F.includes(L.participantId)).map(L=>J(L,void 0,!0));d.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:zv,type:Lp,swappableParticipants:w})}}return d}function Od(t){if(!t)return{error:V};let{drawDefinition:e,event:r}=t,{restrictAdHocRoundParticipants:n=!0,policyDefinitions:o,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c}=t,u=t.tournamentRecord??(t.tournamentId&&Vt(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:q};if(!c||!Vt(c))return{error:ar};if(a&&![1,2].includes(a))return x({result:{error:V},context:{sideNumber:a}});if(!e){let Q=(Ae({tournamentRecord:u}).matchUps??[]).find(st=>st.matchUpId===c);r=(u?.events??[]).find(st=>st.eventId===Q?.eventId);let pt=(r?.drawDefinitions??[]).find(st=>st.drawId===Q?.drawId);pt&&(e=pt)}if(!e)return{error:Z};let p=Gt({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Bt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:xe};let f=yt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[So]?.otherFlightEntries,I=f?.[er]??hs[er],{enabledStructures:h}=uT({actionType:cT,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=pT({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??De({drawDefinition:e}),y=t.inContextDrawMatchUps??ae({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,P=y?.find(z=>z.matchUpId===c),U=a&&P?.sides?.find(z=>z.sideNumber===a),A=P?.sides?.map(z=>z.participantId||z.participant?.participantid).filter(Boolean)??[],{assignedPositions:E,allPositionsAssigned:N}=ye({structure:l}),{structureId:D}=l??{},M=[];if(!D)return{validActions:M};let R=ur({structure:l}),b=d.collectionId;if(R&&!b){let z=bO({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:A,otherFlightEntries:g,drawDefinition:e,structureId:D,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r});M.push(...z)}let v=ai({drawDefinition:e,structure:l}),O=E?.filter(z=>z.participantId).map(z=>z.drawPosition),_=E?.filter(z=>z.bye).map(z=>z.drawPosition),F=d.matchUpStatus===Nt||!b&&d.drawPositions?.reduce((z,Q)=>_?.includes(Q)||z,!1);if(F)return{validActions:M,isByeMatchUp:F};Bn({policyActions:S,action:gT})&&M.push({type:gT,payload:{matchUpId:c}});let w=!Pa({matchUpStatus:d.matchUpStatus}),L=f?.scoring?.structures,G=l?.stage&&L?.stage&&L?.stage[l.stage],k=l?.stageSequence&&G?.stageSequence&&G.stageSequence[l.stageSequence],W=!(f?.scoring?.requireAllPositionsAssigned||G?.requireAllPositionsAssigned||k?.requireAllPositionsAssigned)||N,Y=d.sides&&d.sides.filter(z=>z?.participantId).length===2,$=d.matchUpStatus&&[Te,Me].includes(d.matchUpStatus),B=pr({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),K=Ci({inContextDrawMatchUps:y,drawDefinition:e,targetData:B}),j=(P?.drawPositions?.length===2&&P.drawPositions.every(z=>O?.includes(z))&&P?.sides?.length===2&&P.sides.every(({participantId:z})=>z)||Y)&&!($&&K),nt={method:VS,type:Qs,payload:{drawId:m,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(w&&M.push({payload:{drawId:m,matchUpId:c,schedule:{}},method:lT,type:cD}),Bn({policyActions:S,action:Qs})&&(U?.participant||!a&&A?.length)&&M.push(nt),w&&j&&M.push({type:uD}),W&&j){let{matchUpId:z,matchUpFormat:Q}=d,pt={drawId:m,matchUpId:z,matchUpFormat:Q,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};M.push({info:"set outcome and winningSide",method:lT,type:pD,payload:pt}),Bn({policyActions:S,action:IT})&&M.push({type:IT}),Bn({policyActions:S,action:hT})&&M.push({type:hT})}if(b&&P){let z=MO({specifiedPolicyDefinitions:o,inContextDrawMatchUps:y,matchUpParticipantIds:A,matchUpActionsPolicy:I,inContextMatchUp:P,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:U});M.push(...z)}return{structureIsComplete:v,validActions:M,isDoubleExit:$,...C}}function vO({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:o,positionAssignments:i,drawDefinition:s,drawPosition:a,structureId:c,structure:u,drawId:p,event:m}){if(o.includes(a)||n&&!e)return{};let{sourceStructureIds:d,targetStructureIds:l}=s.links?.reduce((h,S)=>{let T=S.source?.structureId,y=S.target?.structureId;return h.sourceStructureIds.includes(T)||h.sourceStructureIds.push(T),h.targetStructureIds.includes(y)||h.targetStructureIds.push(y),h},{sourceStructureIds:[],targetStructureIds:[]})||{},f=[],g=s.links?.filter(h=>h.target?.structureId===u.structureId)??[];for(let h of g){let S=h?.source?.structureId,{structure:T}=at({structureId:S,drawDefinition:s}),y=T?.finishingPosition===Vi&&(d?.length!==1||l?.length!==1),P={};if(y){let{matchUps:N}=Pt({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:D}=fs({drawPosition:a,matchUps:N}),R=s.links?.find(b=>b.target?.structureId===u?.structureId&&b.target.roundNumber===D)?.source?.roundNumber;P.roundNumbers=[R]}let{completedMatchUps:U}=Tu({structureId:S,inContext:!0,matchUpFilters:P,drawDefinition:s}),A=i.map(N=>N.participantId).filter(Boolean);U?.filter(({matchUpType:N,winningSide:D})=>D&&(m?.eventType!==ve||N===ve)).map(({winningSide:N,sides:D})=>N&&D?.[1-(N-1)]).map(St).filter(N=>N&&!A.includes(N))?.forEach(N=>{f.includes(N)||f.push(N)})}let I=t?.filter(h=>f?.includes(h.participantId));return I?.forEach(h=>{let S=(s.entries??[]).find(T=>T.participantId===h.participantId);h.entryPosition=S?.entryPosition}),f?.length?{validLuckyLosersAction:{type:Dg,method:$v,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function OO({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:o,isWinRatioFedStructure:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,seedingProfile:p,isByePosition:m,drawPosition:d,structureId:l,event:f}){let{drawId:g}=u,I=[],h,S,T=[],y=c?.[wn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=DS({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:p,structureId:l,event:f})),T?.length||(T=s.filter(P=>!P.participantId&&!P.bye&&!P.qualifier).map(P=>P.drawPosition)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:Jv,type:Ed}),i&&y){let P=s.map(D=>D.participantId).filter(Boolean),U={structureIds:t},{completedMatchUps:A}=js({inContext:!0,matchUpFilters:U,drawDefinition:u}),E=ut((A??[]).filter(({matchUpType:D})=>f?.eventType!==ve||D===ve)?.map(({sides:D})=>D?.map(St)).flat().filter(D=>D&&!P.includes(D))),N=a?o?.filter(D=>E?.includes(D.participantId)).map(D=>J(D,void 0,!0)):void 0;return N?.forEach(D=>{let M=(u.entries??[]).find(R=>R.participantId===D.participantId);D.entryPosition=M?.entryPosition}),N?.length&&I.push(ot({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:_P,type:ys,availableParticipantIds:E,participantsAvailable:N})),{validAssignmentActions:I}}if(T.includes(d)||m){let P;if(S?.length){let A=S.filter(E=>h?.includes(E.participantId));A.sort(bG),P=A.map(E=>E.participantId)}else P=e;let U=a?o?.filter(A=>P.includes(A.participantId)).map(A=>J(A,void 0,!0)):void 0;U?.length&&I.push(ot({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:_P,type:ys,availableParticipantIds:P,participantsAvailable:U}))}return{validAssignmentActions:I}}function bG(t,e){return t.bye||hc(t.seedValue)<hc(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function _O({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:r,returnParticipants:n,appliedPolicies:o,drawDefinition:i,drawPosition:s,structureId:a,drawId:c}){let u=[],p=[],m=[],d=[],l=r.map(P=>P.participantId).filter(Boolean),f=o?.[So],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=xg({targetRoundNumber:g,linkType:fo,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=xg({targetRoundNumber:g,linkType:eo,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let P of S){let U=i.structures?.find(E=>E.structureId===P.source.structureId);if(U?.stage!==ct)continue;let A=ai({structureId:P.source.structureId,drawDefinition:i});if(!I||A){let E=U.qualifyingRoundNumber,{matchUps:N}=Pt({matchUpFilters:{roundNumbers:[E],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:U});for(let D of N){let M=D.sides.find(b=>b?.sideNumber===D.winningSide),R=D.matchUpStatus===Nt&&D.sides?.find(({participantId:b})=>b);if(M||R){let{participantId:b,participant:v}=M||R||{};b&&!l.includes(b)&&(v&&n&&u.push(v),p.push(b))}}}}for(let P of y){let U=i.structures?.find(E=>E.structureId===P.source.structureId);if(U?.stage!==ct)continue;let A=ai({structureId:P.source.structureId,drawDefinition:i});if(!I||A){let{positionAssignments:E}=bt({structure:U}),N=E?.map(D=>{let M=D.participantId,R=lt({element:D,name:Zo}).extension?.value;return R?{participantId:M,groupOrder:R?.groupOrder}:{}}).filter(({groupOrder:D,participantId:M})=>D===1&&!l.includes(M)).map(({participantId:D})=>D)??[];if(N&&p.push(...N),n){let D=e.filter(({participantId:M})=>N.includes(M));u.push(...D)}}}return p.length&&m.push(ot({qualifyingParticipants:n?u:void 0,method:jv,type:xp,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:m,sourceStructureIds:d}}function xO({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:r,inactiveDrawPositions:n,activeDrawPositions:o,positionAssignments:i,returnParticipants:s,byeDrawPositions:a,drawDefinition:c,isByePosition:u,drawPosition:p,structureId:m,structure:d,drawId:l,event:f}){if(o.includes(p))return{};let g=D=>!t||D.participantId||D.qualifier||D.bye,I=n?.filter(D=>D!==p&&!(u&&a.includes(D))),h=i?.filter(D=>g(D)&&I?.includes(D.drawPosition))??[],S=h.map(({drawPosition:D})=>D),{matchUps:T}=Pt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:D})=>Fe(D,S)),P=Object.assign({},...y.map(D=>D.sides?.filter(({sourceDrawPositionRange:M})=>M).map(({drawPosition:M,sourceDrawPositionRange:R})=>({[M]:R}))).flat()),U=h.map(D=>D.participantId).filter(Boolean),A=(r??[]).filter(D=>U.includes(D.participantId)),E=Object.assign({},...A.map(D=>({[D.participantId]:D}))),N=h.map(D=>{let M=E?.[D.participantId],R=P[D.drawPosition];return ot({...D,participant:s?J(M,!1,!0):void 0,sourceDrawPositionRange:R})});return N.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:GS,type:Lp,availableAssignments:N}}:{}}function ST(t){let e=et(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return e;let{policyDefinitions:r,returnParticipants:n=!0,provisionalPositioning:o,tournamentRecord:i,drawDefinition:s,drawPosition:a,event:c}=t,u=t.tournamentParticipants??(i&&Gt({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=at({structureId:t.structureId,drawDefinition:s});if(p.error)return p;let m=p.containingStructure||p.structure;if(!m)return{error:wt};let d=m.structureId;if(p=Da({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:Cs};if(p.isAdHoc)return Od(t);if(p.error)return p;let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=yt({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:y}=uT({actionType:wg,appliedPolicies:h,drawDefinition:s,structure:m}),P=S?.activePositionOverrides||[],{sourceStructureIds:U}=xg({finishingPosition:fi,targetRoundNumber:1,linkType:eo,drawDefinition:s,structureId:d})||{},A;U?.length&&(A=U.every(j=>ai({structureId:j,drawDefinition:s})));let E=U.length,N=U.length&&!A,{policyActions:D}=pT({enabledStructures:T,drawDefinition:s,structure:m}),M=![ct,rt].includes(m.stage)||m.stageSequence!==1,{drawId:R}=s,b=[],{assignedPositions:v,positionAssignments:O}=ye({structure:m}),_=v?.find(j=>j.drawPosition===a),F=!!_;if(!O?.map(j=>j.drawPosition)?.includes(a))return{error:Rs};let{stage:L,stageSequence:G}=m,k=[L];L===qe&&k.push(rt),L===rt&&k.push(qe);let H=Ui({entryStatuses:ni,provisionalPositioning:o,drawDefinition:s,stageSequence:G,structureId:d,stages:k}),W=Ri({drawDefinition:s,stages:k}).assignedParticipantIds??[],Y=H.filter(j=>!W.includes(j.participantId)).map(j=>j.participantId),$=I.includes(a),B=g.includes(a);if(y)return{info:"Actions Disabled for structure",isActiveDrawPosition:B,isDrawPosition:!0,hasPositionAssigned:F,validActions:[],isByePosition:$};if(Bn({policyActions:D,action:ys})&&!B&&O&&!N&&(!_||$)){let{validAssignmentActions:j}=OO({positionSourceStructureIds:U,unassignedParticipantIds:Y,possiblyDisablingAction:M,isWinRatioFedStructure:E,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:$,drawPosition:a,structureId:d,event:c});j?.forEach(nt=>b.push(nt))}if(Bn({policyActions:D,action:xp})&&!B){let{validAssignmentActions:j}=_O({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:R});j?.forEach(nt=>b.push(nt))}let{participantId:K}=_||{},X=K&&u.find(j=>j.participantId===K);if(_){Bn({policyActions:D,action:BS})&&!B&&(b.push({type:BS,method:OP,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),$||b.push({type:Pg,method:Yv,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),Bn({policyActions:D,action:Ed})&&!$&&b.push({type:Ed,method:OP,payload:{drawId:R,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:M}));let j=m.stage===ct||m.stage===rt&&m.stageSequence===1;if(!$&&rD({activePositionOverrides:P,activeDrawPositions:g,action:zs})&&Bn({policyActions:D,action:zs})&&vp({drawDefinition:s,structureId:d,drawPosition:a})&&j){let{seedAssignments:nt}=nn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z,seedValue:Q}=nt?.find(pt=>pt.participantId===K)??{};b.push({type:zs,method:Zv,participant:X,seedNumber:z,payload:{drawId:R,structureId:d,participantId:K,seedValue:Q}})}if(!$&&rD({activePositionOverrides:P,activeDrawPositions:g,action:wp})&&Bn({policyActions:D,action:wp})&&vp({drawDefinition:s,structureId:d,drawPosition:a})&&j){let{seedAssignments:nt}=nn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z}=nt?.find(Q=>Q.participantId===K)??{};b.push({method:Xv,type:wp,participant:X,seedNumber:z,payload:{participantId:K,structureId:d,drawId:R}})}if(!$&&K){if(Bn({policyActions:D,action:Qs})){let nt={type:Qs,method:VS,participant:X,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};b.push(nt)}if(Bn({policyActions:D,action:Du})){let nt={type:Du,method:Qv,participant:X,payload:{participantId:K,otherName:void 0}};b.push(nt)}}if(Bn({policyActions:D,action:Lp})){let{validSwapAction:nt}=xO({possiblyDisablingAction:M,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:O,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:$,drawPosition:a,structureId:d,structure:m,drawId:R});nt&&b.push(nt)}}if(Bn({policyActions:D,action:Ug})&&!N){let{validAlternatesAction:j}=RO({possiblyDisablingAction:M,tournamentParticipants:u,positionAssignments:O,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:b,structureId:d,structure:m,drawId:R,event:c});j&&b.push(j)}if(Bn({policyActions:D,action:Dg})&&!N&&!B&&O){let{validLuckyLosersAction:j}=vO({sourceStructuresComplete:A,possiblyDisablingAction:M,isWinRatioFedStructure:E,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:O,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:R});j&&b.push(j)}if(X?.participantType===ft&&Bn({policyActions:D,action:Eg})){let{validModifyAssignedPairAction:j}=PO({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:X,drawId:R,event:c});j&&b.push(j)}return{isActiveDrawPosition:B,isDrawPosition:!0,hasPositionAssigned:F,isByePosition:$,validActions:b,...C}}function Ou({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Bm]?.drawTypeCoercion,o=e?.[Bm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}function Vp({tournamentRecord:t,drawDefinition:e,stage:r=rt,structureId:n,structure:o}){if(!t)return{error:q};if(!o&&!e)return{error:Z};if(!o&&!n&&e?.structures?.filter(a=>a.stage===r).length===1&&(o=e.structures.find(a=>a.stage===r)),!o&&!n)return{error:Ur};let{error:i,positionAssignments:s}=bt({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function TT({structureId:t,drawDefinition:e}){if(!e)return{error:Z};if(!Vt(t))return{error:V};let r=Ws({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!qt([li,En,up,di],n).length;return{...C,valid:o}}function yT({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:V};let r=es(t);return r?{drawSize:r}:x({result:{error:V},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function _u(t){let{drawSizeProgression:e=!1,policyDefinitions:r,drawSize:n}=t||{},{requireParticipantCount:o=!0,tournamentRecord:i,drawDefinition:s,event:a}=t||{},c="getSeedsCount",u=t?.participantsCount??t?.participantCount;if(!r){let I=vo({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return x({result:I,stack:c});r=I.policyDefinitions}let p=It(u);if(u&&!p)return x({result:{error:V},context:{participantsCount:u},stack:c});if(o&&!p)return x({result:{error:pE},stack:c});if(isNaN(n))if(u)({drawSize:n}=yT({participantsCount:u}));else return x({result:{error:qa},stack:c});let m=o&&u||n;if(m&&m>n)return{error:Ql};let d=r?.[wn];if(!d)return{error:JA};let l=d.seedsCountThresholds;return l?(d.drawSizeProgression!==void 0&&(e=d.drawSizeProgression),{seedsCount:l.filter(I=>e?I.drawSize<=n:n===I.drawSize).reduce((I,h)=>u&&u>=h.minimumParticipantCount?h.seedsCount:I,0)}):{error:LA}}function _d({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=Gt({tournamentRecord:r})),!s)return{error:Ka};if(!Array.isArray(s))return{error:V};if(!a)return{error:Ot};let c=e?.[er]??n?.[er]??hs[er],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===ko,l=p===vr&&Ft||d&&ft||Tt,f=Object.assign({},...(t??a.entries??[]).map(S=>({[S.participantId]:S.entryStatus}))),g=Object.keys(f),h=s.filter(S=>g.includes(S.participantId)).filter(S=>{let T=vG({participant:S,participantType:l,eventType:p,entryStatusMap:f}),y=OG({genderEnforced:u,participantMap:o,eventGender:m,participant:S,isDoubles:d,mismatch:T});return T||!y});if(h.length){let S=h.map(T=>T.participantId);return{error:YA,invalidParticipantIds:S}}return{...C,valid:!0}}function vG({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[ko,vr].includes(r)&&t.participantType===Tt&&(Ys(o)||o===so);return t.participantType!==e&&!i}function OG(t){let{participant:e,participantMap:r,eventGender:n,mismatch:o,isDoubles:i,genderEnforced:s}=t,a=!o&&i&&ut(e?.individualParticipantIds?.map(m=>r?.[m]?.participant?.person?.sex).filter(Boolean)??[])||[],c=!n||!a?.length||Pn===n||[Qt,ne].includes(n)&&a[0]===n||yr===n&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||[Pn,yr].includes(n)||[Qt,ne].includes(n)&&u===n;return!s||c&&p}function AT({qualifyingProfiles:t,appliedPolicies:e,idPrefix:r,isMock:n,uuids:o}){let i="generateQualifyingSTructures",s=[],a=[],c=[],u=(g,I)=>g.stageSequence-I.stageSequence,p=(g,I)=>g.roundTarget-I.roundTarget,m=0,d=0,l,f=1;for(let g of t.sort(p)){let I=g.structureProfiles||[];f=g.roundTarget||f;let h=1,S=0,T,y,P;for(let U of(I||[]).sort(u)){let A=Sm(U.drawSize||U.participantsCount),{qualifyingRoundNumber:E,structureOptions:N,matchUpFormat:D,structureName:M,structureId:R,drawType:b}=U,v=U.matchUpType,O=U.qualifyingPositions||_G({drawSize:A,qualifyingRoundNumber:E}),_,F,w;if(!It(A))return x({result:{error:qa},stack:i});let L=t.length>1?`${f}-`:"",G=I.length>1||L?h:"",k=M||(L||G?`${Qe(ct)} ${L}${G}`:Qe(ct));if(b===Nn){let{structures:H,groupCount:W,maxRoundNumber:Y}=Ma({structureName:U.structureName||k,structureId:R||o?.pop(),stage:ct,structureOptions:N,appliedPolicies:e,stageSequence:h,matchUpType:v,roundTarget:f,drawSize:A,idPrefix:r,isMock:n,uuids:o});S=W,_=Y,F=H[0],l=[1]}else({drawSize:A,matchUps:w,roundLimit:_}=bn({qualifyingRoundNumber:E,qualifyingPositions:O,matchUpType:v,drawSize:A,idPrefix:r,isMock:n,uuids:o})),F=Sn({structureName:U.structureName||k,structureId:R||o?.pop(),qualifyingRoundNumber:_,stage:ct,matchUpFormat:D,stageSequence:h,matchUpType:v,roundLimit:_,matchUps:w}),f&&At({extension:{name:Mn,value:f},element:F}),S=w?.filter(H=>H.roundNumber===_)?.length||0;if(h>1){let{link:H}=Ra({sourceStructureId:y,sourceRoundNumber:T,targetStructureId:F.structureId,finishingPositions:P===eo?[1]:void 0,linkType:P});c.push(H),m+=(A||0)-S}else m+=A||0;P=b===Nn?eo:fo,y=F.structureId,T=_,a.push(F),h+=1}d+=S,s.push({qualifiersCount:S,finalQualifyingRoundNumber:T,finalQualifyingStructureId:y,finishingPositions:l,roundTarget:f,linkType:P}),f+=1}return{qualifiersCount:d,qualifyingDrawPositionsCount:m,qualifyingDetails:s,structures:a,...C,links:c}}function _G({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function ET(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=mt(t.drawSize),o=e&&t.drawType!==$r&&(typeof e=="boolean"||e<=2)&&n===2&&go||t.drawType||go,i=lU.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=go;else if(n<4&&r)return{...x({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:$u},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function wO(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Qe(rt),...t,stage:rt},{structures:i,groupCount:s,groupSize:a}=Ma(o);if(s<1)return{error:ME};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Qe(fe)}],[u]=i,{structures:p,links:m}=$S({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...C,structures:i,links:m}}function LO({mainStructure:t,consolationStructure:e,deciderStructure:r}){let o=e.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),i=t.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),s=e.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),a=o.map((p,m)=>{let l=o.indexOf(p)%2?En:li,f=1+m;return{linkType:ro,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:fo,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:En,roundNumber:i,structureId:t.structureId}},u=[{linkType:fo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:En,roundNumber:1,structureId:r.structureId}},{linkType:ro,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:En,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function FO({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=ci({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=Ss({structureName:t||Qe(rt),structureId:i?.pop(),stageSequence:1,stage:rt,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=ci({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=Ss({structureName:Qe(dU),matchUps:p,structureId:i?.pop(),stage:qe,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=bn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=Ss({structureName:Qe(mU),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:fe,matchUpType:e});s.push(l);let f=LO({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...C}}function kO(t){let{qualifyingRoundNumber:e,finishingPositionOffset:r,qualifyingPositions:n,matchUpType:o,idPrefix:i,drawSize:s,isMock:a,uuids:c}=t;if(!It(s)||s<2)return{matchUps:[],roundsCount:0};if(On(s))return bn(t);let u=xG(s),p=u.shift(),m=tt(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=Fp({roundNumber:l,matchUpType:o,idPrefix:i,matchUps:d,isMock:a,nodes:m,uuids:c})),l++;let f=t.roundLimit||e;for(let I of u){let h=I.participantsCount/2,S=tt(1,h+1);n&&h===n&&(f=l-1);let T=S.map(y=>{let P=Ud({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:P}});d.push(...T),l++}let g=l-1;return d=Ua({finishingPositionOffset:r,lucky:!0,roundsCount:g,roundLimit:f,matchUps:d}),f&&(d=d.filter(I=>I.roundNumber<=f)),{matchUps:d,roundsCount:g,roundLimit:f}}function xG(t){let e=mt(t),r=e%2?e+1:e,n=!!(Math.ceil(r/2)%2),o=[{participantsCount:r,preFeedRound:n}];for(;r>2;){let i=Math.ceil(r/2),s=i===1,a=!!(!s&&i%2);r=!s&&a?i+1:i;let c=!!(r!==2&&Math.ceil(r/2)%2);o.push({participantsCount:r,preFeedRound:c,feedRound:a})}return o}function UT(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=rt,matchUpType:o,drawSize:i,uuids:s}=t,a=()=>!t.isMock&&!t.idPrefix?void 0:`${t.drawDefinition.drawId}-s-0`,c=t.structureId||a()||s?.pop(),u=t.appliedPolicies??yt(t),p=t.policyDefinitions?.[nc]||u?.[nc];t.skipRounds=t.skipRounds||i<=4&&(p?.feedFromMainFinal?0:1)||0;let m=t.structureName??e?.["0"]?.name??Qe(rt),d=()=>{let{matchUps:f}=bn(t);return{structures:[Sn({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...C}};return{generators:{[$r]:()=>({structures:[Sn({finishingPosition:fi,stageSequence:r,structureName:m,matchUps:[],matchUpType:o,structureId:c,stage:n})],links:[],...C}),[Gi]:()=>{let{matchUps:f}=kO(t);return{structures:[Sn({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...C}},[go]:()=>d(),[Jc]:()=>FO(t),[Qc]:()=>yc({...t,roundOffsetLimit:3,playoffAttributes:e??Ef}),[Xc]:()=>yc({...t,roundOffsetLimit:2,playoffAttributes:e??Uf}),[fe]:()=>yc(t),[la]:()=>{let{matchUps:f}=ci({drawSize:i,uuids:s,matchUpType:o});return{structures:[Sn({stageSequence:r,structureName:m,matchUpType:o,structureId:c,stage:rt,matchUps:f})],links:[],...C}},[pp]:()=>WS(t),[Zc]:()=>Ec({...t,feedRounds:1,fmlc:!0}),[pU]:()=>Ec({...t,feedRounds:1}),[Eh]:()=>Ec({...t,feedsFromFinal:1}),[Uh]:()=>Ec({...t,feedsFromFinal:2}),[Ph]:()=>Ec({...t,feedsFromFinal:3}),[mp]:()=>Ec(t),[Af]:()=>YS(t),[Nn]:()=>Ma(t),[Io]:()=>wO(t)}}}function xd(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,staggeredEntry:o,drawDefinition:i,tieFormat:s,isMock:a,uuids:c}=t||{},u=mt(t.drawSize),p=t.drawTypeCoercion??Ou({appliedPolicies:n,drawType:t.drawType}),m="generateDrawStructuresAndLinks",d=ET({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:p,drawSize:u});if(d.error)return d;let l=d.drawType,f=[],g=[],I=t?.matchUpType??kt,h=i?.structures?.filter(({stage:H})=>H===ct);h&&f.push(...h);let S=h?.map(({structureId:H})=>H),T=i?.structures?.find(({stage:H,stageSequence:W})=>H===rt&&W===1),y=i?.links?.filter(H=>H.target.structureId===T?.structureId&&S?.includes(H.source.structureId)),P=(H,W)=>{if(H.linkType===eo&&W?.structures){let Y=H.source.finishingPositions||[];return W.structures.length*Y.length}else if(H.linkType===fo&&W?.matchUps?.length){let Y=H.source.roundNumber;return W.matchUps.filter(({roundNumber:B})=>B===Y).length}},U=h?.map(H=>{let W=y?.find(X=>X.target.structureId===H.structureId),Y=bt({structure:H})?.positionAssignments?.length??0;if(!W)return Y;let $=W?.source.structureId,B=i.structures?.find(X=>X.structureId===$),K=P(W,B)||0;return Y-K}).filter(Boolean).reduce((H,W)=>H+W,0),A=y?.map(H=>{let W=H.source.structureId,Y=h?.find($=>$.structureId===W);return P(H,Y)}).filter(Boolean).reduce((H,W)=>H+W,0),E=!!(T&&!T?.matchUps?.length);if(h?.length&&!E)return{error:YI};let N=!h?.length&&t.qualifyingProfiles,D=N?.length&&AT({idPrefix:t.idPrefix,qualifyingProfiles:N,appliedPolicies:n,isMock:a,uuids:c});if(D?.error)return D;let{qualifyingDrawPositionsCount:M,qualifyingDetails:R,qualifiersCount:b}=D||{qualifyingDrawPositionsCount:U,qualifiersCount:A};M&&(D?.structures&&f.push(...D.structures),D?.links&&g.push(...D.links)),Object.assign(t,ot({drawSize:u,matchUpType:I,tieFormat:s}));let v=l!==$r&&(!u||u<2||!o&&![la,Gi].includes(l)&&([Io,Nn].includes(l)&&u<3||![Nn,Io].includes(l)&&!On(u)));if(v&&!M)return x({context:{drawSize:u,invalidDrawSize:v},result:{error:$u},stack:m});let{generators:O,error:_}=UT(t);if(_)return{error:_};let F=O[l];if(!F)return{error:Gl};let w=F?.();if(w.error)return w;let{structures:L,links:G}=w;if(L?.length){let H=L.find(({stage:W,stageSequence:Y})=>W===rt&&Y===1);if(T&&H){if(E){let W=H.structureId;if(H.structureId=T.structureId,G?.length)for(let Y of G)Y.source.structureId===W&&(Y.source.structureId=T.structureId),Y.target.structureId===W&&(Y.target.structureId=T.structureId)}else if(!r)return{error:YI}}f.push(...L)}f.sort(Ti),G?.length&&g.push(...G);let k=w.structures.find(({stage:H,stageSequence:W})=>H===rt&&W===1);for(let H of R||[]){let{finalQualifyingRoundNumber:W,finalQualifyingStructureId:Y,roundTarget:$,finishingPositions:B,linkType:K}=H,X=k&&Ra({targetStructureId:k.structureId,sourceStructureId:Y,sourceRoundNumber:W,finishingPositions:B,targetEntryRound:$,linkType:K})?.link;if(X?.error)return X;X&&g.push(X)}return y&&g.push(...y),{...C,qualifyingResult:{qualifyingDrawPositionsCount:M,qualifiersCount:b},structures:f,links:g}}function wd(t){let{modifyOriginal:e=!0,stageSequence:r=1,isMock:n}=t||{},o="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return x({result:{error:Z},stack:o});let i=e?t.drawDefinition:J(t.drawDefinition,!1,!0),{tieFormat:s,matchUpType:a}=t;if(s){let T=cr({tieFormat:s});if(T.error)return T}s=ir(s??We({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||kt),t.tieFormat=s,t.matchUpType=a;let c=Rp({drawDefinition:i,stage:rt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&_p({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:rt});let u=De({drawDefinition:i}).drawMatchUps.map(Ue),p=xd(t);if(p.error)return x({result:p,stack:o});let{structures:m,links:d,qualifyingResult:l}=p;i.structures=m,i.links=d;let f=Math.max(t.qualifiersCount??0,l?.qualifiersCount||0);if(l?.qualifyingDrawPositionsCount&&!Rp({stage:ct,drawDefinition:i})){let y=_p({drawSize:l.qualifyingDrawPositionsCount,stage:ct,drawDefinition:i});if(y.error)return y}if(f){let T=kS({qualifiersCount:f,drawDefinition:i,stage:rt});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,ot({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=ae({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=Ca({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=$i({drawDefinition:i,matchUpsMap:h});return vt({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...C,structures:m,matchUps:I,links:d}}function Nc(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!GO({scaleItem:o}))return{error:za};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===Ar&&o?.eventType!==vr)return{error:za};let a=VO({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=Lr();c.includes(nr)&&dt({topic:nr,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...C,info:of,existingValue:o?.scaleValue}||s&&{...C,newValue:o?.scaleValue}||{error:re}}function lD(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:q};if(!n.participants)return{error:Ka};let s=0,a={},c=[];for(let m of e){let d=m?.participantId;if(Array.isArray(m?.scaleItems))for(let l of m.scaleItems)if(GO({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:za}}for(let m of n.participants){let{participantId:d}=m||{};if(Array.isArray(a[d]))for(let l of a[d]){if(m.participantType===Ar&&l?.eventType!==vr)return x({context:{participantId:d,scaleItem:l,participantType:m.participantType},info:"Invalid participantType for eventType",result:{error:za}});VO({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++}}let u=s?void 0:_s,{topics:p}=Lr();if(p.includes(nr)&&s&&dt({topic:nr,payload:{tournamentId:n.tournamentId,participants:c}}),i){let{eventId:m,drawId:d,...l}=i,f=l.scaleAttributes?.scaleType&&[l.scaleAttributes.scaleType];if(Object.keys(l).length){let g={itemType:Lf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=ze({tournamentRecord:n,eventId:m,drawId:d});d&&Ag({drawDefinition:I,timeItem:g}),m&&Qi({event:h,timeItem:g})}else Dc({tournamentRecord:n,timeItem:g})}}return o&&p.includes(yi)&&dt({topic:yi,payload:o}),ot({...C,modificationsApplied:s,info:u})}function GO({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function VO({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Li};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:za};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=yo({scaleAttributes:r,participant:e}),c=p=>[void 0,null,""].includes(p),u=!(c(a?.scaleValue)&&c(r.scaleValue))&&JSON.stringify(a?.scaleValue)!==JSON.stringify(r.scaleValue);if(u){let{scaleType:p,eventType:m,scaleName:d}=r,l=[hi,p,m,d].join("."),f=ot({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...C,valueChanged:u,newValue:r.scaleValue}}function Fg(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=et(t,[{[se]:!0},{modifiedScaleValues:!0,[He]:Kr}]);if(o.error)return o;for(let i in r){let s=Nc({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...C}}function Mc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:ie};let{participant:i,tournamentId:s}=To({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...yo({participant:i,scaleAttributes:r}),tournamentId:s}:{error:re}}var wG=(t=0)=>250/Math.pow(t+5,.4),LG=()=>1;function FG(t=3,e=2){let r=t/e;return isNaN(r)?Ld.kDefault():r}var Ld={nSpread:400,diffThreshold:.125,kCalc:wG,kMultiplier:FG,kDefault:LG};function PT(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=_e,winnerCountables:o=1,loserCountables:i=0,ratingType:s=Qn,maxCountables:a,countables:c}=t||{},u=n?.[s];if(!u)return{error:it};let p=u.range||t.ratingRange;e=e||u.defaultInitialization,r=r||u.defaultInitialization;let m=p[0]>p[1],d=u.decimalsCount||0,l=m?p.slice().reverse():p,f=(_,F)=>parseFloat(F)>=Math.min(..._)&&parseFloat(F)<=Math.max(..._);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=Ru({targetRange:_e[Qn].range,sourceRange:l,value:m?p[0]-e:e}),I=Ru({targetRange:_e[Qn].range,sourceRange:l,value:m?p[0]-r:r}),h=(_,F)=>1/(1+Math.pow(10,(F-_)/Ld.nSpread)),S=h(g,I),T=h(I,g),y=Ld.kCalc(o),P=Ld.kCalc(i),U=Ld.kMultiplier(a,c),A=g+U*y*(1-S),E=I+U*P*(0-T),N=Ru({sourceRange:_e[Qn].range,value:A,targetRange:l}),D=Ru({sourceRange:_e[Qn].range,value:E,targetRange:l}),M=m?p[0]-N:N,R=parseFloat(M.toFixed(d)),b=m?p[0]-D:D,v=parseFloat(b.toFixed(d)),O=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(N>D&&O>Ld.diffThreshold||R<0||v<0)&&(R=e,v=r),{newWinnerRating:R,newLoserRating:v}}var BO=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function DT(t){let e=et(t,[{[se]:!0},{matchUpIds:!0,[He]:Be,[gn]:rs},{ratingType:!1,[tr]:S=>_e[S]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i=Qn,refreshDynamic:s,considerGames:a,drawDefinition:c,matchUpIds:u,asDynamic:p}=t,m=_e[i],{accessor:d}=m,l={},f=(t.matchUps||s&&or({drawDefinition:c,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:pe}}).matchUps||Ae({matchUpFilters:{matchUpIds:u,matchUpStatuses:pe},tournamentRecord:o,inContext:!0}).matchUps)??[],g=`${i}.${Vm}`,I=p?g:i;f.sort(Mi);for(let S of f){let{endDate:T,matchUpFormat:y,score:P,sides:U,winningSide:A}=S,E=S.matchUpType,N={eventType:E,scaleName:i,scaleType:Ii},D={scaleName:g,eventType:E,scaleType:Ii},M=Object.assign({},...(U??[]).map(G=>{let{sideNumber:k,participant:H}=G;return k&&{[k]:[H?.participantId,...H?.individualParticipantIds??[]].filter(Boolean).flat()}})),R=Object.assign({},...Object.values(M).flat().map(G=>{let k=l[G],W=!s||k?Mc({scaleAttributes:D,tournamentRecord:o,participantId:G}).scaleItem:void 0,Y=Mc({tournamentRecord:o,scaleAttributes:N,participantId:G}).scaleItem,$=d?{[d]:void 0}:void 0;return G&&{[G]:W??Y??{scaleName:I,eventType:E,scaleDate:T,scaleType:Ii,scaleValue:$}}})),b=y?Ye(y):{},v=b?.bestOf||1,O=b?.setsTo||1,_=a?v&O:v,F=P?.sets&&BO(P.sets)||A===1&&[1,0]||[0,1],w=A?M[A]:[],L=A?M[3-A]:[];for(let G of w){let k=R[G]?.scaleValue,H=typeof k=="object"?k[d]:k;for(let W of L){let Y=R[W]?.scaleValue,$=typeof Y=="object"?Y[d]:Y,B=A?F[A]:[0,0],K=A?F[3-A]:[0,0],{newWinnerRating:X,newLoserRating:j}=PT({winnerCountables:B,loserCountables:K,maxCountables:_,winnerRating:H,loserRating:$,ratingType:i}),nt=d?{...k,[d]:X}:X,z=d?{...Y,[d]:j}:j;R[G].scaleValue=nt,R[W].scaleValue=z,R[G].scaleName=I,R[W].scaleName=I}}Object.assign(l,R),r&&Fg({tournamentRecord:o,modifiedScaleValues:l,removePriorValues:n})}let h=f.map(({matchUpId:S})=>S);return{...C,modifiedScaleValues:l,outputScaleName:I,processedMatchUpIds:h}}function xu(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:Z};let{participantIdPairings:a,matchUpsCount:c}=t,u=vd(t);if(u.error)return x({result:u});let{lastRoundNumber:p,availableMatchUpsCount:m=0,roundMatchUpsCount:d=0}=u;if(!c)o?c=d:m>0&&(c=m);else if(c>d&&t.restrictMatchUpsCount!==!1)return x({result:{error:V,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!It(c)||e&&!Array.isArray(e)||!a&&!c)return{error:V,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:V,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:V,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??tt(0,c).map(()=>({participantIds:[void 0,void 0]}));let f=I=>{if(!t.idPrefix)return;let h=r.drawId,S=t.idPrefix??"ah";return`${h}-${S}-${l}-${I}`},g=a?.map((I,h)=>{let S=I?.participantIds??[void 0,void 0];S.push(void 0,void 0);let y=S.slice(0,2).map((U,A)=>ot({sideNumber:A+1,participantId:U})),P=e[h]??f(h)??Dt();return{roundNumber:l,matchUpStatus:Jt,matchUpId:P,sides:y}});if(g?.length){let I=We({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=Ca({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:Yt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...C}}function WO({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:r,valueObjects:n,deltaObjects:o}){let i=Object.assign({},...e.map(S=>({[S.pairing]:S.value}))),s=Object.keys(r),a=[],c=HO({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[fD(c)];a.push(c);let p=c.value,m=c,d=1,l=0,f=s.length,g;do f-=1,g=s.length*r[s[0]].length;while(g>t&&f>5);let I=[];s.forEach(S=>{r[S].slice(0,f).forEach(y=>{l+=1;let P=Oa(S,y.opponent);if(!I.includes(P)){let U=HO({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(fD(U))){u.push(fD(U)),a.push(U);let{maxDelta:A,value:E}=U;A<m.maxDelta&&(m=U),(E<p||E===p&&Math.round(Math.random()))&&(p=E),I.push(P),d+=1}}}),a=a.filter(y=>Math.abs(y.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=Zr(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function fD(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function HO({valueSortedPairings:t,stipulated:e=[],pairingValueMap:r,deltaObjects:n,valueObjects:o,actorsCount:i}){let s=[].concat(...e),a=[],c=0;e.filter(Boolean).forEach(d=>{let[l,f]=d,g=Oa(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Ee(t,i).map(d=>hr(d).map(l=>({...l,value:l.value+Math.random()*Math.round(Math.random())}))).flat().forEach(d=>{let l=d.pairing.split("|");if(!l.reduce((g,I)=>s.includes(I)||g,!1)){s.push(...l);let g=d.value;c+=g,a.push({participantIds:l,value:g})}}),a.sort((d,l)=>d.value-l.value);let p=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Oa(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Oa(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function Oa(t,e){return[t,e].sort(Au).join("|")}function gD({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=Oa(i,o);r.includes(s)||r.push(s)})});let n=Object.assign({},...r.map(o=>({[o]:0})));return{uniquePairings:r,possiblePairings:e,deltaObjects:n}}function jO({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(St);if(n.length===2){let[o,i]=n,s=Oa(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function YO({possiblePairings:t,valueObjects:e}){let r={};for(let o of Object.keys(t)){let i=t[o].map(s=>n(o,s));r[o]=i.sort((s,a)=>s.value-a.value)}function n(o,i){let s=Oa(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var kG=0;function qO({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=_e[n]?.defaultInitialization??kG;return o.split("|").map(s=>{if(r===qr){let a=t?.find(c=>c.participantId===s)?.individualParticipantIds;return a?a?.map(c=>e[c]||i):i*2}else return e[s]||i})}function $O(t){let{tournamentParticipants:e,adHocRatings:r={},possiblePairings:n,uniquePairings:o,maxIterations:i,minimizeDelta:s,deltaObjects:a,valueObjects:c,eventType:u,scaleName:p,salted:m}=t;o.forEach(T=>{let y=qO({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),P=typeof m=="number"&&m||.5,U=m&&(Math.round(Math.random())?P:P*-1)||0,A=Math.abs(y[0]-y[1])+U,E=Math.abs(y[0]-y[1]);a[T]=E,c[T]||(c[T]=0),c[T]+=A?Math.pow(A,2):0});let d=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=YO({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=WO({valueSortedPairings:d,maxIterations:i,pairingValues:l,deltaObjects:a,valueObjects:c}),{participantIdPairings:S}=s?I:f;return{participantIdPairings:S,candidatesCount:g,deltaCandidate:I,iterations:h,candidate:f}}var GG=100,VG=100,BG=4e3;function Fd(t){let{encounterValue:e=GG,sameTeamValue:r=VG,maxIterations:n=BG,updateParticipantRatings:o,generateMatchUps:i=!0,ignoreLastRoundNumber:s,iterationMatchUps:a,tournamentRecord:c,dynamicRatings:u,refreshDynamic:p,participantIds:m,drawDefinition:d,roundNumber:l,structureId:f,matchUpIds:g,eventType:I,scaleName:h,idPrefix:S,isMock:T,salted:y,event:P}=t;if(!d)return{error:Z};if(!t.structure&&!f)return{error:wt};let U=t.structure||at({drawDefinition:d,structureId:f}).structure;if(!ht(U))return{error:mi};if(!m?.length)return{error:Uo};let A=[...a??[],...U?.matchUps??[]],{encounters:E}=jO({matchUps:A}),N=c?.participants??[],D={};if(u){let B=ut(U?.matchUps?U.matchUps.map(({roundNumber:X})=>X):[]),K=Math.max(...B,0);if(K){let X=U?.matchUps?.filter(({roundNumber:nt})=>nt===K).map(({matchUpId:nt})=>nt),j=DT({ratingType:h??P?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,refreshDynamic:p,drawDefinition:d,matchUpIds:X});if(j.error)return j;j.modifiedScaleValues&&(D=j.modifiedScaleValues)}}let{valueObjects:M}=HG({tournamentParticipants:N,encounterValue:e,sameTeamValue:r,encounters:E}),{uniquePairings:R,possiblePairings:b,deltaObjects:v}=gD({participantIds:m}),O=Object.values(D).length?D:t.adHocRatings,_={tournamentParticipants:N,possiblePairings:b,participantIds:m,uniquePairings:R,drawDefinition:d,maxIterations:n,adHocRatings:O,deltaObjects:v,valueObjects:M,eventType:I,scaleName:h,structure:U,salted:y},{candidatesCount:F,participantIdPairings:w,deltaCandidate:L,iterations:G,candidate:k}=$O(_);if(!F)return{error:Xu};let H,W;if(i){let B=xu({structureId:U?.structureId,ignoreLastRoundNumber:s,participantIdPairings:w,newRound:!0,drawDefinition:d,roundNumber:l,matchUpIds:g,idPrefix:S,isMock:T,event:P});if(B.error)return B;H=B.roundNumber,W=B.matchUps}let{maxDelta:Y,maxDiff:$}=k;return{roundNumber:H,participantIdPairings:w,modifiedScaleValues:D,candidatesCount:F,deltaCandidate:L,...C,iterations:G,matchUps:W,maxDelta:Y,maxDiff:$}}function HG({encounters:t,tournamentParticipants:e,encounterValue:r,sameTeamValue:n}){let o={};for(let s of t)o[s]||(o[s]=0),o[s]+=r;let i=e?.filter(({participantType:s})=>s===Ft);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=gD({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function NT(t){let{drawType:e=go,attachConsolation:r=!0,applyPositioning:n=!0,tournamentRecord:o,staggeredEntry:i,automated:s,placeByes:a,isMock:c,event:u}=t,p=t?.drawDefinition;if(!p)return{error:Z};let m=$e,d=Ui({stageSequence:1,drawDefinition:p,stage:m}),l=[Nn,Jc,Io].includes(e)?d.length:es(d.length);if(!i&&e===la&&d.length<2||e===Nn&&d.length<3)return{error:$u};let{tieFormat:f,matchUpType:g}=t;if(f){let R=cr({tieFormat:f});if(R.error)return R}f=ir(f??We({drawDefinition:p})?.tieFormat),g=g??p.matchUpType;let{structures:I}=In({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:$A};if(I?.[0]?.matchUps?.length)return{error:af};let S=I?.[0]?.structureId;Object.assign(t,ot({structureName:t.structureName??Qe($e),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:m}));let T=UT(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:Gl};let P=y?.();if(P.error)return P;let{structures:U,links:A}=P,E=U.map(R=>Pt({structure:R}).matchUps).flat();f&&E.forEach(R=>{let{tieMatchUps:b}=Ca({matchUp:R,tieFormat:f,isMock:c});Object.assign(R,{tieMatchUps:b,matchUpType:g})}),(!n||!r)&&(p=J(p,!1,!0)),p.links||(p.links=[]),A.length&&p.links.push(...A);let N=U.map(({structureId:R})=>R);p.structures||(p.structures=[]);let D=p.structures.map(({structureId:R})=>R);p.structures=p.structures.map(R=>N.includes(R.structureId)?U.find(({structureId:b})=>b===R.structureId):R);let M=U.filter(({structureId:R})=>!D.includes(R));return M.length&&p.structures.push(...M),s&&Tc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&vt({drawDefinition:p}),{links:A,structures:U,...C}}var jg={};Zt(jg,{addGame:()=>ED,addPoint:()=>AD,addSet:()=>PD,addShot:()=>UD,analyzeScore:()=>Bg,analyzeSet:()=>Fu,calculateHistoryScore:()=>SD,checkScoreHasValue:()=>Se,checkSetIsComplete:()=>Wp,clearHistory:()=>yD,generate:()=>hD,generateScoreString:()=>Yo,generateTieMatchUpScore:()=>Pc,getSetComplement:()=>Wg,getTiebreakComplement:()=>$p,helpers:()=>tN,isValidMatchUpFormat:()=>Dr,keyValueScore:()=>KD,mutate:()=>RD,parseMatchUpFormat:()=>Ye,parseScoreString:()=>jd,query:()=>eN,redo:()=>DD,reverseScore:()=>ID,setServingSide:()=>TD,stringifyMatchUpFormat:()=>sp,tidyScore:()=>ZD,umo:()=>MD,undo:()=>ND,validateScore:()=>Hg,validateTieFormat:()=>cr});var hD={};Zt(hD,{generateScoreString:()=>Yo,generateTieMatchUpScore:()=>Pc,reverseScore:()=>ID});function Yo(t){let{winnerFirst:e=!0,setTBlast:r=!0,addOutcomeString:n,reversed:o=!1,matchUpStatus:i,matchUpFormat:s,autoComplete:a,winningSide:c,sets:u}=t;if(!u)return{error:it,info:"missing sets"};let p=s&&Ye(s),{bestOf:m,finalSetFormat:d,setFormat:l}=p??{},g=o||!(!e||!c||c===1),I=n?WG({matchUpStatus:i}):"",h=u?.sort(jG).map(S).filter(Boolean).join(" ")||"";if(!I)return h;if(c===2)return`${I} ${h}`;return`${h} ${I}`;function S(T){let P=m&&T.setNumber===m&&d?d:l,U=B=>te(B?.side1Score)||te(B?.side2Score),E=(B=>te(B?.side1TiebreakScore)||te(B?.side2TiebreakScore))(T),N=P?.tiebreakSet||!U(T)&&E,{side1Score:D,side2Score:M,side1TiebreakScore:R,side2TiebreakScore:b}=T,v=R||(te(R)||E&&a?0:""),O=b||(te(b)||E&&a?0:"");if(N)return`[${(g?[O,v]:[v,O]).join("-")}]`;let _=E?Math.min(v,O):"",F=_===v?1:2,w=te(_)?`(${_})`:"",L=D||(te(D)||a?0:""),G=M||(te(M)||a?0:""),k=B=>!r&&F===B?w:"",H=`${L}${k(1)}`,W=`${G}${k(2)}`,Y=r&&E?`(${_})`:"",$=g?`${[W,H].join("-")}${Y}`:`${[H,W].join("-")}${Y}`;return["-"," "].includes($)&&($=""),$}}function WG({matchUpStatus:t}){let e={[rr]:"RET",[Ct]:"WO",[Me]:"DF/DF",[Te]:"WO/WO",[ss]:"SUS",[Or]:"ABN",[Rt]:"DEF",[cu]:"DR"};return t&&e[t]||""}function jG(t,e){return t.setNumber-e.setNumber}function ID(t){if(!t?.score)return{error:it};let{sets:e}=t.score,r=e.map(s=>{let{side1TiebreakScore:a,side2TiebreakScore:c,winningSide:u,side1Score:p,side2Score:m,setNumber:d}=s;return ot({winningSide:u?3-u:void 0,side1TiebreakScore:c,side2TiebreakScore:a,side1Score:m,side2Score:p,setNumber:d})}),n=t?.setTBlast,o=Yo({setTBlast:n,sets:r}),i=Yo({sets:r,reversed:!0,setTBlast:n});return{reversedScore:{sets:r,scoreStringSide1:o,scoreStringSide2:i},...C}}var RD={};Zt(RD,{addGame:()=>ED,addPoint:()=>AD,addSet:()=>PD,addShot:()=>UD,calculateHistoryScore:()=>SD,clearHistory:()=>yD,redo:()=>DD,setServingSide:()=>TD,umo:()=>MD,undo:()=>ND});function qo({matchUp:t}){let{extension:e}=lt({name:qm,element:t});if(!e)return{error:Ce};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...C}}function SD(t){if(!t)return{error:it};let{matchUp:e,updateScore:r}=t;if(!e)return{error:Sr};let n=qo({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:V,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Yl};if(!Dr({matchUpFormat:o}))return{error:jl};let i=Ye(o),{bestOf:s,finalSetFormat:a,setFormat:c}=i,u=["0","15","30","40","A","G"],p={sets:[]},m=[],d,l=[0,0],f=1,g=0,I,h=0,S=D=>[1,2].includes(D),T=()=>(g+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:g,games:[]}),y=()=>({winningSide:void 0,points:[]}),P=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),U=P(),A=y(),E=T(),N=0;for(let D of n){N+=1,I=p.sets.length+1===s;let M=I&&a?a:c,{tiebreakAt:R,setTo:b,NoAD:v,tiebbreakFormat:O}=M,_=E.side1Score===R&&E.side1Score===E.side2Score,F=!!M.tiebreakSet,w=F?M.tiebreakSet:O,{tiebreakTo:L,NoAD:G}=w||{},k=()=>{d=void 0,l=[0,0],f=3-f,E.side1TiebreakScore="",E.side2TiebreakScore="",E.side1PointScore="",E.side2PointScore="",h=0},H=$=>{E.winningSide=$;let{s:B,...K}=E;p.sets.push(K),U=P(),A=y(),E=T(),k()},W=$=>{A.winningSide=$;let{g:B,...K}=A;E.games.push(K),U=P(),A=y(),k();let X=`side${$}Score`;E[X]+=1},Y=$=>{U.winningSide=$;let{p:B,...K}=U;A.points.push(K),U=P(),h=0;let X=()=>l.reduce((Q,pt)=>Q+pt)%4/4>.5?f:3-f,j=$-1;if(_||F){l[j]+=1,d=X(),E[`side${$}TiebreakScore`]=l[j],E[`side${3-$}TiebreakScore`]=l[1-j];let nt=G?1:2;if(l[j]>=L&&l[j]>=l[1-j]+nt)return W($),{gameCompleted:!0}}else if(l[1-j]===4&&l[j]===3?l[1-j]-=1:l[j]+=1,E.side1PointScore=u[l[0]],E.side2PointScore=u[l[1]],l[j]===5||l[j]===4&&l[1-j]<3||v&&l[j]===4)return W($),{gameCompleted:!0}};if(S(D.srv)&&(f=D.srv),["p","s","g","o"].includes(D.u)&&m.push(D.u),D.shotOutcome&&(U.shots.push(D),D.shotType==="SERVE"&&["OUT","NET"].includes(D.shotOutcome)&&(h+=1),h===2)){let B=3-f;Y(B)}if(S(D.p)||It(D.pointNumber)){let $=D.winningSide||D.p;if(Y($)?.gameCompleted)continue}if(S(D.g)||It(D.gameNumber)){let $=D.winningSide||D.g;A.winningSide=$;let B=`side${$}Score`,K=`side${3-$}Score`;if(m.length&&(m.includes("p"),m=[]),W($),E[B]===b&&E[B]-E[K]>=(v?1:2)&&(H($),I))break}if(S(D.s)||It(D.setNumber)){let $=D.winningSide||D.s;if(H($),m.length&&(m.includes("p"),m.includes("g"),m=[]),I)break}}return N!==n.length&&console.log({error:"Match completed with excess history"}),(E.side1Score||E.side2Score||E.games.length||E.side1TiebreakScore||E.side2TiebreakScore)&&p.sets.push(E),p.scoreStringSide1=Yo({...p,matchUpFormat:o}),p.scoreStringSide2=Yo({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...C,servingSide:f,score:p}}function $o({undoHistory:t,history:e,matchUp:r}){return At({element:r,extension:{value:{history:e,undoHistory:t},name:qm}})}function TD({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:ql};let{history:r=[]}=qo({matchUp:t});return r.push({srv:e}),$o({matchUp:t,history:r})}function yD({matchUp:t}){return $o({matchUp:t})}function AD({matchUp:t,point:e}){if(!e||!t)return{error:it};if(typeof e!="object")return{error:V,context:{point:e}};let{history:r=[]}=qo({matchUp:t});return r.push(e),$o({matchUp:t,history:r})}function ED({matchUp:t,game:e}){if(typeof e!="object")return{error:V,context:{game:e}};let{history:r=[]}=qo({matchUp:t});return r.push(e),$o({matchUp:t,history:r})}function UD({matchUp:t,shot:e}){if(typeof e!="object")return{error:it};let{history:r=[]}=qo({matchUp:t});return r.push(e),$o({matchUp:t,history:r})}function PD({matchUp:t,set:e}){if(typeof e!="object")return{error:it};let{history:r=[]}=qo({matchUp:t});return r.push(e),$o({matchUp:t,history:r})}function DD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=qo({matchUp:t});return r.length&&e.push(r.pop()),$o({matchUp:t,history:e,undoHistory:r})}function ND({matchUp:t}){let{history:e=[],undoHistory:r=[]}=qo({matchUp:t});return r.push(e.pop()),$o({matchUp:t,history:e,undoHistory:r})}var MD={};var tN={};Zt(tN,{keyValueScore:()=>KD,parseMatchUpFormat:()=>Ye,stringifyMatchUpFormat:()=>sp,tidyScore:()=>ZD});var Js=" ",MT="DEF",KO="COMPLETED",CD="WO",YG="WO/WO",bD="ABN",vD="SUS",OD="RET",_D="INT",RT=[OD,MT,CD,YG,bD,vD,_D];var CT="DEFAULTED";var xD="WALKOVER";var bT="ABANDONED",vT="SUSPENDED",wD="RETIRED",OT="INTERRUPTED";var zO=[wD,CT,xD],qG="Enter Score",As="()",Es="[]",LD=["up","left","shift+tab"],FD=["enter","down","tab","right"],kd="backspace",kD="r",GD="s",VD="a",BD="d",HD="w",WD="i",Gd=[kD,BD,HD,VD,GD,WD],Bp="space",_T=["[","("],Vd=[...LD,...FD,Bp,"]"],QO="-",$G="/",Zs=QO,ui=QO,jD=[$G],XO=0,KG=["=","+","num_1","num_2","shift+=","shift+-"],Xs=["0","1","2","3","4","5","6","7","8","9"].concat(Gd),JO=Xs.map(t=>`shift+${t}`),YD=[Zs,kd].concat(Vd,jD),qD=[Xs,JO,YD].join(","),zG=[qD,LD,FD,KG].join(","),RRt=[].concat(...Xs,...Xs,...YD,...Xs,...Xs,...Xs,...Xs,...Xs,...Xs),ZO={OUTCOMEKEYS:Gd,SIDE1KEYS:Xs,SIDE2KEYS:JO,MODIFIERS:YD,PROMPT:qG,MOVEUP:LD,MOVEDOWN:FD,HOTKEYS:zG};function Hp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=t_({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==Js?Js:"";return t+o+r}else return r+Js+t}function t_({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of RT){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+Js:n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function kg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=t_({scoreString:e});if(e=s,a)return{scoreString:e,sets:r,outcomeRemoved:!0};let c=r[r.length-1]||{},u=Object.values(c).filter(g=>g!==void 0).length;c.setNumber&&u===1&&(r=r.slice(0,r.length-1),c=r[r.length-1]||{});let{tiebreakSet:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p||{},{isTiebreakEntry:l}=wu({brackets:Es,scoreString:e}),f=QG(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=wu({brackets:As,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=wu({brackets:Es,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),y=t.isIncompleteSetScore;if(l&&h){let U=o.slice(I+1).split(ui),A=U?.length>0&&U[0]!==void 0&&!isNaN(parseInt(U[0]))&&parseInt(U[0])||void 0,E=U?.length>1&&U[1]!==void 0&&parseInt(U[1])||void 0,N=[A,E];if(E){let D=n===1?1:0;N[D]=(N?.[1-D]||0)+(d?1:2),(N[D]||0)<m&&(N[D]=m),o=e.slice(0,I+1),o+=N.join(ui)}else A!==void 0?(o=e.slice(0,I+1),o+=A):(o=e.slice(0,I),y=!0);c.side1TiebreakScore=N[0]||0,c.side2TiebreakScore=N[1]||0}if(o.length||(o=void 0),y){let P=c.side1Score?.toString();if(P){let U=P?.slice(0,P.length-1);c.side1Score=!isNaN(U)&&parseInt(U)||void 0,c.side1Score===void 0&&(c.side2Score=void 0)}t.isTimedSet?(i=c.side1Score?r:r?.slice(0,r.length-1)||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]}else if(T){let P=c.side2Score?.toString(),U=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let A=P?.slice(0,P.length-1);c.side2Score=!isNaN(A)&&parseInt(A)||void 0}else{let A=U?.slice(0,U.length-1);c.side1Score=!isNaN(A)&&parseInt(A)||void 0}t.isTimedSet?c.side1Score?(i=r||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]:(i=r||[],i[r.length-1]=c),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0})}else g?(i=r||[],Object.assign(i[i.length-1]||{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(l&&!h?i=r?.slice(0,r.length-1)||[]:(i=r,i[r.length-1]=c),l||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0));return{scoreString:o,sets:i}}return{scoreString:e,sets:r}}function wu({brackets:t=As,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...mo(r,o)),s=Math.max(...mo(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function e_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=Es.split(""),i=t.split(""),s=Math.max(...mo(n,i)),a=Math.max(...mo(o,i)),c=Math.max(...mo(ui,i));return r&&s>a&&c>s}function QG(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function xT(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function $D({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=Ye(t),{bestOf:i}=o,s=Math.ceil(i/2),c=n?.reduce((u,p)=>{let{winningSide:m}=p;return m&&u[m-1]++,u},[0,0])?.indexOf(s)+1||void 0;return zO.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Wp({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,isTimedSet:i,set:s}){if(!s)return{error:it,info:"missing set"};e=e||r&&Ye(r);let a=o&&e.finalSetFormat||e?.setFormat||{},{side1Score:c,side2Score:u}=s,{setTo:p,tiebreakAt:m}=a,d=c||u,l=jp({set:s}),f=Math.abs(c-u),g=c>=p||u>=p,I=n||c>=p&&u>=p||m&&m<p&&(c===m||u===m),h=t||I&&(l===1&&s.side1TiebreakScore>s.side2TiebreakScore||l===2&&s.side2TiebreakScore>s.side1TiebreakScore),S=!I&&a.NoAD||I||n&&a.tiebreakFormat?.NoAD?1:2,T=f>=S;return!!((i&&d||g&&(T||I)||n)&&(!I||h))}function jp({set:t}){if(t.side1Score||t.side2Score){if(t.side1Score>t.side2Score)return 1;if(t.side2Score>t.side1Score)return 2}else if(t.side1TiebreakScore||t.side2TiebreakScore){if(t.side1TiebreakScore>t.side2TiebreakScore)return 1;if(t.side2TiebreakScore>t.side1TiebreakScore)return 2}}function Bd({analysis:t,set:e}){let r=jp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Wp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function r_({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=mt(n);let{validSide2Score:s,requiresTiebreak:a}=XG({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Bd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=As.split("")[0];e+=u}else t.isDecidingSet||(e+=Js)}return{sets:r,scoreString:e,updated:o}}function XG({analysis:t,set:e={},value:r}){let n=t.isDecidingSet&&t.matchUpScoringFormat.finalSetFormat||t.matchUpScoringFormat.setFormat,{tiebreakAt:o,setTo:i,NoAD:s}=n,{side1Score:a}=e,c,u;return o&&o<i?a===o?c=r<=i:c=r<=o:a===i?s?c=r<i:c=r<=i+1:a===i-1?s?c=r<=i:c=r<=i+1:a===i+1?c=r===i||r===i-1:c=r<=i,c&&(o&&o<i?u=a===i&&r===o||a===o&&r===i:u=a>=i&&r>=i&&a!==r),{validSide2Score:c,requiresTiebreak:u}}function wT({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===kD?n?(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:OD}),o=t===2?1:2,i=wD):(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:MT}),o=t===2?1:2,i=CT):e===BD?(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:MT}),o=t===2?1:2,i=CT):e===HD?(s=!0,r=[],n=CD,o=t===2?1:2,i=xD):e===GD&&n?(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:vD}),i=vT,o=void 0):e===VD?(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:bD}),i=bT,o=void 0):e===WD&&n&&(s=!0,n=Hp({scoreString:n,lowSide:t,outcome:_D}),i=OT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function n_(t){let{sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i}=t,{analysis:s,lowSide:a,value:c}=t,u,p;!e?.length&&c!==kd&&(e=[{setNumber:1}]);let m=e.length-1;if(Gd.includes(c)){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;l&&!f?r="missing side2Score":s.finalSetIsComplete||o?r="final set is already complete":s.isIncompleteSetScore?r="incomplete set scoreString":s.isIncompleteSetScore||({sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=wT({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===kd){if({scoreString:n,sets:e,outcomeRemoved:p}=kg({analysis:s,scoreString:n,sets:e}),n?.trim()===""&&(n=n.trim()),n||(e=[]),p){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;if(l&&f){let g=l>f&&1||f>l&&2||void 0;g&&(d.winningSide=g,e.push({setNumber:e.length+1}))}}i=void 0,o=void 0,u=!0}else if(s.hasOutcome)r="has outcome";else{if(o)return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:!1,info:"matchUp is complete"};if(c===Bp){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d,g=l>f&&1||f>l&&2||void 0;g&&!o&&!s.isIncompleteSetScore&&(e[e.length-1].winningSide=g,e.push({setNumber:e.length+1}),n+=" ",u=!0)}else if(c===Zs&&e[m].side1Score!==void 0&&e[m].side2Score===void 0&&n&&s.isNumericEnding)n+="-",e[m].side2Score=0,i=void 0,o=void 0,u=!0;else if(!isNaN(c)){let d;if(e[m].side2Score===void 0){let l=mt((e[m].side1Score||0).toString()+c).toString().slice(0,2);e[m].side1Score=mt(l),d=e[m].side1Score.toString(),u=!0}else{let l=mt((e[m].side2Score||0).toString()+c).toString().slice(0,2);e[m].side2Score=mt(l),d=[e[m].side1Score,e[m].side2Score].join("-"),u=!0}if(u){let l=(e.slice(0,m)||[]).filter(f=>f).map(f=>{let{side1Score:g,side2Score:I}=f;return[g,I].join("-")}).join(" ");l?n=l+" "+d:n=d}}}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function o_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Es.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=wu({brackets:Es,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(ui);if((f[r-1]?.length||0)>=2)a="tiebreak digit limit";else if(e){r===1&&(f[0]=(f[0]||"")+i),r===2&&(f[1]=(f[1]||"")+i);let I=[f[0]||0,f[1]||0].map(T=>mt(T)),h=r===1?1:0;I[h]=I[1-h]+(u?1:2),I[h]<c&&(I[h]=c);let S=o[o.length-1];S.side1TiebreakScore=I[0],S.side2TiebreakScore=I[1],n=n.slice(0,(d??0)+1),n+=I.join(ui),s=!0}else{let I=[f[0]||0,f[1]||0].map(S=>mt(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=xT({lowValue:mt(i||0),tiebreakTo:c,NoAD:u}),l=[mt(i),d];r===2&&l.reverse();let f={side1TiebreakScore:l[0],side2TiebreakScore:l[1],setNumber:o?.length+1||1};o.push(f),n+=l.join(ui),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function i_({analysis:t,lowSide:e,scoreString:r,value:n}){let{setTo:o,tiebreakAt:i,NoAD:s}=t?.setFormat||{},a=n===parseInt(i||o);if(i&&i<o&&n>i)return{scoreString:r};if(s&&n===o||n>o)return{scoreString:r};let c=g(),u=[n,c];e===2&&u.reverse();let m=As.split("")[0],d=u.join(Zs)+(a?m:Js);r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Bd({analysis:t,set:l});return l.winningSide=f||void 0,{scoreString:r,set:l};function g(){return a?n+1:n+1===o?n+(s?1:2):o}}function s_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(W=>W?.winningSide)?.length||0)+(r?0:1),a=Ye(t),c=s===a?.bestOf,u=c&&a?.finalSetFormat||a?.setFormat||{},p=u?.timed,m=c&&o[a?.bestOf-1],d=m?.winningSide,{isTiebreakEntry:l}=wu({brackets:As,scoreString:e}),{isTiebreakEntry:f}=wu({brackets:Es,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===Zs,y=l&&_T.includes(h),P=f&&_T.includes(h),U=f&&h===ui,A=e?.split(""),[E]=Es.split(""),N=A&&Math.max(...mo(E,A)),D=A&&Math.max(...mo(ui,A)),M=A&&D>N,R=o[o.length-1]?.winningSide,b=o?.length&&!R,v=RT.find(W=>e?.indexOf(W)>=0),O=!isNaN(n),_=n===Bp,F=Vd.includes(n),w=e?.split("").find(W=>_T.includes(W)),L=F&&f&&!P&&(U||!e_({scoreString:e}));return{isTiebreakSetValue:I&&O,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:M,isGameScoreEntry:b,isSpace:_,isCloser:F,isTiebreakCloser:F&&w&&g&&S,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:S,isNumericValue:O,hasOpener:w,hasOutcome:v,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:R,isInvalidSetTiebreakValue:_&&g&&y,isInvalidMatchTiebreakValue:L,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:P,isPartialMatchTiebreakValue:U}}function KD(t){let{lowSide:e=1,value:r}=t,{scoreString:n,sets:o,winningSide:i,matchUpStatus:s}=t,{matchUpFormat:a,shiftFirst:c,auto:u=!0}=t,p,m,d=c&&e===2||!c&&e===1;if(!qD.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=$D({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=s_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(jD.includes(r)&&(r=Zs),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&mt(r)===0&&(f.isTiebreakCloser=!0),Vd.includes(r)&&f.hasOpener&&(r=""),Vd.includes(r)&&(r=Bp),f.lastSetIsComplete){let g=n?.length&&n[n.length-1];n&&g!==" "&&(n+=" ")}if(f.isTimedSet)({info:m,sets:o,scoreString:n,updated:p,matchUpStatus:s,winningSide:i}=n_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Gd.includes(r))f.finalSetIsComplete||i?m="final set is already complete":!f.isTiebreakEntry&&!f.isIncompleteSetScore?{sets:o,scoreString:n,matchUpStatus:s,winningSide:i,updated:p}=wT({lowSide:e,sets:o,scoreString:n,matchUpStatus:s,winningSide:i,value:r}):f.isTiebreakEntry||f.isIncompleteSetScore?m="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:r});else if(r===kd)p=!0,{scoreString:n,sets:o}=kg({analysis:f,scoreString:n,sets:o,lowSide:e}),n||(o=[]),s=void 0,i=void 0;else if(f.hasOutcome)m="has outcome";else if(r===Zs&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=kg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===ui&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=ui);else if([Zs,ui].includes(r))m="invalid location for joiner";else{if(i)return{updated:!1,info:"matchUp is complete"};if(f.isIncompleteSetScore)f.isNumericValue&&({sets:o,scoreString:n,updated:p}=r_({analysis:f,scoreString:n,sets:o,value:r}));else if(f.isInvalidMatchTiebreakValue)m="invalid matchUp tiebreak character";else if(f.isInvalidSetTiebreakValue)m="invalid set tiebreak character";else if(f.isTiebreakCloser){let g=f.isSetTiebreakEntry?As:Es,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:P}=T||{},U=jp({set:S});if(!f.isTiebreakSet){let E=parseInt(n.split(h).reverse()[0]),N=xT({lowValue:E,tiebreakTo:y,NoAD:P});U===1?(S.side1TiebreakScore=N,S.side2TiebreakScore=E):(S.side1TiebreakScore=E,S.side2TiebreakScore=N)}n=(n||"")+I,f.isDecidingSet||(n+=Js);let A=Bd({analysis:f,set:S});S.winningSide=A||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=o_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=As.split(""),I=Math.max(...mo(g,n.split(""))),h=n.slice(I+1),S=h&&mt(h)===XO,T=mt(h?h+r:r),{tiebreakFormat:y}=f.setFormat,{tiebreakTo:P,NoAD:U}=y||{};!S&&h.length<2?U&&T>P-1?m="invalid low value for NoAD tiebreak":(p=!0,n=(n||"")+r):m=S?"tiebreak begins with zero":"tiebreak digit limit"}else if(f.isCloser)m=`invalid key: ${r}`;else if(f.isGameScoreEntry)m="game scoreString entry";else if(f.lastSetIsComplete||!o.length){p=!0;let{scoreString:g,set:I}=i_({analysis:f,lowSide:e,scoreString:n,value:mt(r)});I&&(I.setNumber=o?.length+1||1),o=o?.concat(I).filter(Boolean)||[I],n=g||void 0}else console.log("error: unknown outcome")}if(p){o=o?.filter(Boolean);let{matchUpWinningSide:g}=$D({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[Jt,un].includes(s))?(s=KO,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![vT,bT,OT].includes(s)&&(s=void 0),{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}return{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}var Hd="\\d+-\\d+",Yp="\\d+-\\d+\\(\\d+\\)",Gg="\\[\\d+-\\d+\\]",JG="\\d+-\\d+\\(\\d+-\\d+\\)",a_=new RegExp(`(${Hd}),`,"g"),c_=new RegExp(`(${Yp}),`,"g"),ZG=[Hd,Yp,Gg,JG],tV=["0","1","2","00","01","10","11","002","012","102","112","000","001","010","100","011","101","110","111","002","012","102","112","0002","0012","0102","1002","0112","1012","1102","1112","3","03","13","013","103"],eV=tV.map(t=>{let r=t.split("").map(n=>ZG[n]).join(" ");return new RegExp(`^${r}$`)});function zD(t){return!t||eV.some(e=>e.test(t))}function u_(t){let e="[];",r="()",n=e+r,o=[e[0],r[0]],i=Object.assign({},...n.split("").map(c=>({[c]:0}))),s="",a=t.split("").map(c=>{let u=n.includes(c)&&c,p=o.includes(u);if(p&&u)return i[u]+=1,s=u,c;if(!p&&u&&s&&u!==s){i[s]-=1;let m=e.includes(s)&&e||r.includes(s)&&r||"",d=m.split("").find(l=>l!==s);if(m.includes(u))i[s]||(s="");else return i[u]||(s=""),d}return c}).join("");return t!==a?a:t}function Wd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function p_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function _a(t){let r=(n=>n?.split("-").join("").split("/").join(""))(t);if(/^\d+$/.test(r)&&r.length===2){let n=r.split("");return Math.abs(n.reduce((i,s)=>+i-+s))===1}return!1}function qp(t,e){let r=[t.slice(e,e+2),e?t.slice(0,1):t.slice(2)].map(i=>parseInt(i.join("")));e&&r.reverse();let n=r;if(Math.abs(n.reduce((i,s)=>+i-+s))>=2)return n.join("-")}function QD(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function m_(t){return t.startsWith("(")&&t.endsWith(")")}function d_({score:t,applied:e}){t=u_(t);let r=/\)(\d+)/g;if(r.test(t))for(let U of t.match(r)){let A=U.replace(")",") ");t=t.replace(U,A)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let U of i||[]){let[A]=U.match(o).slice(1),E=A.replace(/ /g,"");t=t.replace(U,`(${E})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let U=t.match(s);U.length&&U.forEach(A=>{let E=A.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(A,E)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let U=t.match(s);U.length&&U.forEach(A=>{let E=A.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(A,E)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(U=>{let A=new RegExp(`(\\d+)${U}(\\d+)`,"g"),E=t.match(A);E&&E.forEach(N=>t=t.replace(N,N.split(U).join("-")))}),/^[(-/,]+$/.test(t)&&(t=""),/\)[-/,]+$/.test(t)&&(t=t.slice(0,t.length-1)),/\d \/\d/.test(t)&&(t=t.replace(/ \//g,"/")),t.includes(" /")&&(t=t.replace(/ \//g," "));let c=/\(\d+, \)/g;c.test(t)&&t.match(c).forEach(A=>{let[E]=A.match(/\((\d+), \)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&E==="6"&&(t=t.replace(A,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(A=>{let[E]=A.match(/\((\d+)\/\)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&E==="6"?t=t.replace(A,"(6-0)"):t=t.replace(A,`(${E})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(A=>{let[E]=A.match(/(\d\/\d)\/,/).slice(1);t=t.replace(A,`${E},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(A=>{let[E]=A.match(/\(\/(\d+)\)/).slice(1);E.length===2?t=t.replace(A,`(${E})`):E.length===1&&parseInt(E)<6?t=t.replace(A,`(6-${E})`):t=t.replace(A,`(${E})`)});let d,l,f,g,I,h=()=>{I=Tr(t.split("")),l=I["("]===(I[")"]||0)+1,d=(I["("]||0)+1===I[")"],f=I["["]===I["]"]+1,g=l&&!f};h();let S=/(\d+-\d+\(\d+)0,/;if(S.test(t)){let[U]=t.match(S).slice(1);t=t.replace(S,U+")")}if(I["("]===I[")"]&&I["("]>1){let U=t.split(")(").join(") (").split(" ");U.every(m_)?t=U.map(A=>{let E=A.slice(1,A.length-1);return E.length>2?E:A}).join(" "):t=U.join(" ")}h();let T=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!T&&!y)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(U=>I[U])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(U=>I[U]>1)&&(t=t.slice(1,t.length-1)),t.startsWith("(")&&t.endsWith("))")&&(t=t.slice(1,t.length-1)),I["("]>(I[")"]||0)&&t[t.length-1]==="("&&(t=t.slice(0,t.length-1)+")",h()),I["("]===1&&!I[")"]&&t[0]==="("&&(t=t+")",h()),I["("]>(I[")"]||0)&&t.slice(0,2)==="(("&&(t=t.slice(1)),d){if(/^9\d/.test(t))t="("+t.slice(1);else if(t[0]!=="(")t="("+t;else{let U=[],A=0;for(let E of t.split("").reverse())E===")"&&(A?U.push("("):A+=1),E==="("&&(A-=1),U.push(E);U.reverse(),t=U.join("")}h()}if(I[")"]>(I["("]||0)&&t[0]===")"&&(t="("+t.slice(1),h()),g&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",h()),g&&(!t.endsWith(")")||t.startsWith("(("))&&(t=t+")",h()),g){let U="",A=0;for(let E of t.split(""))E==="("&&(A?U+=")":A+=1),E===")"&&(A-=1),U+=E;t=U}h(),f&&!l&&(t=t+"]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),h()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),h(),I[")"]===1&&!I["("]&&t.endsWith(")")&&(t=t.slice(0,t.length-1)),t.startsWith("(")&&t.endsWith(")")&&I["("]===1&&I[")"]===1&&(t=t.slice(1,t.length-1),h());let P=U=>{let A=U.indexOf("("),E=U.indexOf(")");return A>=0&&E>=0&&A<E};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let U=t.slice(1,t.length-1);P(U)&&(t=U,h())}return{score:t,applied:e}}function Lu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=mo("-",t.split(""));if(!e.length)return t;let r=t.split("-"),n=!(r.length%2),o=!!(e.length%2);return n&&o&&e.length>r.length/2&&e.filter((s,a)=>a%2).forEach(s=>{t=t.substring(0,s)+" "+t.substring(s+1)}),t}function l_({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map(r=>r.trim()).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map(r=>r.trim()).join(")")),[a_,c_].forEach(r=>{let n=t.match(r);n?.length&&(n.forEach(o=>{t=t.replace(o,o.slice(0,o.length-1)+" ")}),e.push("setsEndComma"))}),t=t.split(" ").filter(Boolean).map(Lu).join(" "),{score:t,applied:e}}function f_({score:t}){if(typeof t!="string")return{score:t};let e=d=>d?.split("-").join("").split("/").join(""),r=d=>d.split("[").join("(").split("]").join(")");t=t.split(", ").join(" ");let n=t.split(" ");t=n.map(d=>{let l=/^-(\d+)$/;if(l.test(d)){let[f]=d.match(l).slice(1);if(f.length===2)return f.split("").join("-")}return d}).join(" "),n=t.split(" ");let o=n.filter(Wd),i=0,s="";for(let d of o){let l=mo(d,n).filter(h=>!i||h>i)[0],f=n.slice(i,l-1),g=n[l-1],I=e(g);if(/^\d+$/.test(I)&&I.length===2){let h=I.split(""),S=Math.abs(h.reduce((T,y)=>+T-+y));if(S===1){let T=[f.join(" "),[g,d].join("")].join(" ");s+=T,i=l+1}else if(S===0){let T=Math.max(...h);if([4,5,6,7,8,9].includes(T)){let y=[6,4].includes(T)?T+1:T-1,P=[T,y].sort().reverse().join("-"),U=[f.join(" "),[P,d].join("")].join(" ");s+=U,i=l+1}}}}if(o.length&&s.length){let d=n.slice(i).join(" ");return s=[s,d].join(" "),{score:s.trim()}}if(n.length===2&&["(","["].some(d=>n[1].includes(d))){let l=e(n[0]).split("");if(Math.abs(l.reduce((g,I)=>+g-+I,0))===1)return n[1]=r(n[1]),{score:n.join("")}}let a=n.map(d=>p_(d)&&"bracket"||_a(d)&&"set");if(a.includes("set")&&a.includes("bracket")){let d,l="";return n.forEach((f,g)=>{a[g]==="bracket"&&d==="set"?(f=r(f),l+=f):l+=` ${f}`,d=a[g]}),{score:l.trim()}}n=t.split(" ");let c,u=n.map(d=>{let l=new RegExp(/^(\d+)-(\d+)$/);if(l.test(d)){let[f,g]=d.match(l).slice(1),I=Math.abs([f,g].reduce((S,T)=>+S-+T)),h=Math.max(f,g);if(I===1)return c="tiebreakSet",c;if(I>=2&&h>=7&&c==="tiebreakSet")return c="tiebreak",c}}),p=mo("tiebreak",u);if(p.length){let d="";n.forEach((l,f)=>{p.includes(f)?d+=`(${l}) `:p.includes(f+1)?d+=`${l}`:d+=`${l} `}),t=d.trim()}let m=/(\d+-\d+)\((\d+)-(\d+)\)$/;if(m.test(t)){let[d,l,f]=t.match(m).slice(1),I=Math.max(l,f)>=10;!_a(d)&&I&&(t=t.replace(m,`${d} [${l}-${f}]`))}return u=[],t=t.split(" ").map(d=>{let l=/^\((.*)\)$/,f=l.test(d),g=new RegExp(Gg).test(d)&&"super"||new RegExp(Yp).test(d)&&"tiebreak"||new RegExp(Hd).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function g_({score:t,applied:e}){for(let D of[".",","," ","/"]){let M=new RegExp(`^(\\d+)\\${D}(\\d+)$`);if(M.test(t)){let R=t.match(M).slice(1).map(v=>parseInt(v)),b=Math.abs(R[0]-R[1]);b<=10&&b>=2&&(t=t.split(D).join("-"),e.push("variedJoinerPattern"))}}t.includes(";")&&(t=t.split(";").join(" "),e.push("semicolon set separation"));let r=/(^|\s)(\d)\/(\d)(\d)\/(\d)(\(|$)/;if(r.test(t)){let[D,M,R,b,v,O]=t.match(r).slice(1);t=t.replace(r,`${D}${M}-${R} ${b}-${v}${O}`),e.push("smashSlashPattern")}/.*\s6[/-]+$/.test(t)&&(t+="0",e.push("incompleteFinalSetPattern"));let o=/\(6,\)/g;o.test(t)&&(t=t.replace(o,"(6, 0)"),e.push("missingZeroPattern1"));let i=/^\d{3,}\(/,s=/\(\d+\)\d+/;[i,s].forEach(()=>{t=t.split(" ").map(M=>(i.test(M)&&(M=M.replace("("," (")),s.test(M)&&(M=M.replace(")",") ")),M)).join(" "),e.push("spaceConsiderationPatterns")});let c=Lu(t);c!==t&&(t=c,e.push("deDashMash"));let u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){let[D,M,R]=t.match(u).slice(1),[b,v]=M.split("");t=`${D}-${b} ${v}-${R}`,e.push("smashSetPattern")}let p=/^(\d+)[ -](\d+)$/,m=/^([\d -]+)\/([\d -]+)$/;if(m.test(t)){let[D,M]=t.match(m).slice(1),R=D.trim(),b=M.trim();if(p.test(R)&&p.test(b)){let v=R.match(p).slice(1,3).join("-"),O=b.match(p).slice(1,3).join("-");t=`${v} ${O}`,e.push("slashSeparationPattern")}}let d=/^([\d -]+),([\d -]+)$/;if(d.test(t)){let[D,M]=t.match(d).slice(1),R=D.trim(),b=M.trim();if(p.test(R)&&p.test(b)){let v=R.match(p).slice(1,3).join("-"),O=b.match(p).slice(1,3).join("-");t=`${v} ${O}`,e.push("commaSeparationPattern")}}let l=/^\d \d,/;if(l.test(t)){let D=t.match(l)[0],M=D.slice(0,D.length-1).split(" ").join("-");t=t.replace(D,M),e.push("singleSetCommaSeparationPattern")}let f=0,g=/(\d+)-(\d{2})-(\d+)/;for(;g.test(t)&&f<3;){let[D,M,R]=t.match(g).slice(1),b=M.split(""),v=`${D}-${b[0]} ${b[1]}-${R}`;t=t.replace(g,v),e.push("noSetSeparationPattern"),f+=1}let I=/(^|\s)7-6\s(\d+)\s/g,h=t.match(I);if(h?.length){let D=/(^|\s)7-6\s(\d+)\s/;h.forEach(M=>{let R=M.match(D).slice(2)[0];t=t.replace(M,`7-6(${R}) `),e.push("floatingTiebreakPattern1")})}let S=t.match(/\d \d /);S?.forEach(D=>{let M=D.slice(0,D.length-1).split(" ").join("-");t=t.replace(D,M),e.push("spaceSeparatedSetPattern1")}),S=t.match(/ \d \d$/),S?.forEach(D=>{let M=" "+D.slice(1).split(" ").join("-");t=t.replace(D,M),e.push("spaceSeparatedSetPattern2")});let T=/^\d, *\d\/\d, *\d/;if(T.test(t)){let D=t.match(T)[0],M=D.split("/").map(R=>`(${R})`).join(" ")+" ";t=t.replace(D,M),e.push("slashCommaSetPattern")}let y=/\(6-\)/g;y.test(t)&&(t=t.replace(y,"(6-0)"),e.push("missingZeroPattern2"));let P=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(P.test(t)){let D=t.match(P),M=/(?<!-)(\d+)\/(\d+)(?!-)/,R=t;D.forEach(b=>{let[v,O]=b.match(M).slice(1),_=`${v}-${O}`;R=R.replace(b,_)}),t=R,e.push("slashSetPattern")}let U=/(.*)\s(1\d)\s(\d+)$/;if(U.test(t)){let[D,M,R]=t.match(U).slice(1);D.replace(/\D/g,"").length>=4&&(t=D+` ${M}${R}`,e.push("spaceSeparatedSuperPattern"))}let A=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(let D of t.match(A)||[]){let[M,R,b,v]=D.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[O,_]=R.split("-").map(w=>parseInt(w));Math.abs(O-_)===1&&(t=t.replace(D,`${M}${R}(${b})${v}`),e.push("spaceSeparatedSetPattern"))}let E=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let D of t.match(E)||[]){let M=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[R,b,v]=D.match(M).slice(1),[O,_]=R.split("-").map(w=>parseInt(w));Math.abs(O-_)===1&&(t=t.replace(D,`${R}(${b})${v}`),e.push("floatingTiebreakPattern2"))}let N=/(^|\s)(\d \d)\(/g;for(let D of t.match(N)||[]){let M=/(^|\s)(\d \d)\(/,[R,b]=D.match(M).slice(1);t=t.replace(D,`${R}${b.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}}function I_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(_a(c[0]))return c[0]+`(${c[1].slice(0,c[1].length-1)})`}return a}).join(" ");let n=new RegExp(/(\([\d ]+\))/g);if(n.test(t))for(let a of t.match(n)){let u=a.replace(" ","-").match(/\((.*)\)/)?.[1];if(te(u)&&u?.[0]>2){if([2,4].includes(u.length))u=u.split("").join("-");else if(u.length===3){let p=u.indexOf("1");u=qp(u.split(""),p)}}t=t.replace(a,`(${u})`)}r=t?.split(" ");let o=new RegExp(/^(\d[-/]+\d)\((\d+)[-/]+(\d+)\)$/),i=r.length-1;t=r.map((a,c)=>{let u=[void 0,"","COMPLETED"].includes(e)||c!==i;if(o.test(a)&&u){let[p,m,d]=Array.from(a.match(o)).slice(1),l=Math.min(m,d);return`${p}(${l})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^(\d{2})\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1),p=c.split("");return`${p[0]}-${p[1]}(${u})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^\((\d[-/]+\d)\)(\d+)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1);return _a(c)?`${c}(${u})`:c}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^1-0\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c]=a.match(o).slice(1);return`[${c<9?10:parseInt(c)+2}-${c}]`}return a}).join(" ");let s=/\((\d)+0 /;if(s.test(t)){let a=t.match(s)[1];t=t.replace(s,`(${a}) `)}return{score:t}}function h_({score:t,attributes:e,identifier:r}){if(typeof t!="string")return{score:t,identifier:r};let n=new RegExp(/\([\d,/ ]+\)/g),o=t.match(n);for(let m of o||[]){let l=m.match(/^\((.*)\)$/)?.slice(1)?.[0],g=t.split(m)[0].split(")").reverse()[0].replace(/\D/g,"");if(l?.length===2&&g?.length>=2){let S=g.slice(g.length-2).split("").map(y=>parseInt(y));if(Math.abs(S[0]-S[1])===1)continue}let I=QD(l),h=Lu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=QD(m.match(/^\[(.*)\]$/)[1]);t=t.replace(m,`(${d}) `).trim()});let a=[")","]"],c=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&a.some(m=>t.endsWith(m))&&c.some(m=>t.includes(m))){let m="",d=t.split(/[)\]]/).filter(Boolean).map(h=>(h.startsWith(",")&&(h=h.slice(1)),h.trim())),l=d.every(h=>h.includes(",")||Wd(h)),f=d.every(h=>h.includes("/")||Wd(h)),g=d.every(h=>h.includes("-")||Wd(h)),I=l&&","||g&&"-"||f&&"/";if(I){let h;d.forEach(S=>{if(S.startsWith("("))if(h==="set"&&(m+=" "),S.includes(I))m+=S.slice(1).split(I).map(T=>T.trim()).join("-"),h="set";else{let T=S.slice(1);m+=`(${T}) `,h="tiebreak"}else if(S.startsWith("[")){let T=S.slice(1).split(I).map(P=>parseInt(P.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=Tr(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&_a(t)&&te(e?.removed)&&(t=t+`(${e.removed})`,e.removed=void 0));let p=/\(\)/g;return p.test(t)&&(t=t.replace(p,"").trim()),{score:t}}function LT({score:t}){let e=t.split(""),r=[],n,o=()=>n=[void 0,void 0,void 0],i=()=>{let a=`${n[0]}-${n[1]}`;return n[2]&&(a+=` (${n[2]})`),o(),n.push(n),a};o();let s=()=>n[0]!==void 0&&n[1]!==void 0&&Math.abs(parseInt(n[0])-parseInt(n[1]));for(;e.length;){let a=e.shift(),c=te(a)&&parseInt(a),u=n[0]!==void 0&&n[1]!==void 0;if(te(c)){if(n[0]===void 0){n[0]=c;continue}if(n[1]===void 0&&(n[1]=c,s())){r.push(i()),n=[void 0,void 0];continue}if(u&&e.length===1&&te(e[0])){let p=e.pop();n[0]=n[0].toString()+n[1].toString(),n[1]=p,r.push(i()),n=[void 0,void 0]}u&&s()}}return{sets:r}}function Vg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=qp(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=qp(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function XD(t){let{score:e}=t,{applied:r,matchUpStatus:n}=t,o=e?.toString().split(""),i=o?.every(a=>te(a)),s=a=>Math.abs(a[0]-a[1]);if(typeof e=="number"||i){e=e.toString().toLowerCase(),i&&(e=o.join(""));let a=i?o.map(u=>parseInt(u)):e.split("").map(u=>parseInt(u)),{sets:c}=LT({score:e});if(a.length,e.length===3&&s(a.slice(0,2))===1){let[u,p,m]=a;e=`${u}-${p}(${m})`,r.push("numericTiebreakPattern1")}else if(e.length===3&&a[0]===1){let[u,p,m]=a;e=`[${u}${p}-${m}]`,r.push("numericTiebreakPattern2")}else if(e.length===4&&s(a.slice(0,2))===1&&"987654".split("").includes(a[0].toString())){let[u,p,m,d]=a,l=Math.min(m,d);e=`${u}-${p}(${l})`,r.push("numericTiebreakPattern3")}else if(e.length===4&&a[0]===1&&a[2]===1){let[u,p,m,d]=a;e=`[${u}${p}-${m}${d}]`,r.push("bigSuper")}else if(e.length===4){let[u,p,m,d]=a;e=`${u}${p} ${m}${d}`,r.push("split4")}else if(e.length===5&&s(a.slice(0,2))===1){let[u,p,m,d,l]=a;e=`${u}-${p}(${m}) ${d}-${l}`,r.push("numericTiebreakPattern4")}else if(e.length===5&&s(a.slice(3))===1){let[u,p,m,d,l]=a;e=`${u}-${p} ${m}-${d}(${l})`,r.push("numericTiebreakPattern5")}else if(a.length===7)if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&a[4]===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} [${l}${f}-${g}]`,r.push("numericTiebreakPattern6")}else if(s(a.slice(0,2))===1&&s(a.slice(3,5))>1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p}(${m}) ${d}-${l} ${f}-${g}`,r.push("numericTiebreakPattern7")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))===1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d}(${l}) ${f}-${g}`,r.push("numericTiebreakPattern8")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&s(a.slice(4,6))===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} ${l}-${f}(${g})`,r.push("numericTiebreakPattern9")}else e=e.slice(0,2)+" "+e.slice(2,4)+" "+e.slice(4),r.push("numericMatchTiebreakPattern");else if(e.length%2){let u=Vg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Ee(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(U=>parseInt(U)),y=Math.abs(S-T),P=S>T?1:2;return y>1&&P||P*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=Tr(p),l=p.map(h=>Math.abs(h)),f=Tr(l),g=p[0]<0,I=!g&&p[1]<0;if(p[0]>0&&p[1]>0&&p[0]!==p[1])e=[u.slice(0,2).join(" "),u.slice(2).join("-")].join(" "),r.push("numeric3rdSetTiebreakPattern");else if(m)e=u.join(" "),r.push("chunkSplit");else if(a.length===6){if(d[1]===2||d[2]===2)if(!Object.values(f).includes(3))e=u.join(" "),r.push("chunkSplit");else{let[h,S,T,y,P,U]=a,A=p.reduce((E,N,D)=>N<0?D:E,void 0);if(A===0){let E=Math.min(T,y);e=`${h}-${S}(${E}) ${P}-${U}`,r.push("chunkSplitTiebreak1")}else if(A===1){let E=Math.min(P,U);e=`${h}-${S} ${T}-${y}(${E})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${y}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,y,P,U,A,E]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${y}-${P} [${U}${A}-${E}]`:e=`${h}-${S} ${T}-${y}(${P}) [${U}${A}-${E}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function FT(t){let e=[0,0],r=[],n=t.split(" "),o=/(\d+)-(\d+)/;n.forEach(c=>{if(o.test(c)){let u=c.match(o).slice(1).map(m=>parseInt(m)),p=u[0]>u[1]&&1||u[1]>u[0]&&2;p&&(e[p-1]+=1,r.push(p))}});let i=e[0]>e[1]&&1||e[1]>e[0]&&2,s=e[0]>0&&e[0]===e[1],a=e.reduce((c,u)=>c+u,0);return{setsWon:e,setsTied:s,setWinners:r,totalSets:a,winningSide:i}}function S_({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(Yp).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!_a(f)&&!e){let I=Math.max(...g),h=f.indexOf(I),S=[I,I-1];return h&&S.reverse(),S.join("-")+l}}else if(p.length===2&&te(p))return p.split("").join("-");p=Lu(p);let d=new RegExp(`^${Gg}$`).test(p)&&"super"||new RegExp(`^${Yp}$`).test(p)&&"tiebreak"||new RegExp(`^${Hd}$`).test(p)&&"standard"||"unknown";if(n.push(d),s>1&&d==="standard"&&m<2){let[l,f]=p.split("-"),g=Math.abs(parseInt(l)-parseInt(f)),I=Math.max(l,f),h=Math.min(l,f),S=[parseInt(l),parseInt(f)].indexOf(h);if(I>9&&g>2){let T=I.toString().split(""),y=T.find(P=>parseInt(P)>h||m&&parseInt(P)<=o)??T[0];y&&(p=S?[y,h].join("-"):[h,y].join("-"))}I>(o||0)&&(o=I)}if(d==="standard"){let[l,f]=p.split("-");if(!Math.abs(parseInt(l)-parseInt(f))&&e!=="RETIRED")return""}return p}).filter(Boolean).join(" ");let{setsWon:a,setWinners:c,totalSets:u}=FT(t);if(u===1&&r?.removed==="6"&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...a)>=2&&c[0]===c[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...a)>2){let p=[0,0];t=t.split(" ").map((m,d)=>(p[c[d]]+=1,Math.max(...p)>2?void 0:m)).filter(Boolean).join(" ")}return{score:t,profile:n}}function T_({score:t}){let{setsTied:e,winningSide:r}=FT(t),n=/\s\((\d+)\)$/;if(!r&&e&&n.test(t)){let a=t.match(n).slice(1)[0],c=a<=8?10:a+2;t=t.replace(n,` [${c}-${a}]`)}let o=t.split(" "),i=o[o.length-1];if(!i.includes("-")||i.indexOf("(")>0)return{score:t};let s=i.split("(").join("").split(")").join("").split("-");if(!s.every(a=>te(a)))return{score:t};if(s[0]==="76"){let a=s[1].length===2?Math.min(...s[1].split("").map(c=>parseInt(c))):s[1];t=[...o.slice(0,o.length-1),`7-6(${a})`].join(" ")}else{s=s.map(u=>parseInt(u));let a=Math.max(...s),c=Math.abs(s[0]-s[1]);if(a>=10){if(c>2&&s.every(u=>+u>=10)){let u=s.map(p=>p===a?p-10:10).sort();c=Math.abs(u[0]-u[1]),c>2&&(s=u)}t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" ")}else o.length===3&&a>=7&&c>2&&(t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" "))}return{score:t}}function rV({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function nV({score:t,applied:e}){return typeof t!="string"?{score:t}:(t.toLowerCase().includes("o")&&(t=t.toLowerCase().split(" ").map(r=>r.split("o").join("0")).join(" "),e.push("replaceOh")),{score:t,applied:e})}function oV({score:t,applied:e}){return typeof t!="string"?{score:t}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length>2){let n=r.indexOf("1");if(r.length%2){if(r.length===3&&n===0){let o=qp(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=XD({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function iV({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&Vg(t)?{score:Vg(t)}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length===1){e.push("removeErroneous1");return}return r}).filter(Boolean).join(" "),{score:t,applied:e})}function sV({score:t,applied:e}){return["walkover","wo","w/o","w-o"].includes(t?.toString().toLowerCase())?(e.push("handleWalkover"),{matchUpStatus:"walkover",score:"",applied:e}):{score:t}}function aV({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(ret|con)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleRetired"),{score:a.trim(),matchUpStatus:"retired",applied:r}}let o=e?.matchUpStatuses?.retired,s=["rtd",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleRetired"),{matchUpStatus:"retired",score:t?.replace(s,"").trim(),applied:r}):{score:t}}function cV({score:t,attributes:e}){(t.endsWith(" am")||t.endsWith(" pm"))&&(t=""),t=t.replace(/[A-Za-z]+/g,"").trim(),[".",","].some(o=>t.endsWith(o))&&(t=t.slice(0,t.length-1));let r="()/-".split("").some(o=>t.includes(o));/ \d$/.test(t)&&r&&(e={removed:t.slice(t.length-2).trim()},t=t.slice(0,t.length-2));let n=/(.*)[A-Za-z]+$/;return n.test(t)&&(t=t.match(n).slice(1)[0].trim()),{score:t,attributes:e}}function uV({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function pV({score:t}){let e=new RegExp(/^\d+\/\d+/),r=t.split(" ");r.some(o=>e.test(o))&&(t=r.map(o=>e.test(o)?o.replace("/","-"):o).join(" "));let n=/^(\d+), *(\d+)$/;if(n.test(t)){let[o,i]=t.match(n).slice(1);t=[o,i].join("-")}return{score:t}}function mV({score:t}){let e=new RegExp(/\(\d+\/\d+\)/g),r=t.match(e);for(let n of r||[]){let o=n.replace("/","-");t=t.replace(n,o)}return{score:t}}function dV({score:t}){if(t.includes(",")){let e=t.split(",").map(o=>o.trim()),r=o=>/\d \d/.test(o);e.every(r)&&(t=e.map(o=>{let i=/\d+ \d+/g;for(let s of o.match(i)){let[a,c]=s.match(/(\d+) (\d+)/).slice(1);o=o.replace(s,`${a}-${c}`)}return o}).join(" "))}if(t.includes(" ")){let e=t.replace(/[ ,]/g,"");e.split("").every(n=>te(n))&&e.length===4&&(t=e)}return{score:t}}function lV({score:t}){let e=new RegExp(/^\[\d+\](.*)$/);e.test(t)&&(t=t.match(e).slice(1)[0].trim());let r=/\(,/g;return r.test(t)&&(t=t.replace(r,"(")),{score:t}}var y_={handleTiebreakSlashSeparation:mV,handleSetSlashSeparation:uV,punctuationAdjustments:d_,handleGameSeparation:pV,joinFloatingTiebreak:f_,handleBracketSpacing:l_,handleSpaceSeparator:dV,separateScoreBlocks:oV,matchKnownPatterns:g_,removeDanglingBits:cV,removeErroneous:iV,handleWalkover:sV,properTiebreak:I_,handleNumeric:XD,handleRetired:aV,containedSets:h_,sensibleSets:S_,stringScore:rV,superSquare:T_,setBuilder:LT,excisions:lV,replaceOh:nV};var JD={},fV=[],gV=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],IV=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function ZD(t){if(!t.score)return{error:V};let{score:e,sheetName:r,identifier:n,fileName:o,stepLog:i,fullLog:s,profile:a}=t,c=[],u,p=[],m,d,l=e,f=I=>{I.forEach(h=>{d=y_[h]({profile:a,identifier:n,matchUpStatus:u,attributes:m,applied:p,score:l});let S=d.score!==l;S&&c.push({method:h,score:d.score}),i&&(s||S||d.matchUpStatus!==u)&&console.log(u?{score:d.score,matchUpStatus:u}:{score:d.score},h),d.matchUpStatus&&(u=d.matchUpStatus),d.attributes&&(m=d.attributes),d.applied&&(p=d.applied),l=d.score})};f(gV);let g=zD(l);return g||(l=e.toString().replace(/\D/g,""),m?.removed&&(m.removed=void 0),f(IV),g=zD(l),g||(fV.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{JD[I]||(JD[I]=0),JD[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var eN={};Zt(eN,{analyzeScore:()=>Bg,analyzeSet:()=>Fu,checkScoreHasValue:()=>Se,checkSetIsComplete:()=>Wp,getSetComplement:()=>Wg,getTiebreakComplement:()=>$p,isValidMatchUpFormat:()=>Dr,parseScoreString:()=>jd,validateScore:()=>Hg,validateTieFormat:()=>cr});function Bg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(A=>A?.winningSide)||[]).reduce((A,E)=>{let{winningSide:N}=E;if(!N)return A;let D=N-1;return A[D]++,A},[0,0]),c=n?n-1:void 0,u=c!==void 0?1-c:void 0,p=c!==void 0&&a[c],m=u!==void 0&&a[u],d=e?Ye(e):void 0,l=Math.max(...a),f=Tr(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf,h=I&&Math.ceil(I/2)||1,S=r??t,T=S&&[Rt,rr,Ct].includes(S),y=!d||!i.length||i.every((A,E)=>{let N=E+1,D=N===I,M=N===i.length,{side1Score:R,side2Score:b,side1TiebreakScore:v,side2TiebreakScore:O,winningSide:_}=A,F=Math.max(R??0,b??0),w=v??O,{finalSetFormat:L,setFormat:G}=d,k=D&&L||G;if(w){let{tiebreakTo:W,NoAD:Y}=k?.tiebreakFormat||{},$=Math.max(v??0,O??0);if(Y&&$>W||$<W&&_&&(M&&!T||!M))return!1}return k.setTo?!(!k.noTiebreak&&F>k.setTo+1):!0}),P=(!e||l===h)&&f===1&&a.indexOf(l)+1||void 0;return{valid:!!(y&&(n&&p>m&&n===P||n&&T||!n&&!P&&(![ge,Rt,rr,Ct].includes(S)||g&&S===ge)))}}function Hg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:V};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:V,info:c};if(a!==void 0&&typeof a!="string")return{error:V,info:c};if(i!==void 0&&!Array.isArray(i))return{error:V,info:si("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==ut(u).length)return{error:V,info:"setNumbers not unique"};for(let m of i){let{side1Score:d,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,side1PointScore:I,side2PointScore:h,winningSide:S,setNumber:T}=m;if(![[d,l],[f,g],[I,h]].filter(U=>U.some(A=>![void 0,null].includes(A))).every(U=>U.every(A=>It(A))))return{error:V,info:"non-numeric values"};if(![T,S].filter(U=>![void 0,null].includes(U)).every(U=>It(U)))return{error:V,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:V,info:"winningSide must be 1 or 2"}}let{valid:p}=Bg({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:oE,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Wg=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=mt(r);s?.toString().length>2&&(s=parseInt(s.toString().slice(0,2))),o&&o<n&&s>o&&(s=o);let a;return i&&!o?(s>n&&(a=n),a=s<n?n:n-1):a=s+1<n&&n||o&&o<n&&s===o&&n||!o&&s+2||n+1,[e?s:a,e?a:s]},$p=t=>{let{isSide1:e,lowValue:r,tiebreakTo:n,tiebreakNoAd:o}=t;if(r===void 0)return!1;let i=typeof r=="string"?parseInt(r):r;i?.toString().length>2&&(i=parseInt(i.toString().slice(0,2))),o&&i>n-1&&(i=n-1);let s=hV({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function hV(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function jd({tiebreakTo:t=7,scoreString:e=""}){return e?.split(" ").filter(Boolean).map((n,o)=>r({set:n,setNumber:o+1}));function r({set:n,setNumber:o}){let i=/\(([^)]+)\)/,s=/\[([^)]+)\]/,a=i.exec(n),c=s.exec(n),u=n?.startsWith("[")&&c&&c[1].split("-").map(y=>parseInt(y)),p=a&&n.replace(a[0],"")||c&&n.replace(c[0],"")||n,m=!u&&p.split("-").map(y=>parseInt(y)),d=u?u[0]>u[1]&&1||u[0]<u[1]&&2||void 0:m[0]>m[1]&&1||m[0]<m[1]&&2||void 0,l=a?a[1]:void 0,g=(l&&$p({lowValue:l,isSide1:d===2,tiebreakTo:t}))??[],[I,h]=m||[],[S,T]=u||g||[];return{side1Score:I,side2Score:h,side1TiebreakScore:S,side2TiebreakScore:T,winningSide:d,setNumber:o}}}function A_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=jp({set:o});return Wp({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function Fu(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:$l};let{setNumber:n}=e||{},{bestOf:o,exactly:i}=r||{},s=o||i,a=!!(n&&s&&n===s),c=a&&r?.finalSetFormat||r?.setFormat,u=!!c?.tiebreakSet,p=!!c?.timed,m=!u&&!p,d=!!(n&&s&&n<=s),l=[e?.side1Score,e?.side2Score],f=[e?.side1PointScore,e?.side2PointScore],g=[e?.side1TiebreakScore,e?.side2TiebreakScore],I=l.filter(w=>w!==void 0).length,h=f.filter(w=>w!==void 0).length,S=g.filter(w=>w!==void 0).length,T=l?.filter(w=>!isNaN(w)).length,y=g?.filter(w=>!isNaN(w)).length,{tiebreakAt:P}=c||{},U=P&&l.filter(w=>w>=P).length===2,A=U&&(l[0]>l[1]&&1||l[1]>l[0]&&2||void 0),E=!!(y&&!T),N=!!e?.winningSide,{error:D,result:M}=SV({sideTiebreakScores:g,sideGameScores:l,setFormat:c,setObject:e}),{error:R,result:b}=TV({sideTiebreakScores:g,setObject:e,setFormat:c}),v=m&&!E&&M||u&&E&&b||p,O=d&&!(u&&!E)&&!(m&&E)&&(!N||v),_=A_({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:E,setObject:e}),F={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:U,isCompletedSet:N,isDecidingSet:a,isTiebreakSet:E,isValidSet:O,isValidSetNumber:d,isValidSetOutcome:v,leadingSide:A,setFormat:c,sideGameScores:l,sideGameScoresCount:I,sidePointScores:f,sidePointScoresCount:h,sideTiebreakScores:g,sideTiebreakScoresCount:S,winningSide:_};return e?.winningSide!==void 0&&(E?(F.isValidTiebreakSetOutcome=b,b||(F.tiebreakSetError=R)):(F.isValidStandardSetOutcome=M,M||(F.standardSetError=D))),F}function SV({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:$l};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:V};if(!(r?.filter(M=>!isNaN(M)).length===2))return{result:!1,error:VI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(M=>M>=a)))return{result:!1,error:VI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:Um};let l=t?.winningSide-1,f=1-l,g=r[l],I=r[f],h=g-I;if(!(g>I))return{result:!1,error:{message:"winningSide game scoreString is not high"}};let T=c&&u,y=n?.filter(M=>!isNaN(M)).length===2,P=n?.[l],U=n?.[f],A=c&&r.filter(M=>M>=c).length===2;if(T){let{NoAD:M,tiebreakTo:R}=u;if(A){if(h>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!y)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(R))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(R&&n?.find(G=>G>=R)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let O=c<a?a:a+1;if(g>O)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!P||!U||P<U)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let _=M?1:2,F=P-U,w=U>=R-1;if(F&&w&&F<_)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(g>a&&!A)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}let E=p?1:2,N=I>=a-1;return h&&N&&!A&&h<E?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>E&&g>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function TV({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:$l};let n=!!e?.tiebreakSet,o=!!e?.timed;if(!e||!n||o)return{result:!1,error:{message:"not tiebreak set"}};let i=[1,2].includes(t?.winningSide);if(!t||!i)return{result:!1,error:Um};let{tiebreakSet:s}=e||{},{NoAD:a,tiebreakTo:c}=s||{};if(!(r?.filter(T=>!isNaN(T)).length===2))return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(c))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!r?.find(T=>T>=c))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let m=t?.winningSide-1,d=1-m,l=r[m],f=r[d];if(!l||!f||l<f)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let g=a?1:2,I=l-f,h=f>=c-1;return I&&h&&I<g?{result:!1,error:{message:"invalid tiebreak scores (3)"}}:{result:!0}}function E_(t){let{existingDrawDefinition:e,hydrateCollections:r,enforceGender:n,tieFormatName:o,matchUpType:i,eventType:s,isMock:a,event:c}=t,{tieFormat:u,matchUpFormat:p}=t;if(i===ve&&s===ve){let m=e?.structures?.find(({stage:d})=>d===rt)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&to({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||to({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=Dn));if(u){let m=cr({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function U_(t){let e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:r,appliedPolicies:n,drawEntries:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u=t.qualifyingProfiles,p=u?.length?AT({uuids:t.uuids,qualifyingProfiles:u,appliedPolicies:n,idPrefix:s,isMock:a}):void 0;if(p?.error)return p;e.structures=e.structures?.filter(({structureId:T})=>T!==r),e.links=e.links?.filter(({source:T})=>T.structureId!==r);let{qualifiersCount:m,qualifyingDrawPositionsCount:d,qualifyingDetails:l}=p??{};d&&(p?.structures&&e.structures?.push(...p.structures),p?.links&&e.links?.push(...p.links));let f=e.structures?.find(({stage:T,stageSequence:y})=>T===rt&&y===1),{qualifiersCount:g}=Is({stageSequence:1,drawDefinition:e,structureId:i,stage:rt}),I=Math.max(m??0,g??0),h=kS({qualifiersCount:I,drawDefinition:e,stage:rt});if(h.error||(h=_p({drawSize:d,stage:ct,drawDefinition:e}),h.error))return h;yV({drawDefinition:e,drawEntries:o,event:c});let S=AV({mainStructure:f,qualifyingDetails:l,drawDefinition:e});return S.error?S:{drawDefinition:e,structureId:i}}function yV({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===ct)){let o={...n,entryStage:n.entryStage??rt,drawDefinition:t,event:r};fd(o)}}function AV({mainStructure:t,qualifyingDetails:e,drawDefinition:r}){for(let n of e||[]){let{finalQualifyingRoundNumber:o,finalQualifyingStructureId:i,roundTarget:s,finishingPositions:a,linkType:c}=n,u=t&&Ra({targetStructureId:t.structureId,sourceStructureId:i,sourceRoundNumber:o,finishingPositions:a,targetEntryRound:s,linkType:c})?.link;if(u?.error)return u;u&&(r.links||(r.links=[]),r.links.push(u))}return{error:void 0}}function kT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Qr.includes(o)}).map(St)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return x({result:{error:dn},info:{invalidParticipantIds:n}})}else e=r;return t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>e.length-1&&(!t.enableDoubleRobin||t.roundsCount>(e.length-1)*2)?{error:V,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:V,info:"roundsCount must be less than 32"}:{participantIds:e}}function Yd(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=kT(t);if(p.error)return p;for(let m of tt(1,r+1)){let d=xu({restrictMatchUpsCount:t.restrictMatchUpsCount,ignoreLastRoundNumber:!!u,newRound:!u,drawDefinition:n,matchUpsCount:o,structureId:i,roundNumber:u,idPrefix:s,isMock:a,event:c});if(d.error)return x({result:d,info:{iteration:m}});d.matchUps?.length&&e.push(...d.matchUps),u=(d?.roundNumber??1)+1}return{matchUps:e}}function D_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??_e[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=P_({scaleName:`${n}.${Vm}`,participant:u,eventType:o});!p&&n&&(p=P_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function P_({scaleType:t=Ii,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&yo({scaleAttributes:{eventType:o??Fs,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&ht(a)?a[e]:a}function qd(t){let e=UV(t);if(e?.error)return e;let r=kT(t);if(r.error)return r;let n=EV(t);if(n.error)return n;let o=D_(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of tt(1,(t.roundsCount??1)+1)){let m=Fd({...t,participantIds:r.participantIds,structure:n.structure,ignoreLastRoundNumber:!0,iterationMatchUps:a,adHocRatings:o,roundNumber:u,eventType:s,isMock:i});if(m.error)return m;let{matchUps:d,...l}=m;l.modifiedScaleValues&&(o=l.modifiedScaleValues),c.push({...l,iteration:p,matchUpsCount:d?.length}),u=(l?.roundNumber??1)+1,d?.length&&a.push(...d)}return{...C,matchUps:a,roundResults:c}}function EV(t){if(t.structureId)return t.structureId;let e=t.drawDefinition,r=e?.structures?.filter(i=>i.stageSequence===1)?.reduce((i,s)=>{let a=s.stage&&ks[s.stage];return ur({structure:s})&&a>(ks[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?ur({structure:n})?{structure:n}:{error:pa}:{error:wt}}function UV(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:V,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==$r?{error:pa}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:V,info:"Missing Entries"}:{error:void 0}}function N_(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,idPrefix:o,isMock:i,event:s}=t,a=s?.entries?.filter(({entryStage:p,entryStatus:m})=>(!p||p===rt)&&m&&Qr.includes(m)),c=a?.map(St),u=a?Math.floor(a.length/2):0;if(t.automated)return PV({...t,participantIds:c});{let p=Yd({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&bd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...C}}function PV(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=qd({...t,eventType:t.drawMatic?.eventType??t.matchUpType,generateMatchUps:r??!0,scaleAccessor:s??t.scaleAccessor,scaleName:i??t.scaleName,participantIds:t.participantIds,roundsCount:t.roundsCount,restrictEntryStatus:e,structureId:n,matchUpIds:o});return a.error?a:(a?.matchUps?.length&&bd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...C})}function M_({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:r,participantsCount:n,participantCount:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,seedsCount:u}){n=n??o;let p=at({drawDefinition:s,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:wt};let{positionAssignments:d}=ye({structure:m}),l=d?.length||0;if(u>l)return{error:wA};let f=m.structures?.length,g=It(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=Ig({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=_u({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[wn]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=tt(1,u+1).map(S=>{let T=I?.find(U=>U.includes(S)),y=T&&Math.min(...T),P=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:P}}),vt({drawDefinition:s,structureIds:[c]}),{...C,seedLimit:u}}function ta({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:q};return i=i??s?.entries??[],{scaledEntries:i.filter(d=>(!a||!d.entryStage||d.entryStage===a)&&(!o||!d.entryStageSequence||d.entryStageSequence===o)&&Qr.includes(d.entryStatus)).map(d=>{let{participantId:l}=d,{scaleItem:f}=Mc({tournamentRecord:e,scaleAttributes:r,participantId:l});return{...d,...f}}).filter(d=>{let l=d.scaleValue;return!n&&(isNaN(l)||!parseFloat(l))?!1:l}).sort(n||p)};function p(d,l){return t?m(l)-m(d):m(d)-m(l)}function m(d){return parseFloat(d.scaleValue||(t?-1:1e5))}}function GT(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=In({stageSequence:t.stageSequence||1,roundTarget:t.roundTarget,stage:t.stage,drawDefinition:r}),o=t.preparedStructureIds||[],i=n?.find(({structureId:l})=>!o.includes(l));if(!i)return x({result:{error:wt},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=OV({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&MV({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==$r&&!(t.qualifyingOnly&&t.stage!==ct),m=(n?.length||0)>1,d=p?NV({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?x({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function DV({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=lt({name:Mn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&ni.includes(o.entryStatus)})}function NV(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Tc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function MV(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(St);e?RV({...t,enteredParticipantIds:i}):(o||r)&&CV({...t,enteredParticipantIds:i})}function RV(t){let{provisionalPositioning:e,enteredParticipantIds:r,seededParticipants:n,tournamentRecord:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,structure:u,event:p}=t,m=u?Ts({provisionalPositioning:e,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structure:u}):void 0;n.filter(({participantId:d})=>r.includes(d)).filter(d=>!d.seedNumber||d.seedNumber<=n.length).sort((d,l)=>d.seedNumber<l.seedNumber?-1:d.seedNumber<l.seedNumber?1:0).forEach(d=>{let{participantId:l,seedNumber:f,seedValue:g}=d;$s({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function CV(t){let e=t.seedsCount,{provisionalPositioning:r,enteredParticipantIds:n,seedAssignmentProfile:o,assignSeedsCount:i,tournamentRecord:s,drawDefinition:a,seedByRanking:c,seedingProfile:u,structureId:p,event:m}=t,{categoryName:d,ageCategoryCode:l}=m?.category||{},f=m?.eventType,g=bV({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&vV({...t,ageCategoryCode:l,categoryName:d,eventType:f}),I=g?.length??0;I<e&&(e=I),g?.filter(({participantId:h})=>n.includes(h)).slice(0,i||e).forEach((h,S)=>{let T=S+1,{participantId:y,scaleValue:P}=h,U=o?.[T]||P||T;$s({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:U,event:m})})}function bV(t){let{tournamentRecord:e,seedingScaleName:r,stageSequence:n,entries:o,stage:i,event:s}=t,{categoryName:a,ageCategoryCode:c}=s?.category||{},u=s?.eventType,p={scaleName:r||a||c||s.eventId,scaleType:ho,eventType:u};return ta({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function vV(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ta({scaleAttributes:{scaleName:s||a,scaleType:gi,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function OV(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=DV(t);e>r.length&&(e=r.length);let{seedLimit:n}=M_({enforcePolicyLimits:t.enforcePolicyLimits??!0,appliedPolicies:t.appliedPolicies,participantsCount:r.length,seedingProfile:t.seedingProfile,drawDefinition:t.drawDefinition,structureId:t.structureId,seedsCount:e});return n&&n<e&&(e=n),{seedsCount:e,stageEntries:r,seedLimit:n}}function R_(t){let e=wd({...t,modifyOriginal:!1});if(e.error)return e;let r=e.drawDefinition,{suppressDuplicateEntries:n=!0,ignoreStageSpace:o,appliedPolicies:i,qualifyingOnly:s,seedingProfile:a,participants:c,drawEntries:u,placeByes:p,drawSize:m,drawType:d,entries:l}=t,f=[],g=[],I=_V({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===Gi?0:mt(t.seedsCount??0),S=GT({...t,qualifyingOnly:!m||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:rt,seedsCount:h,placeByes:p,drawSize:m,entries:l});if(S.error&&!S.conflicts)return S;S.positioningReport?.length&&f.push({[rt]:S.positioningReport});let T=S.structureId;return S.conflicts&&(g=S.conflicts),d===$r&&t.roundsCount&&N_({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function _V(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,entries:i}=t;for(let s of i){if(n&&s.entryStage&&s.entryStage!==rt)continue;let a={...s,ignoreStageSpace:e??o===$r,entryStage:s.entryStage??rt,event:t.event,drawDefinition:r,drawType:o},c=fd(a);if(n&&c.error)return c}return{error:void 0}}var xV=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var C_=xV;function b_(t){let{drawId:e=Dt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=C_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function $d(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=et(t,[{[Ve]:!0,[Fm]:!0}]);if(c.error)return c;if(!Dr({matchUpFormat:o}))return{error:$a};let u="setMatchUpFormat";if(s){let p=Bt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===ve)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:dr};m&&(m.matchUpFormat=o,gt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===ve)return{error:Wn};for(let p of e){let m=at({drawDefinition:n,structureId:p});if(m.error)return m;m.structure&&(m.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===ve)return{error:Wn};let p=at({drawDefinition:n,structureId:i});if(p.error)return p;p.structure&&(p.structure.matchUpFormat=o)}else n&&(n.matchUpFormat=o);return e=e??(i?[i]:void 0),vt({drawDefinition:n,structureIds:e}),{...C}}function v_({tieFormat:t}){let e=cr({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Dt());return{tieFormat:t}}function O_({tournamentRecord:t,drawDefinition:e,matchUpFormat:r,matchUpType:n,tieFormat:o,event:i}){if((r||o)&&!(r&&i?.matchUpFormat===r||i?.tieFormat&&o&&JSON.stringify(i.tieFormat)===JSON.stringify(o))){if(o){let a=v_({tieFormat:o});if(a.error)return a;e.tieFormat=a.tieFormat??o}else if(r){let a=$d({tournamentRecord:t,drawDefinition:e,matchUpFormat:r,event:i});if(a.error)return{info:"matchUpFormat or tieFormat error",error:a.error}}n&&(e.matchUpType=n)}return{error:void 0}}var iN={};Zt(iN,{attachPolicies:()=>Xi,findPolicy:()=>ri,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>vo,mutate:()=>nN,query:()=>oN,removePolicy:()=>rN});var nN={};Zt(nN,{attachPolicies:()=>Xi,removePolicy:()=>rN});function rN(t){let e=et(t,[{[ob]:!0,_anyOf:{[Ne]:!1,[se]:!1,[Ve]:!1,[Do]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return __(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:q};for(let i of o){let s=t.tournamentRecords[i],a=__(t,s);if(a.error)return a;r=!0}}else return{error:q};return r?{...C}:{error:kc}}function __(t,e){let r=yt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?At({element:e,extension:{name:ou,value:r}}):fr({element:e,name:ou}),{...C}):{error:kc}}var oN={};Zt(oN,{findPolicy:()=>ri,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>vo});var sN={[wn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Io]:{positioning:di},[Nn]:{positioning:di}},positioning:XC},policyName:"USTA SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:96,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}},Yg=sN;function x_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return x({info:"policyDefinitions must be an object",result:{error:V},stack:n});let o={[nu]:t?.[nu]};return e?wV({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&Xi({drawDefinition:r,policyDefinitions:o}),!t?.[wn]&&!e?.[wn]&&(Xi({policyDefinitions:Yg,drawDefinition:r}),t&&Object.assign(t,Yg)),{error:void 0}}function wV({policyDefinitions:t,appliedPolicies:e,policiesToAttach:r,drawDefinition:n}){for(let o of Object.keys(t))JSON.stringify(e?.[o])!==JSON.stringify(t[o])&&(r[o]=t[o]);Object.keys(r).length&&(Xi({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function w_(t){let{tournamentRecord:e,matchUpFormat:r,appliedPolicies:n,policyDefinitions:o,matchUpType:i,tieFormat:s,drawType:a,stack:c,event:u}=t,p=t.drawId?u?.drawDefinitions?.find(h=>h.drawId===t.drawId):void 0;p&&a!==p.drawType&&(p.drawType=a);let m=p??b_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),d=O_({tournamentRecord:e,drawDefinition:m,matchUpFormat:r,matchUpType:i,tieFormat:s,event:u});if(d.error)return x({result:d,stack:c});let l=x_({appliedPolicies:n,policyDefinitions:o,drawDefinition:m,stack:c});if(l.error)return l;let f=p?.structures?.find(h=>h.stage===rt&&h.stageSequence===1)?.structureId,g=p?p.structures?.filter(h=>h.stage===ct):[],I=g?.length===1&&!g[0].matchUps?.length&&g[0].structureId;return{drawDefinition:m,structureId:f,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:I}}function L_(t){let e="generateOrGetExisting",r=[],n=[],o=w_(t);if(o.error)return x({result:o,stack:e});let i=o.existingDrawDefinition,s=o.drawDefinition??{},a=o.structureId,c=t.drawEntries??t.eventEntries??[],u=o.existingQualifyingPlaceholderStructureId&&U_({...t,...o})||R_({...t,...o,entries:c});return u.error?x({result:u,stack:e}):(u.positioningReports?.length&&r.push(...u.positioningReports??[]),u.conflicts?.length&&n.push(...u.conflicts??[]),s=u.drawDefinition,a=u.structureId,{existingDrawDefinition:i,positioningReports:r,drawDefinition:s,structureId:a,conflicts:n,entries:c})}function F_(t){let{qualifyingPlaceholder:e,qualifyingProfiles:r,existingDrawDefinition:n,positioningReports:o,appliedPolicies:i,qualifyingOnly:s,drawDefinition:a,seedingProfile:c,participants:u,structureId:p,entries:m,stack:d}=t,l=e&&!r?.length&&!n,f=[];if(r){let g=(T,y)=>T.stageSequence-y.stageSequence,I=(T,y)=>T.roundTarget-y.roundTarget,h=[],S=1;r.sort(I);for(let T of r){if(!Array.isArray(T.structureProfiles))return x({info:si("structureProfiles"),result:{error:it},stack:d});S=T.roundTarget||S;let y=T.structureProfiles?.sort(g)||[],P=1;for(let U of y){let{qualifyingRoundNumber:A,qualifyingPositions:E,seededParticipants:N,seedingScaleName:D,seedsCount:M=0,seedByRanking:R,placeByes:b,drawSize:v}=U,O=GT({...t,seedingProfile:U.seedingProfile??c,stageSequence:P,qualifyingRoundNumber:A,preparedStructureIds:h,qualifyingPositions:E,seededParticipants:N,stage:ct,seedingScaleName:D,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:R,participants:u,roundTarget:S,seedsCount:M,placeByes:b,drawSize:v,entries:m});if(O.error)return O;O.structureId&&h.push(O.structureId),P+=1,O.conflicts?.length&&f.push(...O.conflicts),O.positioningReport?.length&&o.push({[ct]:O.positioningReport})}S+=1}}else if(p&&l){let g=Sn({structureName:Qe(ct),stage:ct}),{link:I}=Ra({sourceStructureId:g.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:eo});a.structures||(a.structures=[]),a.structures.push(g),a.links||(a.links=[]),a.links.push(I)}return{qualifyingConflicts:f,error:void 0}}var MN={};Zt(MN,{addGoesTo:()=>$i,allCompetitionMatchUps:()=>Un,allDrawMatchUps:()=>or,allEventMatchUps:()=>Kn,allPlayoffPositionsFilled:()=>xS,allTournamentMatchUps:()=>Ae,analyzeDraws:()=>vu,analyzeMatchUp:()=>Jp,analyzeTournament:()=>QT,bulkUpdatePublishedEventIds:()=>JT,calculateWinCriteria:()=>Ps,categoryCanContain:()=>qc,checkMatchUpIsComplete:()=>ds,checkValidEntries:()=>_d,compareTieFormats:()=>Ko,competitionScheduleMatchUps:()=>Gu,courtGridRows:()=>ol,credits:()=>k_,drawMatchUps:()=>gy,eventMatchUps:()=>cl,filterMatchUps:()=>Ni,filterParticipants:()=>Eu,findDrawDefinition:()=>sT,findExtension:()=>lt,findVenue:()=>jo,getAggregateTeamResults:()=>zT,getAllDrawMatchUps:()=>ae,getAllEventData:()=>ZT,getAllStructureMatchUps:()=>Pt,getAllowedDrawTypes:()=>Kd,getAllowedMatchUpFormats:()=>YT,getAppliedPolicies:()=>yt,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Nu,getCategoryAgeDetails:()=>Ls,getCheckedInParticipantIds:()=>us,getCompetitionDateRange:()=>Qd,getCompetitionMatchUps:()=>Xp,getCompetitionParticipants:()=>VT,getCompetitionPenalties:()=>qT,getCompetitionVenues:()=>Kp,getCourtInfo:()=>ud,getCourts:()=>Iy,getDrawData:()=>tl,getDrawDefinitionTimeItem:()=>Xh,getDrawParticipantRepresentativeIds:()=>oT,getDrawStructures:()=>In,getDrawTypeCoercion:()=>Ou,getEligibleVoluntaryConsolationParticipants:()=>nT,getEntriesAndSeedsCount:()=>il,getEvent:()=>Ty,getEventData:()=>el,getEventMatchUpFormatTiming:()=>sy,getEventProperties:()=>hy,getEventPublishStatus:()=>Xr,getEventStructures:()=>Sg,getEventTimeItem:()=>fu,getEvents:()=>Sy,getFlightProfile:()=>Ht,getHomeParticipantId:()=>py,getLinkedTournamentIds:()=>su,getMatchUpCompetitiveProfile:()=>hu,getMatchUpContextIds:()=>my,getMatchUpDailyLimits:()=>pl,getMatchUpDailyLimitsUpdate:()=>ay,getMatchUpDependencies:()=>on,getMatchUpFormat:()=>dy,getMatchUpFormatTiming:()=>Su,getMatchUpFormatTimingUpdate:()=>oy,getMatchUpScheduleDetails:()=>pd,getMatchUpType:()=>md,getMatchUpsMap:()=>De,getMatchUpsStats:()=>ly,getMatchUpsToSchedule:()=>rl,getMaxEntryPosition:()=>ry,getModifiedMatchUpFormatTiming:()=>sl,getPairedParticipant:()=>hn,getParticipantEventDetails:()=>BT,getParticipantIdFinishingPositions:()=>iT,getParticipantMembership:()=>HT,getParticipantResults:()=>Cu,getParticipantScaleItem:()=>Mc,getParticipantSchedules:()=>WT,getParticipantSignInStatus:()=>jT,getParticipantTimeItem:()=>Jh,getParticipants:()=>Gt,getPersonRequests:()=>bi,getPolicyDefinitions:()=>vo,getPositionAssignments:()=>Vp,getPositionsPlayedOff:()=>Ac,getPredictiveAccuracy:()=>uy,getProfileRounds:()=>nl,getPublishState:()=>gs,getRoundMatchUps:()=>Ke,getRounds:()=>fy,getScaleValues:()=>fa,getScaledEntries:()=>ta,getScheduledRoundsDetails:()=>ku,getSchedulingProfile:()=>zo,getSchedulingProfileIssues:()=>ey,getSeedingThresholds:()=>PS,getSeedsCount:()=>_u,getStructureSeedAssignments:()=>nn,getTeamLineUp:()=>ms,getTieFormat:()=>Zd,getTimeItem:()=>en,getTournamentIds:()=>hp,getTournamentInfo:()=>Us,getTournamentPenalties:()=>zd,getTournamentPersons:()=>KT,getTournamentPoints:()=>Xd,getTournamentPublishStatus:()=>yu,getTournamentStructures:()=>_S,getTournamentTimeItem:()=>Jm,getValidGroupSizes:()=>bp,getVenueData:()=>lc,getVenuesAndCourts:()=>Ao,isAdHoc:()=>ur,isCompletedStructure:()=>ai,isValidForQualifying:()=>TT,isValidMatchUpFormat:()=>Dr,matchUpActions:()=>Od,participantScaleItem:()=>yo,participantScheduledMatchUps:()=>cy,positionActions:()=>ST,publicFindCourt:()=>gS,publicFindVenue:()=>fS,tallyParticipantResults:()=>ba,tieFormatGenderValidityCheck:()=>Rm,tournamentMatchUps:()=>ul,validMatchUp:()=>eg,validMatchUps:()=>Vr,validateCollectionDefinition:()=>$c,validateLineUp:()=>Td});function k_(){return`