tods-competition-factory 5.2.2 → 5.2.3
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 +2 -2
- package/dist/tods-competition-factory.development.cjs.js +14 -7
- package/dist/tods-competition-factory.development.cjs.js.map +1 -1
- package/dist/tods-competition-factory.production.cjs.min.js +1 -1
- package/dist/tods-competition-factory.production.cjs.min.js.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var Gj=Object.defineProperty;var _t=(t,e)=>{for(var r in e)Gj(t,r,{get:e[r],enumerable:!0})};var UL="5.2.2";function bi(){return UL}var cI={};_t(cI,{availabilityGovernor:()=>gw,competitionGovernor:()=>cC,drawsGovernor:()=>EO,entriesGovernor:()=>CO,eventGovernor:()=>WO,generationGovernor:()=>KO,matchUpFormatGovernor:()=>QN,matchUpGovernor:()=>f_,mocksGovernor:()=>yT,officiatingGovernor:()=>Uw,participantGovernor:()=>q_,policyGovernor:()=>Jv,practiceGovernor:()=>ww,publishingGovernor:()=>ex,queryGovernor:()=>TO,rankingGovernor:()=>ET,reportGovernor:()=>px,scheduleGovernor:()=>Dx,scoreGovernor:()=>WS,tieFormatGovernor:()=>wx,tournamentGovernor:()=>tw,venueGovernor:()=>qw});var cC={};_t(cC,{getCompetitionLeaderboard:()=>LE,getCompetitionParticipantState:()=>wE,getCompetitionPolicy:()=>wo,getCompetitionState:()=>Ko,getLinkedTournamentIds:()=>Bp,getTournamentIds:()=>Sm,initializeCompetitionState:()=>eC,linkTournaments:()=>Hb,mutate:()=>sC,processCompetitionMatchUp:()=>Tm,processCompetitionRound:()=>oC,query:()=>aC,resetCompetitionState:()=>iC,unlinkTournament:()=>jb,unlinkTournaments:()=>Wb});var sC={};_t(sC,{initializeCompetitionState:()=>eC,linkTournaments:()=>Hb,processCompetitionMatchUp:()=>Tm,processCompetitionRound:()=>oC,resetCompetitionState:()=>iC,unlinkTournament:()=>jb,unlinkTournaments:()=>Wb});var ks="SINGLES",Ct="SINGLES",si="DOUBLES",Ut="DOUBLES",hr="TEAM",xt="TEAM",Bj="HYBRID",qd="HYBRID",RL={SINGLES_MATCHUP:ks,SINGLES:Ct,DOUBLES_MATCHUP:si,DOUBLES:Ut,TEAM_MATCHUP:hr,TEAM:xt,HYBRID_MATCHUP:Bj,HYBRID:qd};var yy={[Ct]:[Ct,"S"],[Ut]:[Ut,"D"],[xt]:[xt,"T"],[qd]:[qd,"H"],S:[Ct,"S"],D:[Ut,"D"],T:[xt,"T"],H:[qd,"H"]};function ee(t,e){return(t??0)-(e??0)}function st(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function Vr(t){return typeof t=="function"}function wt(t){return typeof t=="string"}function St(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bL(t,e){if(!St(t)||!St(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 Ay(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(St).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var CL=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function Ey(t,e){if(t===void 0)return null;if(!St(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=>Ey(i))}:{[o]:e?n(t[o]):Ey(t[o])}))}function EU(t){return Array.isArray(t)?t.length+t.map(EU).reduce((e,r)=>e+r,0):St(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>EU(t[e])).reduce((e,r)=>e+r,0):0}function ML(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=EU(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function rn(t){return Number.isNaN(Number(t))?!1:t>0&&(t&t-1)===0}function vL(t){if(!t.length)return;let e=[...t].sort(ee),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function OL(t){if(t===1||Number.isNaN(Number(t))||!rn(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function xl(t){return Number.isNaN(Number(t))?0:t%2&&t+1||t}function wl(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function He(t){return!Number.isNaN(Number.parseFloat(t))}function Py(t){let e=st(t);if(!Number.isNaN(e))return e===0?!1:(e&-e)===1}function Ci(t){if(Number.isNaN(Number(t)))return!1;for(;!rn(t);)t++;return t}function pn(t,e,r){return t=Math.ceil(t),e=Math.floor(e),Math.floor((r??Math.random)()*(e-t+1))+t}function It(t){return wt(t)&&!t.trim().length?!1:Number.isSafeInteger(typeof t=="string"?+t:t)}function _L(t=1,e=3,r=!0,n){let o=n??Math.random,i=0;for(let s=0;s<e;s++)i+=o()*(t/e);return r&&t>1?Math.round(i):i}function Hj(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function AU(t,e,r,n,o=2,i){let s=i??Math.random,a=1-s(),c=1-s(),u=Math.sqrt(-2*Math.log(a))*Math.cos(2*Math.PI*c);return u=u/10+.5,u>1||u<0?u=AU(t,e,r,void 0,2,i):(u=Math.pow(u,r),u*=e-t,u+=t),n&&(u=Hj(u,n)),Number.parseFloat(u.toFixed(o))}function SI(t,e=2){return Number.parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function ct(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function xL(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function dr(t,e){if(!Array.isArray(t))return[];let r=e??Math.random;return t.map(n=>[r(),n]).sort((n,o)=>n[0]-o[0]).map(n=>n[1])}function Jc(t){return It(t)?t:1/0}function dn(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function wL(t){return PU(dn(t))}function PU(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function Wj(t,e,r){return r.indexOf(t)===e}function Ny(t){return t.filter(Wj)}function Sr(t,e){return Array.isArray(t)&&t.length?t.splice(Math.floor((e??Math.random)()*t.length),1)[0]:void 0}function Dn(t,e){let r=Math.floor((e??Math.random)()*t.length);return t[r]}function J(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function Is(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function Ht(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 NU(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function we(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function LL(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function FL(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 Ae(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 DU(t,[e,...r]){return t.length?[t.slice(0,e),...DU(t.slice(e),[...r,e])]:[]}function kL(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 Dy(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function Uy(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function TI(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 GL(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return J(r,n+1).filter(o=>!t.includes(o))}function Gs(t,e){return!Array.isArray(t)||!wt(e)?!1:Ht(t,yy[e]).length}var P={success:!0},UU="error",VL={SUCCESS:P,ERROR:UU};function Ry({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!==ct(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...P}}var nF={};_t(nF,{addNotice:()=>it,callListener:()=>Hl,createInstanceState:()=>$R,cycleMutationStatus:()=>XI,deepCopyEnabled:()=>JI,deleteNotice:()=>Vy,deleteNotices:()=>Mi,disableNotifications:()=>JR,enableNotifications:()=>QI,getAuditAuthorityServer:()=>rm,getDevContext:()=>We,getMethods:()=>nm,getNotices:()=>Bl,getPayloads:()=>rF,getProvider:()=>By,getSaveDrawDeletions:()=>em,getSchemaWriteMode:()=>zI,getTopics:()=>rr,getTournamentId:()=>Yi,getTournamentRecord:()=>ZI,getTournamentRecords:()=>Qn,globalLog:()=>tb,handleCaughtError:()=>im,hasTopic:()=>pu,removeTournamentRecord:()=>ZR,setAuditAuthorityServer:()=>QR,setDeepCopy:()=>yp,setDevContext:()=>Tp,setGlobalLog:()=>ZL,setGlobalMethods:()=>tF,setGlobalSubscriptions:()=>TY,setMethods:()=>eF,setSaveDrawDeletions:()=>zR,setSchemaWriteMode:()=>KR,setStateMethods:()=>eb,setStateProvider:()=>hY,setSubscriptions:()=>Gy,setTournamentId:()=>om,setTournamentRecord:()=>XR,setTournamentRecords:()=>Wl,timeKeeper:()=>SY,writeLegacyEnabled:()=>uu,writeNativeEnabled:()=>cu});var by={message:"Chronological error; time violation.",code:"ANACHRONISM"},Ll={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},RU={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},Cy={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},kt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},Y={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Xc={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},Ic={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},Ua={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},K={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},bU={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Cr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Wo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},yI={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},EI={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Zc={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},CU={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},MU={message:"Schedule conflict: court slot already occupied",code:"ERR_SCHEDULE_CONFLICT_DOUBLE_BOOKING"},vU={message:"Schedule conflict: matchUps scheduled outside court availability",code:"ERR_SCHEDULE_CONFLICT_COURT_UNAVAILABLE"},OU={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},jj={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},mp={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},tu={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},eu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},BL={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},hs={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Ra={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Fl={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},$d={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},Yj={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},ru={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Un={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},_U={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},xU={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},wU={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},LU={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},FU={message:"Invalid action",code:"ERR_INVALID_ACTION"},My={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},kU={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},GU={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},VU={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},AI={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},BU={message:"Existing round",code:"ERR_EXISTING_ROUND"},qj={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},mn={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Pt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},PI={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Hi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},NI={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},HU={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},so={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Se={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Br={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},WU={message:"Event exists",code:"ERR_EXISTING_EVENT"},jU={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},YU={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},DI={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},UI={message:"Missing stage",code:"ERR_MISSING_STAGE"},hc={message:"Invalid stage",code:"ERR_INVALID_STAGE"},qU={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},RI={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},$U={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},KU={message:"Lucky draw first round allows at most one BYE",code:"ERR_LUCKY_DRAW_BYE_LIMIT"},vy={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},nu={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},bI={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},HL={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},Sc={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ai={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},zU={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},QU={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},JU={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},ba={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},cr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},Vs={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},be={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},zn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},nr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},mr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},Oy={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Ca={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},$j={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},XU={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},_y={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},ZU={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},xy={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},Kj={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},lp={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},zj={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},tR={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},Qj={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},CI={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},Jj={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},Xj={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},MI={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},nt={message:"Missing value",code:"ERR_MISSING_VALUE"},eR={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},rR={message:"Missing date",code:"ERR_MISSING_DATE"},vI={message:"No valid dates",code:"ERR_NO_VALID_DATES"},kl={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},OI={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},nR={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},de={message:"Invalid Date",code:"ERR_INVALID_DATE"},Bs={message:"Invalid time",code:"ERR_INVALID_TIME"},oR={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},WL={message:"Missing date range",info:"Event or tournament must have start and end dates",code:"ERR_MISSING_DATE_RANGE"},fp={message:"Invalid Time Zone",code:"ERR_INVALID_TIME_ZONE"},gp={message:"Invalid embargo: must be an ISO 8601 datetime with timezone (Z or \xB1HH:MM offset)",code:"ERR_INVALID_EMBARGO"},wy={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},iR={message:"Invalid score",code:"ERR_INVALID_SCORE"},Gl={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var jL={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},_I={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},sR={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Kd={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},aR={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Vl={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Wi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Hr={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},vr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},cR={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Rn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},uR={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Ma={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},va={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},$e={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},pR={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},Wt={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},dR={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},Zj={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},mR={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},jo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},lR={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},fR={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},gR={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Oa={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},zd={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},xI={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},wI={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},Ly={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},YL={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},qL={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},IR={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},hR={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},LI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},FI={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},kI={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},SR={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},TR={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Ip={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},yR={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},So={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},ER={message:"Court exists",code:"ERR_EXISTING_COURT"},Qd={message:"Booking not found",code:"ERR_NOT_FOUND_BOOKING"},AR={message:"An active draft already exists for this draw",code:"ERR_EXISTING_DRAFT"},PR={message:"Existing matchUps conflict with booking",code:"ERR_EXISTING_MATCHUPS"},NR={message:"Venue exists",code:"ERR_EXISTING_VENUE"},ji={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Hs={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},DR={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},UR={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},RR={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},bR={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},$L={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},GI={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},CR={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},VI={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},BI={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},hp={message:"Missing context",code:"ERR_MISSING_CONTEXT"},MR={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},ou={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},vR={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},_a={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},OR={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Jd={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},ci={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},_R={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},vo={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Xd={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Sp={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},O={message:"Invalid values",code:"ERR_INVALID_VALUES"},xR={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},HI={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},wR={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},iu={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},WI={message:"Value unchanged",code:"ABORT_UNCHANGED"},fe={message:"Not found",code:"ERR_NOT_FOUND"},jI={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},LR={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},YI={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},FR={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},kR={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},Fy={message:"Existing stage",code:"ERR_EXISTING_STAGE"},qI={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},su={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},GR={message:"Mutation blocked by active lock",code:"ERR_MUTATION_LOCKED"},VR={message:"Active mutation lock already exists for scope",code:"ERR_EXISTING_MUTATION_LOCK"},BR={message:"Mutation lock not found",code:"ERR_NOT_FOUND_MUTATION_LOCK"},HR={message:"Lock token does not match",code:"ERR_UNAUTHORIZED_LOCK_OPERATION"},WR={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},au={message:"Scores present",code:"ERR_SCORES_PRESENT"},jR={message:"Tournament category is referenced by one or more events",code:"ERR_TOURNAMENT_CATEGORY_IN_USE"},$I={message:"Practice registration not found",code:"ERR_NOT_FOUND_REGISTRATION"},Zd={message:"Booking capacity exceeded",code:"ERR_CAPACITY_EXCEEDED"},KL={ANACHRONISM:by,BOOKING_NOT_FOUND:Qd,CANNOT_CHANGE_WINNING_SIDE:Vl,CAPACITY_EXCEEDED:Zd,REGISTRATION_NOT_FOUND:$I,CANNOT_MODIFY_TIEFORMAT:_I,TOURNAMENT_CATEGORY_IN_USE:jR,CANNOT_MODIFY_PARTICIPANT_TYPE:sR,CANNOT_REMOVE_MAIN_STRUCTURE:RU,CANNOT_REMOVE_PARTICIPANTS:Kd,CATEGORY_MISMATCH:aR,COURT_EXISTS:ER,COURT_NOT_FOUND:So,EXISTING_DRAFT:AR,EXISTING_MATCHUPS:PR,DRAW_DEFINITION_NOT_FOUND:Cr,DRAW_ID_EXISTS:_U,DRAW_POSITION_ACTIVE:eu,DRAW_POSITION_ASSIGNED:Zc,DRAW_POSITION_NOT_CLEARED:OU,DRAW_POSITION_NOT_FOUND:jj,DRAW_SIZE_MISMATCH:Yj,DUPLICATE_ENTRY:Ll,DUPLICATE_VALUE:xR,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:hR,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:IR,EVENT_EXISTS:WU,EVENT_NOT_FOUND:Br,EXISTING_DRAW_DEFINITIONS:bU,EXISTING_END_TIME:UR,EXISTING_FLIGHT:LR,EXISTING_MATCHUP_ID:kR,EXISTING_OUTCOME:FR,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Oa,EXISTING_PARTICIPANT:zd,EXISTING_POLICY_TYPE:xy,EXISTING_PROFILE:YI,EXISTING_ROUND:BU,EXISTING_STAGE:Fy,EXISTING_STRUCTURE:qI,INCOMPATIBLE_MATCHUP_STATUS:bI,INCOMPLETE_SOURCE_STRUCTURE:yI,INSUFFICIENT_DRAW_POSITIONS:kI,INVALID_ACTION:FU,INVALID_ASSIGNMENT:My,INVALID_BOOKINGS:kl,INVALID_CATEGORY:Sp,INVALID_COLLECTION_DEFINITION:_R,INVALID_CONFIGURATION:ci,INVALID_DATE_AVAILABILITY:OI,INVALID_DATE:de,INVALID_DRAW_DEFINITION:Ua,INVALID_DRAW_POSITION_FOR_SEEDING:EI,INVALID_DRAW_POSITION:hs,INVALID_DRAW_SIZE:$d,INVALID_END_TIME:DR,INVALID_ENTRIES:YU,INVALID_EVENT_TYPE:so,INVALID_GAME_SCORES:wy,INVALID_GENDER:Xd,INVALID_MATCHUP_FORMAT:zU,INVALID_MATCHUP_STATUS:Sc,INVALID_MATCHUP_STATUS_BYE:$U,INVALID_MATCHUP:mr,INVALID_OBJECT:vo,INVALID_PARTICIPANT_ID:Hr,INVALID_PARTICIPANT_IDS:vr,INVALID_PARTICIPANT_ROLE:cR,INVALID_PARTICIPANT_SEEDING:xU,INVALID_PARTICIPANT_TYPE:Rn,INVALID_PARTICIPANT:Wi,INVALID_POLICY_DEFINITION:ZU,INVALID_RECORDS:Cy,INVALID_SCALE_ITEM:ou,INVALID_SEED_NUMBER:GU,INVALID_SEED_POSITION:VU,INVALID_SET_NUMBER:Qj,INVALID_SIDE_NUMBER:tR,INVALID_SCORE:iR,INVALID_STAGE:hc,INVALID_START_TIME:bR,INVALID_STRUCTURE:Wo,INVALID_STOP_TIME:RR,INVALID_TIE_FORMAT:ai,INVALID_TIME:Bs,INVALID_TIME_ITEM:GI,INVALID_TOURNAMENT_DATES:oR,INVALID_TOURNAMENT_RECORD:Xc,INVALID_VALUES:O,INVALID_WINNING_SIDE:Gl,LUCKY_DRAW_BYE_LIMIT:KU,MATCHUP_NOT_FOUND:be,METHOD_NOT_FOUND:su,MUTATION_LOCKED:GR,MUTATION_LOCK_EXISTS:VR,MUTATION_LOCK_NOT_FOUND:BR,MISSING_ASSIGNMENTS:DI,MISSING_ASYNC_STATE_PROVIDER:CR,MISSING_AVOIDANCE_POLICY:XU,MISSING_BIRTH_DATE:eR,MISSING_COLLECTION_DEFINITION:JU,MISSING_COURT_ID:MI,MISSING_COURTS_INFO:yR,MISSING_DATE_AVAILABILITY:nR,MISSING_DATE:rR,MISSING_DRAW_DEFINITION:K,MISSING_DRAW_ID:Un,MISSING_DRAW_POSITION:Ra,MISSING_DRAW_POSITIONS:tu,MISSING_DRAW_SIZE:ru,MISSING_ENTRIES:jU,MISSING_EVENT:Se,MISSING_QUALIFIED_PARTICIPANTS:pR,MISSING_MATCHUP_FORMAT:QU,MISSING_MATCHUP_ID:cr,MISSING_MATCHUP_IDS:Vs,MISSING_MATCHUP:nr,MISSING_MATCHUPS:zn,MISSING_PARTICIPANT_COUNT:lR,MISSING_PARTICIPANT_ID:$e,MISSING_PARTICIPANT_IDS:jo,MISSING_PARTICIPANT_ROLE:uR,MISSING_PARTICIPANT:Ma,MISSING_PARTICIPANTS:va,MISSING_PENALTY_ID:TR,MISSING_PENALTY_TYPE:SR,MISSING_PERSON_DETAILS:gR,MISSING_POLICY_ATTRIBUTES:_y,MISSING_POLICY_DEFINITION:Ca,MISSING_POLICY_TYPE:Oy,MISSING_POSITION_ASSIGNMENTS:RI,MISSING_ROUND_NUMBER:qj,MISSING_SCHEDULE:MR,MISSING_SCORING_POLICY:zj,MISSING_SEED_ASSIGNMENTS:kU,MISSING_SEEDCOUNT_THRESHOLDS:LU,MISSING_SEEDING_POLICY:$j,MISSING_SET_NUMBER:Jj,MISSING_SET_OBJECT:CI,MISSING_SIDE_NUMBER:Xj,MISSING_STAGE:UI,MISSING_STRUCTURE_ID:mn,MISSING_STRUCTURE:Hi,MISSING_MAIN_STRUCTURE:NI,MISSING_STRUCTURES:PI,MISSING_TARGET_LINK:AI,MISSING_TIE_FORMAT:ba,MISSING_TIME_ITEM:VI,MISSING_TIME_ITEMS:BI,MISSING_TOURNAMENT_ID:Ic,MISSING_TOURNAMENT_RECORD:Y,MISSING_TOURNAMENT_RECORDS:kt,MISSING_VALUE:nt,MISSING_VENUE_ID:Hs,MODIFICATIONS_FAILED:vR,NO_CANDIDATES:Jd,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:FI,NO_MODIFICATIONS_APPLIED:_a,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:LI,NO_PARTICIPANT_REMOVED:mR,NO_VALID_ACTIONS:wR,NO_VALID_ATTRIBUTES:iu,NO_VALID_DATES:vI,NOT_FOUND:fe,NOT_IMPLEMENTED:jI,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:xI,PARTICIPANT_ID_EXISTS:dR,PARTICIPANT_NOT_CHECKED_IN:fR,PARTICIPANT_NOT_FOUND:Wt,PARTICIPANT_PAIR_EXISTS:Zj,PENALTY_NOT_FOUND:Ip,POLICY_NOT_ATTACHED:Kj,POLICY_NOT_FOUND:lp,SCHEDULE_NOT_CLEARED:CU,SCHEDULE_CONFLICT_DOUBLE_BOOKING:MU,SCHEDULE_CONFLICT_COURT_UNAVAILABLE:vU,SCHEDULED_MATCHUPS:WR,SCORES_PRESENT:au,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:wU,STAGE_SEQUENCE_LIMIT:qU,STRUCTURE_NOT_FOUND:Pt,TEAM_NOT_FOUND:HI,UNABLE_TO_ASSIGN_COURT:OR,UNAUTHORIZED_LOCK_OPERATION:HR,UNLINKED_STRUCTURES:HU,UNRECOGNIZED_DRAW_TYPE:mp,UNRECOGNIZED_MATCHUP_FORMAT:nu,UNRECOGNIZED_MATCHUP_STATUS:vy,VALUE_UNCHANGED:WI,VENUE_EXISTS:NR};var er={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},YR={addNotice:dY,callListener:gY,cycleMutationStatus:pY,deleteNotice:lY,deleteNotices:mY,disableNotifications:tY,enableNotifications:eY,getMethods:tm,getNotices:zL,getPayloads:zL,getTopics:fY,getTournamentId:QL,getTournamentRecord:rY,getTournamentRecords:nY,removeTournamentRecord:aY,setMethods:uY,setSubscriptions:cY,setTournamentId:iY,setTournamentRecord:oY,setTournamentRecords:sY,handleCaughtError:IY};function tY(){er.disableNotifications=!0}function eY(){er.disableNotifications=!1}function QL(){return er.tournamentId}function rY(t){return er.tournamentRecords[t]}function nY(){return er.tournamentRecords}function oY(t){let e=t?.tournamentId;return e?(er.tournamentRecords[e]=t,{success:!0}):{error:Xc}}function iY(t){return t?er.tournamentRecords[t]?(er.tournamentId=t,{success:!0}):{error:Y}:(er.tournamentId=void 0,{success:!0})}function sY(t){er.tournamentRecords=t;let e=Object.keys(t);e.length===1?er.tournamentId=e[0]:e.length||(er.tournamentId=void 0)}function aY(t){if(typeof t!="string")return{error:O};if(!er.tournamentRecords[t])return{error:fe};delete er.tournamentRecords[t];let e=Object.keys(er.tournamentRecords);return e.length===1?er.tournamentId=e[0]:e.length||(er.tournamentId=void 0),{success:!0}}function cY(t){return t.subscriptions===null||Object.keys(t.subscriptions).length===0?(er.subscriptions={},{...P}):typeof t.subscriptions!="object"?{error:O}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?er.subscriptions[e]=t.subscriptions[e]:delete er.subscriptions[e]}),{...P})}function uY(t){return typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(er.methods[e]=t[e])}),{...P})}function pY(){let t=er.modified;return er.modified=!1,t}function dY({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(er.disableNotifications||(er.modified=!0),!(er.disableNotifications||!er.subscriptions[t]&&!n)))return r&&(er.notices=er.notices.filter(o=>!(o.topic===t&&o.key===r))),er.notices.push({topic:t,payload:e,key:r}),{...P}}function tm(){return er.methods??{}}function zL({topic:t}){return er.notices.filter(e=>e.topic===t).map(e=>e.payload)}function mY(){er.notices=[]}function lY({topic:t,key:e}){er.notices=er.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function fY(){return{topics:Object.keys(er.subscriptions)}}function gY({topic:t,payloads:e,notices:r},n){let o=e??r??[],i=er.subscriptions[t];i&&typeof i=="function"&&i(o);let s=n?.[t];s&&typeof s=="function"&&s(o)}function IY({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:QL(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var KI="native",qR="legacy",ky="dual",JL=[KI,ky,qR];var se={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],schemaWriteMode:KI,saveDrawDeletions:!1,auditAuthorityServer:!1,deepCopy:!0},Wr=YR,XL=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function hY(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Ht(Object.keys(t),XL).length!==XL.length)throw new Error("Global state provider is missing required methods");return Wr=t,{success:!0}}function $R(){if(Wr.createInstanceState){try{Wr.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:CR}}function We(t){return!t||typeof t!="object"?se.devContext??!1:typeof se.devContext!="object"?!1:Object.keys(t).every(e=>se.devContext?.[e]===t[e])&&se.devContext}function SY(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(se.timers).filter(o=>o!=="default"||se.timers[o].startTime).map(o=>{let i=se.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:se.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=se.timers[e].state==="stopped"?0:(r-(se.timers[e]?.startTime??0))/1e3,o=se.timers[e].elapsedTime+n;return{state:se.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!se.timers[e]||t==="reset"){if(e==="allTimers")return se.timers={default:{elapsedTime:0}},!0;se.timers[e]={startTime:r,state:"active",elapsedTime:0}}return se.timers[e].elapsedTime||(se.timers[e].elapsedTime=0),t==="stop"&&se.timers[e].state!=="stopped"&&(se.timers[e].state="stopped")&&(se.timers[e].elapsedTime+=(r-(se.timers[e]?.startTime??0))/1e3),t==="start"&&(se.timers[e].startTime=r)&&(se.timers[e].state="active"),se.timers[e]}function ZL(t){Vr(t)?se.globalLog=t:delete se.globalLog}function Tp(t){se.devContext=t}function KR(t){return t===void 0?(se.schemaWriteMode=KI,{...P}):JL.includes(t)?(se.schemaWriteMode=t,{...P}):{error:O}}function zI(){return se.schemaWriteMode}function cu(){return se.schemaWriteMode===KI||se.schemaWriteMode===ky}function uu(){return se.schemaWriteMode===qR||se.schemaWriteMode===ky}function zR(t){return t===void 0?(se.saveDrawDeletions=!1,{...P}):typeof t!="boolean"?{error:O}:(se.saveDrawDeletions=t,{...P})}function em(){return se.saveDrawDeletions}function QR(t){return t===void 0?(se.auditAuthorityServer=!1,{...P}):typeof t!="boolean"?{error:O}:(se.auditAuthorityServer=t,{...P})}function rm(){return se.auditAuthorityServer}function JR(){Wr.disableNotifications()}function QI(){Wr.enableNotifications()}function yp(t,e){typeof t=="boolean"&&(se.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(se.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(se.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(se.deepCopyAttributes.stringify=e.stringify),e.threshold&&(se.deepCopyAttributes.threshold=e.threshold))}function JI(){return{enabled:se.deepCopy,...se.deepCopyAttributes}}function TY(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{se.globalSubscriptions[e]=t.subscriptions[e]}),{...P}):{error:nt,info:"missing subscriptions"}}function Gy(t){return t?.subscriptions?Wr.setSubscriptions({subscriptions:t.subscriptions}):{error:nt,info:"missing subscriptions"}}function tF(t){return t?typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{Vr(t[e])&&(se.globalMethods[e]=t[e])}),{...P}):{error:nt,info:"missing method declarations"}}function eF(t){return t?typeof t!="object"?{error:O}:Wr.setMethods(t):{error:nt,info:"missing method declarations"}}function XI(){return Wr.cycleMutationStatus()}function it(t){if(typeof t?.topic!="string")return;let e=se.globalSubscriptions[t.topic];return Wr.addNotice(t,e)}function nm(){return{...se.globalMethods,...Wr.getMethods()}}function Bl(t){return rF(t)}function rF(t){return typeof Wr.getPayloads=="function"?Wr.getPayloads(t):Wr.getNotices(t)}function Vy({key:t,topic:e}){return Wr.deleteNotice({key:t,topic:e})}function Mi(){return Wr.deleteNotices()}function rr(){return Wr.getTopics()}function pu(t){return rr()?.topics?.includes(t)}async function Hl(t){return Wr.callListener(t,se.globalSubscriptions)}function Yi(){return Wr.getTournamentId()}function ZI(t){return Wr.getTournamentRecord(t)}function Qn(){return Wr.getTournamentRecords()}function XR(t){return Wr.setTournamentRecord(t)}function Wl(t){return Wr.setTournamentRecords(t)}function om(t){return Wr.setTournamentId(t)}function ZR(t){return Wr.removeTournamentRecord(t)}function By(){return Wr}function im({engineName:t,methodName:e,params:r,err:n}){let o=Vr(Wr.handleCaughtError)&&Wr.handleCaughtError||YR.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function tb(t,e){if(se.globalLog)try{se.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),ZL()}else console.log(e,t)}function eb(t,e,r,n){if(!St(t))return{error:O};He||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Vr(a[u])?i[u]=a[u]:St(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?tF(i):eF(i),{methods:i}}function yY(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function et(t,e,r,n){if(typeof t!="object"||t===null)return t;JI()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=yY(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>et(c))}:{[a]:n?t[a]:et(t[a])}))}function M({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&&(e.context??={},Object.assign(e.context,et(t))),e&&!e?.error&&!e?.success&&Object.assign(e,{...P}),e??{success:!0}}var or="FEMALE",ui="OTHER",Ss="MIXED",Le="MALE";var jl={FEMALE_ABBR:"F",OTHER_ABBR:"O",MIXED_ABBR:"X",MALE_ABBR:"M",ANY_ABBR:"A",FEMALE:or,MIXED:Ss,OTHER:ui,MALE:Le,ANY:"ANY"};function Ts(t){return[or,"F"].includes(t)}function xa(t){return[Le,"M"].includes(t)}function jr(t){return[Ss,"X"].includes(t)}function To(t){return["ANY","A"].includes(t)}function lr(t){if(t){if(Ts(t))return or;if(jr(t))return Ss;if(xa(t))return Le;if(To(t))return"ANY"}return ui}function bn(t){return Ts(t)||xa(t)}var NY="MIXED events can not contain mixed singles or { gender: ANY } collections",DY="events with { gender: ANY } can not contain MIXED singles collections";function Yl(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&bn(r)&&lr(r)!==lr(o)?M({result:{valid:!1,error:Xd},context:{gender:o},stack:e}):jr(r)&&(To(o)||jr(o)&&n!==Ut)?M({result:{error:Xd,valid:!1},info:NY,stack:e}):To(r)&&jr(o)&&n!==Ut?M({result:{error:Xd,valid:!1},info:DY,stack:e}):{valid:!0}}var UY="normal",rb="timed",RY="final",th="NOAD";var nb=["SET","HAL","QTR","PER","INN","RND","FRM","MAP","MAT"],Hy="CONSECUTIVE",Wy="TRADITIONAL",bY="game",CY="matchUp",oF={S:UY,F:RY,G:bY,M:CY};function sm(t,e){if(St(t)&&(t?.bestOf||t?.exactly)&&t?.setFormat)return vY(t,e)}function ql(t){return!Number.isNaN(Number(t))&&Number(t)}function aF(t){let e=`T${t.minutes}`;return t.based==="P"&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function MY(t){let e=t?.deuceAfter?`${t.deuceAfter}D`:"";if(t?.type===Wy)return`TN${e}`;if(t?.type===Hy&&Number.isInteger(t.count))return`${t.count}C${e}`}function vY(t,e){let r=ql(t.bestOf)||void 0,n=ql(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return aF(t.setFormat);let i=t.matchRoot||"SET",s=n&&n!==1?"X":"",a=t.aggregate?"A":"",c=o&&`${i}${o}${s}${a}`||"",u=iF(t.setFormat,e),p=u&&`S:${u}`||"",d=iF(t.finalSetFormat,e),m=o&&o>1&&d&&u!==d&&`F:${d}`||"",l=t.gameFormat?`G:${MY(t.gameFormat)}`:"",f=t.matchUpConstraint?.timed?`M:T${t.matchUpConstraint.minutes}`:"";if(c&&u)return[c,p,l,m,f].filter(Boolean).join("-")}function iF(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return aF(t);if(t.outs)return`O${t.outs}`;if(t.tiebreakSet)return sF(t.tiebreakSet);let r=ql(t.setTo);if(r){let n=t.NoAD&&th||"",o=ql(t.winBy),i=sF(t.tiebreakFormat),s=i&&`/${i}`||"",a=o&&o!==2&&!i?`WB${o}`:"",c=ql(t.tiebreakAt),u=c&&(c!==r||e)&&`@${c}`||"";if(i!==!1)return`${r}${n}${a}${s}${u}`}}}function sF(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&ql(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?th:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function ne(t){if(wt(t)){let e=t.startsWith("T")&&rb||nb.some(r=>t.startsWith(r))&&"SET"||"";if(e===rb){let r=dF(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e==="SET")return xY(t)}}function OY(t){let e=nb.find(u=>t.startsWith(u));if(!e)return;let r=t.slice(e.length),n=/^(\d+)([A-Z]*)$/.exec(r);if(!n)return;let o=Ap(n[1]);if(!o)return;let i=n[2],s=!1,a=!1,c=[];for(let u of i)u==="X"?s=!0:u==="A"?a=!0:c.push(u);return{matchRoot:e,count:o,exactly:s,aggregate:a,matchMods:c}}function _Y(t){let e=/^(.+?)(\d+D)$/.exec(t),r=e?e[1]:t,n=e?Number(e[2].slice(0,-1)):void 0;if(n!==void 0&&(n<1||!Number.isInteger(n)))return;if(r==="TN"){let i={type:Wy};return n&&(i.deuceAfter=n),i}let o=/^([1-9]\d*)C$/.exec(r);if(o){let i={type:Hy,count:Number(o[1])};return n&&(i.deuceAfter=n),i}}function xY(t){let e=t.split("-"),r=OY(e[0]);if(!r)return;let{matchRoot:n,count:o,exactly:i,aggregate:s,matchMods:a}=r,c=i&&o!==1?void 0:o,u=i&&o!==1?o:void 0,p,d,m,l,S={setFormat:p,finalSetFormat:d,gameFormat:m,matchUpConstraint:l,sCount:0,fCount:0,gCount:0,mCount:0};for(let T=1;T<e.length;T++)if(!wY(e[T],S))return;return{setFormat:p,finalSetFormat:d,gameFormat:m,matchUpConstraint:l}=S,LY({setFormat:p,finalSetFormat:d,gameFormat:m,matchUpConstraint:l,matchRoot:n,aggregate:s,matchMods:a,bestOf:c,exactly:u})}function wY(t,e){let r=t.indexOf(":");if(r<0)return!1;let n=t.slice(0,r),o=t.slice(r+1);if(!(n in oF))return!1;if(n==="S"){if(e.sCount++,e.sCount>1)return!1;e.setFormat=cF(t,o)}else if(n==="F"){if(e.fCount++,e.fCount>1)return!1;e.finalSetFormat=cF(t,o)}else if(n==="G"){if(e.gCount++,e.gCount>1||(e.gameFormat=_Y(o),!e.gameFormat))return!1}else if(n==="M"&&(e.mCount++,e.mCount>1||(e.matchUpConstraint=HY(o),!e.matchUpConstraint)))return!1;return!0}function LY({setFormat:t,finalSetFormat:e,gameFormat:r,matchUpConstraint:n,matchRoot:o,aggregate:i,matchMods:s,bestOf:a,exactly:c}){let u=t&&t.timed||e&&e.timed;if(o==="SET"&&!(a&&a<6||u&&c)||!t||!(!e||e))return;let m=et({setFormat:t,exactly:c,bestOf:a});return o!=="SET"&&(m.matchRoot=o),i&&(m.aggregate=!0),s.length>0&&(m.matchMods=s),e&&(m.finalSetFormat=e),r&&(m.gameFormat=r),n&&(m.matchUpConstraint=n),m}function cF(t,e){return e.startsWith("TB")?FY(e):e.startsWith("O")?kY(e):e.startsWith("T")?dF(e):GY(t,e)}function FY(t){let e=pF(t);return e===!1?!1:typeof e=="object"?{tiebreakSet:e}:void 0}function kY(t){let e=/^O([1-9]\d*)$/.exec(t);if(e)return{outs:Number(e[1])}}function GY(t,e){let r=/^[FS]:(\d+)([A-Za-z]*?)(WB(\d+))?(?=[/@]|$)/.exec(t),n=r&&mF(r[2])||!1,o=!r?.[2]||n,i=r?Ap(r[1]):void 0,s=r?.[4],a=s?Ap(s):void 0,c=a===void 0||a>=1,u=uF(e),p=u!==!1,d=p&&u||i,m=pF(e.split("/")[1]);return!i||!o||!(m!==!1)||!p||!c||a!==void 0&&m?!1:VY(i,n,m,d,a)}function VY(t,e,r,n,o){let i={setTo:t};return e&&(i.NoAD=!0),r?(i.tiebreakFormat=r,i.tiebreakAt=n):(i.noTiebreak=!0,o!==void 0&&o!==2&&(i.winBy=o)),i}function uF(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Ap(r[1]):r[1])||!1}function pF(t){if(t)return t.startsWith("TB")?BY(t):!1}function BY(t){let e=uF(t,!1),r=/^TB(\d+)([A-Za-z]*)/.exec(t),n=r?.[1],o=r&&mF(r[2]),i=!r?.[2]||o,s=Ap(n);if(!s||!i)return!1;let a={tiebreakTo:s};return e&&typeof e=="string"&&!It(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}function dF(t){let e=t.slice(1),r=/^(\d+)([PG])?(?:\/TB(\d+))?(@[A-Za-z]+)?$/.exec(e),n=Ap(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2];i==="P"?o.based="P":i==="G"&&(o.based="G");let s=r?.[3];if(s){let u=Ap(s);u&&(o.tiebreakFormat={tiebreakTo:u})}let a=r?.[4],c=[void 0,"P","G",""].includes(a);if(a&&!c){let u=/^(\d+)([PGA])?(?:\/TB\d+)?(@)([A-Za-z]+)$/.exec(e)?.[4];return u?(o.modifier=u,o):void 0}return a&&(o.based=a),o}function HY(t){let e=/^T(\d+)$/.exec(t);if(!e)return;let r=Ap(e[1]);if(r)return{timed:!0,minutes:r}}function mF(t){return t?.includes(th)}function Ap(t){let e=Number(t);return Number.isNaN(e)?0:e}function WY(t){return t.replaceAll(/T(\d+)G(?=\/TB|@|-|$)/g,"T$1")}function Or({matchUpFormat:t}){if(!wt(t)||t==="")return!1;let e=ne(t),r=/-S:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),n=r?.[1],o=r?.[2],i=r?.[3],s=/-F:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),a=s?.[1],c=s?.[2],u=s?.[3];return sm(e,!!(r&&o&&n===i||s&&c&&a===u))===WY(t)}var am=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/,jy=/^((0\d|1\d|2[0-3]):[0-5]\d(:[0-5]\d)?)([.,]\d{3})?$/,Yo=/^(\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?$/,du=/^(\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 Kl(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=ut(t.scheduledTime)),!e)return;let r=Kt(t.scheduledTime),n=ut(e);return n&&r&&(n+=`T${r}`),n}function lF(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function cm(t){let e=typeof t=="string"?t?.split(" "):[];if(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))return!1;let r=Pp(t,!0,!0);return!!(!t||r&&du.test(r))}function Fe(t){return ys(t)||am.test(t)}function jY(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+3600*e.getHours();return YY(r,{displaySeconds:!1})}function YY(t,e){let r=Number.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(yo).join(":")}var nh=t=>{let e=eh(t)||ys(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${yo(n)}-${yo(e.getUTCDate())}`};function qY(t){let e=eh(t)||ys(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function ao(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&!t.includes("T")&&(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 Yy(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function $Y(t){return Yy(t).getTime()}function eh(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!Number.isNaN(Number(t))&&new Date(t)||!1;return e&&!Number.isNaN(Number(e.valueOf()))}function KY(t,e){return t<=e}function wa(t,e){if(!Fe(t)||!Fe(e))return[];let r=ut(t)+"T00:00",n=ut(e)+"T00:00",o=new Date(r),i=new Date(n),s=eh(i)&&eh(o)&&KY(o,i),a=[],c=0;if(s){let u=o,p=u.getTime();for(;p<=i.getTime()&&c<300;)c+=1,a.push(new Date(u)),p=u.setDate(u.getDate()+1)}return a.map(u=>ao(u))}var zY=/^([+-]?\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 ys(t){return typeof t!="string"?!1:zY.test(t)}function La(t){return typeof t!="string"||!ys(t)?!1:/([zZ]|[+-]\d{2}:?\d{2})$/.test(t)}function $y(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!Number.isNaN(Number.parseInt(i)));return!(r.length<2||!n||Number.parseInt(r[0])>23||Number.parseInt(r[1])>60)}function Yt(t){let e=Kt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>Number.parseInt(o));return r*60+n}function fF(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[yo(e),yo(r)].join(":")}function rh(t){return $y(t)?t.split(":").slice(0,2).map(yo).join(":"):void 0}function Kt(t){return ys(t)&&t.indexOf("T")>0?rh(t.split("T").reverse()[0]):rh(t)}function ut(t){return ys(t)||Yo.test(t)?t.split("T")[0]:""}function um(t,e){let r=new Date(t);return r.setUTCDate(r.getUTCDate()+e),ut(r.toISOString())}function qy(t){t=typeof t=="string"?t:"00:00";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,Number.isNaN(Number.parseInt(r.hours))||Number.isNaN(Number.parseInt(r.minutes))||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function QY(t){let e=qy(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&Number.parseInt(e.hours)<12&&(e.hours=(e.hours&&Number.parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(yo).join(":")}function JY(t){let e=qy(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 Pp(t,e,r){let n=ut(t),o=Kt(t),i=n?o:t;return t?e&&(n&&r&&t||QY(i))||JY(i):void 0}function Ky(t,e){let r=qy(t),n=qy(e);if(Number.parseInt(r.hours)<Number.parseInt(n.hours))return-1;if(Number.parseInt(r.hours)>Number.parseInt(n.hours))return 1;if(r.hours===n.hours){if(Number.parseInt(r.minutes)<Number.parseInt(n.minutes))return-1;if(Number.parseInt(r.minutes)>Number.parseInt(n.minutes))return 1}return 0}function zy(t,e=7){let r=ut(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return ao(o)}function XY(t){return zy(t)}function ZY(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())),ao(o,r)}function gF(t,e,r){let n=new Date(t,0);return ao(new Date(n.setDate(e)),r)}function ke(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(yo),o=Yy(e).setHours(r,n,0,0);return Yy(o)}function Ws(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=Kt(t);if(!r)return"00:00";let n=Number.isNaN(e)?0:e;return Kt(oh(ke(r),n).toISOString())||"00:00"}function oh(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function yo(t){return t.toString()[1]?t:"0"+t}function nn(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 Qy={addDays:zy,addWeek:XY,addMinutesToTimeString:Yr,convertTime:Pp,getIsoDateString:Kl,getUTCdateString:nh,DateHHMM:jY,extractDate:ut,extractTime:Kt,formatDate:ao,getDateByWeek:ZY,isISODateString:ys,isValidEmbargoDate:La,isDate:eh,isTimeString:$y,offsetDate:Yy,offsetTime:$Y,sameDay:nn,timeStringMinutes:Yt,timeToDate:ke,timeUTC:qY,validTimeValue:cm,validDateString:am,timeValidation:du,dateValidation:Yo};var tq=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),eq=t=>t.filter(Boolean).every(He);function zl(t,e){return`${t}-${e}`}function Es(t){let e=t.category;if(typeof e!="object"||!e)return{error:Sp};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(tq([r,n,o,a],"string")&&eq([i,s])&&[n,o].filter(Boolean).every(Fe)))return{error:Sp};let p=t.consideredDate??ut(new Date().toLocaleDateString("sv"));if(!p||!Fe(p))return{error:de};let[d]=p.split("-").slice(0,3).map(B=>Number.parseInt(B)),m=um(p,-1);if(!m)return{error:de};let[l,f]=m.split("-").slice(1,3).map(B=>Number.parseInt(B)),g=`${yo(l)}-${yo(f)}`,I=um(p,1);if(!I)return{error:de};let[h,S]=I.split("-").slice(1,3).map(B=>Number.parseInt(B)),T=`${yo(h)}-${yo(S)}`,y=s&&um(p,-1*365*s),E=i&&um(p,-1*365*i),A=[],N=B=>!A.includes(B)&&A.push(B);r=r??a;let D=/^([UO]?)(\d{1,2})([UO]?)$/,R=/^C(\d{1,2})-(\d{1,2})$/,U=r?.includes("-"),b=U&&r?.match(R),C=r?.match(D);function _(B){let $=d-B,H=zl($,T);e.ageMinDate&&e.ageMinDate!==H&&N(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==B-1&&(N(`Invalid submitted ageMax: ${i}`),E=void 0),i=B-1)}function v(B){let $=d-B-1,H=zl($,T);e.ageMin&&e.ageMin>B&&N(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>B&&N(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&N(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==B&&(N(`Invalid submitted ageMax: ${i}`),y=void 0),i=B)}function x(B){let $=d-B,H=zl($,g);e.ageMaxDate&&e.ageMaxDate!==H&&N(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==B+1&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B+1)}function w(B){let $=d-B-1,H=zl($,g);e.ageMaxDate&&e.ageMaxDate!==H&&N(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==B&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B)}function F(B){let $=D.exec(B)??[],[H,z,W]=$.slice(1),Q=Number.parseInt(z);H==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),_(Q)):H==="O"&&x(Q),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(Q)):W==="O"&&w(Q),n=(n??y)||void 0,o=(o??E)||void 0}function L(){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=d-e.ageMin;n=zl(H,g)}if(e.ageMax){let H=d-e.ageMax-1;o=zl(H,T)}let[B,$]=(r?.match(R)??[]).slice(1).map(H=>Number.parseInt(H));B<=$?(s=B,i=$,c=!0):N(`Invalid combined age range ${r}`)}function k(){s&&x(s),i&&v(i)}function G(){b?L():U?r?.split("-").forEach(F):C&&r?F(r):k()}G(),i&&e?.ageMin&&e?.ageMin>i&&(N(`Invalid submitted ageMin: ${e?.ageMin}`),s=void 0);let V=et({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return A.length&&(V.errors=A),V}function Np({category:t}){if(!St(t))return{error:O};let e=Es({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!He(r)?M({result:{error:O},context:{ratingMax:r}}):n&&!He(n)?M({result:{error:O},context:{ratingMin:n}}):{...e}}function Dp({childCategory:t,withDetails:e,category:r}){let n=Np({category:r}),o=Np({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),d=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=et({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:d,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!d&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function Up({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}`),M({result:{errors:c,error:vo},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:d,collectionId:m,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:y}=e;if(r&&typeof m!="string"&&c.push(`collectionId is not type string: ${m}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Gs([Ct,Ut,qd],I)&&c.push(`matchUpType must be SINGLES, DOUBLES, or HYBRID: ${I}`),[!!u?.length].concat([g,d,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}`),d&&typeof d!="number"&&c.push(`collectionValue is not type number: ${d}`),u&&l){let A=Ry({collectionValueProfiles:u,matchUpCount:l});A.errors&&c.push(...A.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${d}`),f&&!Or({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let A=Yl({referenceGender:i,matchUpType:I,gender:y});if(A.error)return M({context:{referenceGender:i,gender:y},result:A,stack:a})}if(t&&o&&T){let A=Dp({category:o,childCategory:T});if(!A.valid)return M({result:{error:Sp},context:A,stack:a})}return c.length?M({result:{errors:c,error:_R},stack:a}):{valid:!0}}function ur(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=rq({...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:E}=Up({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(E)&&a.push(...E),!1)}),d=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(d||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),M({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:ai},stack:s});let m=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||m.length===ct(m).length,f=p&&d&&l,g={valid:f,errors:a};return f?g:M({result:{error:ai},context:{tieFormat:o,errors:a},stack:s})}function rq(t){let{tieFormat:e,stack:r}=t;return!t||!e||!St(e)?M({result:{error:ai},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):St(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...P}:M({result:{error:ai},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):M({result:{error:ai},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var Ql="resourceSubType",Jl="resourceType",mu="identifier",Jy="name",IF={RESOURCE_SUB_TYPE:Ql,RESOURCE_TYPE:Jl,IDENTIFIER:mu,NAME:Jy};function q(t,e,r,n,o=0){if(By().makeDeepCopy)return By().makeDeepCopy(t,e,r,n);let i=JI(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i??{};if(!i?.enabled&&!r||typeof t!="object"||Vr(t)||t===null||typeof i?.threshold=="number"&&o>=i.threshold)return t;let p=Array.isArray(t)?[]:{},d=Object.keys(t).filter(l=>!r||!c||Array.isArray(c)&&!c.includes(l)||Vr(c)&&!c(l)),m=(l,f)=>{p[l]=Vr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of d){let f=t[l],g=Vr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=ih(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?m(l,f):Array.isArray(a)&&a.includes(l)&&Vr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:lF(f)?p[l]=new Date(f).toISOString():p[l]=q(f,e,r,n,o+1)}return p}function ih(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function Xy(t=1,e,r){return J(0,t).map(()=>ot(e,r))}function ot(t,e){let r=e??Math.random,n=[];for(let u=0;u<256;u++)n[u]=(u<16?"0":"")+u.toString(16);let o=Math.trunc(r()*4294967295),i=Math.trunc(r()*4294967295),s=Math.trunc(r()*4294967295),a=Math.trunc(r()*4294967295),c=n[o&255]+n[o>>8&255]+n[o>>16&255]+n[o>>24&255]+"-"+n[i&255]+n[i>>8&255]+"-"+n[i>>16&15|64]+n[i>>24&255]+"-"+n[s&63|128]+n[s>>8&255]+"-"+n[s>>16&255]+n[s>>24&255]+n[a&255]+n[a>>8&255]+n[a>>16&255]+n[a>>24&255];return typeof t=="string"?`${t}_${c.replaceAll("-","")}`:c}var Zy={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 tE={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 eE={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 rE={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 nE={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 oE={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 iE={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:"Brewer Cup",winCriteria:{valueGoal:4}};var sE={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 kn="SET3-S:6/TB7",dq="SET3-S:6NOAD",ob="SET3-S:6NOAD/TB7-F:TB10",mq="SET3-S:4/TB7",lq="SET3-S:4/TB5@3",fq="SET5-S:6/TB7",gq="SET1-S:6/TB7",Iq="SET1-S:TB10",hq="SET3-S:6/TB7-F:TB7",Sq="SET1-S:T20",Tq="SET1-S:8/TB7",yq="SET1-S:8/TB7@7",hF={FORMAT_STANDARD:kn,FORMAT_STANDARD_NOAD:dq,FORMAT_ATP_DOUBLES:ob,FORMAT_SHORT_SETS:mq,FORMAT_FAST4:lq,FORMAT_GRAND_SLAM:fq,FORMAT_ONE_SET:gq,FORMAT_MATCH_TIEBREAK:Iq,FORMAT_SET3_TB7:hq,FORMAT_PRO_SET:Tq,FORMAT_COLLEGE_PRO_SET:yq,TIMED20:Sq};var aE={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 cE={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 Collegiate",winCriteria:{valueGoal:4}};var uE={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 pE={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:"World Team Tennis ITT",winCriteria:{aggregateValue:!0}};var SF={tieFormatName:"INTENNSE 2026",winCriteria:{aggregateValue:!0},collectionDefinitions:[{collectionId:"intennse-ms",collectionName:"Men's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MS"}},{collectionId:"intennse-ws",collectionName:"Women's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WS"}},{collectionId:"intennse-md",collectionName:"Men's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MD"}},{collectionId:"intennse-wd",collectionName:"Women's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WD"}},{collectionId:"intennse-xd",collectionName:"Mixed Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MIXED",category:{categoryName:"XD"}}]};var dE={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 mE={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/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:6NOAD/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:6NOAD/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 lE={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 Tennis on Campus",winCriteria:{aggregateValue:!0}};var sh="COLLEGE_DEFAULT",ib="COLLEGE_JUCO",sb="COLLEGE_D3",ab="DOMINANT_DUO",cb="DOMINANT_DUO_MIXED",ub="INTENNSE_2026",pb="LAVER_CUP",db="TEAM_DOUBLES_3_AGGREGATION",mb="USTA_BREWER_CUP",lb="USTA_OZAKI_CUP",fb="USTA_COLLEGE",gb="USTA_GOLD_TEAM_CHALLENGE",Ib="USTA_LEVEL_1",hb="USTA_INTERSECTIONAL",Sb="USTA_SECTION_BATTLE",Tb="USTA_SOUTHERN_LEVEL_5",yb="USTA_TOC",Eb="USTA_WTT_ITT",Ab="USTA_ZONAL",TF={COLLEGE_D3:sb,COLLEGE_DEFAULT:sh,COLLEGE_JUCO:ib,DOMINANT_DUO:ab,DOMINANT_DUO_MIXED:cb,INTENNSE_2026:ub,LAVER_CUP:pb,TEAM_DOUBLES_3_AGGREGATION:db,USTA_BREWER_CUP:mb,USTA_OZAKI_CUP:lb,USTA_COLLEGE:fb,USTA_GOLD_TEAM_CHALLENGE:gb,USTA_INTERSECTIONAL:hb,USTA_LEVEL_1:Ib,USTA_SECTION_BATTLE:Sb,USTA_SOUTHERN_LEVEL_5:Tb,USTA_TOC:yb,USTA_WTT_ITT:Eb,USTA_ZONAL:Ab};var EF="STANDARD",yF={[EF]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[sb]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:kn,matchUpCount:6,matchUpValue:1},tieFormatName:"College D3",valueGoal:5},[sh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:kn,matchUpCount:6,matchUpValue:1},tieFormatName:"College Default",valueGoal:4},[ib]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:kn,matchUpCount:6,matchUpValue:1},tieFormatName:"College JUCO",valueGoal:5},[pb]:mE,[ab]:aE,[cb]:oE,[ub]:SF,[db]:tE,[mb]:iE,[lb]:sE,[fb]:cE,[gb]:Zy,[hb]:nE,[Ib]:uE,[Sb]:rE,[Tb]:eE,[Eb]:pE,[yb]:lE,[Ab]:dE},Cq=t=>{let e=t?.namedFormat&&Object.keys(yF).includes(t.namedFormat)?t.namedFormat:EF,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=q(yF[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??ot();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:ob,collectionName:"Doubles",matchUpType:Ut,...s.doubles},{collectionId:a(1),matchUpFormat:kn,collectionName:"Singles",matchUpType:Ct,...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},Eo=Cq;var ue="SINGLES",Fa="SINGLES",Xt="DOUBLES",pi="DOUBLES",Ce="TEAM",Tr="TEAM",Tc="HYBRID",ah="HYBRID";var Mq="RATING",vq="BOTH",AF={AGE:"AGE",BOTH:vq,DOUBLES:Xt,DOUBLES_EVENT:pi,HYBRID:Tc,HYBRID_EVENT:ah,RATING:Mq,SINGLES:ue,SINGLES_EVENT:Fa,TEAM_EVENT:Tr,TEAM:Ce};var j="MAIN",rt="QUALIFYING",je="CONSOLATION",Qe="VOLUNTARY_CONSOLATION",Vt="PLAY_OFF",lu=[j,rt,je,Vt,Qe],ka={[rt]:1,[j]:2,[Vt]:3,[je]:3,[Qe]:4},Pb="finishingPositions",Nb="aggregateEventStructures",Db={[j]:1,[Vt]:2,[je]:3,[rt]:4,[Qe]:5},PF={[Vt]:1,[j]:2,[je]:3,[rt]:4,[Qe]:5},fu="CLUSTER",pm="ADJACENT",Ub="SEPARATE",qi="WATERFALL",gu="ITEM",Ie="CONTAINER",ln="DRAW",dm="RANDOM",Je="TOP_DOWN",$i="BOTTOM_UP",fn="POSITION",Ar="WINNER",pr="LOSER",Jn="FIRST_MATCHUP",vi="AD_HOC",Oq="AD_HOC",yc="FEED_IN",js="COMPASS",Rp="OLYMPIC",_q="SINGLE_ELIMINATION";var on="SINGLE_ELIMINATION",Ys="DOUBLE_ELIMINATION",qs="FIRST_MATCH_LOSER_CONSOLATION",Ga="FIRST_ROUND_LOSER_CONSOLATION",di="LUCKY_DRAW",Ki="ADAPTIVE",ch="CURTIS_CONSOLATION",NF="CURTIS_CONSOLATION",fE="FEED_IN_CHAMPIONSHIP_TO_SF",bp="FEED_IN_CHAMPIONSHIP_TO_SF",gE="FEED_IN_CHAMPIONSHIP_TO_QF",Cp="FEED_IN_CHAMPIONSHIP_TO_QF",IE="FEED_IN_CHAMPIONSHIP_TO_R16",Xl="FEED_IN_CHAMPIONSHIP_TO_R16",Rb="MODIFIED_FEED_IN_CHAMPIONSHIP",Zl="MODIFIED_FEED_IN_CHAMPIONSHIP",mm="FEED_IN_CHAMPIONSHIP",lm="PAGE_PLAYOFF",fm="PLAYOFF",$s="SWISS",xq={0:{name:"Qualifier 1",abbreviation:"Q1"},"0-1":{name:"Eliminator",abbreviation:"EL"},"0-2":{name:"Final",abbreviation:"F"}},hE="DOUBLE_ROUND_ROBIN",_r="ROUND_ROBIN",sn="ROUND_ROBIN_WITH_PLAYOFF",bb="DECIDER",Cb="BACKDRAW",uh={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"}},ph={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},dh={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"}},Ao="WIN_RATIO",As="ROUND_OUTCOME",Mb=[Ki,js,ch,Cp,Xl,bp,mm,gE,IE,fE,qs,Ga,di,Zl,Rp,lm,fm,sn],wq=[vi,Ki,js,ch,Ys,Cp,Xl,bp,mm,yc,qs,Ga,di,Zl,Rp,lm,fm,_r,sn,on,$s],vb={MAIN:j,QUALIFYING:rt,CONSOLATION:je,ITEM:gu,CONTAINER:Ie,FIRST_MATCHUP:Jn,WINNER:Ar,LOSER:pr,AD_HOC:vi,FEED_IN:yc,FLEX_ROUNDS:Oq,COMPASS:js,PLAY_OFF:Vt,PAGE_PLAYOFF:lm,PAGE_PLAYOFF_ATTRIBUTES:xq,PLAYOFF:fm,SWISS:$s,OLYMPIC:Rp,KNOCKOUT:_q,SINGLE_ELIMINATION:on,DOUBLE_ELIMINATION:Ys,CURTIS:ch,FICSF:fE,FICQF:gE,FICR16:IE,MFIC:Rb,VOLUNTARY_CONSOLATION:Qe,FIRST_MATCH_LOSER_CONSOLATION:qs,FIRST_ROUND_LOSER_CONSOLATION:Ga,MODIFIED_FEED_IN_CHAMPIONSHIP:Zl,FEED_IN_CHAMPIONSHIP_TO_R16:Xl,FEED_IN_CHAMPIONSHIP_TO_QF:Cp,FEED_IN_CHAMPIONSHIP_TO_SF:bp,FEED_IN_CHAMPIONSHIP:mm,LUCKY_DRAW:di,ADAPTIVE:Ki,ROUND_ROBIN_WITH_PLAYOFF:sn,ROUND_ROBIN:_r,DECIDER:bb,BACKDRAW:Cb,COMPASS_ATTRIBUTES:uh,OLYMPIC_ATTRIBUTES:ph,ADAPTIVE_ATTRIBUTES:dh,DRAW:ln,RANDOM:dm,TOP_DOWN:Je,BOTTOM_UP:$i,CLUSTER:fu,ADJACENT:pm,SEPARATE:Ub,WATERFALL:qi,WIN_RATIO:Ao,ROUND_OUTCOME:As,MULTI_STRUCTURE_DRAWS:Mb,generatedDrawTypes:wq,stageOrder:ka,finishOrder:Db,AGGREGATE_EVENT_STRUCTURES:Nb,FINISHING_POSITIONS:Pb},DF=vb;var Ne="tournamentRecords",mh="policyDefinitions",Z="tournamentRecord",SE="onlineResource",zt="drawDefinition",TE="tieFormatName",tf="matchUpFormat",Ge="participantId",ef="scheduleDates",UF="tournamentId",RF="scheduleDate",bF="roundNumber",Po="structureId",gm="participant",Iu="matchUpIds",yE="entryStage",CF="policyType",Ob="structures",lh="eventType",xr="matchUpId",rf="tieFormat",Mp="inContext",Ec="structure",Im="courtIds",MF="personId",hm="venueIds",fh="matchUps",Oo="courtId",EE="eventId",Cn="matchUp",Ac="drawId",qr="error",me="event",zi="param",gh="uuids",AE="penaltyType",nf="penaltyId",vp="venueId",vF="stage",OF="averageMatchUpMinutes",_F="recoveryMinutes",xF="periodLength",wF="number";var $r="object",Ye="array";var Xe="_validate",PE="_message",wr="_invalid",qe="_ofType",Op="_anyOf",Va="_oneOf";var LF={[SE]:t=>Ht(Object.keys(t),[Ql,Jl,mu]).length===3,[TE]:t=>t&&Eo({namedFormat:t}),[gh]:t=>!t||Array.isArray(t)&&t.every(wt),[rf]:t=>!ur({tieFormat:t}).error,[lh]:t=>[ue,Xt,Ce].includes(t),[yE]:t=>lu.includes(t)},Lq={[Ne]:kt,[Z]:Y,[mh]:Ca,[zt]:K,[Ge]:$e,[tf]:QU,[UF]:Ic,[Po]:mn,[Iu]:Vs,[gm]:Ma,[SE]:vo,[lh]:so,[Ob]:PI,[xr]:cr,[rf]:ai,[Ec]:Hi,[Oo]:MI,[fh]:zn,[EE]:Br,[Cn]:nr,[Im]:nt,[hm]:nt,[AE]:SR,[nf]:TR,[vp]:Hs,[Ac]:Un,[me]:Se,[vF]:UI},Fq={[Ne]:$r,[mh]:$r,[Z]:$r,[zt]:$r,[SE]:$r,[ef]:Ye,[gm]:$r,[Iu]:Ye,[Ob]:Ye,[rf]:$r,[Ec]:$r,[Im]:Ye,[hm]:Ye,[fh]:Ye,[Cn]:$r,[me]:$r,[gh]:Ye};function X(t,e,r){if(!t&&!St(t))return{error:O};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:O};let{paramError:n,errorParam:o}=Vq(t,e);if(!n)return{valid:!0};let i=n[Xe]&&(n[qr]||n[wr])||t?.[o]==null&&(n[qr]||n[wr]||Lq[o]||O)||O,s=o??(n[Va]&&Object.keys(n[Va]).join(", "));return M({info:{param:s,message:n[PE]},result:{error:i},stack:r})}function FF(t,e){let r=Object.keys(t),n=Object.keys(e);return Ht(r,n)}function kq(t,e){if(!e)return;let r=FF(t,e);return r.length!==1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function Gq(t,e){if(!e)return;let r=FF(t,e).filter(n=>t[n]);return r.length<1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function Vq(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let d=s&&kq(t,s);if(d?.error)return d.error;d&&Object.assign(p,d);let m=a&&Gq(t,a);if(m?.error)return m.error;m&&Object.assign(p,m);let l=Object.keys(p).filter(g=>typeof p[g]=="boolean"),f=l.find(g=>{let I=c&&!Vr(c),h=t[g]!==void 0&&!c&&Bq(t,g,i),S=p[g]&&t[g]==null,y=I||h||S||c&&t[g]!==void 0&&!Hq(t[g],c)||LF[g]&&!LF[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function Bq(t,e,r){return r=r||Fq[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function Hq(t,e){return Vr(e)?e(t):!0}var _p="DYNAMIC",co="RANKING",qo="RATING",mi="SCALE",_o="SEEDING",kF={RANKING:co,RATING:qo,SCALE:mi,SEEDING:_o};function Pc(t){let e=X(t,[{[gm]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(mi)&&[co,qo,_o].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=ct(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,d]=a.itemType.split("."),m=d?`${p}.${d}`:p,l=c===_o&&"seedings"||c===co&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:m})}}}return{...P,...n}}function Ps(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()),d=u.concat(...Object.keys(p)),m=d.includes("*");for(let l of c)if(d.indexOf(l)>=0||m){let f=p[l]||l,g=s[f]||m,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]||m&&s[l]!==!1)&&(a[l]=h)}}}}var NE="voluntaryConsolation",gn="competitiveBands",Ih="roundRobinTally",uo="positionActions",Ke="matchUpActions",In="rankingPoints",$o="roundNaming",Ba="participant",xp="progression",No="scheduling",Nc="avoidance",Wq="participant",jq="display",Jr="scoring",Xn="seeding",hu="feedIn",Yq="sanctioning",qq="audit",Su="competition",of="draws",_b="print",GF={POLICY_TYPE_VOLUNTARY_CONSOLATION:NE,POLICY_TYPE_COMPETITIVE_BANDS:gn,POLICY_TYPE_ROUND_ROBIN_TALLY:Ih,POLICY_TYPE_POSITION_ACTIONS:uo,POLICY_TYPE_MATCHUP_ACTIONS:Ke,POLICY_TYPE_RANKING_POINTS:In,POLICY_TYPE_ROUND_NAMING:$o,POLICY_TYPE_PARTICIPANT:Ba,POLICY_TYPE_PROGRESSION:xp,POLICY_TYPE_SCHEDULING:No,POLICY_TYPE_AVOIDANCE:Nc,POLICY_TYPE_COMPETITION:Su,POLICY_TYPE_DISPLAY:jq,POLICY_TYPE_PRIVACY:Wq,POLICY_TYPE_FEED_IN:hu,POLICY_TYPE_SCORING:Jr,POLICY_TYPE_SEEDING:Xn,POLICY_TYPE_SANCTIONING:Yq,POLICY_TYPE_AUDIT:qq,POLICY_TYPE_DRAWS:of,POLICY_TYPE_PRINT:_b};function li({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=q(s,!1,o);if(a){let c=e?.[Ba];if(r?.withScaleValues){let{ratings:u,rankings:p}=Pc({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Ps({template:c.participant,source:a})}return a}var VF="element required",BF="missing name";function Mn(t){if(!t||typeof t!="object")return{error:nt};if(t.element&&typeof t?.element!="object")return{error:O};if(!t?.name)return{error:nt,info:BF};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=Mn({element:r,name:t.name});if(n.error)return M({result:n,stack:"removeExtension"})}return{...P}}return{error:nt,info:VF}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...P}):{...P,info:fe}}function Zn({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 Qt(t){if(typeof t!="object")return{error:nt};let e="addExtension";if(t?.element&&typeof t.element!="object")return M({result:{error:O},stack:e});if(!Zn({extension:t.extension}))return M({result:{error:O,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=Qt({extension:t.extension,element:o});if(i.error)return M({result:i,stack:e})}return{...P}}else return M({result:{error:nt},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),{...P}}function hh(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?Qt({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:Y}}function Sh(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?Qt({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Cr}}function xb(t){return!t||typeof t!="object"?{error:nt}:t.event?Qt({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Br}}function wb(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:$e};let e=t.tournamentRecord?.participants??[],r=li({participantId:t.participantId,tournamentParticipants:e});return r?Qt({creationTime:t.creationTime,extension:t.extension,element:r}):{error:Wt}}function Th(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?Mn({element:t.tournamentRecord,name:t.name}):{error:Y}}function Lb(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?Mn({element:t.drawDefinition,name:t.name}):{error:Cr}}function yh(t){return!t||typeof t!="object"?{error:nt}:t?.event?Mn({element:t.event,name:t.name}):{error:Br}}function Fb(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:$e};let e=t.tournamentRecord?.participants??[],r=li({participantId:t.participantId,tournamentParticipants:e});return r?Mn({element:r,name:t.name}):{error:Wt}}var $q="extensionQueries";function qt({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(d=>d?.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:fe}}return M({result:{error:nt},stack:$q})}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:fe}}var Kq="activeSuspension",wp="appliedPolicies",Ns="competitionState",kb="context",Lp="delegatedOutcome",Gn="disabled",Ks="disableAutoCalc",Fp="disableLinks",sf="display",fi="draftState",Dc="drawDeletions",zq="drawProfile",Qq="eventProfile",Jq="eventWithdrawalRequests",Gb="factory",Kr="flightProfile",DE="groupingAttribute",po="lineUps",Uc="linkedTournamentsIds",an="mutationLocks",UE="participantRepresentatives",Rc="personRequests",Tu="positionActions",Xq="rankingPoints",Zq="registration",Xr="roundTarget",Vb="sanctioningConstraints",bc="scheduleLimits",xo="scheduleTiming",Ha="schedulingProfile",t$="statusDetail",Wa="subOrder",to="tally",af="tieFormatModification",RE={ACTIVE_SUSPENSION:Kq,APPLIED_POLICIES:wp,COMPETITION_STATE:Ns,CONTEXT:kb,DELEGATED_OUTCOME:Lp,DISABLED:Gn,DISABLE_LINKS:Fp,DISABLE_AUTO_CALC:Ks,DISPLAY:sf,DRAFT_STATE:fi,DRAW_DELETIONS:Dc,DRAW_PROFILE:zq,EVENT_PROFILE:Qq,EVENT_WITHDRAWAL_REQUESTS:Jq,FLIGHT_PROFILE:Kr,GROUPING_ATTRIBUTE:DE,LINEUPS:po,LINKED_TOURNAMENTS:Uc,MUTATION_LOCKS:an,PARTICIPANT_REPRESENTATIVES:UE,PERSON_REQUESTS:Rc,POSITION_ACTIONS:Tu,RANKING_POINTS:Xq,REGISTRATION:Zq,ROUND_TARGET:Xr,SANCTIONING_CONSTRAINTS:Vb,SCHEDULE_LIMITS:bc,SCHEDULE_TIMING:xo,SCHEDULING_PROFILE:Ha,STATUS_DETAIL:t$,SUB_ORDER:Wa,TALLY:to,TIE_FORMAT_MODIFICATIONS:af,FACTORY:Gb},Bb=[Lp,Gn,Ks,Fp,Kr,po,Uc,an,UE,Rc,Xr,bc,xo,Ha,Wa,to,af];function cf(t){if(Array.isArray(t?.linkedTournamentIds))return t.linkedTournamentIds;let{extension:e}=qt({element:t,name:Uc});return e?.value?.tournamentIds??[]}function Sm({tournamentRecords:t}){return{tournamentIds:St(t)?Object.keys(t):[],...P}}function bE(t,e){let r=!e.length;cu()&&!r?t.linkedTournamentIds=[...e]:t?.linkedTournamentIds!==void 0&&delete t.linkedTournamentIds,uu()&&!r?hh({tournamentRecord:t,extension:{name:Uc,value:{tournamentIds:[...e]}}}):Th({tournamentRecord:t,name:Uc})}function Hb({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=Sm({tournamentRecords:t}),{tournamentIds:r}=e;if(r?.length>1)for(let n of Object.values(t))bE(n,r);return{...P}}function Wb({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};for(let r of Object.values(t))bE(r,[]);let e=Mn({name:Uc,tournamentRecords:t,discover:!0});return M({result:e,stack:"unlinkTournaments"})}function jb({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:O};if(!e)return{error:Ic};let r=Sm({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:Ic};for(let o of n){let i=t[o],s=cf(i);if(!s?.length||s.length===1&&s.includes(e)||o===e){bE(i,[]);continue}let a=s.filter(c=>c!==e);bE(i,a)}return{...P}}function gt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:Oy};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...P};function a(c){let p=c?.extensions?.find(d=>d.name===wp)?.value;if(p)for(let d of Object.keys(p))(t?e.includes(d):!e.length||e.includes(d))&&(s[d]=q(p[d],!1,!0))}}function Do({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:Oy};let{appliedPolicies:i}=gt({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:lp.message}}function wo(t){let{appliedPolicies:e}=gt({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,event:t.event});return{competitionPolicy:e?.[Su]}}function Qi({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=q(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[m,l]of u.entries())if(c?.[l]){let f=u.slice(m+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],d({targetElement:c,index:m})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function d({targetElement:m,index:l}){if(m&&l===u.length-1&&["string","number"].includes(typeof m)){let f=p?m.slice(0,p):m;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}function Lo({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Ma};if(!St(e))return{error:O};if(r.timeItems??=[],Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[mi,o,i,s].join("."),u=r.timeItems.filter(p=>p?.itemType===a).filter(p=>!t||p?.itemDate).sort((p,d)=>(p.createdAt?new Date(p.createdAt).getTime():0)-(d.createdAt?new Date(d.createdAt).getTime():0)).pop();if(u){let[p,d,m,l]=u.itemType?.split(".")??[];if(p!==mi)return{error:ou};let f=n&&Qi({element:u.itemValue,accessor:n}),g=f?.value||u.itemValue,I={rawValue:f&&u.itemValue,eventType:m,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:d};return{...P,scaleItem:I}}}return{...P,scaleItem:void 0}}function kp({value:t,sourceRange:e,targetRange:r}){if(!Array.isArray(e)||e.length!==2)return 0;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 Yb="NTRP";var qb="DUPR",$b="UTR_P",Kb="UTPR";var zb="SQUASH_LEVELS",Qb="US_SQUASH",Jb="USATT",Xb="ITTF",Zb="USAR";var HF={ELO:"ELO",NTRP:Yb,TRN:"TRN",UTR:"UTR",WTN:"WTN",DUPR:qb,UTR_P:$b,UTPR:Kb,PSA:"PSA",SQUASH_LEVELS:zb,US_SQUASH:Qb,USATT:Jb,ITTF:Xb,USAR:Zb,BWF:"BWF"};var o$={ELO:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!1},[Yb]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!1,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!1,range:[1,16]},WTN:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!0,decimalsCount:2,range:[40,1]},[qb]:{defaultInitialization:3.5,accessors:["duprRating","reliabilityScore"],accessor:"duprRating",attributes:{reliabilityScore:{generator:!0,range:[0,100]}},decimalsCount:3,ascending:!1,range:[2,8]},[$b]:{defaultInitialization:5,accessors:["utrpRating","verified"],accessor:"utrpRating",attributes:{verified:{type:"boolean"},provisional:{type:"string"}},decimalsCount:1,ascending:!1,range:[1,10]},[Kb]:{defaultInitialization:3.5,accessor:"utprRating",decimalsCount:1,ascending:!1,range:[2,5],deprecated:!0},PSA:{defaultInitialization:500,accessor:"psaPoints",decimalsCount:0,ascending:!1,range:[0,3e3],attributes:{tournaments:{generator:!0,range:[1,20]},divisor:{generator:!0,range:[10,20]}}},[zb]:{defaultInitialization:2e3,accessor:"squashLevel",decimalsCount:0,ascending:!1,range:[0,7e3]},[Qb]:{defaultInitialization:3.5,accessor:"usSquashRating",decimalsCount:1,ascending:!1,range:[2,6]},[Jb]:{defaultInitialization:1e3,accessor:"usattRating",decimalsCount:0,ascending:!1,range:[200,3e3]},[Xb]:{defaultInitialization:500,accessor:"ittfPoints",decimalsCount:0,ascending:!1,range:[0,2e4]},[Zb]:{defaultInitialization:1e4,accessor:"usarRanking",decimalsCount:0,ascending:!0,range:[1,25e3]},BWF:{defaultInitialization:5e3,accessor:"bwfPoints",decimalsCount:0,ascending:!0,range:[0,15e4],attributes:{tournaments:{generator:!0,range:[1,10]}}}},Ze=o$;function Gp({sourceRatingType:t,sourceRating:e}){let r=Ze[t]?.range,n=r?.[0]>r?.[1],o=Ze["ELO"].range;return kp({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function jF({targetRatingType:t,sourceRating:e}){let r=Ze[t]?.decimalsCount||0,n=Ze[t]?.range,o=n?.[0]>n?.[1],i=Math.max(...n),s=Ze["ELO"]?.range,a=kp({targetRange:n,sourceRange:s,value:e}),c=Number.parseFloat(a?.toFixed(r))||0;return o?i-c:c}function uf(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,convertToELO:i,adHocRatings:s={}}=t,a=t.scaleAccessor??Ze[n]?.accessor,c=e.participants??[];for(let u of r??[]){let p=c?.find(m=>m.participantId===u),d;i&&(d=tC({scaleName:`${"ELO"}.${_p}`,participant:p,eventType:o})),d||(d=tC({scaleName:`${n}.${_p}`,participant:p,eventType:o}),d&&i&&n!=="ELO"&&(d=Gp({sourceRatingType:n,sourceRating:d}))),!d&&n&&(d=tC({scaleAccessor:a,participant:p,scaleName:n,eventType:o}),d&&i&&n!=="ELO"&&(d=Gp({sourceRatingType:n,sourceRating:d}))),d&&!s[u]&&(s[u]=d)}return s}function tC({scaleType:t=qo,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Lo({scaleAttributes:{eventType:o??Fa,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&St(a)?a[e]:a}function At(t){let e="setFirstClassOrExtension";if(typeof t!="object")return{error:nt};let{element:r,attribute:n,name:o,value:i,creationTime:s}=t;if(!r||typeof r!="object")return M({result:{error:O},stack:e});if(typeof n!="string"||!n)return M({result:{error:O},stack:e});if(typeof o!="string"||!o)return M({result:{error:O},stack:e});if(cu()&&(i==null?delete r[n]:r[n]=i),uu())if(i==null)Mn({element:r,name:o});else{let a=Qt({element:r,extension:{name:o,value:i},creationTime:s});if(a.error)return M({result:a,stack:e})}else Array.isArray(r.extensions)&&r.extensions.some(a=>a?.name===o)&&Mn({element:r,name:o});return{...P}}function eC(t){let{tournamentRecord:e,drawDefinition:r,participantIds:n,event:o}=t;if(!r)return{error:K};if(!n?.length)return{error:nt};let{competitionPolicy:i}=wo({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let s=i.ratingPolicy,a=s.baselineRating.scaleName,c=s.ratingAggregation??"AVERAGE",u=o?.eventType,p=a?uf({tournamentRecord:e,participantIds:n,scaleName:a,eventType:u}):{},d={};for(let l of n){let f=i$({tournamentRecord:e,participantId:l,adHocRatings:p,aggregation:c,eventType:u});d[l]={participantId:l,baselineRating:f,dynamicFormRating:f,pressureRating:0,roundsPlayed:0,wins:0,losses:0,draws:0,totalPointsWon:0,totalPointsLost:0,ratingHistory:[]}}let m={participantStates:d,roundStates:{}};return At({element:r,attribute:"competitionState",name:Ns,value:m}),{competitionState:m,...P}}function i$({tournamentRecord:t,participantId:e,adHocRatings:r,aggregation:n,eventType:o}){if(r[e]!==void 0)return r[e];if(o===Xt){let s=t.participants?.find(a=>a.participantId===e)?.individualParticipantIds;if(s?.length){let a=s.map(c=>r[c]??0);return s$(a,n)}}return 0}function s$(t,e){if(!t.length)return 0;switch(e){case"MIN":return Math.min(...t);case"MAX":return Math.max(...t);case"SUM":return t.reduce((r,n)=>r+n,0);default:return t.reduce((r,n)=>r+n,0)/t.length}}function $t({element:t,attribute:e,name:r}){if(t?.[e]!==void 0)return t[e];let{extension:n}=qt({element:t,name:r});return n?.value}function Ko({drawDefinition:t}){return{competitionState:$t({element:t,attribute:"competitionState",name:Ns})}}function qF(t){let e=t.score?.sets??[];if(!e.length)return YF(t);let r=0,n=0;for(let o of e){let i=o.side1Score??0,s=o.side2Score??0;if(o.side1TiebreakScore!==void 0||o.side2TiebreakScore!==void 0){let a=o.side1TiebreakScore??0,c=o.side2TiebreakScore??0,u=a+c;if(u>0){r+=i-(o.winningSide===1?1:0)+a/u,n+=s-(o.winningSide===2?1:0)+c/u;continue}}r+=i,n+=s}return r>0||n>0?{side1Count:r,side2Count:n}:YF(t)}function YF(t){let{winningSide:e}=t;return e===1?{side1Count:1,side2Count:0}:e===2?{side1Count:0,side2Count:1}:{side1Count:0,side2Count:0}}function rC({pointsWon:t,pointsLost:e,competitionPolicy:r}){let n=t+e;if(n===0)return .5;let o=t/n,i=r.ratingPolicy.pressureRating;if(!i||i.actualOutputMethod==="POINT_SHARE")return o;let s=i.weights??{pointShare:1},a=(t-e)/n,c=0,u=s.pointShare??1,p=s.pointDifferential??0,d=s.contextFactor??0,m=u+p+d;return m===0?o:(u*o+p*a+d*c)/m}function Eh(t,e,r){return 1/(1+Math.pow(10,(e-t)/r))}function Tm(t){let{tournamentRecord:e,drawDefinition:r,matchUp:n,event:o}=t;if(!r)return{error:K};if(!n)return{error:nr};let{competitionPolicy:i}=wo({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let{competitionState:s}=Ko({drawDefinition:r});if(!s)return{...P};let a=n.sides??[],c=a[0]?.participantId,u=a[1]?.participantId;if(!c||!u)return{...P};let p=s.participantStates[c],d=s.participantStates[u];if(!p||!d)return{...P};let{winningSide:m}=n,{side1Count:l,side2Count:f}=qF(n),g=rC({pointsWon:l,pointsLost:f,competitionPolicy:i}),I=rC({pointsWon:f,pointsLost:l,competitionPolicy:i}),h=i.ratingPolicy.dynamicFormRating.logisticScale,S=i.ratingPolicy.dynamicFormRating.kFactor,T=Eh(p.baselineRating,d.baselineRating,h),y=Eh(d.baselineRating,p.baselineRating,h),E=Eh(p.dynamicFormRating,d.dynamicFormRating,h),A=Eh(d.dynamicFormRating,p.dynamicFormRating,h),N=i.ratingPolicy.pressureRating?.enabled,D=N?g-T:0,R=N?I-y:0,U=i.ratingPolicy.dynamicFormRating.enabled,b=U?p.dynamicFormRating+S*(g-E):p.dynamicFormRating,C=U?d.dynamicFormRating+S*(I-A):d.dynamicFormRating,_=n.roundNumber??0;return p.dynamicFormRating=b,p.pressureRating+=D,p.roundsPlayed+=1,p.wins+=m===1?1:0,p.losses+=m===2?1:0,p.draws+=m?0:1,p.totalPointsWon+=l,p.totalPointsLost+=f,p.ratingHistory.push({roundNumber:_,opponentParticipantId:u,dynamicFormRatingBefore:p.dynamicFormRating-S*(g-E),dynamicFormRatingAfter:b,pressureDelta:D,actualOutput:g,expectedOutput:T}),d.dynamicFormRating=C,d.pressureRating+=R,d.roundsPlayed+=1,d.wins+=m===2?1:0,d.losses+=m===1?1:0,d.draws+=m?0:1,d.totalPointsWon+=f,d.totalPointsLost+=l,d.ratingHistory.push({roundNumber:_,opponentParticipantId:c,dynamicFormRatingBefore:d.dynamicFormRating-S*(I-A),dynamicFormRatingAfter:C,pressureDelta:R,actualOutput:I,expectedOutput:y}),At({element:r,attribute:"competitionState",name:Ns,value:s}),{...P}}var Lr="ABANDONED",yu="AWAITING_RESULT";var mo="CANCELLED",ae="COMPLETED",Vp="DEAD_RUBBER",Mt="DEFAULTED",Te="DOUBLE_DEFAULT",Zt="DOUBLE_WALKOVER",vn="IN_PROGRESS",Zr="INCOMPLETE",nC="NOT_PLAYED",ve="RETIRED",Ji="SUSPENDED",Jt="TO_BE_PLAYED",vt="WALKOVER",$F=[yu,ae,Mt,vn,Zr,ve,Ji],CE=[yu,ae,Mt,Zt,Te,vn,Zr,ve,Ji,vt],ME=[Lr,yu,"BYE",mo,ae,Vp,Mt,Zt,Te,vn,Zr,nC,ve,Ji,Jt,vt],vE=["BYE",Zt,Te,ae,Mt,ve,vt],OE=[Lr,yu,mo,Vp,vn,Zr,nC,Ji,Jt,void 0],Rt=[mo,Lr,ae,Vp,Mt,Zt,Te,ve,vt],pf=[Lr,ae,Mt,Zt,Te,vn,ve,vt],_E=[vn,Zr,Ji,Jt],xE={ABANDONED:Lr,AWAITING_RESULT:yu,BYE:"BYE",CANCELLED:mo,COMPLETED:ae,DEAD_RUBBER:Vp,DEFAULTED:Mt,DOUBLE_WALKOVER:Zt,DOUBLE_DEFAULT:Te,IN_PROGRESS:vn,INCOMPLETE:Zr,NOT_PLAYED:nC,RETIRED:ve,SUSPENDED:Ji,TO_BE_PLAYED:Jt,WALKOVER:vt};function oC(t){let{tournamentRecord:e,drawDefinition:r,roundNumber:n,matchUps:o,event:i}=t;if(!r)return{error:K};let{competitionPolicy:s}=wo({tournamentRecord:e,drawDefinition:r,event:i});if(!s)return{...P};let{competitionState:a}=Ko({drawDefinition:r});if(!a)return{...P};if(a.roundStates[n]?.processed)return{...P};let c=o.filter(p=>p.roundNumber===n&&(p.winningSide||Rt.includes(p.matchUpStatus)));for(let p of c)Tm({tournamentRecord:e,drawDefinition:r,matchUp:p,event:i});let{competitionState:u}=Ko({drawDefinition:r});return u&&(u.roundStates[n]={roundNumber:n,processed:!0},At({element:r,attribute:"competitionState",name:Ns,value:u})),{...P}}function iC({drawDefinition:t}){return t?(At({element:t,attribute:"competitionState",name:Ns,value:void 0}),{...P}):{error:K}}var aC={};_t(aC,{getCompetitionLeaderboard:()=>LE,getCompetitionParticipantState:()=>wE,getCompetitionPolicy:()=>wo,getCompetitionState:()=>Ko,getLinkedTournamentIds:()=>Bp,getTournamentIds:()=>Sm});function wE({drawDefinition:t,participantId:e}){let{competitionState:r}=Ko({drawDefinition:t});return{participantState:r?.participantStates?.[e]}}function LE(t){let{tournamentRecord:e,drawDefinition:r,event:n}=t,{competitionPolicy:o}=wo({tournamentRecord:e,drawDefinition:r,event:n}),{competitionState:i}=Ko({drawDefinition:r});if(!i||!o)return{leaderboard:[]};let s=o.victoryPolicy.primaryRanking;return{leaderboard:[...Object.values(i.participantStates)].sort((p,d)=>{let m=KF(d,s)-KF(p,s);if(m!==0)return m;for(let l of o.victoryPolicy.tiebreakOrder??[]){let f=a$(p,d,l,i.participantStates);if(f!==0)return f}return 0}).map((p,d)=>({participantId:p.participantId,rank:d+1,baselineRating:p.baselineRating,dynamicFormRating:p.dynamicFormRating,pressureRating:p.pressureRating,wins:p.wins,losses:p.losses,draws:p.draws,pointsWon:p.totalPointsWon,pointsLost:p.totalPointsLost}))}}function KF(t,e){switch(e){case"PRESSURE_RATING":return t.pressureRating;case"DYNAMIC_FORM_RATING":return t.dynamicFormRating;case"WINS":return t.wins;case"POINTS":return t.totalPointsWon;default:return t.wins}}function a$(t,e,r,n){switch(r){case"POINT_DIFFERENTIAL":return e.totalPointsWon-e.totalPointsLost-(t.totalPointsWon-t.totalPointsLost);case"DYNAMIC_FORM_RATING":return e.dynamicFormRating-t.dynamicFormRating;case"PRESSURE_RATING":return e.pressureRating-t.pressureRating;case"HEAD_TO_HEAD":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.filter(c=>c.actualOutput>.5).length;return i.filter(c=>c.actualOutput>.5).length-s}case"HEAD_TO_HEAD_PRESSURE":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.reduce((c,u)=>c+u.pressureDelta,0);return i.reduce((c,u)=>c+u.pressureDelta,0)-s}case"STRENGTH_OF_OPPOSITION":{let o=t.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),i=e.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),s=o.length?o.reduce((c,u)=>c+u,0)/o.length:0;return(i.length?i.reduce((c,u)=>c+u,0)/i.length:0)-s}default:return 0}}function Bp({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,i=cf(n).filter(s=>s!==o);return{[r]:i}}))}}var EO={};_t(EO,{adHocPositionSwap:()=>kM,addAdHocMatchUps:()=>md,addDrawDefinitionTimeItem:()=>SS,addFinishingRounds:()=>aa,addGoesTo:()=>bs,addLinkedConsolationStructure:()=>gM,addPlayoffStructures:()=>DS,addQualifyingStructure:()=>LM,addVoluntaryConsolationStructure:()=>rS,allPlayoffPositionsFilled:()=>BA,alternateDrawPositionAssignment:()=>hM,assignDrawPosition:()=>WM,assignDrawPositionBye:()=>Mr,attachConsolationStructures:()=>cS,attachPlayoffStructures:()=>uS,attachQualifyingStructure:()=>hS,attachStructures:()=>pS,autoSeeding:()=>OV,automatedPlayoffPositioning:()=>Ja,automatedPositioning:()=>Gu,buildDrawHierarchy:()=>vV,checkValidEntries:()=>ig,deleteAdHocMatchUps:()=>YM,drawMatic:()=>Td,findDrawDefinition:()=>iP,generateAdHocMatchUps:()=>Vc,generateAdHocRounds:()=>hg,generateAndPopulatePlayoffStructures:()=>Xf,generateConsolationStructure:()=>fM,generateDrawDefinition:()=>jc,generateDrawMaticRound:()=>ug,generateDrawStructuresAndLinks:()=>sg,generateDrawTypeAndModifyDrawDefinition:()=>ag,generateQualifyingStructure:()=>Kf,generateSwissRound:()=>CV,generateVoluntaryConsolation:()=>MP,getAssignedParticipantIds:()=>ss,getAvailableMatchUpsCount:()=>Zf,getAvailablePlayoffProfiles:()=>sd,getDraftState:()=>PP,getDrawDefinitionTimeItem:()=>qE,getDrawParticipantRepresentativeIds:()=>eP,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>gd,getEligibleVoluntaryConsolationParticipants:()=>tP,getLuckyDrawRoundStatus:()=>zf,getMatchUpsMap:()=>ye,getParticipantIdFinishingPositions:()=>rg,getPositionAssignments:()=>Bu,getPositionsPlayedOff:()=>wu,getRandomQualifierList:()=>SP,getSeedingThresholds:()=>PA,getSeedsCount:()=>Id,getStructureSeedAssignments:()=>Dr,getSwissChart:()=>AP,getSwissStandings:()=>TP,getTally:()=>EP,getTeamLineUp:()=>oa,getValidGroupSizes:()=>Cm,hasLuckyRounds:()=>Wh,initializeDraft:()=>jM,isAdHoc:()=>De,isCompletedStructure:()=>Bo,isValidForQualifying:()=>yP,luckyDrawAdvancement:()=>GM,luckyLoserDrawPositionAssignment:()=>cM,modifyDrawDefinition:()=>VM,modifyDrawName:()=>US,modifySeedAssignment:()=>DM,mutate:()=>KM,positionActions:()=>hP,predictDrawCompetitiveBands:()=>ld,pruneDrawDefinition:()=>HM,qualifierDrawPositionAssignment:()=>mS,qualifierProgression:()=>SM,query:()=>uv,remapDrawDefinitionMatchUpIds:()=>dS,removeDrawPositionAssignment:()=>od,removeRoundMatchUps:()=>qM,removeSeededParticipant:()=>wM,removeStructure:()=>MM,renameStructures:()=>RM,resetDrawDefinition:()=>BM,resetQualifyingStructure:()=>CM,resetVoluntaryConsolationStructure:()=>hC,resolveDraftPositions:()=>bM,seedWithdrawalCascade:()=>FM,setDrawParticipantRepresentativeIds:()=>uC,setDrawPositionPreferences:()=>IM,setPositionAssignments:()=>pM,setStructureOrder:()=>UM,setSubOrder:()=>$M,shiftAdHocRounds:()=>uM,swapAdHocRounds:()=>dM,swapDrawPositionAssignments:()=>xM,updateTeamLineUp:()=>vs,validatePlayoffGroups:()=>Yf,withdrawParticipantAtDrawPosition:()=>sM});var KM={};_t(KM,{adHocPositionSwap:()=>kM,addAdHocMatchUps:()=>md,addDrawDefinitionTimeItem:()=>SS,addLinkedConsolationStructure:()=>gM,addPlayoffStructures:()=>DS,addQualifyingStructure:()=>LM,addVoluntaryConsolationStructure:()=>rS,alternateDrawPositionAssignment:()=>hM,assignDrawPosition:()=>WM,assignDrawPositionBye:()=>Mr,attachConsolationStructures:()=>cS,attachPlayoffStructures:()=>uS,attachQualifyingStructure:()=>hS,attachStructures:()=>pS,automatedPlayoffPositioning:()=>Ja,automatedPositioning:()=>Gu,deleteAdHocMatchUps:()=>YM,initializeDraft:()=>jM,luckyDrawAdvancement:()=>GM,luckyLoserDrawPositionAssignment:()=>cM,modifyDrawDefinition:()=>VM,modifyDrawName:()=>US,modifySeedAssignment:()=>DM,pruneDrawDefinition:()=>HM,qualifierDrawPositionAssignment:()=>mS,qualifierProgression:()=>SM,remapDrawDefinitionMatchUpIds:()=>dS,removeDrawPositionAssignment:()=>od,removeRoundMatchUps:()=>qM,removeSeededParticipant:()=>wM,removeStructure:()=>MM,renameStructures:()=>RM,resetDrawDefinition:()=>BM,resetQualifyingStructure:()=>CM,resetVoluntaryConsolationStructure:()=>hC,resolveDraftPositions:()=>bM,seedWithdrawalCascade:()=>FM,setDrawParticipantRepresentativeIds:()=>uC,setDrawPositionPreferences:()=>IM,setPositionAssignments:()=>pM,setStructureOrder:()=>UM,setSubOrder:()=>$M,shiftAdHocRounds:()=>uM,swapAdHocRounds:()=>dM,swapDrawPositionAssignments:()=>xM,updateTeamLineUp:()=>vs,withdrawParticipantAtDrawPosition:()=>sM});var FE=t=>e=>t[e],df=(t=[])=>t.map(Pe).filter(Boolean),Ah=(t=[])=>t.map(lt).filter(Boolean),lt=(t={})=>FE(t)("participantId"),zF=(t={})=>FE(t)("drawPosition");var Pe=(t={})=>FE(t)("matchUpId"),Cc=(t={})=>FE(t)("drawId");function uC({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Cr};if(!Array.isArray(t))return{error:O};let r=Ah(e?.entries??[]);return t.length&&Ht(t,r).length<t.length?{error:O}:Sh({drawDefinition:e,extension:{name:UE,value:t}})}function Xi(t,e,r){let n=d=>$t({element:d,attribute:"roundTarget",name:Xr}),o=r?.deprioritizeCompleted,i=r?.mode===Nb&&PF,s=r?.mode===Pb&&Db,a=s||i||ka,c=d=>d?.stage===j&&d?.stageSequence===1,u=d=>c(d)?-1:a[d?.stage],p=d=>d?.matchUps.every(({matchUpStatus:m})=>Rt.includes(m)?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)||(Ph(t)||0)-(Ph(e)||0)}function Ph(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 tt(t){let e=X(t,[{[zt]:!0,[Po]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=hn({drawDefinition:r}),i=o?.flatMap(c=>c.structures?[...c.structures].concat(c):c),s=i?.find(c=>c.structureId===n);if(!s)return{error:Pt};let a=s.structureType===gu?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function hn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&K||!e?.structures&&PI||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=$t({element:f,attribute:"roundTarget",name:Xr});return!o||o===g},p=e?.structures?.filter(m).filter(l).filter(u).sort((f,g)=>Xi(f,g,i))??[],d=t?Object.assign({},...lu.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:d};function m(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 kE({drawDefinition:t}){if(!t)return{error:K};let e={};return{allPositionedParticipantIds:(t.structures??[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=yt({structure:n}),s=i?.map(lt).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function yt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:K};if({structure:r,error:n}=tt({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>yt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=RI,{positionAssignments:o,error:n}}function pe({drawDefinition:t,structureId:e,structure:r}){let n=yt({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}}function at(t,e,r){let n=e.reduce((o,i)=>(o[i]=!0,o),{});return X(t,[n],r)}var Nh="addDrawDefinition",ym="addMatchUps",Oi="addParticipants",Dh="addScaleItems",pC="addEvent",GE="addVenue",Zi="audit",VE="dataIssue",Uh="deleteParticipants",Rh="deleteVenue",bh="deletedDrawIds",Ch="deletedMatchUpIds",Mh="modifyDrawDefinition",dC="modifyDrawEntries",mC="modifyEventEntries",vh="modifyMatchUp",Oe="modifyParticipants",Oh="modifyPositionAssignments",_h="modifySeedAssignments",ko="modifyTournamentDetail",Sn="modifyVenue",mf="mutations",BE="publishEvent",lC="publishEventSeeding",fC="publishOrderOfPlay",gC="publishParticipants",xh="unPublishEvent",wh="unPublishEventSeeding",Lh="unPublishOrderOfPlay",IC="unPublishParticipants",lf="unPublishTournament",Hp="updateInContextMatchUp",QF={ADD_DRAW_DEFINITION:Nh,ADD_MATCHUPS:ym,ADD_PARTICIPANTS:Oi,ADD_SCALE_ITEMS:Dh,ADD_EVENT:pC,ADD_VENUE:GE,AUDIT:Zi,DATA_ISSUE:VE,DELETE_PARTICIPANTS:Uh,DELETE_VENUE:Rh,DELETED_DRAW_IDS:bh,DELETED_MATCHUP_IDS:Ch,MODIFY_DRAW_DEFINITION:Mh,MODIFY_DRAW_ENTRIES:dC,MODIFY_EVENT_ENTRIES:mC,MODIFY_MATCHUP:vh,MODIFY_PARTICIPANTS:Oe,MODIFY_POSITION_ASSIGNMENTS:Oh,MODIFY_SEED_ASSIGNMENTS:_h,MODIFY_TOURNAMENT_DETAIL:ko,MODIFY_VENUE:Sn,MUTATIONS:mf,PUBLISH_EVENT_SEEDING:lC,PUBLISH_EVENT:BE,PUBLISH_ORDER_OF_PLAY:fC,PUBLISH_PARTICIPANTS:gC,UNPUBLISH_EVENT_SEEDING:wh,UNPUBLISH_EVENT:xh,UNPUBLISH_ORDER_OF_PLAY:Lh,UNPUBLISH_PARTICIPANTS:IC,UNPUBLISH_TOURNAMENT:lf,UPDATE_INCONTEXT_MATCHUP:Hp};function HE(t,e){if(!t)return{error:K};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)}),{...P}}function JF(t){if(!t)return;let e=Date.now(),r=t.updatedAt;if(r){let n=typeof r=="string"?new Date(r).getTime():r.getTime();!Number.isNaN(n)&&e<=n&&(e=n+1)}t.updatedAt=new Date(e).toISOString()}function zo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){if(t&&HE(t),Array.isArray(r))for(let o of r)JF(o);return it({payload:{matchUps:r,tournamentId:e,eventId:n},topic:ym}),{...P}}function Vn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&HE(t),it({topic:Ch,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)Vy({key:i});return{...P}}function mt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Lt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),JF(i),it({topic:vh,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...P}):(console.log(nr),{error:nr})}function XF({tournamentId:t,inContextMatchUp:e}){return e?(it({payload:{inContextMatchUp:e,tournamentId:t},topic:Hp,key:e.matchUpId}),{...P}):{error:nr}}function Mc({tournamentId:t,eventId:e,drawDefinition:r}){return r?(HE(r),it({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:Nh,key:r.drawId}),{...P}):(console.log(K),{error:K})}function ZF({tournamentId:t,eventId:e,drawId:r}){return it({payload:{drawId:r,tournamentId:t,eventId:e},topic:bh,key:r}),Vy({key:r}),{...P}}function Lt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(HE(t,r),it({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Mh,key:t.drawId}),{...P}):{error:K}}function ff({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){let o=at({drawDefinition:t,structure:r},[zt,Ec]);if(o.error)return o;let i=r.seedAssignments,s=r.structureId,a=t.drawId;return it({payload:{tournamentId:e,eventId:n,drawId:a,structureId:s,seedAssignments:i},topic:_h,key:t.drawId}),Lt({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:n}),{...P}}function Tn({drawDefinition:t,tournamentId:e,structure:r,event:n}){let o=at({drawDefinition:t,structure:r},[zt,Ec]);if(o.error)return o;let i=yt({structure:r}),s=r.structureId,a=t.drawId,c=n?.eventId;return it({topic:Oh,payload:{positionAssignments:i,tournamentId:e,structureId:s,eventId:c,drawId:a},key:s}),Lt({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:c}),{...P}}function hC({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:K};let o=e.structures?.find(s=>s.stage===Qe);if(!o)return{error:Pt};let i=o.matchUps?.map(({matchUpId:s})=>s)??[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Vn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==Qe)),Lt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...P}}function gf({drawPositions:t,structure:e}){if([rt,j].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=yt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,attribute:"disableLinks",name:Fp,value:!0})})}function vc(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[Tu]===!1)return;let{extension:o}=qt({name:Tu,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===j);if(a){let c=yt({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:d,qualifier:m})=>({drawPosition:u,participantId:p,qualifier:m,bye:d}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:Tu};Qt({element:n,extension:s})}function ts({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(d=>d.structureId))&&u.forEach(d=>s[d.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function Wp(t){let{sides:e,matchUpType:r}=t??{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===Ut?s?.individualParticipantIds??[]:s.participantId).flat():[],o=(e??[]).map(s=>r===Ut&&(s?.participant?.individualParticipantIds??[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Pr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var Eu="SIGN_IN_STATUS",SC="SIGNED_OUT",jp="SIGNED_IN",Fh="PAYMENT_STATUS",tk="REFUNDED",ek="PARTIAL",rk="WAIVED",nk="UNPAID",ok="PAID",WE=[ok,nk,ek,rk,tk],fr="TEAM",ft="INDIVIDUAL",zr="GROUP",dt="PAIR",bt="TEAM",Yp={TEAM_PARTICIPANT:fr,INDIVIDUAL:ft,GROUP:zr,TEAM:bt,PAIR:dt},ik={INDIVIDUAL:ft,GROUP:zr,PAIR:dt,TEAM:bt,SIGN_IN_STATUS:Eu,SIGNED_OUT:SC,SIGNED_IN:jp,PAYMENT_STATUS:Fh,REFUNDED:tk,PARTIAL:ek,WAIVED:rk,UNPAID:nk,PAID:ok};function qp({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?q(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===bt),s=o.filter(c=>c.participantType===zr),a=o.filter(c=>c.participantType===dt);return o.forEach(c=>{if(c.participantType===ft){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds??[]).forEach(d=>{d===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(d=>{d===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds??[]).forEach(d=>{d===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 TC(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function sk(t){let e=Object.assign({},..._i.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return TC(e[t])}var _i=[{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 jE({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=_i.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 ak({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?Ps({template:e,source:s}):s)}}}}function Bn(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:Wt}}function YE(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Bn({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:nt}}function Fr(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=YE(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:O,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:BI};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=q(i.pop(),!1,!0);if(s){let a={timeItem:s,...P};return e&&Object.assign(a,{previousItems:i}),a}else return{info:fe}}function qE({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Un};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Fr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function $p({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Se};if(!n.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Fr({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function If({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Y};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Fr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function $E({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){let i=at({tournamentRecord:e,participantId:r},[Z,Ge]);if(i.error)return i;let s=Bn({tournamentRecord:e,participantId:r});if(s.error)return s;let{participant:a}=s;if(!a?.timeItems)return{info:fe};let{timeItem:c,previousItems:u,info:p}=Fr({element:s.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return c&&{timeItem:c,previousItems:u}||{info:p}}var c$={[zr]:"groupParticipantIds",[dt]:"pairParticipantIds",[bt]:"teamParticipantIds"},u$={[zr]:"groups",[bt]:"teams"};function KE({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,withGroupings:i,internalUse:s,withISO2:a,withIOC:c}){let u=[],p={};for(let m of r.participants??[]){let l=m?.participantId;l&&m$({participantMap:p,participantId:l})}for(let m of r.participants??[]){let l=q(m,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=d$({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=p$(l)),o){let{ratings:h,rankings:S,seedings:T}=Pc({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&jE({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let m=St(t)?t:void 0;ak({participantMap:p,template:m})}let d;return i&&(d=qp({participants:Object.values(p).map(({participant:m})=>m),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:d}}function p$(t){let{timeItem:e}=Fr({itemType:Eu,element:t});return e?.itemValue===jp}function d$({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[c$[n]].push(o),[bt,zr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:d,teamId:m}=e,l=u$[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:d,teamId:m})}if(n===dt){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function m$({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:{[Ct]:{...r},[Ut]:{...r},[bt]:{...r},...r}}}function gi({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return KE({...t,...n,tournamentRecord:r});let i=q(r.participants,!1,!0)??[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>jE({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=qp({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=Pc({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}var zE="WALKOVER",yC="RETIRED",hf="COMPETITIVE",Au="ROUTINE",Pu="DECISIVE",Sf="winRatio";var l$={[gn]:{policyName:"Competitive Bands Default",profileBands:{[Pu]:20,[Au]:50},predictionModel:{competitiveAnchors:[{delta:0,probability:.7},{delta:1.5,probability:.25}],decisiveAnchors:[{delta:0,probability:.1},{delta:1.5,probability:.55}]}}},zs=l$;function lo({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=Do({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[gn]??s?.[gn]??zs[gn];i.policies[gn]=a}return i}function f$(t,e,r,n){if(n==null){t[e]&&(delete t[e][r],Object.keys(t[e]).length===0&&delete t[e]);return}t[e]||(t[e]={}),t[e][r]=n}function g$(t,e){Array.isArray(t.extensions)&&t.extensions.some(r=>r?.name===e)&&Mn({element:t,name:e})}function Tf(t){let e="setGroupLeafOrExtension";if(typeof t!="object")return{error:nt};let{element:r,groupAttribute:n,leafAttribute:o,name:i,value:s,creationTime:a}=t;if(!r||typeof r!="object")return M({result:{error:O},stack:e});if(typeof n!="string"||!n)return M({result:{error:O},stack:e});if(typeof o!="string"||!o)return M({result:{error:O},stack:e});if(typeof i!="string"||!i)return M({result:{error:O},stack:e});if(cu()&&f$(r,n,o,s),uu())if(s==null)Mn({element:r,name:i});else{let c=Qt({element:r,extension:{name:i,value:s},creationTime:a});if(c.error)return M({result:c,stack:e})}else g$(r,i);return{...P}}function Qs({element:t,groupAttribute:e,leafAttribute:r,name:n}){let o=t?.[e]?.[r];return o!==void 0?o:(t?.extensions??[]).find(s=>s?.name===n)?.value}function Uo({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:Y};let{appliedPolicies:i}=gt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:lp?.message}}function Oc({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}=Uo({policyType:No,tournamentRecord:t,event:n}),i=t?Qs({element:t,groupAttribute:"scheduling",leafAttribute:"timing",name:xo}):void 0,a=(n&&qt({name:xo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:i,eventScheduling:a,categoryName:e,categoryType:r,policy:o}}}function QE({tournamentRecord:t,event:e}){if(!t)return{};let{extension:r}=qt({element:t,name:Vb}),n=r?.value;if(!n?.events?.length)return{};let o=e?n.events.find(s=>s.eventType===e.eventType&&(!s.eventName||s.eventName===e.eventName)&&(!s.category?.categoryName||s.category?.categoryName===e.category?.categoryName)):void 0;if(!o)return{};let i={};return o.drawSize!==void 0&&(i.drawSize=o.drawSize),o.maxWildcards!==void 0&&(i.maxWildcards=o.maxWildcards),o.maxAlternates!==void 0&&(i.maxAlternates=o.maxAlternates),o.maxQualifiers!==void 0&&(i.maxQualifiers=o.maxQualifiers),Object.keys(i).length?{constraints:i}:{}}var Nu="GEMscore",ck={GEM_SCORE:Nu};function uk({provisionalPositioning:t,rankBy:e=Nu,finishingPositions:r,groupResults:n,bestOf:o}){let i=[],s=[],a=[...r].sort(ee),c=Math.max(...a);for(let{structureId:m,results:l}of n)for(let[f,g]of Object.entries(l)){let I=g.groupOrder||t&&g.provisionalOrder;if(!I)continue;let h={groupingValue:m,GEMscore:g.GEMscore,isBestFinisher:!1,finishingPosition:I,participantId:f};a.includes(I)?s.push(h):I>c&&i.push(h)}let u=[...s],p=o-s.length;p>0&&i.length>0&&i.toSorted((f,g)=>f.finishingPosition!==g.finishingPosition?f.finishingPosition-g.finishingPosition:e===Nu?(g.GEMscore??0)-(f.GEMscore??0):0).slice(0,p).forEach(f=>{f.isBestFinisher=!0,u.push(f)});let d={};for(let m of u){let l=m.finishingPosition;d[l]=(d[l]||0)+1}return{selectedParticipants:u,consumedPositions:d}}var tn="ALTERNATE",kh="CONFIRMED",Nr="DIRECT_ACCEPTANCE",Kp="FEED_IN",Gh="JUNIOR_EXEMPT",Js="LUCKY_LOSER",Vh="ORGANISER_ACCEPTANCE",yf="QUALIFIER",I$="REGISTERED",Bh="SPECIAL_EXEMPT",kr="UNGROUPED",es="UNPAIRED",zp="WILDCARD",On="WITHDRAWN",Em=[kh,Nr,Gh,Vh,Bh],EC=[Kp,Js,yf],rs=[kh,Nr,Kp,Gh,Vh,Bh,zp],yr=[kh,Nr,Gh,Js,yf,Vh,Bh,zp],AC=[tn,kh,Nr,Kp,Gh,Js,Vh,yf,I$,Bh,kr,es,zp,On],pk={ALTERNATE:tn,CONFIRMED:kh,DIRECT_ACCEPTANCE:Nr,DIRECT_ENTRY_STATUSES:rs,DRAW_SPECIFIC_STATUSES:EC,EQUIVALENT_ACCEPTANCE_STATUSES:Em,FEED_IN:Kp,JUNIOR_EXEMPT:Gh,LUCKY_LOSER:Js,ORGANISER_ACCEPTANCE:Vh,QUALIFIER:yf,SPECIAL_EXEMPT:Bh,STRUCTURE_SELECTED_STATUSES:yr,UNGROUPED:kr,UNPAIRED:es,VALID_ENTRY_STATUSES:AC,WILDCARD:zp,WITHDRAWN:On};function dk({stage:t,drawDefinition:e}){return lu.includes(t)?e?.structures?.some(n=>n.stage===t)||lu.includes(t):!1}function JE({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function ns({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,d)=>{let m=$t({element:d,attribute:"roundTarget",name:Xr}),l=c&&d.entryStage===c||a?.length&&d.entryStage&&a.includes(d.entryStage),f=!o||d.entryStatus&&o.includes(d.entryStatus),g=d.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!m||s===m)?p.concat(d):p},[])??[];if(i&&c===Vt){let{playoffEntries:p,error:d}=h$({provisionalPositioning:t,drawDefinition:r,structureId:i});return d&&console.log("playoff entries error"),(p?.length?p:u).filter(m=>!e||m.placementGroup===e)}return u}function h$({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===fn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s,bestOf:a,rankBy:c}=o.source,{structure:u}=tt({drawDefinition:e,structureId:s});if(u?.structureType===Ie){let d=(u.structures??[]).map(m=>{let l=m.positionAssignments??[],{structureId:f}=m,g=Object.assign({},...l.map(I=>{let{participantId:h}=I,S=$t({element:I,attribute:"tally",name:to});return S&&h?{[h]:S}:void 0}).filter(Boolean));return{structureId:f,results:g}});if(o.source.remainder)S$({provisionalPositioning:t,allGroupResults:d,drawDefinition:e,playoffEntries:n,inboundLink:o,structureId:s});else if(a!==void 0&&i){let{selectedParticipants:m}=uk({groupResults:d,provisionalPositioning:t,finishingPositions:i,bestOf:a,rankBy:c});m.forEach(l=>{let g=i.includes(l.finishingPosition)?[...i].sort(ee).indexOf(l.finishingPosition)+1:[...i].sort(ee).length+1;n.push({isBestFinisher:l.isBestFinisher,groupingValue:l.groupingValue,participantId:l.participantId,GEMscore:l.GEMscore,entryStatus:Kp,entryStage:Vt,placementGroup:g})})}else T$({provisionalPositioning:t,finishingPositions:i,allGroupResults:d,playoffEntries:n})}}return{playoffEntries:n}}function S$({provisionalPositioning:t,allGroupResults:e,drawDefinition:r,playoffEntries:n,inboundLink:o,structureId:i}){let s=new Set,a=(r.links??[]).filter(c=>c.linkType===fn&&c.source.structureId===i&&c.target.structureId!==o.target.structureId&&c.source.bestOf!==void 0);for(let c of a){let{structure:u}=tt({structureId:c.target.structureId,drawDefinition:r});if(u)for(let p of u.positionAssignments??[])p.participantId&&s.add(p.participantId)}e.forEach(({structureId:c,results:u})=>{Object.keys(u).forEach(p=>{if(!s.has(p)){let d=u[p],{groupOrder:m,provisionalOrder:l,GEMscore:f}=d,g=m||t&&l;n.push({groupingValue:c,entryStage:Vt,entryStatus:Kp,placementGroup:g||1,participantId:p,GEMscore:f})}})})}function T$({provisionalPositioning:t,finishingPositions:e,allGroupResults:r,playoffEntries:n}){r.forEach(({structureId:o,results:i})=>{let s=o,c=Object.keys(i).reduce((p,d)=>{let m=i[d],l=m.groupOrder||t&&m.provisionalOrder;return p.includes(l)||p.push(l),p},[]).length===Object.keys(i).length,u=Object.keys(i).filter(p=>{let d=i[p],m=d.groupOrder||t&&d.provisionalOrder;return e?.includes(m)});(!t||c)&&u.forEach(p=>{let d=i[p],{groupOrder:m,provisionalOrder:l,GEMscore:f}=d,g=m||t&&l,I=[...e??[]].sort(ee).indexOf(g)+1;n.push({entryStage:Vt,entryStatus:Kp,placementGroup:I,groupingValue:s,participantId:p,GEMscore:f})})})}function Dr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=tt({drawDefinition:r,structureId:n}));let a=yt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Pt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,d=c===Vt&&r&&ns({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),m=d?d.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=m?.slice(0,e?m.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=kU;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function Qo(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 Am({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 tr({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:Am({item:r,drawDefinition:t,structure:e,event:n})||Am({item:e,drawDefinition:t,structure:e,event:n})||Qo(t)||Qo(n)}}function mk({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 ye({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,d=u.matchUps;r[u.structureId]={matchUps:d,itemStructureIds:[],structureName:p},d&&(n.push(...d),d.forEach(m=>{m.tieMatchUps&&n.push(...m.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 Jo({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(q(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps??[]).concat(...i)}function XE({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:o}){let i=t?.[gn];if(i?.profileBands)return i.profileBands;if(e){let{appliedPolicies:s}=gt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),a=s?.[gn];if(a?.profileBands)return a.profileBands}return zs[gn].profileBands}var y$=(t,e)=>(t||0)+(e||0);function ZE(t,e){let r=Array.isArray(t)?t[0]:t;return r===void 0||Number.isNaN(r)?zE:r<=e[Pu]&&Pu||r<=e[Au]&&Au||hf}function Ef({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(y$)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function E$(t){let e=t?.games;if(!e?.length)return;let r=Math.max(...e);if(r===0)return;let n=Math.min(...e);return Math.round(n/r*100)}function tA(t){return t.map(E$).filter(e=>e!==void 0).sort((e,r)=>e-r).map(e=>parseFloat(e.toFixed(2)))}function Xs({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:nr};let{score:n,winningSide:o}=r;if(!o)return{error:O};let i=e||XE({tournamentRecord:t}),s=Ef({score:n}),a=tA([s]),c=ZE(a,i),u=Array.isArray(a)?a[0]:a;return{...P,competitiveness:c,pctSpread:u}}function eA({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ae(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(ee);return n.map(i=>o.indexOf(i)+1)}function Hh(t){if(!St(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 Ur(t){return Array.isArray(t)?t.every(Hh):!1}function A$(t,e){return e?.find(r=>t.includes(r))}function _e({matchUps:t=[],interpolate:e}){if(!Ur(t))return{roundMatchUps:[],error:O};let r=t.reduce((m,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return!l.roundNumber||m.includes(f)?m:m.concat(f)},[]).sort(ee).map(m=>{let l=t.filter(h=>h.roundNumber===m),g=l.find(({matchUpType:h})=>h===xt)?l.filter(({matchUpType:h})=>h===xt):l,I=h=>h.sort((S,T)=>ee(S.roundPosition,T.roundPosition));return{[m]:I(g)}}),n=t.reduce((m,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return m[f]||(m[f]=et({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),m},{}),o=Object.assign({},...r);if(e){let m=Math.max(...Object.keys(o).map(f=>st(f)).filter(f=>!Number.isNaN(f))),l=o[m]?.length;if(l>1&&rn(l)){let f=m+1,g=f+l/2;J(f,g).forEach((h,S)=>{o[h]=J(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(m=>{let l=o[m]?.length,f=o[m]?.filter(I=>!Rt.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[m]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(m=>st(m)).filter(m=>!Number.isNaN(m));u.forEach(m=>{let l=o[m].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.flatMap(g=>g?.drawPositions??[]);if(s[m].roundNumber=m,s[m].roundFactor=s[m].matchUpsCount?i/s[m].matchUpsCount:1,s[m].finishingRound=n[m]?.finishingRound,s[m].roundName=n[m]?.roundName,s[m].abbreviatedRoundName=n[m]?.abbreviatedRoundName,s[m].finishingPositionRange=o[m]?.[0]?.finishingPositionRange,m===1||!s[m-1]){let g=f.sort(ee),I=Ae(g,2);s[m].drawPositions=g,s[m].pairedDrawPositions=I}else{let g=s[m-1],I=g.drawPositions,h=g.matchUpsCount/s[m].matchUpsCount,S=Ae(I,h),T=l.map(y=>{let{roundPosition:E}=y,A=[...y.drawPositions??[],void 0,void 0].slice(0,2);if(!E)return A;let N=A?.filter(Boolean)??[];if(!N?.length)return[void 0,void 0];if(m<3&&N?.length===2)return A?.slice().sort(ee);let D=Ht(I,N).length!==N?.length;if(N?.length&&D)return N?.length===1?[N[0],void 0]:A?.slice().sort(ee);let R=(E-1)*2;return S.slice(R,R+2).map(b=>A$(b,N))});s[m].drawPositions=T?.flat(),s[m].pairedDrawPositions=T}s[m+1]?.matchUpsCount===s[m].matchUpsCount&&(s[m+1].feedRound=!0,s[m+1].feedRoundIndex=c,s[m].preFeedRound=!0,c+=1),s[m]&&!s[m].feedRound&&(s[m].roundIndex=a,a+=1)});let p=!!Object.values(s).some(({matchUpsCount:m})=>!rn(m));return{hasNoRoundPositions:t.some(m=>!m.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...P}}function Af(t){if(!Array.isArray(t))return"";let e=t.filter(He);return e.length?ct([Math.min(...e),Math.max(...e)]).join("-"):""}function lk({drawDefinition:t,structureId:e,matchUpsMap:r}){let n=at({drawDefinition:t,structureId:e},[zt,Po]);if(n.error)return n;let{structure:o}=tt({drawDefinition:t,structureId:e});if(o?.stage!==je)return{error:hc,info:"Structure is not CONSOLATION stage"};let{links:i}=t,s=i?.filter(m=>m.target.structureId===e)??[],a=s?.reduce((m,l)=>{let{structureId:f}=l.source;return m.includes(f)?m:m.concat(f)},[])??[],c=Object.assign({},...a.map(m=>{let l=Jo({structureId:m,matchUpsMap:r}),g=_e({matchUps:l}).roundProfile;return{[m]:g}})),u=Jo({matchUpsMap:r,structureId:e}),{roundProfile:p}=_e({matchUps:u}),d={};return s?.forEach(m=>{let{structureId:l,roundNumber:f}=m.source,{feedProfile:g,groupedOrder:I,positionInterleave:h,roundNumber:S}=m.target,T=c[l],y=T[1]?.drawPositions,A=T[f]?.matchUpsCount;if(!A)return;let N=A?y.length/A:0,D=y.length/N,R=y.slice(),U=eA({roundPositionsCount:D,groupedOrder:I}),b=U?.length||1;if(b<=D){let x=y.length/b,w=Ae(R,x);g===$i&&w.forEach(F=>F.reverse()),R=U?.length&&U?.map(F=>w[F-1]).flat()||w.flat()}let C=Ae(R,N);if(h){let x=J(0,h.interleave).map(()=>{}),w=J(0,h.offset).map(()=>{});C=C.map(L=>[L,...x]),C.unshift(w),C=C.flat(1);let F=C.length-h.offset;C=C.slice(0,F)}d[S]||(d[S]={});let v=p?.[S]?.feedRound?2:1;C.forEach((x,w)=>{let F=1+w*v;d[S][F]||(d[S][F]=Af(x))})}),{sourceDrawPositionRanges:d}}function Pf({drawDefinition:t}){if(typeof t!="object")return{error:Ua};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:d}){s[c]||(s[c]=[]),a==="0"&&[je,Vt].includes(d)||s[c].push(a);let m=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of m){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 fk({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){let o=at({drawDefinition:t,structureId:r},[zt,Po]);if(o.error)return o;if(!e){let u=Jo({matchUpsMap:n,structureId:r});if({roundProfile:e}=_e({matchUps:u}),!e)return{error:nt}}let s=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,a=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(a??[]).map(u=>{let p=e?.[u]?.matchUpsCount,d=e?.[1]?.drawPositions??[],m=Ae(d,d.length/p),l=m.map(Af),f=m.map(T=>T.map(y=>y-s)).map(Af),g=a.map(T=>{if(T>u)return;let y=e?.[T]?.drawPositions??[];return Ae(y,y.length/p)}).filter(Boolean),I=J(0,p).map(T=>g.map(y=>y[T]).flat().filter(Boolean).sort(ee)).map(T=>ct(T)),h=I.map(T=>kL(T).map(Af).join(", ")),S=Object.assign({},...J(0,p).map(T=>({[T+1]:{firstRoundDrawPositionsRange:l[T],firstRoundOffsetDrawPositionsRange:f[T],possibleDrawPositions:I[T],drawPositionsRange:h[T]}})));return{[u]:S}}))}}var P$=new Set([di,Ki]);function cn(t){return!!t&&P$.has(t)}function Wh({structure:t,matchUps:e}){e=e??t?.matchUps??[];let r=_e({matchUps:e}),n=r.roundProfile,o=r.roundNumbers;if(!n||!o?.length||o.length<2)return!1;let i=[...o].sort((s,a)=>s-a);for(let s=0;s<i.length-1;s++){let a=n[i[s]]?.matchUpsCount??0,c=n[i[s+1]]?.matchUpsCount??0;if(a%2===1&&c%2===0)return!0}return!1}function _c({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){return!r||(n=n??r.matchUps??[],t=t??_e({matchUps:n}).roundsNotPowerOf2,!(!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length))||r?.structures)||e?.drawType&&cn(e.drawType)||!t?!1:Wh({structure:r,matchUps:n})}function De({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?.stage===Qe?t?.structures||t?.structureType===gu&&n?!1:t?.finishingPosition===Ao:!t?.structures&&(!e.length||!r&&!n)}var jh={[$o]:{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:{[j]:"",[Vt]:"P",[rt]:"Q",[je]:"C"}}},gk=jh;function rA({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=_e({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=De({structure:r}),u=_c({structure:r}),p=r.structures,d={},m=jh[$o],l=r.stage===rt,f=l?Math.max(...(e?.structures??[]).filter(_=>_.stage===rt).map(({stageSequence:_})=>_??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||m.affixes.preQualifying)||"",h=t?.roundNamingMap||(m.roundNamingMap??{}),S=t?.abbreviatedRoundNamingMap||(m.abbreviatedRoundNamingMap??{}),T=t?.affixes?.preFeedRound||m.affixes.preFeedRound,y=t?.affixes?.roundNumber||m.affixes.roundNumber,A=(t?.namingConventions||m.namingConventions).round,N=a&&a!==j?a[0]:"",D=t?.stageConstants||m.stageConstants,R=a&&D?.[a]||N,U=`${I}${R}${g}`,b=o?Object.keys(o):[],C=l&&D?.[rt]?`${D?.[rt]}-`:"";if(p||c||u)Object.assign(d,...b.map(_=>{let v=`${C}${A} ${_}`,x=`${y}${_}`;return{[_]:{roundName:v,abbreviatedRoundName:x}}}));else{let _=l&&(t?.qualifyingFinishMap||(m?.qualifyingFinishMap??{}));Object.assign(d,...b.map(v=>{if(!o?.[v])return;let{matchUpsCount:x,preFeedRound:w}=o[v],F=x*2,L=_?.[o?.[v].finishingRound]||_&&`${y}${F}`||h[x]||`${y}${F}`,k=w?`-${T}`:"",G=`${L}${k}`,V=[U,s,G].filter(Boolean).join("-"),$=`${S[x]||`${y}${F}`}${k}`,H=[U,s,$].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:H,roundName:V}}}))}return{roundNamingProfile:d,roundProfile:o,roundMatchUps:i}}function nA({matchUp:t}){if(!t)return{error:nr};if(t&&!t.sides)return{error:mr};if(t&&!t.hasContext)return{error:hp};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===ft).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=ct(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...P}}var Nf="CHECK_IN",Df="CHECK_OUT",N$="SCHEDULE",Ii="SCHEDULE.ASSIGNMENT.VENUE",Hn="SCHEDULE.ALLOCATION.COURTS",Ro="SCHEDULE.ASSIGNMENT.COURT",Ds="SCHEDULE.COURT.ORDER",Us="SCHEDULE.COURT.ANNOTATION",hi="SCHEDULE.DATE",D$="COMPLETED.DATE",xc="HOME_PARTICIPANT_ID",Du="SCHEDULE.ASSIGNMENT.OFFICIAL",Si="SCHEDULE.TIME.SCHEDULED",Ti="SCHEDULE.TIME.START",ja="SCHEDULE.TIME.STOP",Zs="SCHEDULE.TIME.RESUME",Rs="SCHEDULE.TIME.END",Ya="SCHEDULE.TIME.MODIFIERS",Ik="TO_BE_ANNOUNCED",hk="NEXT_AVAILABLE",Sk="FOLLOWED_BY",Tk="AFTER_REST",yk="RAIN_DELAY",U$="NOT_BEFORE",oA=[Ik,hk,Sk,Tk,yk],R$="ELIGIBILITY",b$="REGISTRATION",C$="SUSPENSION",M$="MEDICAL",v$="PENALTY",PC="SCALE",NC="RATING",DC="RANKING",Yh="SEEDING",Xo="PUBLISH",Rr="PUBLIC",Zo="STATUS",O$="MODIFICATION",_$="RETRIEVAL",x$="other",Ek={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:oA,AFTER_REST:Tk,ALLOCATE_COURTS:Hn,ASSIGN_COURT:Ro,ASSIGN_OFFICIAL:Du,ASSIGN_VENUE:Ii,CHECK_IN:Nf,CHECK_OUT:Df,COMPLETED_DATE:D$,COURT_ANNOTATION:Us,COURT_ORDER:Ds,ELIGIBILITY:R$,END_TIME:Rs,FOLLOWED_BY:Sk,MEDICAL:M$,MODIFICATION:O$,NEXT_AVAILABLE:hk,NOT_BEFORE:U$,OTHER:x$,PENALTY:v$,PUBLIC:Rr,PUBLISH:Xo,RANKING:DC,RATING:NC,RAIN_DELAY:yk,REGISTRATION:b$,RESUME_TIME:Zs,RETRIEVAL:_$,SCALE:PC,SCHEDULE:N$,SCHEDULED_DATE:hi,SCHEDULED_TIME:Si,SEEDING:Yh,START_TIME:Ti,STATUS:Zo,STOP_TIME:ja,SUSPENSION:C$,TIME_MODIFIERS:Ya,TO_BE_ANNOUNCED:Ik};function ta({matchUp:t}){if(!t)return{error:nr};if(!t.hasContext)return{error:hp};if(!t.sides||t?.sides.filter(Boolean).length!==2)return{error:mr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=nA({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Nf,Df].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===Nf);e?.forEach((u,p)=>{let d=n?.[p],m=u?.length&&u.every(l=>a.includes(l));d&&m&&!a.includes(d)&&a.push(d)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(d=>{d&&!a.includes(d)&&a.push(d)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...P}}var oe=t=>e=>{let r=St(e)&&e?.matchUpType||wt(e)&&e;return r&&yy[t].includes(r)};function Pm(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 Nm(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 iA({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 Ak({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Nm({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Nm({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Nm({...a,averageMinutes:r,matchUpFormat:o}),d=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return iA({categoryName:i,categoryType:s,timesBlockArray:d})}function Pk({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Pm({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Pm({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Pm({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return iA({categoryName:e,categoryType:r,timesBlockArray:p})}var UC="ADULT",RC="JUNIOR",sA="WHEELCHAIR",qh={[No]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[Ut]:30,default:60}}]},defaultDailyLimits:{[Ct]:2,[Ut]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[kn],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[sA],minutes:{default:120}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:85}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:70}}]},{matchUpFormatCodes:["SET3-S:4NOAD-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB7"],averageTimes:[{categoryNames:[],minutes:{default:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:50}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB5@3"],averageTimes:[{categoryNames:[],minutes:{default:45}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7"],averageTimes:[{categoryNames:[],minutes:{default:40}}]},{matchUpFormatCodes:["SET1-S:5/TB9@4"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6/TB7"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6NOAD"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB7","SET1-S:4/TB5@3","SET3-S:TB10","SET1-S:T20"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:4NOAD"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:TB10"],averageTimes:[{categoryNames:[],minutes:{default:10}}]}],matchUpRecoveryTimes:[{matchUpFormatCodes:["SET3-S:6/TB7","SET3-S:6/TB7-F:TB10","SET3-S:6/TB7-F:TB7"],recoveryTimes:[{categoryTypes:[UC,sA],minutes:{default:60,[Ut]:30}},{categoryTypes:[RC],minutes:{default:60,[Ut]:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7","SET3-S:4/TB7-F:TB10","SET3-S:4NOAD-F:TB7","SET3-S:4/TB7","SET3-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[UC,sA],minutes:{default:30}},{categoryTypes:[RC],minutes:{default:60}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7","SET1-S:5/TB9@4","SET1-S:6/TB7","SET1-S:6NOAD","SET1-S:4/TB7","SET1-S:4NOAD","SET3-S:TB10","SET1-S:T20"],recoveryTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[UC,RC],minutes:{default:30}},{categoryTypes:[sA],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},Nk=qh;var bC="DOUBLES_SINGLES",CC="SINGLES_DOUBLES",fo="total",aA="participantConflict",cA="potentialParticipantConflict",yi="matchUpConflict",MC="courtDoubleBooking",vC="positionLinkConflict",OC="ISSUE_IDS",ea="CONFLICT",ra="WARNING",Uf="ERROR",Rf="ISSUE",$h="STATE",w$="BLOCKED",Kh="PRACTICE",L$="MAINTENANCE",Dk={SINGLES_DOUBLES:CC,DOUBLES_SINGLES:bC,TOTAL:fo,CONFLICT_MATCHUP_ORDER:yi,CONFLICT_PARTICIPANTS:aA,CONFLICT_POTENTIAL_PARTICIPANTS:cA,CONFLICT_COURT_DOUBLE_BOOKING:MC,CONFLICT_POSITION_LINK:vC,SCHEDULE_ISSUE_IDS:OC,SCHEDULE_CONFLICT:ea,SCHEDULE_WARNING:ra,SCHEDULE_ERROR:Uf,SCHEDULE_ISSUE:Rf,SCHEDULE_STATE:$h,BLOCKED:w$,PRACTICE:Kh,MAINTENANCE:L$};function Qp({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:Y};s=s??a?.eventType??Fa;let c=ne(n),u=F$(c),d={averageTimes:[{minutes:{default:u??t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:m}=Oc({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),l=m.policy??qh[No];typeof u=="number"&&l&&(l={...l,defaultTimes:{...l.defaultTimes,averageTimes:[{minutes:{default:u}}]}});let f={...m,policy:l,matchUpFormat:n,categoryType:i,defaultTiming:d};return Dm({eventType:s,timingDetails:f})}function F$(t){if(!t)return;let e=t.matchUpConstraint?.timed?t.matchUpConstraint.minutes:void 0;if(typeof e=="number")return e;let r=t.setFormat?.timed&&typeof t.setFormat.minutes=="number"?t.setFormat.minutes:void 0;if(typeof r!="number")return;let n=t.bestOf??1,o=t.finalSetFormat?.timed&&typeof t.finalSetFormat.minutes=="number"?t.finalSetFormat.minutes:void 0;return n<=1?r:typeof o=="number"?(n-1)*r+o:n*r}function Dm({timingDetails:t,eventType:e}){let r=Pk(t),n=Object.keys(r?.minutes??{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Ak({...t,averageMinutes:o}),s=Object.keys(i?.minutes??{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=oe(Fa)(e)?CC:bC,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function _C(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Ei({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>_C(o)-_C(i)).pop(),n=r&&_C(r);return{itemValue:r?.itemValue,timeStamp:n}}function bf({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ei({timeItems:r?.timeItems??[],itemType:Si});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function na({timeStamp:t,schedule:e,matchUp:r}){let n=r?.schedule?.scheduledDate,{itemValue:o,timeStamp:i}=Ei({timeItems:r?.timeItems??[],itemType:hi}),s=n??o;return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{scheduledDate:s}:e}function Um(t){if(jy.test(t)){let e=nh();return new Date(`${e}T${t}`)}else return new Date(t)}function Uk({matchUp:t}){if(!t)return{error:nr};if(!t.timeItems)return{error:BI};let e=t.timeItems.filter(n=>[Ti,ja,Zs,Rs].includes(n?.itemType)).sort((n,o)=>Um(n.itemValue).getTime()-Um(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 Ti:i=0;break;case Rs:if(n.lastValue&&[Ti,Zs].includes(n.lastType)){let u=Um(o.itemValue).getTime()-Um(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case ja:if([Ti,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=Um(o.itemValue).getTime()-Um(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([Ti,Zs].includes(r.lastType)){let n=new Date().getTime()-Um(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:k$(r.milliseconds),relevantTimeItems:e}}function k$(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 Rk({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===Ti&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function uA(t){return parseInt(t)}function Cf({startTime:t="",endTime:e=""}={}){if(!t||!e||!du.test(t)||!du.test(e))return!1;let[r,n]=t.split(":").map(uA),[o,i]=e.split(":").map(uA);return o<r?!1:!(r===o&&i<n)}function bk(t,e){let[r,n]=t.startTime.split(":").map(uA),[o,i]=e.startTime.split(":").map(uA);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function Jp({dateAvailability:t}){if(!t)return{error:nR};if(!Array.isArray(t))return{error:OI};for(let e of t){if(typeof e!="object")return{error:OI};let{date:r,startTime:n,endTime:o,bookings:i=[]}=e;if(!n||!o)return{error:OI};let s=V$(r);if(s)return s;let a=Mk(n,o);if(a)return a;if(i){let c=B$(i);if(c)return c}}return{valid:!0}}var G$="Dates must be formated => YYYY-MM-DD",Ck="Times must be 24 hour => 00:00";function V$(t){if(t&&!Yo.test(t))return{error:de,dateAvailability:{date:t},info:G$}}function Mk(t,e){if(!du.test(t))return{error:Bs,dateAvailability:{startTime:t},info:Ck};if(!du.test(e))return{error:Bs,dateAvailability:{endTime:e},info:Ck};if(t===e)return{error:Bs,dateAvailability:{startTime:t,endTime:e},info:"startTime and endTime are equivalent"};if(!Cf({startTime:t,endTime:e}))return{error:Bs,dateAvailability:{startTime:t,endTime:e},info:"endTime must be after startTime"}}function B$(t){if(!Array.isArray(t))return{error:kl};for(let e of t){if(typeof e!="object")return{error:kl};let{startTime:r,endTime:n}=e,o=Mk(r,n);if(o)return o}}function pA({tournamentRecord:t}){for(let e of t.venues??[])e.isPrimary&&delete e.isPrimary}function Uu(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:O};let o=Pr(t);r.venueId??=ot();let i;for(let s of Object.values(o)){let a=H$({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||it({topic:GE,payload:{venue:r}}),et({...P,venue:i})}function H$({tournamentRecord:t,disableNotice:e,context:r,venue:n}){let o=at({tournamentRecord:t},[Z]);if(o.error)return o;if(!n)return{error:nt,info:"missing venue"};if(t.venues??=[],n.venueId??=ot(),t.venues.reduce((s,a)=>s||a.venueId===n.venueId,void 0))return{error:NR};if(n.dateAvailability?.length){let s=Jp({dateAvailability:n.dateAvailability});if(s.error)return s}if(n.defaultStartTime||n.defaultEndTime){if(!n.defaultStartTime||!n.defaultEndTime)return{error:O,info:"both defaultStartTime and defaultEndTime are required"};if(!Cf({startTime:n.defaultStartTime,endTime:n.defaultEndTime}))return{error:O,info:"defaultEndTime must be after defaultStartTime"}}return r&&Qt({element:n,extension:{value:r,name:kb}}),n.isPrimary&&pA({tournamentRecord:t}),t.venues.push(n),e||it({payload:{venue:n,tournamentId:t.tournamentId},topic:GE}),{...P,venue:q(n)}}function Wn({tournamentRecords:t,tournamentRecord:e,venueId:r}){let n=at({tournamentRecord:e,venueId:r},[Z,vp]);if(n.error)return n;let i=(e.venues??[]).reduce((s,a)=>a.venueId===r?a:s,void 0);if(!i&&t){let a=(Bp({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=Wn({tournamentRecord:u,venueId:r});if(p.success&&p.venue)return Uu({tournamentRecord:e,venue:p.venue}),{...P,venue:i}}}return i?{...P,venue:i}:{error:ji}}function dA({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Wn({tournamentRecords:r,tournamentRecord:n,venueId:o});return q(i,t,!0)}function Go({tournamentRecords:t,tournamentRecord:e,courtId:r}){let n=at({tournamentRecord:e,courtId:r},[Z,Oo]);if(n.error)return n;let o="findCourt",i,s;if((e.venues??[]).forEach(a=>{(a.courts??[]).forEach(c=>{c.courtId===r&&(i=c,s=a)})}),i)return{...P,court:i,venue:s};if(t){let c=(Bp({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let u of c){let p=t[u],d=Go({tournamentRecord:p,courtId:r});if(d.success)return d.venue&&Uu({tournamentRecord:e,venue:d.venue}),{...P,court:i,venue:s}}}return M({result:{error:So},stack:o})}function mA(t){return q(Go(t),!1,!0)}function Mf({tournamentRecord:t,internalUse:e,courtId:r}){let n=at({tournamentRecord:t,courtId:r},[Z,Oo]);if(n.error)return n;let o=Go({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.court&&(({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:d,surfaceCategory:m,surfaceType:l,surfacedDate:f,pace:g,notes:I})=>({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:d,surfaceCategory:m,surfaceType:l,surfacedDate:f,pace:g,notes:I}))(o.court);return{...P,courtInfo:q(i,!1,e)}}function Ru(t){let e=X(t,[{[Z]:!0},{venueId:!0,[qr]:Hs}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=Wn({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(Mf({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:d})=>({venueAbbreviation:d,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...P,venueData:q(c,!1,!0)}}function vk({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===Rs&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Gt({event:t,eventId:e}){if(!t)return{error:Se};let r=$t({element:t,attribute:"flightProfile",name:Kr}),n=e?q(r,!1,!0):r;return e&&t.drawDefinitions?.forEach(o=>{n?.flights?.forEach(i=>{i.drawId===o.drawId&&Object.assign(i,{drawDefinition:o})})}),{flightProfile:n}}function Ve(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(d=>{i[d.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(d=>{let l=(d?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[d.eventId].tournamentId;else{let g=(d&&Gt({event:d})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[d.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,...M({result:{error:Br},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,...M({result:{error:Cr},context:{drawId:n,eventId:r},stack:o})}}function vf(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:nr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let N=t.drawDefinition||e?.drawDefinitions?.find(R=>R.drawId===p.drawId);!N&&i&&({drawDefinition:N,event:e}=Ve({drawId:p.drawId,tournamentRecord:i}));let D=p.structureId?N?.structures?.find(({structureId:R})=>R===p.structureId):void 0;r=t.matchUpType||D?.matchUpType||N?.matchUpType||e?.eventType!==Ce&&e?.eventType}let{milliseconds:d,time:m}=Uk({matchUp:p}),{startTime:l}=Rk({matchUp:p}),{endTime:f}=vk({matchUp:p}),{eventIds:g,drawIds:I}=n??{},S=(!g||g.includes(p.eventId))&&(!I||I.includes(p.drawId))?W$({tournamentRecord:i,scheduleTiming:a,afterRecoveryTimes:o,matchUpFormat:c,matchUpType:r,matchUp:p,endTime:f,startTime:l,milliseconds:d,time:m}):et({milliseconds:d,startTime:l,endTime:f,time:m}),{scheduledDate:T}=na({matchUp:p}),{scheduledTime:y}=bf({matchUp:p});if(s&&u?.displaySettings?.draws){let N=u.displaySettings.draws,D=(N?.[p.drawId]??N?.default)?.scheduleDetails;if(D){let R=(D.find(U=>T&&U.dates?.includes(T))??D.find(U=>!U.dates?.length))?.attributes;if(R){let U=Object.assign({},...Object.keys(S).map(b=>({[b]:!0})),R);S=Ps({source:S,template:U})}}}let A=p.matchUpStatus&&Rt.includes(p.matchUpStatus)&&(ut(f)||ut(T)||ut(y))||void 0;return{schedule:S,endDate:A}}function W$({tournamentRecord:t,scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,startTime:a,milliseconds:c,time:u}){let p=_=>_.createdAt?new Date(_.createdAt).getTime():0,d=new Map,m=i.timeItems?.toSorted((_,v)=>p(_)-p(v))??[];for(let _ of m)d.set(_.itemType,_.itemValue);let l=i.schedule??{},f=l.homeParticipantId??d.get(xc),g=l.courtAnnotation??d.get(Us),I=l.allocatedCourts??d.get(Hn),h=l.scheduledTime??d.get(Si),S=l.timeModifiers??d.get(Ya),T=l.scheduledDate??d.get(hi),y=l.official??d.get(Du),E=l.courtOrder??d.get(Ds),A=l.venueId??d.get(Ii),N=l.courtId??d.get(Ro),D=j$({scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,scheduledTime:h});!T&&h&&(T=ut(h));let R=Kl({scheduledDate:T,scheduledTime:h}),{venueName:U,venueAbbreviation:b,courtName:C}=Y$({tournamentRecord:t,allocatedCourts:I,venueId:A,courtId:N});return et({typeChangeTimeAfterRecovery:D.typeChangeTimeAfterRecovery,typeChangeRecoveryMinutes:D.typeChangeRecoveryMinutes,timeAfterRecovery:D.timeAfterRecovery,recoveryMinutes:D.recoveryMinutes,averageMinutes:D.averageMinutes,homeParticipantId:f,courtAnnotation:g,venueAbbreviation:b,allocatedCourts:I,scheduledDate:T,scheduledTime:h,isoDateString:R,timeModifiers:S,venueName:U,venueId:A,courtOrder:E,courtName:C,courtId:N,official:y,milliseconds:c,startTime:a,endTime:s,time:u})}function j$({scheduleTiming:t,afterRecoveryTimes:e,matchUpFormat:r,matchUpType:n,matchUp:o,endTime:i,scheduledTime:s}){let a,c,u,p,d,m=o.matchUpType??n;if(t&&s&&e&&m){let l={matchUpFormat:o.matchUpFormat??r,...t};({averageMinutes:c=0,recoveryMinutes:u=0,typeChangeRecoveryMinutes:p=0}=Dm({timingDetails:l,eventType:m})),(c||u)&&(a=i?Yr(Kt(i),u):Yr(s,c+u)),p&&(d=i?Yr(Kt(i),p):Yr(s,c+p))}return{timeAfterRecovery:a,averageMinutes:c,recoveryMinutes:u,typeChangeRecoveryMinutes:p,typeChangeTimeAfterRecovery:d}}function Y$({tournamentRecord:t,allocatedCourts:e,venueId:r,courtId:n}){let o={},i=(t&&r&&Ru({tournamentRecord:t,venueId:r}))?.venueData??{};r&&(o[r]=i);let{venueName:s,venueAbbreviation:a,courtsInfo:c}=i,p=(n&&c?.find(d=>d.courtId===n))?.courtName;for(let d of e??[]){if(!t)break;d.venueId&&!o[d.venueid]&&(o[d.venueId]=Ru({venueId:d.venueId,tournamentRecord:t})?.venueData);let m=o[d.venueId];d.venueName=m?.venueName;let l=m?.courtsInfo?.find(f=>f.courtId===d.courtId);d.courtName=l?.courtName}return{venueName:s,venueAbbreviation:a,courtName:p}}function Ok({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(Uy(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>we(c??[],t.filter(Boolean)))??n,a=o?.feedRound;if(Dy(t)){let c=[...t].sort(ee);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(st(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Rm({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(d=>d.collectionPosition===t&&d.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(d=>d!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function yn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:Y};if(!Array.isArray(r)||r.length>2)return{error:vr};if(!r.length)return M({result:{error:jo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===dt&&Ht(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return M({result:{error:Wt},stack:n});let s=q(o.slice(1),!1,!0);return{participant:q(i),duplicatedPairParticipants:s,...P}}function oa({drawDefinition:t,participantId:e}){return typeof t!="object"?{error:K}:typeof e!="string"?{error:$e}:{lineUp:($t({element:t,attribute:"lineUps",name:po})??{})[e]}}function _k({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:d,lineUp:m,teamParticipant:l})=>{let{assignedParticipantIds:f,substitutions:g}=Rm({collectionPosition:r,collectionId:s,lineUp:m});if(c===Ut){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||yn({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[d]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[d]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[d]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let d=a?.map(m=>{let{teamParticipant:l,sideNumber:f}=m,g=m.lineUp||oa({participantId:l.teamParticipantId,drawDefinition:i})?.lineUp;return u({attribute:f,lineUp:g,teamParticipant:l})}).filter(Boolean)??{};return{sideNumberCollectionAssignment:Object.assign({},...d)}}let p=n?.map(d=>{let m=e.find(I=>I.drawPosition===d)?.participantId,l=a?.find(I=>I?.drawPosition===d),f=l?.teamParticipant||m&&o?.[m]?.participant||t?.find(({participantId:I})=>I===m),g=l?.lineUp||oa({participantId:m,drawDefinition:i})?.lineUp;return u({attribute:d,lineUp:g,teamParticipant:f})}).filter(Boolean)??{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function Of(t){let e=X(t,[{[Cn]:!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===ft&&Ct||s===dt&&Ut||s===bt&&bt||void 0}return{matchUpType:n}}function xk({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,d=u?u[i]?.participantId:c?.participantId,m=c?q$({displaySideNumber:n,seedAssignments:o,participantId:d,assignment:c,sideNumber:a}):{...p?.[a]};if(s&&(a===1?Object.assign(m,{participantFed:!0}):Object.assign(m,{participantAdvanced:!0})),i&&u){let l=u[i]?.teamParticipant,f=u[i]?.participant,g=u[i]?.substitutions;f&&(m.participant=f),g&&(m.substitutions=g),l&&(m.teamParticipant=l)}return m}function q$({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=$$({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 $$({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function Vo(t){let e=t?.embargo;return!e||!ys(e)?!1:new Date(e).getTime()>Date.now()}function go(t){return!!t?.published&&!Vo(t)}function K$({publishStatus:t,drawDefinition:e,structure:r,matchUp:n,schedule:o}){if(!t||!e?.drawId||!r?.structureId)return o;let i=t?.drawDetails?.[e.drawId]?.structureDetails?.[r.structureId];if(!i)return o;let s=n.roundNumber;if(!It(s))return o;let a=i.scheduledRounds?.[s];if(!(a&&Vo(a)))return o}function z$({matchUp:t,collectionDefinition:e,structure:r,drawDefinition:n,event:o,tournamentRecord:i}){return t.processCodes?.length&&t.processCodes||e?.processCodes?.length&&e?.processCodes||r?.processCodes?.length&&r?.processCodes||n?.processCodes?.length&&n?.processCodes||o?.processCodes?.length&&o?.processCodes||i?.processCodes}function xC({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:d,appliedPolicies:m,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,publishStatus:E,scoringActive:A,matchUpTieId:N,isRoundRobin:D,roundProfile:R,sideLineUps:U,structure:b,context:C,matchUp:_,event:v}){c=c??{};let x=tr({drawDefinition:y,structure:b,matchUp:_,event:v})?.tieFormat,{roundOffset:w,structureId:F,structureName:L,stage:k,stageSequence:G}=b,{drawId:V,drawName:B,drawType:$}=y??{},H=x?.collectionDefinitions,z=_.collectionId&&H?.find(io=>io.collectionId===_.collectionId),W=_.collectionId?z?.matchUpFormat:_.matchUpFormat??b?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,Q=_.matchUpType||z?.matchUpType||b?.matchUpType||y?.matchUpType||!oe(Ce)(v?.eventType)&&v?.eventType,pt=l?"BYE":_.matchUpStatus,{schedule:Tt,endDate:Ot}=vf({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:W,publishStatus:E,matchUpType:Q,matchUp:_,event:v});g&&Tt&&(Tt=K$({publishStatus:E,drawDefinition:y,structure:b,matchUp:_,schedule:Tt}));let Et=d??_.drawPositions??[],{collectionPosition:Bt,collectionId:ce,roundPosition:ge}=_,he=_.roundNumber??c.roundNumber,oo=ce?_k({tournamentParticipants:r,positionAssignments:n,collectionPosition:Bt,participantMap:I,drawDefinition:y,drawPositions:Et,collectionId:ce,sideLineUps:U,matchUpType:Q}):void 0,Ln=u?.[he]?.roundName||c.roundName,Fn=u?.[he]?.abbreviatedRoundName||c.abbreviatedRoundName,Ui=R?.[he]?.feedRound,ii=R?.[he]?.preFeedRound,Pa=R?.[he]?.roundFactor,Fs=o?.[he],cp=ge?Fs?.[ge]:void 0,mc=e?.[he],Ol=z?.category?{...C?.category,...z.category}:C?.category??v?.category,lc=z$({matchUp:_,collectionDefinition:z,structure:b,drawDefinition:y,event:v,tournamentRecord:p}),Me=T?.withCompetitiveness&&Xs({...h,matchUp:_}),Ri=_.finishingPositionRange??c.finishingPositionRange,gs=k!==rt&&It(a)&&a+(he||0),fc=io=>et(io,void 0,!0),Nn={...fc(C),...fc({matchUpFormat:Q===Ce?void 0:W,tieFormat:Q===Ce?x:void 0,gender:z?.gender??v?.gender,endDate:_.endDate??Ot,discipline:v?.discipline,category:Ol,finishingPositionRange:Ri,abbreviatedRoundName:Fn,drawPositionsRange:cp,competitiveProfile:Me,structureName:L,stageSequence:G,drawPositions:Et,matchUpStatus:pt,processCodes:lc,isRoundRobin:D,matchUpTieId:N,preFeedRound:ii,matchUpType:Q,roundFactor:Pa,roundOffset:w,structureId:F,roundNumber:he,roundOfPlay:gs,feedRound:Ui,roundName:Ln,drawName:B,drawType:$,schedule:Tt,drawId:V,stage:k}),...q(fc(_),!0,!0)};if(W&&_.score?.scoreStringSide1&&Q$(Nn,W),Array.isArray(Et)){let io=J$({sourceDrawPositionRoundRanges:mc,collectionAssignmentDetail:oo,positionAssignments:n,seedAssignments:f,drawPositions:Et,roundPosition:ge,roundProfile:R,roundNumber:he,onlyDefined:fc,matchUp:_});Object.assign(Nn,q({sides:io},!0,!0))}if(r&&Nn.sides){if(X$({tournamentParticipants:r,hydrateParticipants:i,positionAssignments:n,appliedPolicies:m,drawDefinition:y,participantMap:I,contextProfile:T,matchUpWithContext:Nn,event:v}),!Nn.matchUpType){let{matchUpType:io}=Of({matchUp:Nn});io&&Object.assign(Nn,{matchUpType:io})}t3({contextProfile:T,matchUpWithContext:Nn})}Nn.tieMatchUps&&e3({matchUpWithContext:Nn,abbreviatedRoundName:Fn,roundNumber:he,roundName:Ln,drawPositions:Et,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,appliedPolicies:m,usePublishState:g,publishStatus:E,isRoundRobin:D,roundProfile:R,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:A,structure:b,context:C});let Qc=Nn.sides?.filter(io=>io?.participantId).length===2,up=!Nn.winningSide;if(Object.assign(Nn,{readyToScore:A&&Qc&&up,hasContext:!0}),Qc){let{allParticipantsCheckedIn:io,checkedInParticipantIds:_l}=ta({matchUp:Nn});Object.assign(Nn,{allParticipantsCheckedIn:io,checkedInParticipantIds:_l})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(io=>delete Nn[io]),Nn}function Q$(t,e){let r=ne(e),{bestOf:n,finalSetFormat:o,setFormat:i}=r??{};!o?.tiebreakSet&&!i?.tiebreakSet&&!i?.timed||(t.score.sets=t.score.sets.sort((s,a)=>s.setNumber-a.setNumber).map((s,a)=>{let p=a+1===n&&o?o:i,d=p?.tiebreakSet&&!p?.timed,m=p?.timed;return d?(s.tiebreakSet=!0,[1,2].includes(s.winningSide)&&(s.side1Score=s.winningSide===1?1:0,s.side2Score=s.winningSide===2?1:0)):m&&(s.timed=!0),s}))}function J$({sourceDrawPositionRoundRanges:t,collectionAssignmentDetail:e,positionAssignments:r,seedAssignments:n,drawPositions:o,roundPosition:i,roundProfile:s,roundNumber:a,onlyDefined:c,matchUp:u}){let{orderedDrawPositions:p,displayOrder:d}=Ok({drawPositions:o,roundProfile:s,roundNumber:a}),m=s?.[a]?.feedRound,l=d[0]!==p[0];return p.concat(void 0,void 0).slice(0,2).map((g,I)=>{let h=I+1,S=l?3-h:h,T=xk({...e,positionAssignments:r,displaySideNumber:S,seedAssignments:n,drawPosition:g,isFeedRound:m,sideNumber:h}),y=u.sides?.find(N=>N.sideNumber===h),E=i?(i-1)*2+I+1:void 0,A=E?t?.[E]:void 0;return c({sourceDrawPositionRange:A,...y,...T})})}function X$({tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,participantMap:i,contextProfile:s,matchUpWithContext:a,event:c}){let u=n?.[Ba],p=d=>{let m=i?.[d]?.participant;return m&&Ps({template:u?.participant,source:m})};a.sides.filter(Boolean).forEach(d=>{if(Z$({side:d,getMappedParticipant:p,tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,contextProfile:s,event:c}),d?.participant?.individualParticipantIds?.length&&!d.participant.individualParticipants?.length){let m=d.participant.individualParticipantIds.map(l=>p(l)||(t?li({policyDefinitions:n,tournamentParticipants:t,internalUse:!0,contextProfile:s,participantId:l}):void 0));e!==!1&&Object.assign(d.participant,{individualParticipants:m})}})}function Z$({side:t,getMappedParticipant:e,tournamentParticipants:r,hydrateParticipants:n,positionAssignments:o,appliedPolicies:i,drawDefinition:s,contextProfile:a,event:c}){if(!t.participantId)return;let u=q(e(t.participantId)||(r?li({policyDefinitions:i,participantId:t.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:a}):void 0),void 0,!0);if(!u)return;let p,d;if(s?.entries){let l=s.entries.find(g=>g.participantId===t.participantId),f=c?.entries?.find(g=>g.participantId===t.participantId);p=l?.entryStatus||f?.entryStatus,u.entryStatus=p,l?.entryStage&&(d=l.entryStage,u.entryStage=d)}let m;t.drawPosition&&o&&o.find(f=>f.drawPosition===t.drawPosition)?.extensions?.some(f=>f.name==="luckyAdvancement")&&(m=!0,u.luckyAdvancement=!0),n===!1?Object.assign(t,{participant:{entryStage:d,entryStatus:p,luckyAdvancement:m}}):Object.assign(t,{participant:u})}function t3({contextProfile:t,matchUpWithContext:e}){if(!(t?.inferGender&&(!e.gender||e.gender===Ss)&&e.sides?.length===2&&e.matchUpType!==Ce))return;let n=e.sides.map(o=>{if(oe(Ct)(e.matchUpType))return o.participant?.person?.sex;if(o.participant?.individualParticipants?.length===2){let i=ct(o.participant.individualParticipants.map(s=>s.person?.sex)).filter(Boolean);if(i.length===1)return i[0]}});n.filter(Boolean).length===2&&ct(n).length===1&&(e.inferredGender=n[0])}function e3(t){let{matchUpWithContext:e}=t,r=e.matchUpStatus==="BYE",n=e.sides?.map(({participant:o,drawPosition:i,sideNumber:s,lineUp:a})=>{let c=o?.participantType===Ce&&o;return{teamParticipant:c&&et({participantRoleResponsibilities:c.participantRoleResponsibilities,participantOtherName:c.participantOtherName,participantName:c.participantName,participantId:c.participantId,teamId:c.teamId}),drawPosition:i,sideNumber:s,lineUp:a}});e.tieMatchUps=e.tieMatchUps.map(o=>{let i=e.matchUpId,a={finishingPositionRange:e.finishingPositionRange,abbreviatedRoundName:t.abbreviatedRoundName,roundNumber:t.roundNumber,roundName:t.roundName};return xC({tieDrawPositions:t.drawPositions,scheduleVisibilityFilters:t.scheduleVisibilityFilters,sourceDrawPositionRanges:t.sourceDrawPositionRanges,sideLineUps:n,drawPositionsRanges:t.drawPositionsRanges,initialRoundOfPlay:t.initialRoundOfPlay,roundNamingProfile:t.roundNamingProfile,additionalContext:a,appliedPolicies:t.appliedPolicies,isCollectionBye:r,usePublishState:t.usePublishState,publishStatus:t.publishStatus,matchUpTieId:i,isRoundRobin:t.isRoundRobin,roundProfile:t.roundProfile,matchUp:o,event:t.event,tournamentParticipants:t.tournamentParticipants,positionAssignments:t.positionAssignments,tournamentRecord:t.tournamentRecord,seedAssignments:t.seedAssignments,participantMap:t.participantMap,contextContent:t.contextContent,scheduleTiming:t.scheduleTiming,contextProfile:t.contextProfile,drawDefinition:t.drawDefinition,scoringActive:t.scoringActive,structure:t.structure,context:t.context})})}function wk({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ei({timeItems:r?.timeItems??[],itemType:Hn});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:q(n,!1,!0)}:e}function Lk({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ei({timeItems:r?.timeItems??[],itemType:Ro});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function Fk({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ei({timeItems:r?.timeItems??[],itemType:Ii});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function os(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:d,roundNumbers:m,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:E,tournamentIds:A,matchUpTypes:N,structureIds:D,readyToScore:R,courtIds:U,eventIds:b,venueIds:C,drawIds:_,stages:v}=t,x=Array.isArray(y)?y.filter(Boolean):[],w=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],L=Array.isArray(v)?v.filter(Boolean):[],k=Array.isArray(h)?h.filter(Boolean):[],G=Array.isArray(p)?p.filter(Boolean):[],V=Array.isArray(f)?f.filter(Boolean):[],B=Array.isArray(m)?m.filter(Boolean):[],$=Array.isArray(c)?c.filter(Boolean):[],H=Array.isArray(l)&&I?l.filter(Boolean):[],z=Array.isArray(N)&&g?N.filter(Boolean):[],W=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(C)?C.filter(Boolean):[],pt=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],Tt=Array.isArray(S)&&S.filter(Boolean).length&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],Ot=Array.isArray(A)?A.filter(Boolean):[],Et=Array.isArray(b)?b.filter(Boolean):[],Bt=Array.isArray(_)?_.filter(Boolean):[],ce=Array.isArray(D)?D.filter(Boolean):[];return e.filter(ge=>!(!r3({matchUp:ge,readyToScore:R,hasWinningSide:s,isMatchUpTie:d,isCollectionMatchUp:o})||!n3({matchUp:ge,targetStages:L,targetStageSequences:k,targetCollectionIds:G,targetRoundNames:V,targetRoundNumbers:B,targetRoundPositions:$,targetMatchUpStatuses:w,excludeTargetMatchUpStatuses:F,targetMatchUpIds:H,targetMatchUpTypes:z,targetMatchUpFormats:pt})||!o3({matchUp:ge,targetScheduledDates:Tt,targetCourtIds:W,targetVenueIds:Q})||E&&!i3({matchUp:ge,targetTournamentIds:Ot,targetEventIds:Et,targetDrawIds:Bt,targetStructureIds:ce,targetParticipantIds:x,hasParticipantsCount:n})))}function r3({matchUp:t,readyToScore:e,hasWinningSide:r,isMatchUpTie:n,isCollectionMatchUp:o}){return!(e&&!oe(hr)(t)&&!t.readyToScore||t.winningSide&&r&&![1,2].includes(t.winningSide)||n!==void 0&&(n&&!t.tieMatchUps||!n&&t.tieMatchUps)||o!==void 0&&(o&&!t.collectionId||!o&&t.collectionId))}function n3({matchUp:t,targetStages:e,targetStageSequences:r,targetCollectionIds:n,targetRoundNames:o,targetRoundNumbers:i,targetRoundPositions:s,targetMatchUpStatuses:a,excludeTargetMatchUpStatuses:c,targetMatchUpIds:u,targetMatchUpTypes:p,targetMatchUpFormats:d}){return!(e.length&&!e.includes(t.stage)||r.length&&!r.includes(t.stageSequence)||n.length&&(!t.collectionId||!n.includes(t.collectionId))||o.length&&(!t.roundName||!o.includes(t.roundName))||i.length&&(!t.roundNumber||!i.includes(t.roundNumber))||s.length&&(!t.roundPosition||!s.includes(t.roundPosition))||a.length&&(!t.matchUpStatus||!a.includes(t.matchUpStatus))||c.length&&t.matchUpStatus&&c.includes(t.matchUpStatus)||u.length&&!u.includes(t.matchUpId)||p.length&&(!t.matchUpType||!Gs(p,t.matchUpType))||d.length&&(!t.matchUpFormat||!d.includes(t.matchUpFormat)))}function o3({matchUp:t,targetScheduledDates:e,targetCourtIds:r,targetVenueIds:n}){if(e?.length){let{scheduledTime:o}=bf({matchUp:t}),{scheduledDate:i}=na({matchUp:t}),a=ut(o)||i;if(!e.some(c=>nn(c,a)))return!1}if(r.length){let{courtId:o}=Lk({matchUp:t}),{allocatedCourts:i}=wk({matchUp:t}),s=i?.map(({courtId:a})=>a);if(!r.filter(Boolean).includes(o)||s?.includes(o))return!1}if(n.length){let{venueId:o}=Fk({matchUp:t});if(!n.filter(Boolean).includes(o))return!1}return!0}function i3({matchUp:t,targetTournamentIds:e,targetEventIds:r,targetDrawIds:n,targetStructureIds:o,targetParticipantIds:i,hasParticipantsCount:s}){if(e.length&&!e.includes(t.tournamentId)||r.length&&!r.includes(t.eventId)||n.length&&!n.includes(t.drawId)||o.length&&!o.includes(t.structureId))return!1;let a=t.sides?.map(({participantId:c})=>c).filter(Boolean)??[];return!(s&&a.length<s||i.length&&!i.some(u=>a.includes(u)))}function ht(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:d,contextContent:m,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:Hi,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),E=!S?.length||S.includes(c.structureId),A=!s||!T?.length||T.includes(s.drawId);if(!y||!E||!A)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!m&&(m=lo({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:N}=gt({drawDefinition:s}),D={...t.tournamentAppliedPolicies,...N,...t.policyDefinitions},R=D?.scoring?.structures,U=c.stage&&R?.stage?.[c.stage],b=c.stageSequence&&U?.stageSequence?.[c.stageSequence],C=D?.scoring?.requireAllPositionsAssigned||U?.requireAllPositionsAssigned||b?.requireAllPositionsAssigned;f??=ye({drawDefinition:s,structure:c});let{positionAssignments:_,allPositionsAssigned:v}=pe({structure:c}),x=!C||v,{seedAssignments:w}=Dr({provisionalPositioning:e,drawDefinition:s,structure:c});d=d??w;let{structureId:F}=c;l=l||s&&Pf({drawDefinition:s}).exitProfiles;let L=l?.[F],k=L?.length&&(L[0].split("-").map(W=>Number.parseInt(W)).reduce((W,Q)=>W+Q,0)||0),G=!!c.structures,V=Jo({matchUpsMap:f,structureId:F,inContext:u}),B=D?.[$o],$=rA({roundNamingPolicy:B,drawDefinition:s,structure:c,matchUps:V}),{roundNamingProfile:H,roundProfile:z}=$;if(I=$?.roundMatchUps??[],o){let W=new Set(V.filter(Q=>Array.isArray(Q.tieMatchUps)).map(Q=>Q.matchUpId));V=os({matchUps:W.size?V.filter(Q=>!W.has(Q.matchUpId)):V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1}).concat(W.size?V.filter(Q=>W.has(Q.matchUpId)):[])}return u?V=a3({positionAssignments:_,initialRoundOfPlay:k,roundNamingProfile:H,tournamentRecord:r,appliedPolicies:D,seedAssignments:d,contextContent:m,contextProfile:i,drawDefinition:s,contextFilters:n,scoringActive:x,isRoundRobin:G,roundProfile:z,matchUpsMap:f,structureId:F,structure:c,context:a,params:t,event:p,matchUps:V}):(V=kk(V),i?.withCompetitiveness&&(V=s3({policyDefinitions:t.policyDefinitions,tournamentRecord:r,drawDefinition:s,structure:c,matchUps:V,event:p}))),o&&(V=os({matchUps:V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(V=os({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:V})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=_e({matchUps:V}).roundMatchUps??[]),tr({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=mk({matchUps:V})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:G,roundProfile:z,matchUpsMap:f,matchUps:V}}function kk(t){let e=t?.filter(n=>Array.isArray(n.tieMatchUps)),r=t;return e.forEach(n=>{r=r.concat(...n.tieMatchUps)}),r}function s3({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,matchUps:o,event:i}){let s=XE({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:i});return o.map(a=>{if(a.competitiveProfile||!a.winningSide)return a;let c=Xs({profileBands:s,matchUp:a});return c.error?a:{...a,competitiveProfile:c}})}function a3({positionAssignments:t,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,contextProfile:a,drawDefinition:c,contextFilters:u,scoringActive:p,isRoundRobin:d,roundProfile:m,matchUpsMap:l,structureId:f,structure:g,context:I,params:h,event:S,matchUps:T}){let{sourceDrawPositionRanges:y}=lk({drawDefinition:c,matchUpsMap:l,structureId:f}),E=c?fk({drawDefinition:c,roundProfile:m,matchUpsMap:l,structureId:f}).drawPositionsRanges:void 0,A=h.tournamentParticipants,N=h.participantMap;!A?.length&&!N&&n&&({participants:A=[],participantMap:N}=gi({participantsProfile:h.participantsProfile,useParticipantMap:h.useParticipantMap,policyDefinitions:h.policyDefinitions,tournamentRecord:n,contextProfile:a,inContext:!0}));let D=T.map(R=>xC({scheduleVisibilityFilters:h.scheduleVisibilityFilters,hydrateParticipants:h.hydrateParticipants,afterRecoveryTimes:h.afterRecoveryTimes,usePublishState:h.usePublishState,scheduleTiming:h.scheduleTiming,publishStatus:h.publishStatus,sourceDrawPositionRanges:y,tournamentParticipants:A,positionAssignments:t,drawPositionsRanges:E,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,participantMap:N,contextProfile:a,drawDefinition:c,scoringActive:p,isRoundRobin:d,roundProfile:m,structure:g,context:I,matchUp:R,event:S}));return D=kk(D),u&&(D=os({processContext:!0,...u,matchUps:D})),D}function ia({matchUp:t}){return t?Rt.includes(t?.matchUpStatus)||t?.winningSide:!1}function Xp({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:d,participantMap:m,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structureId:T,inContext:y,structure:E,context:A,event:N}){!E&&T&&({structure:E}=tt({drawDefinition:I,structureId:T}));let D=ht({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:d,participantMap:m,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structure:E,inContext:y,context:A,event:N}),R=[],U=[],b=[],C=[],_=[];if(D.error)return D;let{matchUps:v}=D,{assignedPositions:x}=pe({structure:E}),w=x?.filter(L=>L.participantId).map(L=>L.drawPosition),F;return v.filter(L=>{let k=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===xt;return!(L.matchUpType!==xt&&k)}).forEach(L=>{if(L.matchUpStatus===Lr){R.push(L);return}L.matchUpType===xt&&(F=!0);let k=!!L.collectionId,G=k&&L.sides?.every(Q=>Q.participantId),V=!k&&L.drawPositions?.filter(Boolean).length===2,B=!k&&L.drawPositions?.every(Q=>w?.includes(Q)),$=x?.filter(Q=>Q.bye).map(Q=>Q.drawPosition),H=!k&&L.drawPositions?.find(Q=>$?.includes(Q)),W=_E.includes(L.matchUpStatus)&&(G||V&&(!t||B));return H?_.push(L):ia({matchUp:L})?U.push(L):W?b.push(L):C.push(L)}),{includesTeamMatchUps:F,abandonedMatchUps:R,completedMatchUps:U,upcomingMatchUps:b,pendingMatchUps:C,byeMatchUps:_,structure:E}}function Gk({drawDefinition:t,roundNumber:e,structureId:r}){let n=at({drawDefinition:t,structureId:r},[zt,Po]);if(n.error)return n;let{links:o}=qa({drawDefinition:t,structureId:r}),i=o.source.reduce((a,c)=>!c.source.roundNumber||c.source.roundNumber===e?a.concat(c):a,[]),s=o.target.reduce((a,c)=>!c.target.roundNumber||c.target.roundNumber===e?a.concat(c):a,[]);return{links:{source:i,target:s}}}function lA({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||we(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Ar,pr].includes(o?.linkType)&&!o?.source?.roundNumber?M({result:{error:O},stack:"getTargetLink",context:o}):o}function qa({drawDefinition:t,structureId:e,roundNumber:r}){let n=at({drawDefinition:t,structureId:e},[zt,Po]);return n.error?n:{links:(t.links??[]).filter(Boolean).reduce((s,a)=>(a.source?.structureId===e&&(!r||a.source.roundNumber===r)&&(s.source=s.source.concat(a)),a.target?.structureId===e&&(!r||a.target.roundNumber===r)&&(s.target=s.target.concat(a)),s),{source:[],target:[]})}}function Vk({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 fA({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:AI};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=tt({drawDefinition:n,structureId:i}),{positionAssignments:d}=yt({structure:p}),l=(e?.filter(U=>U.structureId===p?.structureId)).filter(U=>U.roundNumber===c&&!U.matchUpTieId),f=l.length,g=J(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let U=u.offset+(r-1)*u.interleave,b=r+U;h=Math.ceil(b/2),S=1-b%2}let T=g,y=g[h-1],E=eA({roundPositionsCount:g.length,groupedOrder:a}),A=E?.length||1;if(A<=g.length){let U=f/A,b=Ae(g,U);s===$i&&b.forEach(C=>C.reverse()),T=E?.length&&E?.map(C=>b[C-1]).flat()||T}s===Je?y=T[h-1]:s===$i?((!E?.length||A>g.length)&&(h=l.length+1-h),y=T[h-1]):s===dm&&We()&&console.log(jI,{feedProfile:s});let N=y&&l.reduce((U,b)=>b.roundPosition===y?b:U,void 0),D;N?.feedRound?(S=0,D=Math.min(...(N.drawPositions??[]).filter(Boolean))):D=N?.drawPositions?.length===2&&N?.drawPositions[S];let R=d?.find(({drawPosition:U})=>U===D);return R&&$t({element:R,attribute:"disableLinks",name:Fp})?{disabledDrawPosition:D}:{matchUp:N,targetDrawPosition:D,matchUpDrawPositionIndex:S}}function ir({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}=tt({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===As?c3({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):u3({matchUp:i})}function c3({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=Gk({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=lA({source:c,linkType:Ar}),p=lA({linkCondition:Jn,linkType:pr,source:c}),d=lA({source:c,linkType:pr}),m=p&&d;d||(d=p);let l=u?.target?.feedProfile,f=d?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,E,A,N,D,R;if(e&&(i||s)&&(A=i&&l!==ln&&t.find(({matchUpId:C})=>C===i),T=s&&f!==ln&&t.find(({matchUpId:C})=>C===s),A||T))return{matchUp:o,targetLinks:{loserTargetLink:d,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:A}};let{roundPosition:U}=o;R=R||t.filter(C=>C.structureId===n.structureId);let b=R.reduce((C,_)=>_.roundNumber===o.roundNumber&&!_.matchUpTieId?C+1:C,0);return d&&!T&&f!==ln&&({matchUpDrawPositionIndex:E,targetDrawPosition:y,matchUp:T}=fA({targetLink:d,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),m&&g!==ln&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=fA({targetLink:p,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),u&&!A&&l!==ln&&({matchUpDrawPositionIndex:D,targetDrawPosition:N,matchUp:A}=fA({targetLink:u,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),A||(R=R||t.filter(C=>C.structureId===n.structureId),{matchUp:A}=Vk({structureMatchUps:R,matchUp:o})),et({matchUp:o,targetLinks:{loserTargetLink:d,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:D,loserMatchUpDrawPositionIndex:E,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:N,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:A,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function u3({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Hk({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=tt({drawDefinition:t,structureId:i});a?.finishingPosition===Ao?p3({inContextMatchUp:n,structure:a,drawPositions:s}):d3({scheduleConflictMatchUpIds:r,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o})}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function p3({inContextMatchUp:t,structure:e,drawPositions:r}){let{roundNumber:n}=t,o=n&&st(n)+1,i=e.matchUps??[],{roundMatchUps:s}=_e({matchUps:i});if(o&&s?.[o]){let a=[...r].sort(ee).map((c,u)=>{let p=s[o].find(d=>d.drawPositions?.includes(c));return{matchUpId:p?.matchUpId,roundNumber:o,schedule:p?.schedule,sideNumber:u+1,structureName:e.structureName}});Object.assign(t,{sidesTo:a})}}function d3({scheduleConflictMatchUpIds:t,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=ir({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}),{winnerMatchUp:s}=i.targetMatchUps,{loserMatchUp:a}=i.targetMatchUps;!r.winnerMatchUpId&&s&&(r.winnerMatchUpId=s.matchUpId),!r.loserMatchUpId&&a&&(r.loserMatchUpId=a.matchUpId);let c=wC({upcomingMatchUp:s}),u=wC({upcomingMatchUp:a});if(r.matchUpStatus!=="BYE"&&a?.matchUpStatus==="BYE"){let{matchUp:d}=Wk({matchUp:a,drawDefinition:n,inContextDrawMatchUps:e})??{};u=d&&wC({upcomingMatchUp:d})||u}let p=r.schedule?.timeAfterRecovery;p&&(Bk({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:c}),Bk({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:u})),Object.assign(r,{winnerTo:c,loserTo:u}),r.drawPositions?.filter(Boolean).length&&m3({inContextDrawMatchUps:e,inContextMatchUp:r,winnerMatchUp:s,loserMatchUp:a,targetData:i})}function Bk({scheduleConflictMatchUpIds:t,inContextMatchUp:e,timeAfterRecovery:r,upcomingTo:n}){n?.schedule?.scheduledTime&&Yt(n.schedule.scheduledTime)<Yt(r)&&(t[n.matchUpId]=e.matchUpId,n.schedule.scheduleConflict=e.matchUpId)}function m3({inContextDrawMatchUps:t,inContextMatchUp:e,winnerMatchUp:r,loserMatchUp:n,targetData:o}){let s=o.targetLinks?.loserTargetLink?.linkCondition===Jn,a=l3(e);if(!a.length)return;let c=Ah(r?.sides),u=Ah(n?.sides),d=a.find(({participantId:f})=>c.includes(f))?[]:a,l=a.find(({participantId:f})=>u.includes(f))?[]:a;n&&s&&l.length<2&&l.push({bye:!0,tbd:!0}),d?.length&&r&&(!o.targetMatchUpIds&&r&&(r=t.find(({matchUpId:f})=>f===r.matchUpId)),r.potentialParticipants??=[],r.potentialParticipants.push(d)),l?.length&&n&&(o.targetMatchUpIds||(r=t.find(({matchUpId:f})=>f===n.matchUpId)),n.potentialParticipants||(n.potentialParticipants=[]),n.potentialParticipants.push(l))}function l3(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)??[]}function Wk({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==="BYE"){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=ir({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps??{},Wk({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function wC(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 re(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=$a(t);if(r.error)return M({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 $a(t){if(!t?.drawDefinition)return{error:K};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:d,contextFilters:m,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:y,context:E,event:A}=t,N=[],D=[],R=[],U=[],b=[];h&&!r&&(r=lo({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:A}));let C;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:C}=qp({participants:e,participantsProfile:a})));let{structures:_}=hn({drawDefinition:S});if(!_)return{error:Pt};n||(n=ye({drawDefinition:S}));let v=S&&Pf({drawDefinition:S}).exitProfiles;_.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:k=[],upcomingMatchUps:G=[],completedMatchUps:V=[],abandonedMatchUps:B=[]}=Xp({matchUpFilters:T?void 0:l,contextFilters:T?void 0:m,inContext:y||T||m,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:d,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:v,matchUpsMap:n,structure:F,context:E,event:A});N=N.concat(...B),D=D.concat(...V),R=R.concat(...G),U=U.concat(...k),b=b.concat(...L)});let x=F=>(!l&&!T&&!m||(l&&(F=os({matchUps:F,...l})),m&&(F=os({matchUps:F,...m,processContext:!0}))),F),w={abandonedMatchUps:x(N),completedMatchUps:x(D),upcomingMatchUps:x(R),pendingMatchUps:x(U),byeMatchUps:x(b),matchUpsMap:n,...P,groupInfo:C};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:k,upcoming:G,pending:V,bye:B}=F,$=[].concat(...(L&&N)??[],...(k&&D)??[],...(G&&R)??[],...(V&&U)??[],...(B&&b)??[]);Hk({inContextDrawMatchUps:$,drawDefinition:S})}return w}function _n(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:d,contextFilters:m,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:h,event:S}=t;if(!S)return{error:Se};let{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:D,matchUpFormat:R}=S??{},U={...h,...et({indoorOutDoor:S.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:S.surfaceCategory??p?.surfaceCategory,endDate:S.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:R,eventName:y,eventType:A,category:N,eventId:T,gender:D})};E&&(U.endDate=E),f&&!r&&(r=lo({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:S}));let b;if(!e?.length&&!n&&p){let x=gi({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=x.participantMap,e=x.participants??[],b=x.groupInfo}let C=S.drawDefinitions??[],_=Oc({tournamentRecord:p,event:S}).scheduleTiming;return{matchUps:C.flatMap(x=>{let{matchUps:w}=re({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:U,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:d,contextFilters:m,contextProfile:f,drawDefinition:x,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:_,nextMatchUps:g,inContext:I,event:S});return w??[]}),groupInfo:b}}function jt(t){let e=X(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:Y};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:d,contextProfile:m,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,h=t.tournamentId??u.tournamentId,S=u?.events??[];n||({participants:n,participantMap:r}=gi({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:T}=gt({tournamentRecord:u}),y={...I,tournamentId:h,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},E=lo({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:S.flatMap(N=>(y.eventDrawsCount=N.drawDefinitions?.length??0,_n({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:d,contextContent:E,contextFilters:f,contextProfile:m,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:N}).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:kt};let d=Object.keys(n).map(m=>{let l=n[m];return jt({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...P,matchUps:d}}function sa(t,e){return f3(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function f3(t,e){return(ka[t?.stage]||0)-(ka[e?.stage]||0)}function sr(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:d,contextFilters:m,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:D,matchUpFormat:R}=S??{},U={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:R,eventType:A,eventName:y,category:N,eventId:T,endDate:E,gender:D},b;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:b}=gi({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=lo({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...re({context:U,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:m,contextProfile:l,matchUpFilters:d,participantMap:r,nextMatchUps:g,inContext:I,event:S}),groupInfo:b}}var LC=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Qi({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Qi({element:e,accessor:r})?.value}))||(typeof t=="string"&&Qi({element:e,accessor:t}))?.value,Gr=LC;function aa({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Ur(i))return[];let{roundProfile:c,roundNumbers:u=[]}=_e({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,d=p&&c?.[n-p]?.matchUpsCount,m=c&&Object.values(c).map(Gr("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);d&&h&&S===1&&(S=d);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=m?.slice(I-1).reduce((C,_)=>C+(_||0),0),E=a&&I!==1,A=1+t+(E?r??0:0),N=1,D=J(A,s?A+S*2:y+A+N),R=y+N-S,U=l(D.slice(R)),b=l(D.slice(0,R),!0);return T.finishingPositionRange={loser:U,winner:b},{[I]:T}})),g=We({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 bs({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:K};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=re({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];aa({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=ir({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,d=u?.matchUpId,m=p?.matchUpId,f=Jo({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(d&&(n.winnerMatchUpIds[f.matchUpId]=d,Object.assign(f,{winnerMatchUpId:d}),Object.assign(i,{winnerMatchUpId:d})),m&&(n.loserMatchUpIds[f.matchUpId]=m,i.loserMatchUpId=m,f.loserMatchUpId=m,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 en(t){let e=Pr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:zn};if(!Array.isArray(n))return{error:Un};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:Vs};let c={},u={},p={},d={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let m=Object.values(e),f=m.reduce((T,y)=>T.concat(y.events??[]).map(E=>(E.drawDefinitions??[]).map(A=>A.links??[])).flat(1/0),[]).filter(({linkType:T})=>T===fn),g=r;f.length&&(g=un({nextMatchUps:!0,tournamentRecords:e}).matchUps,g3({positionLinks:f,sourceStructureIdMap:p,positionDependencies:c,matchUps:g}));let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},d[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(A=>{u[y].matchUpIds.push(A)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(A=>u[y].participantIds.push(A))},S=T=>{let y=Object.keys(c).length;for(let E of T??[]){let{matchUpId:A,winnerMatchUpId:N,loserMatchUpId:D}=E;if(!a.length||a.includes(A)){if(I(A),o){let{individualParticipantIds:b}=Wp(E);u[A].participantIds=b}N&&(I(N),h(A,N),d[N].push(A)),D&&(I(D),h(A,D),d[D].push(A)),u[A].sources.push(d[A]);let R=d[A].map(b=>u[b].sources[0]).flat(),U=d[A].map(b=>u[b].sources[1]).flat();if(u[A].sources.push(R,U),y){let b=E.containerStructureId||E.structureId,C=p[b];if(c[C])for(let _ of c[C])I(_),h(_,A),d[_].push(A)}}}};if(s)bs({drawDefinition:s}),g?.length||(g=sr({drawDefinition:s}).matchUps),S(g);else{g?.length||(g=un({nextMatchUps:!0,tournamentRecords:e}).matchUps),n.length||(n=I3(m));for(let T of n)h3({matchUps:g,drawId:T,tournamentRecords:e,processMatchUps:S})}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:d,matchUps:g,...P}}function g3({positionLinks:t,sourceStructureIdMap:e,positionDependencies:r,matchUps:n}){let o=t.reduce((i,s)=>{let a=s.source?.structureId,c=s.target?.structureId;return a&&c&&(e[c]=a),a&&!i.includes(a)&&i.push(a),i},[]);for(let i of o)r[i]=[];for(let i of n??[]){let s=i.containerStructureId||i.structureId;o.includes(s)&&r[s].push(i.matchUpId)}}function I3(t){return t?.length?t.map(({events:e=[]})=>e.map(({drawDefinitions:r=[]})=>r.map(({drawId:n})=>n))).flat(1/0):[]}function h3({matchUps:t,drawId:e,tournamentRecords:r,processMatchUps:n}){let o=t?.filter(s=>s.drawId===e).sort(sa);if(!o?.find(({roundPosition:s})=>!s)){let s=o?.find(({tournamentId:c})=>c),{drawDefinition:a}=Ve({tournamentRecord:r[s?.tournamentId],drawId:e});a&&bs({drawDefinition:a})}n(o)}function le(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 Ka({matchUpStatus:t}){return vE.includes(t)}function jk({matchUpStatus:t}){return pf.includes(t)}function zh({matchUpStatus:t}){return OE.includes(t)}function Qh({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(Qh)?.length;return le({score:o})||s||e&&i||t&&jk({matchUpStatus:t})&&![Mt,vt,vn].includes(t)}function is(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=ts({drawDefinition:e}),a=n?s[n]??[]:[],c={isCollectionMatchUp:!1};if(!i){let N=tt({drawDefinition:e,structureId:n});if(N.error)return N;i=r?N.containingStructure??N.structure:N.structure}if(De({structure:i}))return{structure:i,isAdHoc:!0,error:hs};let{matchUps:u}=re({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(N=>N.structureId===n||a.includes(N.structureId)),{matchUpDependencies:d}=en({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),m=[],l=[],f={},g=[];for(let N of u??[]){if(N.structureId===n||a.includes(N.structureId)){l.push(...N.drawPositions??[]);let D=N.roundNumber;for(let R of(N.drawPositions??[]).filter(Boolean))(!f[R]||D&&f[R]>D)&&(f[R]=D)}Qh(N)&&(g.push(N),m.push(N.matchUpId,...d?.[N?.matchUpId]?.matchUpIds??[]))}let I=ct(l.filter(Boolean)).sort(ee),h=ct(m),S=ct(p?.map(({matchUpId:N,drawPositions:D})=>h.includes(N)?D:[]).flat().filter(Boolean)).sort(ee),{positionAssignments:T}=yt({drawDefinition:e,structure:i}),y=T?.filter(N=>N.bye).map(N=>N.drawPosition),E=T?.filter(N=>N.qualifier).map(N=>N.drawPosition),A=I?.filter(N=>!S.includes(N))??[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:E,inactiveDrawPositions:A,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function ca({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(ee)[0]}}var wc={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 gA=[];function Ue(t,e){wt(t)&&(t={method:t}),(e||We())&&gA.push(t)}function S3(t){let e=gA.slice();return t&&(gA.length=0),e}function Yk(t){let r=S3(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(wc).includes(o)?wc[o]:wc.cyan,p=Object.keys(n).filter(m=>!["color","keyColors","method","newline"].includes(m)).map(m=>{let l=i&&Object.keys(i).includes(m)&&wc[i[m]]?wc[i[m]]:wc.brightwhite;return`${wc.white}${m}: ${l}${n[m]}`}).join(", "),d=s?.length<15?" ":" ";return[a?`
|
|
1
|
+
var Gj=Object.defineProperty;var _t=(t,e)=>{for(var r in e)Gj(t,r,{get:e[r],enumerable:!0})};var UL="5.2.3";function bi(){return UL}var cI={};_t(cI,{availabilityGovernor:()=>gw,competitionGovernor:()=>cC,drawsGovernor:()=>EO,entriesGovernor:()=>CO,eventGovernor:()=>WO,generationGovernor:()=>KO,matchUpFormatGovernor:()=>QN,matchUpGovernor:()=>f_,mocksGovernor:()=>yT,officiatingGovernor:()=>Uw,participantGovernor:()=>q_,policyGovernor:()=>Jv,practiceGovernor:()=>ww,publishingGovernor:()=>ex,queryGovernor:()=>TO,rankingGovernor:()=>ET,reportGovernor:()=>px,scheduleGovernor:()=>Dx,scoreGovernor:()=>WS,tieFormatGovernor:()=>wx,tournamentGovernor:()=>tw,venueGovernor:()=>qw});var cC={};_t(cC,{getCompetitionLeaderboard:()=>LE,getCompetitionParticipantState:()=>wE,getCompetitionPolicy:()=>wo,getCompetitionState:()=>Ko,getLinkedTournamentIds:()=>Bp,getTournamentIds:()=>Sm,initializeCompetitionState:()=>eC,linkTournaments:()=>Hb,mutate:()=>sC,processCompetitionMatchUp:()=>Tm,processCompetitionRound:()=>oC,query:()=>aC,resetCompetitionState:()=>iC,unlinkTournament:()=>jb,unlinkTournaments:()=>Wb});var sC={};_t(sC,{initializeCompetitionState:()=>eC,linkTournaments:()=>Hb,processCompetitionMatchUp:()=>Tm,processCompetitionRound:()=>oC,resetCompetitionState:()=>iC,unlinkTournament:()=>jb,unlinkTournaments:()=>Wb});var ks="SINGLES",Ct="SINGLES",si="DOUBLES",Ut="DOUBLES",hr="TEAM",xt="TEAM",Bj="HYBRID",qd="HYBRID",RL={SINGLES_MATCHUP:ks,SINGLES:Ct,DOUBLES_MATCHUP:si,DOUBLES:Ut,TEAM_MATCHUP:hr,TEAM:xt,HYBRID_MATCHUP:Bj,HYBRID:qd};var yy={[Ct]:[Ct,"S"],[Ut]:[Ut,"D"],[xt]:[xt,"T"],[qd]:[qd,"H"],S:[Ct,"S"],D:[Ut,"D"],T:[xt,"T"],H:[qd,"H"]};function ee(t,e){return(t??0)-(e??0)}function st(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function Vr(t){return typeof t=="function"}function wt(t){return typeof t=="string"}function St(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bL(t,e){if(!St(t)||!St(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 Ay(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(St).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var CL=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function Ey(t,e){if(t===void 0)return null;if(!St(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=>Ey(i))}:{[o]:e?n(t[o]):Ey(t[o])}))}function EU(t){return Array.isArray(t)?t.length+t.map(EU).reduce((e,r)=>e+r,0):St(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>EU(t[e])).reduce((e,r)=>e+r,0):0}function ML(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=EU(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function rn(t){return Number.isNaN(Number(t))?!1:t>0&&(t&t-1)===0}function vL(t){if(!t.length)return;let e=[...t].sort(ee),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function OL(t){if(t===1||Number.isNaN(Number(t))||!rn(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function xl(t){return Number.isNaN(Number(t))?0:t%2&&t+1||t}function wl(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function He(t){return!Number.isNaN(Number.parseFloat(t))}function Py(t){let e=st(t);if(!Number.isNaN(e))return e===0?!1:(e&-e)===1}function Ci(t){if(Number.isNaN(Number(t)))return!1;for(;!rn(t);)t++;return t}function pn(t,e,r){return t=Math.ceil(t),e=Math.floor(e),Math.floor((r??Math.random)()*(e-t+1))+t}function It(t){return wt(t)&&!t.trim().length?!1:Number.isSafeInteger(typeof t=="string"?+t:t)}function _L(t=1,e=3,r=!0,n){let o=n??Math.random,i=0;for(let s=0;s<e;s++)i+=o()*(t/e);return r&&t>1?Math.round(i):i}function Hj(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function AU(t,e,r,n,o=2,i){let s=i??Math.random,a=1-s(),c=1-s(),u=Math.sqrt(-2*Math.log(a))*Math.cos(2*Math.PI*c);return u=u/10+.5,u>1||u<0?u=AU(t,e,r,void 0,2,i):(u=Math.pow(u,r),u*=e-t,u+=t),n&&(u=Hj(u,n)),Number.parseFloat(u.toFixed(o))}function SI(t,e=2){return Number.parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function ct(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function xL(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function dr(t,e){if(!Array.isArray(t))return[];let r=e??Math.random;return t.map(n=>[r(),n]).sort((n,o)=>n[0]-o[0]).map(n=>n[1])}function Jc(t){return It(t)?t:1/0}function dn(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function wL(t){return PU(dn(t))}function PU(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function Wj(t,e,r){return r.indexOf(t)===e}function Ny(t){return t.filter(Wj)}function Sr(t,e){return Array.isArray(t)&&t.length?t.splice(Math.floor((e??Math.random)()*t.length),1)[0]:void 0}function Dn(t,e){let r=Math.floor((e??Math.random)()*t.length);return t[r]}function J(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function Is(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function Ht(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 NU(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function we(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function LL(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function FL(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 Ae(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 DU(t,[e,...r]){return t.length?[t.slice(0,e),...DU(t.slice(e),[...r,e])]:[]}function kL(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 Dy(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function Uy(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function TI(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 GL(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return J(r,n+1).filter(o=>!t.includes(o))}function Gs(t,e){return!Array.isArray(t)||!wt(e)?!1:Ht(t,yy[e]).length}var P={success:!0},UU="error",VL={SUCCESS:P,ERROR:UU};function Ry({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!==ct(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...P}}var nF={};_t(nF,{addNotice:()=>it,callListener:()=>Hl,createInstanceState:()=>$R,cycleMutationStatus:()=>XI,deepCopyEnabled:()=>JI,deleteNotice:()=>Vy,deleteNotices:()=>Mi,disableNotifications:()=>JR,enableNotifications:()=>QI,getAuditAuthorityServer:()=>rm,getDevContext:()=>We,getMethods:()=>nm,getNotices:()=>Bl,getPayloads:()=>rF,getProvider:()=>By,getSaveDrawDeletions:()=>em,getSchemaWriteMode:()=>zI,getTopics:()=>rr,getTournamentId:()=>Yi,getTournamentRecord:()=>ZI,getTournamentRecords:()=>Qn,globalLog:()=>tb,handleCaughtError:()=>im,hasTopic:()=>pu,removeTournamentRecord:()=>ZR,setAuditAuthorityServer:()=>QR,setDeepCopy:()=>yp,setDevContext:()=>Tp,setGlobalLog:()=>ZL,setGlobalMethods:()=>tF,setGlobalSubscriptions:()=>TY,setMethods:()=>eF,setSaveDrawDeletions:()=>zR,setSchemaWriteMode:()=>KR,setStateMethods:()=>eb,setStateProvider:()=>hY,setSubscriptions:()=>Gy,setTournamentId:()=>om,setTournamentRecord:()=>XR,setTournamentRecords:()=>Wl,timeKeeper:()=>SY,writeLegacyEnabled:()=>uu,writeNativeEnabled:()=>cu});var by={message:"Chronological error; time violation.",code:"ANACHRONISM"},Ll={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},RU={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},Cy={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},kt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},Y={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Xc={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},Ic={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},Ua={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},K={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},bU={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Cr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Wo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},yI={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},EI={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Zc={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},CU={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},MU={message:"Schedule conflict: court slot already occupied",code:"ERR_SCHEDULE_CONFLICT_DOUBLE_BOOKING"},vU={message:"Schedule conflict: matchUps scheduled outside court availability",code:"ERR_SCHEDULE_CONFLICT_COURT_UNAVAILABLE"},OU={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},jj={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},mp={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},tu={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},eu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},BL={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},hs={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Ra={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Fl={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},$d={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},Yj={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},ru={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Un={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},_U={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},xU={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},wU={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},LU={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},FU={message:"Invalid action",code:"ERR_INVALID_ACTION"},My={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},kU={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},GU={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},VU={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},AI={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},BU={message:"Existing round",code:"ERR_EXISTING_ROUND"},qj={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},mn={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Pt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},PI={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Hi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},NI={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},HU={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},so={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Se={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Br={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},WU={message:"Event exists",code:"ERR_EXISTING_EVENT"},jU={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},YU={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},DI={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},UI={message:"Missing stage",code:"ERR_MISSING_STAGE"},hc={message:"Invalid stage",code:"ERR_INVALID_STAGE"},qU={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},RI={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},$U={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},KU={message:"Lucky draw first round allows at most one BYE",code:"ERR_LUCKY_DRAW_BYE_LIMIT"},vy={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},nu={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},bI={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},HL={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},Sc={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ai={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},zU={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},QU={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},JU={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},ba={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},cr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},Vs={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},be={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},zn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},nr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},mr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},Oy={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Ca={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},$j={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},XU={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},_y={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},ZU={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},xy={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},Kj={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},lp={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},zj={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},tR={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},Qj={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},CI={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},Jj={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},Xj={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},MI={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},nt={message:"Missing value",code:"ERR_MISSING_VALUE"},eR={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},rR={message:"Missing date",code:"ERR_MISSING_DATE"},vI={message:"No valid dates",code:"ERR_NO_VALID_DATES"},kl={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},OI={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},nR={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},de={message:"Invalid Date",code:"ERR_INVALID_DATE"},Bs={message:"Invalid time",code:"ERR_INVALID_TIME"},oR={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},WL={message:"Missing date range",info:"Event or tournament must have start and end dates",code:"ERR_MISSING_DATE_RANGE"},fp={message:"Invalid Time Zone",code:"ERR_INVALID_TIME_ZONE"},gp={message:"Invalid embargo: must be an ISO 8601 datetime with timezone (Z or \xB1HH:MM offset)",code:"ERR_INVALID_EMBARGO"},wy={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},iR={message:"Invalid score",code:"ERR_INVALID_SCORE"},Gl={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var jL={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},_I={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},sR={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Kd={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},aR={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Vl={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Wi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Hr={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},vr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},cR={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Rn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},uR={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Ma={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},va={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},$e={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},pR={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},Wt={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},dR={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},Zj={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},mR={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},jo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},lR={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},fR={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},gR={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Oa={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},zd={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},xI={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},wI={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},Ly={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},YL={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},qL={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},IR={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},hR={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},LI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},FI={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},kI={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},SR={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},TR={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Ip={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},yR={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},So={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},ER={message:"Court exists",code:"ERR_EXISTING_COURT"},Qd={message:"Booking not found",code:"ERR_NOT_FOUND_BOOKING"},AR={message:"An active draft already exists for this draw",code:"ERR_EXISTING_DRAFT"},PR={message:"Existing matchUps conflict with booking",code:"ERR_EXISTING_MATCHUPS"},NR={message:"Venue exists",code:"ERR_EXISTING_VENUE"},ji={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Hs={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},DR={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},UR={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},RR={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},bR={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},$L={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},GI={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},CR={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},VI={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},BI={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},hp={message:"Missing context",code:"ERR_MISSING_CONTEXT"},MR={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},ou={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},vR={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},_a={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},OR={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Jd={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},ci={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},_R={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},vo={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Xd={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Sp={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},O={message:"Invalid values",code:"ERR_INVALID_VALUES"},xR={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},HI={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},wR={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},iu={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},WI={message:"Value unchanged",code:"ABORT_UNCHANGED"},fe={message:"Not found",code:"ERR_NOT_FOUND"},jI={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},LR={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},YI={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},FR={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},kR={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},Fy={message:"Existing stage",code:"ERR_EXISTING_STAGE"},qI={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},su={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},GR={message:"Mutation blocked by active lock",code:"ERR_MUTATION_LOCKED"},VR={message:"Active mutation lock already exists for scope",code:"ERR_EXISTING_MUTATION_LOCK"},BR={message:"Mutation lock not found",code:"ERR_NOT_FOUND_MUTATION_LOCK"},HR={message:"Lock token does not match",code:"ERR_UNAUTHORIZED_LOCK_OPERATION"},WR={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},au={message:"Scores present",code:"ERR_SCORES_PRESENT"},jR={message:"Tournament category is referenced by one or more events",code:"ERR_TOURNAMENT_CATEGORY_IN_USE"},$I={message:"Practice registration not found",code:"ERR_NOT_FOUND_REGISTRATION"},Zd={message:"Booking capacity exceeded",code:"ERR_CAPACITY_EXCEEDED"},KL={ANACHRONISM:by,BOOKING_NOT_FOUND:Qd,CANNOT_CHANGE_WINNING_SIDE:Vl,CAPACITY_EXCEEDED:Zd,REGISTRATION_NOT_FOUND:$I,CANNOT_MODIFY_TIEFORMAT:_I,TOURNAMENT_CATEGORY_IN_USE:jR,CANNOT_MODIFY_PARTICIPANT_TYPE:sR,CANNOT_REMOVE_MAIN_STRUCTURE:RU,CANNOT_REMOVE_PARTICIPANTS:Kd,CATEGORY_MISMATCH:aR,COURT_EXISTS:ER,COURT_NOT_FOUND:So,EXISTING_DRAFT:AR,EXISTING_MATCHUPS:PR,DRAW_DEFINITION_NOT_FOUND:Cr,DRAW_ID_EXISTS:_U,DRAW_POSITION_ACTIVE:eu,DRAW_POSITION_ASSIGNED:Zc,DRAW_POSITION_NOT_CLEARED:OU,DRAW_POSITION_NOT_FOUND:jj,DRAW_SIZE_MISMATCH:Yj,DUPLICATE_ENTRY:Ll,DUPLICATE_VALUE:xR,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:hR,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:IR,EVENT_EXISTS:WU,EVENT_NOT_FOUND:Br,EXISTING_DRAW_DEFINITIONS:bU,EXISTING_END_TIME:UR,EXISTING_FLIGHT:LR,EXISTING_MATCHUP_ID:kR,EXISTING_OUTCOME:FR,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Oa,EXISTING_PARTICIPANT:zd,EXISTING_POLICY_TYPE:xy,EXISTING_PROFILE:YI,EXISTING_ROUND:BU,EXISTING_STAGE:Fy,EXISTING_STRUCTURE:qI,INCOMPATIBLE_MATCHUP_STATUS:bI,INCOMPLETE_SOURCE_STRUCTURE:yI,INSUFFICIENT_DRAW_POSITIONS:kI,INVALID_ACTION:FU,INVALID_ASSIGNMENT:My,INVALID_BOOKINGS:kl,INVALID_CATEGORY:Sp,INVALID_COLLECTION_DEFINITION:_R,INVALID_CONFIGURATION:ci,INVALID_DATE_AVAILABILITY:OI,INVALID_DATE:de,INVALID_DRAW_DEFINITION:Ua,INVALID_DRAW_POSITION_FOR_SEEDING:EI,INVALID_DRAW_POSITION:hs,INVALID_DRAW_SIZE:$d,INVALID_END_TIME:DR,INVALID_ENTRIES:YU,INVALID_EVENT_TYPE:so,INVALID_GAME_SCORES:wy,INVALID_GENDER:Xd,INVALID_MATCHUP_FORMAT:zU,INVALID_MATCHUP_STATUS:Sc,INVALID_MATCHUP_STATUS_BYE:$U,INVALID_MATCHUP:mr,INVALID_OBJECT:vo,INVALID_PARTICIPANT_ID:Hr,INVALID_PARTICIPANT_IDS:vr,INVALID_PARTICIPANT_ROLE:cR,INVALID_PARTICIPANT_SEEDING:xU,INVALID_PARTICIPANT_TYPE:Rn,INVALID_PARTICIPANT:Wi,INVALID_POLICY_DEFINITION:ZU,INVALID_RECORDS:Cy,INVALID_SCALE_ITEM:ou,INVALID_SEED_NUMBER:GU,INVALID_SEED_POSITION:VU,INVALID_SET_NUMBER:Qj,INVALID_SIDE_NUMBER:tR,INVALID_SCORE:iR,INVALID_STAGE:hc,INVALID_START_TIME:bR,INVALID_STRUCTURE:Wo,INVALID_STOP_TIME:RR,INVALID_TIE_FORMAT:ai,INVALID_TIME:Bs,INVALID_TIME_ITEM:GI,INVALID_TOURNAMENT_DATES:oR,INVALID_TOURNAMENT_RECORD:Xc,INVALID_VALUES:O,INVALID_WINNING_SIDE:Gl,LUCKY_DRAW_BYE_LIMIT:KU,MATCHUP_NOT_FOUND:be,METHOD_NOT_FOUND:su,MUTATION_LOCKED:GR,MUTATION_LOCK_EXISTS:VR,MUTATION_LOCK_NOT_FOUND:BR,MISSING_ASSIGNMENTS:DI,MISSING_ASYNC_STATE_PROVIDER:CR,MISSING_AVOIDANCE_POLICY:XU,MISSING_BIRTH_DATE:eR,MISSING_COLLECTION_DEFINITION:JU,MISSING_COURT_ID:MI,MISSING_COURTS_INFO:yR,MISSING_DATE_AVAILABILITY:nR,MISSING_DATE:rR,MISSING_DRAW_DEFINITION:K,MISSING_DRAW_ID:Un,MISSING_DRAW_POSITION:Ra,MISSING_DRAW_POSITIONS:tu,MISSING_DRAW_SIZE:ru,MISSING_ENTRIES:jU,MISSING_EVENT:Se,MISSING_QUALIFIED_PARTICIPANTS:pR,MISSING_MATCHUP_FORMAT:QU,MISSING_MATCHUP_ID:cr,MISSING_MATCHUP_IDS:Vs,MISSING_MATCHUP:nr,MISSING_MATCHUPS:zn,MISSING_PARTICIPANT_COUNT:lR,MISSING_PARTICIPANT_ID:$e,MISSING_PARTICIPANT_IDS:jo,MISSING_PARTICIPANT_ROLE:uR,MISSING_PARTICIPANT:Ma,MISSING_PARTICIPANTS:va,MISSING_PENALTY_ID:TR,MISSING_PENALTY_TYPE:SR,MISSING_PERSON_DETAILS:gR,MISSING_POLICY_ATTRIBUTES:_y,MISSING_POLICY_DEFINITION:Ca,MISSING_POLICY_TYPE:Oy,MISSING_POSITION_ASSIGNMENTS:RI,MISSING_ROUND_NUMBER:qj,MISSING_SCHEDULE:MR,MISSING_SCORING_POLICY:zj,MISSING_SEED_ASSIGNMENTS:kU,MISSING_SEEDCOUNT_THRESHOLDS:LU,MISSING_SEEDING_POLICY:$j,MISSING_SET_NUMBER:Jj,MISSING_SET_OBJECT:CI,MISSING_SIDE_NUMBER:Xj,MISSING_STAGE:UI,MISSING_STRUCTURE_ID:mn,MISSING_STRUCTURE:Hi,MISSING_MAIN_STRUCTURE:NI,MISSING_STRUCTURES:PI,MISSING_TARGET_LINK:AI,MISSING_TIE_FORMAT:ba,MISSING_TIME_ITEM:VI,MISSING_TIME_ITEMS:BI,MISSING_TOURNAMENT_ID:Ic,MISSING_TOURNAMENT_RECORD:Y,MISSING_TOURNAMENT_RECORDS:kt,MISSING_VALUE:nt,MISSING_VENUE_ID:Hs,MODIFICATIONS_FAILED:vR,NO_CANDIDATES:Jd,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:FI,NO_MODIFICATIONS_APPLIED:_a,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:LI,NO_PARTICIPANT_REMOVED:mR,NO_VALID_ACTIONS:wR,NO_VALID_ATTRIBUTES:iu,NO_VALID_DATES:vI,NOT_FOUND:fe,NOT_IMPLEMENTED:jI,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:xI,PARTICIPANT_ID_EXISTS:dR,PARTICIPANT_NOT_CHECKED_IN:fR,PARTICIPANT_NOT_FOUND:Wt,PARTICIPANT_PAIR_EXISTS:Zj,PENALTY_NOT_FOUND:Ip,POLICY_NOT_ATTACHED:Kj,POLICY_NOT_FOUND:lp,SCHEDULE_NOT_CLEARED:CU,SCHEDULE_CONFLICT_DOUBLE_BOOKING:MU,SCHEDULE_CONFLICT_COURT_UNAVAILABLE:vU,SCHEDULED_MATCHUPS:WR,SCORES_PRESENT:au,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:wU,STAGE_SEQUENCE_LIMIT:qU,STRUCTURE_NOT_FOUND:Pt,TEAM_NOT_FOUND:HI,UNABLE_TO_ASSIGN_COURT:OR,UNAUTHORIZED_LOCK_OPERATION:HR,UNLINKED_STRUCTURES:HU,UNRECOGNIZED_DRAW_TYPE:mp,UNRECOGNIZED_MATCHUP_FORMAT:nu,UNRECOGNIZED_MATCHUP_STATUS:vy,VALUE_UNCHANGED:WI,VENUE_EXISTS:NR};var er={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},YR={addNotice:dY,callListener:gY,cycleMutationStatus:pY,deleteNotice:lY,deleteNotices:mY,disableNotifications:tY,enableNotifications:eY,getMethods:tm,getNotices:zL,getPayloads:zL,getTopics:fY,getTournamentId:QL,getTournamentRecord:rY,getTournamentRecords:nY,removeTournamentRecord:aY,setMethods:uY,setSubscriptions:cY,setTournamentId:iY,setTournamentRecord:oY,setTournamentRecords:sY,handleCaughtError:IY};function tY(){er.disableNotifications=!0}function eY(){er.disableNotifications=!1}function QL(){return er.tournamentId}function rY(t){return er.tournamentRecords[t]}function nY(){return er.tournamentRecords}function oY(t){let e=t?.tournamentId;return e?(er.tournamentRecords[e]=t,{success:!0}):{error:Xc}}function iY(t){return t?er.tournamentRecords[t]?(er.tournamentId=t,{success:!0}):{error:Y}:(er.tournamentId=void 0,{success:!0})}function sY(t){er.tournamentRecords=t;let e=Object.keys(t);e.length===1?er.tournamentId=e[0]:e.length||(er.tournamentId=void 0)}function aY(t){if(typeof t!="string")return{error:O};if(!er.tournamentRecords[t])return{error:fe};delete er.tournamentRecords[t];let e=Object.keys(er.tournamentRecords);return e.length===1?er.tournamentId=e[0]:e.length||(er.tournamentId=void 0),{success:!0}}function cY(t){return t.subscriptions===null||Object.keys(t.subscriptions).length===0?(er.subscriptions={},{...P}):typeof t.subscriptions!="object"?{error:O}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?er.subscriptions[e]=t.subscriptions[e]:delete er.subscriptions[e]}),{...P})}function uY(t){return typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(er.methods[e]=t[e])}),{...P})}function pY(){let t=er.modified;return er.modified=!1,t}function dY({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(er.disableNotifications||(er.modified=!0),!(er.disableNotifications||!er.subscriptions[t]&&!n)))return r&&(er.notices=er.notices.filter(o=>!(o.topic===t&&o.key===r))),er.notices.push({topic:t,payload:e,key:r}),{...P}}function tm(){return er.methods??{}}function zL({topic:t}){return er.notices.filter(e=>e.topic===t).map(e=>e.payload)}function mY(){er.notices=[]}function lY({topic:t,key:e}){er.notices=er.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function fY(){return{topics:Object.keys(er.subscriptions)}}function gY({topic:t,payloads:e,notices:r},n){let o=e??r??[],i=er.subscriptions[t];i&&typeof i=="function"&&i(o);let s=n?.[t];s&&typeof s=="function"&&s(o)}function IY({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:QL(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var KI="native",qR="legacy",ky="dual",JL=[KI,ky,qR];var se={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],schemaWriteMode:KI,saveDrawDeletions:!1,auditAuthorityServer:!1,deepCopy:!0},Wr=YR,XL=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function hY(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Ht(Object.keys(t),XL).length!==XL.length)throw new Error("Global state provider is missing required methods");return Wr=t,{success:!0}}function $R(){if(Wr.createInstanceState){try{Wr.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:CR}}function We(t){return!t||typeof t!="object"?se.devContext??!1:typeof se.devContext!="object"?!1:Object.keys(t).every(e=>se.devContext?.[e]===t[e])&&se.devContext}function SY(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(se.timers).filter(o=>o!=="default"||se.timers[o].startTime).map(o=>{let i=se.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:se.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=se.timers[e].state==="stopped"?0:(r-(se.timers[e]?.startTime??0))/1e3,o=se.timers[e].elapsedTime+n;return{state:se.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!se.timers[e]||t==="reset"){if(e==="allTimers")return se.timers={default:{elapsedTime:0}},!0;se.timers[e]={startTime:r,state:"active",elapsedTime:0}}return se.timers[e].elapsedTime||(se.timers[e].elapsedTime=0),t==="stop"&&se.timers[e].state!=="stopped"&&(se.timers[e].state="stopped")&&(se.timers[e].elapsedTime+=(r-(se.timers[e]?.startTime??0))/1e3),t==="start"&&(se.timers[e].startTime=r)&&(se.timers[e].state="active"),se.timers[e]}function ZL(t){Vr(t)?se.globalLog=t:delete se.globalLog}function Tp(t){se.devContext=t}function KR(t){return t===void 0?(se.schemaWriteMode=KI,{...P}):JL.includes(t)?(se.schemaWriteMode=t,{...P}):{error:O}}function zI(){return se.schemaWriteMode}function cu(){return se.schemaWriteMode===KI||se.schemaWriteMode===ky}function uu(){return se.schemaWriteMode===qR||se.schemaWriteMode===ky}function zR(t){return t===void 0?(se.saveDrawDeletions=!1,{...P}):typeof t!="boolean"?{error:O}:(se.saveDrawDeletions=t,{...P})}function em(){return se.saveDrawDeletions}function QR(t){return t===void 0?(se.auditAuthorityServer=!1,{...P}):typeof t!="boolean"?{error:O}:(se.auditAuthorityServer=t,{...P})}function rm(){return se.auditAuthorityServer}function JR(){Wr.disableNotifications()}function QI(){Wr.enableNotifications()}function yp(t,e){typeof t=="boolean"&&(se.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(se.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(se.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(se.deepCopyAttributes.stringify=e.stringify),e.threshold&&(se.deepCopyAttributes.threshold=e.threshold))}function JI(){return{enabled:se.deepCopy,...se.deepCopyAttributes}}function TY(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{se.globalSubscriptions[e]=t.subscriptions[e]}),{...P}):{error:nt,info:"missing subscriptions"}}function Gy(t){return t?.subscriptions?Wr.setSubscriptions({subscriptions:t.subscriptions}):{error:nt,info:"missing subscriptions"}}function tF(t){return t?typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{Vr(t[e])&&(se.globalMethods[e]=t[e])}),{...P}):{error:nt,info:"missing method declarations"}}function eF(t){return t?typeof t!="object"?{error:O}:Wr.setMethods(t):{error:nt,info:"missing method declarations"}}function XI(){return Wr.cycleMutationStatus()}function it(t){if(typeof t?.topic!="string")return;let e=se.globalSubscriptions[t.topic];return Wr.addNotice(t,e)}function nm(){return{...se.globalMethods,...Wr.getMethods()}}function Bl(t){return rF(t)}function rF(t){return typeof Wr.getPayloads=="function"?Wr.getPayloads(t):Wr.getNotices(t)}function Vy({key:t,topic:e}){return Wr.deleteNotice({key:t,topic:e})}function Mi(){return Wr.deleteNotices()}function rr(){return Wr.getTopics()}function pu(t){return rr()?.topics?.includes(t)}async function Hl(t){return Wr.callListener(t,se.globalSubscriptions)}function Yi(){return Wr.getTournamentId()}function ZI(t){return Wr.getTournamentRecord(t)}function Qn(){return Wr.getTournamentRecords()}function XR(t){return Wr.setTournamentRecord(t)}function Wl(t){return Wr.setTournamentRecords(t)}function om(t){return Wr.setTournamentId(t)}function ZR(t){return Wr.removeTournamentRecord(t)}function By(){return Wr}function im({engineName:t,methodName:e,params:r,err:n}){let o=Vr(Wr.handleCaughtError)&&Wr.handleCaughtError||YR.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function tb(t,e){if(se.globalLog)try{se.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),ZL()}else console.log(e,t)}function eb(t,e,r,n){if(!St(t))return{error:O};He||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Vr(a[u])?i[u]=a[u]:St(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?tF(i):eF(i),{methods:i}}function yY(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function et(t,e,r,n){if(typeof t!="object"||t===null)return t;JI()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=yY(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>et(c))}:{[a]:n?t[a]:et(t[a])}))}function M({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&&(e.context??={},Object.assign(e.context,et(t))),e&&!e?.error&&!e?.success&&Object.assign(e,{...P}),e??{success:!0}}var or="FEMALE",ui="OTHER",Ss="MIXED",Le="MALE";var jl={FEMALE_ABBR:"F",OTHER_ABBR:"O",MIXED_ABBR:"X",MALE_ABBR:"M",ANY_ABBR:"A",FEMALE:or,MIXED:Ss,OTHER:ui,MALE:Le,ANY:"ANY"};function Ts(t){return[or,"F"].includes(t)}function xa(t){return[Le,"M"].includes(t)}function jr(t){return[Ss,"X"].includes(t)}function To(t){return["ANY","A"].includes(t)}function lr(t){if(t){if(Ts(t))return or;if(jr(t))return Ss;if(xa(t))return Le;if(To(t))return"ANY"}return ui}function bn(t){return Ts(t)||xa(t)}var NY="MIXED events can not contain mixed singles or { gender: ANY } collections",DY="events with { gender: ANY } can not contain MIXED singles collections";function Yl(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&bn(r)&&lr(r)!==lr(o)?M({result:{valid:!1,error:Xd},context:{gender:o},stack:e}):jr(r)&&(To(o)||jr(o)&&n!==Ut)?M({result:{error:Xd,valid:!1},info:NY,stack:e}):To(r)&&jr(o)&&n!==Ut?M({result:{error:Xd,valid:!1},info:DY,stack:e}):{valid:!0}}var UY="normal",rb="timed",RY="final",th="NOAD";var nb=["SET","HAL","QTR","PER","INN","RND","FRM","MAP","MAT"],Hy="CONSECUTIVE",Wy="TRADITIONAL",bY="game",CY="matchUp",oF={S:UY,F:RY,G:bY,M:CY};function sm(t,e){if(St(t)&&(t?.bestOf||t?.exactly)&&t?.setFormat)return vY(t,e)}function ql(t){return!Number.isNaN(Number(t))&&Number(t)}function aF(t){let e=`T${t.minutes}`;return t.based==="P"&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function MY(t){let e=t?.deuceAfter?`${t.deuceAfter}D`:"";if(t?.type===Wy)return`TN${e}`;if(t?.type===Hy&&Number.isInteger(t.count))return`${t.count}C${e}`}function vY(t,e){let r=ql(t.bestOf)||void 0,n=ql(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return aF(t.setFormat);let i=t.matchRoot||"SET",s=n&&n!==1?"X":"",a=t.aggregate?"A":"",c=o&&`${i}${o}${s}${a}`||"",u=iF(t.setFormat,e),p=u&&`S:${u}`||"",d=iF(t.finalSetFormat,e),m=o&&o>1&&d&&u!==d&&`F:${d}`||"",l=t.gameFormat?`G:${MY(t.gameFormat)}`:"",f=t.matchUpConstraint?.timed?`M:T${t.matchUpConstraint.minutes}`:"";if(c&&u)return[c,p,l,m,f].filter(Boolean).join("-")}function iF(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return aF(t);if(t.outs)return`O${t.outs}`;if(t.tiebreakSet)return sF(t.tiebreakSet);let r=ql(t.setTo);if(r){let n=t.NoAD&&th||"",o=ql(t.winBy),i=sF(t.tiebreakFormat),s=i&&`/${i}`||"",a=o&&o!==2&&!i?`WB${o}`:"",c=ql(t.tiebreakAt),u=c&&(c!==r||e)&&`@${c}`||"";if(i!==!1)return`${r}${n}${a}${s}${u}`}}}function sF(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&ql(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?th:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function ne(t){if(wt(t)){let e=t.startsWith("T")&&rb||nb.some(r=>t.startsWith(r))&&"SET"||"";if(e===rb){let r=dF(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e==="SET")return xY(t)}}function OY(t){let e=nb.find(u=>t.startsWith(u));if(!e)return;let r=t.slice(e.length),n=/^(\d+)([A-Z]*)$/.exec(r);if(!n)return;let o=Ap(n[1]);if(!o)return;let i=n[2],s=!1,a=!1,c=[];for(let u of i)u==="X"?s=!0:u==="A"?a=!0:c.push(u);return{matchRoot:e,count:o,exactly:s,aggregate:a,matchMods:c}}function _Y(t){let e=/^(.+?)(\d+D)$/.exec(t),r=e?e[1]:t,n=e?Number(e[2].slice(0,-1)):void 0;if(n!==void 0&&(n<1||!Number.isInteger(n)))return;if(r==="TN"){let i={type:Wy};return n&&(i.deuceAfter=n),i}let o=/^([1-9]\d*)C$/.exec(r);if(o){let i={type:Hy,count:Number(o[1])};return n&&(i.deuceAfter=n),i}}function xY(t){let e=t.split("-"),r=OY(e[0]);if(!r)return;let{matchRoot:n,count:o,exactly:i,aggregate:s,matchMods:a}=r,c=i&&o!==1?void 0:o,u=i&&o!==1?o:void 0,p,d,m,l,S={setFormat:p,finalSetFormat:d,gameFormat:m,matchUpConstraint:l,sCount:0,fCount:0,gCount:0,mCount:0};for(let T=1;T<e.length;T++)if(!wY(e[T],S))return;return{setFormat:p,finalSetFormat:d,gameFormat:m,matchUpConstraint:l}=S,LY({setFormat:p,finalSetFormat:d,gameFormat:m,matchUpConstraint:l,matchRoot:n,aggregate:s,matchMods:a,bestOf:c,exactly:u})}function wY(t,e){let r=t.indexOf(":");if(r<0)return!1;let n=t.slice(0,r),o=t.slice(r+1);if(!(n in oF))return!1;if(n==="S"){if(e.sCount++,e.sCount>1)return!1;e.setFormat=cF(t,o)}else if(n==="F"){if(e.fCount++,e.fCount>1)return!1;e.finalSetFormat=cF(t,o)}else if(n==="G"){if(e.gCount++,e.gCount>1||(e.gameFormat=_Y(o),!e.gameFormat))return!1}else if(n==="M"&&(e.mCount++,e.mCount>1||(e.matchUpConstraint=HY(o),!e.matchUpConstraint)))return!1;return!0}function LY({setFormat:t,finalSetFormat:e,gameFormat:r,matchUpConstraint:n,matchRoot:o,aggregate:i,matchMods:s,bestOf:a,exactly:c}){let u=t&&t.timed||e&&e.timed;if(o==="SET"&&!(a&&a<6||u&&c)||!t||!(!e||e))return;let m=et({setFormat:t,exactly:c,bestOf:a});return o!=="SET"&&(m.matchRoot=o),i&&(m.aggregate=!0),s.length>0&&(m.matchMods=s),e&&(m.finalSetFormat=e),r&&(m.gameFormat=r),n&&(m.matchUpConstraint=n),m}function cF(t,e){return e.startsWith("TB")?FY(e):e.startsWith("O")?kY(e):e.startsWith("T")?dF(e):GY(t,e)}function FY(t){let e=pF(t);return e===!1?!1:typeof e=="object"?{tiebreakSet:e}:void 0}function kY(t){let e=/^O([1-9]\d*)$/.exec(t);if(e)return{outs:Number(e[1])}}function GY(t,e){let r=/^[FS]:(\d+)([A-Za-z]*?)(WB(\d+))?(?=[/@]|$)/.exec(t),n=r&&mF(r[2])||!1,o=!r?.[2]||n,i=r?Ap(r[1]):void 0,s=r?.[4],a=s?Ap(s):void 0,c=a===void 0||a>=1,u=uF(e),p=u!==!1,d=p&&u||i,m=pF(e.split("/")[1]);return!i||!o||!(m!==!1)||!p||!c||a!==void 0&&m?!1:VY(i,n,m,d,a)}function VY(t,e,r,n,o){let i={setTo:t};return e&&(i.NoAD=!0),r?(i.tiebreakFormat=r,i.tiebreakAt=n):(i.noTiebreak=!0,o!==void 0&&o!==2&&(i.winBy=o)),i}function uF(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Ap(r[1]):r[1])||!1}function pF(t){if(t)return t.startsWith("TB")?BY(t):!1}function BY(t){let e=uF(t,!1),r=/^TB(\d+)([A-Za-z]*)/.exec(t),n=r?.[1],o=r&&mF(r[2]),i=!r?.[2]||o,s=Ap(n);if(!s||!i)return!1;let a={tiebreakTo:s};return e&&typeof e=="string"&&!It(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}function dF(t){let e=t.slice(1),r=/^(\d+)([PG])?(?:\/TB(\d+))?(@[A-Za-z]+)?$/.exec(e),n=Ap(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2];i==="P"?o.based="P":i==="G"&&(o.based="G");let s=r?.[3];if(s){let u=Ap(s);u&&(o.tiebreakFormat={tiebreakTo:u})}let a=r?.[4],c=[void 0,"P","G",""].includes(a);if(a&&!c){let u=/^(\d+)([PGA])?(?:\/TB\d+)?(@)([A-Za-z]+)$/.exec(e)?.[4];return u?(o.modifier=u,o):void 0}return a&&(o.based=a),o}function HY(t){let e=/^T(\d+)$/.exec(t);if(!e)return;let r=Ap(e[1]);if(r)return{timed:!0,minutes:r}}function mF(t){return t?.includes(th)}function Ap(t){let e=Number(t);return Number.isNaN(e)?0:e}function WY(t){return t.replaceAll(/T(\d+)G(?=\/TB|@|-|$)/g,"T$1")}function Or({matchUpFormat:t}){if(!wt(t)||t==="")return!1;let e=ne(t),r=/-S:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),n=r?.[1],o=r?.[2],i=r?.[3],s=/-F:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),a=s?.[1],c=s?.[2],u=s?.[3];return sm(e,!!(r&&o&&n===i||s&&c&&a===u))===WY(t)}var am=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/,jy=/^((0\d|1\d|2[0-3]):[0-5]\d(:[0-5]\d)?)([.,]\d{3})?$/,Yo=/^(\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?$/,du=/^(\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 Kl(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=ut(t.scheduledTime)),!e)return;let r=Kt(t.scheduledTime),n=ut(e);return n&&r&&(n+=`T${r}`),n}function lF(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function cm(t){let e=typeof t=="string"?t?.split(" "):[];if(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))return!1;let r=Pp(t,!0,!0);return!!(!t||r&&du.test(r))}function Fe(t){return ys(t)||am.test(t)}function jY(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+3600*e.getHours();return YY(r,{displaySeconds:!1})}function YY(t,e){let r=Number.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(yo).join(":")}var nh=t=>{let e=eh(t)||ys(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${yo(n)}-${yo(e.getUTCDate())}`};function qY(t){let e=eh(t)||ys(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function ao(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&!t.includes("T")&&(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 Yy(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function $Y(t){return Yy(t).getTime()}function eh(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!Number.isNaN(Number(t))&&new Date(t)||!1;return e&&!Number.isNaN(Number(e.valueOf()))}function KY(t,e){return t<=e}function wa(t,e){if(!Fe(t)||!Fe(e))return[];let r=ut(t)+"T00:00",n=ut(e)+"T00:00",o=new Date(r),i=new Date(n),s=eh(i)&&eh(o)&&KY(o,i),a=[],c=0;if(s){let u=o,p=u.getTime();for(;p<=i.getTime()&&c<300;)c+=1,a.push(new Date(u)),p=u.setDate(u.getDate()+1)}return a.map(u=>ao(u))}var zY=/^([+-]?\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 ys(t){return typeof t!="string"?!1:zY.test(t)}function La(t){return typeof t!="string"||!ys(t)?!1:/([zZ]|[+-]\d{2}:?\d{2})$/.test(t)}function $y(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!Number.isNaN(Number.parseInt(i)));return!(r.length<2||!n||Number.parseInt(r[0])>23||Number.parseInt(r[1])>60)}function Yt(t){let e=Kt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>Number.parseInt(o));return r*60+n}function fF(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[yo(e),yo(r)].join(":")}function rh(t){return $y(t)?t.split(":").slice(0,2).map(yo).join(":"):void 0}function Kt(t){return ys(t)&&t.indexOf("T")>0?rh(t.split("T").reverse()[0]):rh(t)}function ut(t){return ys(t)||Yo.test(t)?t.split("T")[0]:""}function um(t,e){let r=new Date(t);return r.setUTCDate(r.getUTCDate()+e),ut(r.toISOString())}function qy(t){t=typeof t=="string"?t:"00:00";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,Number.isNaN(Number.parseInt(r.hours))||Number.isNaN(Number.parseInt(r.minutes))||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function QY(t){let e=qy(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&Number.parseInt(e.hours)<12&&(e.hours=(e.hours&&Number.parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(yo).join(":")}function JY(t){let e=qy(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 Pp(t,e,r){let n=ut(t),o=Kt(t),i=n?o:t;return t?e&&(n&&r&&t||QY(i))||JY(i):void 0}function Ky(t,e){let r=qy(t),n=qy(e);if(Number.parseInt(r.hours)<Number.parseInt(n.hours))return-1;if(Number.parseInt(r.hours)>Number.parseInt(n.hours))return 1;if(r.hours===n.hours){if(Number.parseInt(r.minutes)<Number.parseInt(n.minutes))return-1;if(Number.parseInt(r.minutes)>Number.parseInt(n.minutes))return 1}return 0}function zy(t,e=7){let r=ut(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return ao(o)}function XY(t){return zy(t)}function ZY(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())),ao(o,r)}function gF(t,e,r){let n=new Date(t,0);return ao(new Date(n.setDate(e)),r)}function ke(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(yo),o=Yy(e).setHours(r,n,0,0);return Yy(o)}function Ws(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=Kt(t);if(!r)return"00:00";let n=Number.isNaN(e)?0:e;return Kt(oh(ke(r),n).toISOString())||"00:00"}function oh(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function yo(t){return t.toString()[1]?t:"0"+t}function nn(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 Qy={addDays:zy,addWeek:XY,addMinutesToTimeString:Yr,convertTime:Pp,getIsoDateString:Kl,getUTCdateString:nh,DateHHMM:jY,extractDate:ut,extractTime:Kt,formatDate:ao,getDateByWeek:ZY,isISODateString:ys,isValidEmbargoDate:La,isDate:eh,isTimeString:$y,offsetDate:Yy,offsetTime:$Y,sameDay:nn,timeStringMinutes:Yt,timeToDate:ke,timeUTC:qY,validTimeValue:cm,validDateString:am,timeValidation:du,dateValidation:Yo};var tq=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),eq=t=>t.filter(Boolean).every(He);function zl(t,e){return`${t}-${e}`}function Es(t){let e=t.category;if(typeof e!="object"||!e)return{error:Sp};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(tq([r,n,o,a],"string")&&eq([i,s])&&[n,o].filter(Boolean).every(Fe)))return{error:Sp};let p=t.consideredDate??ut(new Date().toLocaleDateString("sv"));if(!p||!Fe(p))return{error:de};let[d]=p.split("-").slice(0,3).map(B=>Number.parseInt(B)),m=um(p,-1);if(!m)return{error:de};let[l,f]=m.split("-").slice(1,3).map(B=>Number.parseInt(B)),g=`${yo(l)}-${yo(f)}`,I=um(p,1);if(!I)return{error:de};let[h,S]=I.split("-").slice(1,3).map(B=>Number.parseInt(B)),T=`${yo(h)}-${yo(S)}`,y=s&&um(p,-1*365*s),E=i&&um(p,-1*365*i),A=[],N=B=>!A.includes(B)&&A.push(B);r=r??a;let D=/^([UO]?)(\d{1,2})([UO]?)$/,R=/^C(\d{1,2})-(\d{1,2})$/,U=r?.includes("-"),b=U&&r?.match(R),C=r?.match(D);function _(B){let $=d-B,H=zl($,T);e.ageMinDate&&e.ageMinDate!==H&&N(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==B-1&&(N(`Invalid submitted ageMax: ${i}`),E=void 0),i=B-1)}function v(B){let $=d-B-1,H=zl($,T);e.ageMin&&e.ageMin>B&&N(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>B&&N(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&N(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==B&&(N(`Invalid submitted ageMax: ${i}`),y=void 0),i=B)}function x(B){let $=d-B,H=zl($,g);e.ageMaxDate&&e.ageMaxDate!==H&&N(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==B+1&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B+1)}function w(B){let $=d-B-1,H=zl($,g);e.ageMaxDate&&e.ageMaxDate!==H&&N(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==B&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B)}function F(B){let $=D.exec(B)??[],[H,z,W]=$.slice(1),Q=Number.parseInt(z);H==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),_(Q)):H==="O"&&x(Q),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(Q)):W==="O"&&w(Q),n=(n??y)||void 0,o=(o??E)||void 0}function L(){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=d-e.ageMin;n=zl(H,g)}if(e.ageMax){let H=d-e.ageMax-1;o=zl(H,T)}let[B,$]=(r?.match(R)??[]).slice(1).map(H=>Number.parseInt(H));B<=$?(s=B,i=$,c=!0):N(`Invalid combined age range ${r}`)}function k(){s&&x(s),i&&v(i)}function G(){b?L():U?r?.split("-").forEach(F):C&&r?F(r):k()}G(),i&&e?.ageMin&&e?.ageMin>i&&(N(`Invalid submitted ageMin: ${e?.ageMin}`),s=void 0);let V=et({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return A.length&&(V.errors=A),V}function Np({category:t}){if(!St(t))return{error:O};let e=Es({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!He(r)?M({result:{error:O},context:{ratingMax:r}}):n&&!He(n)?M({result:{error:O},context:{ratingMin:n}}):{...e}}function Dp({childCategory:t,withDetails:e,category:r}){let n=Np({category:r}),o=Np({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),d=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=et({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:d,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!d&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function Up({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}`),M({result:{errors:c,error:vo},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:d,collectionId:m,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:y}=e;if(r&&typeof m!="string"&&c.push(`collectionId is not type string: ${m}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Gs([Ct,Ut,qd],I)&&c.push(`matchUpType must be SINGLES, DOUBLES, or HYBRID: ${I}`),[!!u?.length].concat([g,d,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}`),d&&typeof d!="number"&&c.push(`collectionValue is not type number: ${d}`),u&&l){let A=Ry({collectionValueProfiles:u,matchUpCount:l});A.errors&&c.push(...A.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${d}`),f&&!Or({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let A=Yl({referenceGender:i,matchUpType:I,gender:y});if(A.error)return M({context:{referenceGender:i,gender:y},result:A,stack:a})}if(t&&o&&T){let A=Dp({category:o,childCategory:T});if(!A.valid)return M({result:{error:Sp},context:A,stack:a})}return c.length?M({result:{errors:c,error:_R},stack:a}):{valid:!0}}function ur(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=rq({...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:E}=Up({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(E)&&a.push(...E),!1)}),d=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(d||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),M({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:ai},stack:s});let m=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||m.length===ct(m).length,f=p&&d&&l,g={valid:f,errors:a};return f?g:M({result:{error:ai},context:{tieFormat:o,errors:a},stack:s})}function rq(t){let{tieFormat:e,stack:r}=t;return!t||!e||!St(e)?M({result:{error:ai},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):St(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...P}:M({result:{error:ai},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):M({result:{error:ai},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var Ql="resourceSubType",Jl="resourceType",mu="identifier",Jy="name",IF={RESOURCE_SUB_TYPE:Ql,RESOURCE_TYPE:Jl,IDENTIFIER:mu,NAME:Jy};function q(t,e,r,n,o=0){if(By().makeDeepCopy)return By().makeDeepCopy(t,e,r,n);let i=JI(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i??{};if(!i?.enabled&&!r||typeof t!="object"||Vr(t)||t===null||typeof i?.threshold=="number"&&o>=i.threshold)return t;let p=Array.isArray(t)?[]:{},d=Object.keys(t).filter(l=>!r||!c||Array.isArray(c)&&!c.includes(l)||Vr(c)&&!c(l)),m=(l,f)=>{p[l]=Vr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of d){let f=t[l],g=Vr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=ih(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?m(l,f):Array.isArray(a)&&a.includes(l)&&Vr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:lF(f)?p[l]=new Date(f).toISOString():p[l]=q(f,e,r,n,o+1)}return p}function ih(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function Xy(t=1,e,r){return J(0,t).map(()=>ot(e,r))}function ot(t,e){let r=e??Math.random,n=[];for(let u=0;u<256;u++)n[u]=(u<16?"0":"")+u.toString(16);let o=Math.trunc(r()*4294967295),i=Math.trunc(r()*4294967295),s=Math.trunc(r()*4294967295),a=Math.trunc(r()*4294967295),c=n[o&255]+n[o>>8&255]+n[o>>16&255]+n[o>>24&255]+"-"+n[i&255]+n[i>>8&255]+"-"+n[i>>16&15|64]+n[i>>24&255]+"-"+n[s&63|128]+n[s>>8&255]+"-"+n[s>>16&255]+n[s>>24&255]+n[a&255]+n[a>>8&255]+n[a>>16&255]+n[a>>24&255];return typeof t=="string"?`${t}_${c.replaceAll("-","")}`:c}var Zy={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 tE={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 eE={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 rE={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 nE={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 oE={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 iE={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:"Brewer Cup",winCriteria:{valueGoal:4}};var sE={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 kn="SET3-S:6/TB7",dq="SET3-S:6NOAD",ob="SET3-S:6NOAD/TB7-F:TB10",mq="SET3-S:4/TB7",lq="SET3-S:4/TB5@3",fq="SET5-S:6/TB7",gq="SET1-S:6/TB7",Iq="SET1-S:TB10",hq="SET3-S:6/TB7-F:TB7",Sq="SET1-S:T20",Tq="SET1-S:8/TB7",yq="SET1-S:8/TB7@7",hF={FORMAT_STANDARD:kn,FORMAT_STANDARD_NOAD:dq,FORMAT_ATP_DOUBLES:ob,FORMAT_SHORT_SETS:mq,FORMAT_FAST4:lq,FORMAT_GRAND_SLAM:fq,FORMAT_ONE_SET:gq,FORMAT_MATCH_TIEBREAK:Iq,FORMAT_SET3_TB7:hq,FORMAT_PRO_SET:Tq,FORMAT_COLLEGE_PRO_SET:yq,TIMED20:Sq};var aE={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 cE={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 Collegiate",winCriteria:{valueGoal:4}};var uE={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 pE={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:"World Team Tennis ITT",winCriteria:{aggregateValue:!0}};var SF={tieFormatName:"INTENNSE 2026",winCriteria:{aggregateValue:!0},collectionDefinitions:[{collectionId:"intennse-ms",collectionName:"Men's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MS"}},{collectionId:"intennse-ws",collectionName:"Women's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WS"}},{collectionId:"intennse-md",collectionName:"Men's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MD"}},{collectionId:"intennse-wd",collectionName:"Women's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WD"}},{collectionId:"intennse-xd",collectionName:"Mixed Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MIXED",category:{categoryName:"XD"}}]};var dE={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 mE={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/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:6NOAD/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:6NOAD/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 lE={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 Tennis on Campus",winCriteria:{aggregateValue:!0}};var sh="COLLEGE_DEFAULT",ib="COLLEGE_JUCO",sb="COLLEGE_D3",ab="DOMINANT_DUO",cb="DOMINANT_DUO_MIXED",ub="INTENNSE_2026",pb="LAVER_CUP",db="TEAM_DOUBLES_3_AGGREGATION",mb="USTA_BREWER_CUP",lb="USTA_OZAKI_CUP",fb="USTA_COLLEGE",gb="USTA_GOLD_TEAM_CHALLENGE",Ib="USTA_LEVEL_1",hb="USTA_INTERSECTIONAL",Sb="USTA_SECTION_BATTLE",Tb="USTA_SOUTHERN_LEVEL_5",yb="USTA_TOC",Eb="USTA_WTT_ITT",Ab="USTA_ZONAL",TF={COLLEGE_D3:sb,COLLEGE_DEFAULT:sh,COLLEGE_JUCO:ib,DOMINANT_DUO:ab,DOMINANT_DUO_MIXED:cb,INTENNSE_2026:ub,LAVER_CUP:pb,TEAM_DOUBLES_3_AGGREGATION:db,USTA_BREWER_CUP:mb,USTA_OZAKI_CUP:lb,USTA_COLLEGE:fb,USTA_GOLD_TEAM_CHALLENGE:gb,USTA_INTERSECTIONAL:hb,USTA_LEVEL_1:Ib,USTA_SECTION_BATTLE:Sb,USTA_SOUTHERN_LEVEL_5:Tb,USTA_TOC:yb,USTA_WTT_ITT:Eb,USTA_ZONAL:Ab};var EF="STANDARD",yF={[EF]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[sb]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:kn,matchUpCount:6,matchUpValue:1},tieFormatName:"College D3",valueGoal:5},[sh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:kn,matchUpCount:6,matchUpValue:1},tieFormatName:"College Default",valueGoal:4},[ib]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:kn,matchUpCount:6,matchUpValue:1},tieFormatName:"College JUCO",valueGoal:5},[pb]:mE,[ab]:aE,[cb]:oE,[ub]:SF,[db]:tE,[mb]:iE,[lb]:sE,[fb]:cE,[gb]:Zy,[hb]:nE,[Ib]:uE,[Sb]:rE,[Tb]:eE,[Eb]:pE,[yb]:lE,[Ab]:dE},Cq=t=>{let e=t?.namedFormat&&Object.keys(yF).includes(t.namedFormat)?t.namedFormat:EF,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=q(yF[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??ot();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:ob,collectionName:"Doubles",matchUpType:Ut,...s.doubles},{collectionId:a(1),matchUpFormat:kn,collectionName:"Singles",matchUpType:Ct,...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},Eo=Cq;var ue="SINGLES",Fa="SINGLES",Xt="DOUBLES",pi="DOUBLES",Ce="TEAM",Tr="TEAM",Tc="HYBRID",ah="HYBRID";var Mq="RATING",vq="BOTH",AF={AGE:"AGE",BOTH:vq,DOUBLES:Xt,DOUBLES_EVENT:pi,HYBRID:Tc,HYBRID_EVENT:ah,RATING:Mq,SINGLES:ue,SINGLES_EVENT:Fa,TEAM_EVENT:Tr,TEAM:Ce};var j="MAIN",rt="QUALIFYING",je="CONSOLATION",Qe="VOLUNTARY_CONSOLATION",Vt="PLAY_OFF",lu=[j,rt,je,Vt,Qe],ka={[rt]:1,[j]:2,[Vt]:3,[je]:3,[Qe]:4},Pb="finishingPositions",Nb="aggregateEventStructures",Db={[j]:1,[Vt]:2,[je]:3,[rt]:4,[Qe]:5},PF={[Vt]:1,[j]:2,[je]:3,[rt]:4,[Qe]:5},fu="CLUSTER",pm="ADJACENT",Ub="SEPARATE",qi="WATERFALL",gu="ITEM",Ie="CONTAINER",ln="DRAW",dm="RANDOM",Je="TOP_DOWN",$i="BOTTOM_UP",fn="POSITION",Ar="WINNER",pr="LOSER",Jn="FIRST_MATCHUP",vi="AD_HOC",Oq="AD_HOC",yc="FEED_IN",js="COMPASS",Rp="OLYMPIC",_q="SINGLE_ELIMINATION";var on="SINGLE_ELIMINATION",Ys="DOUBLE_ELIMINATION",qs="FIRST_MATCH_LOSER_CONSOLATION",Ga="FIRST_ROUND_LOSER_CONSOLATION",di="LUCKY_DRAW",Ki="ADAPTIVE",ch="CURTIS_CONSOLATION",NF="CURTIS_CONSOLATION",fE="FEED_IN_CHAMPIONSHIP_TO_SF",bp="FEED_IN_CHAMPIONSHIP_TO_SF",gE="FEED_IN_CHAMPIONSHIP_TO_QF",Cp="FEED_IN_CHAMPIONSHIP_TO_QF",IE="FEED_IN_CHAMPIONSHIP_TO_R16",Xl="FEED_IN_CHAMPIONSHIP_TO_R16",Rb="MODIFIED_FEED_IN_CHAMPIONSHIP",Zl="MODIFIED_FEED_IN_CHAMPIONSHIP",mm="FEED_IN_CHAMPIONSHIP",lm="PAGE_PLAYOFF",fm="PLAYOFF",$s="SWISS",xq={0:{name:"Qualifier 1",abbreviation:"Q1"},"0-1":{name:"Eliminator",abbreviation:"EL"},"0-2":{name:"Final",abbreviation:"F"}},hE="DOUBLE_ROUND_ROBIN",_r="ROUND_ROBIN",sn="ROUND_ROBIN_WITH_PLAYOFF",bb="DECIDER",Cb="BACKDRAW",uh={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"}},ph={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},dh={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"}},Ao="WIN_RATIO",As="ROUND_OUTCOME",Mb=[Ki,js,ch,Cp,Xl,bp,mm,gE,IE,fE,qs,Ga,di,Zl,Rp,lm,fm,sn],wq=[vi,Ki,js,ch,Ys,Cp,Xl,bp,mm,yc,qs,Ga,di,Zl,Rp,lm,fm,_r,sn,on,$s],vb={MAIN:j,QUALIFYING:rt,CONSOLATION:je,ITEM:gu,CONTAINER:Ie,FIRST_MATCHUP:Jn,WINNER:Ar,LOSER:pr,AD_HOC:vi,FEED_IN:yc,FLEX_ROUNDS:Oq,COMPASS:js,PLAY_OFF:Vt,PAGE_PLAYOFF:lm,PAGE_PLAYOFF_ATTRIBUTES:xq,PLAYOFF:fm,SWISS:$s,OLYMPIC:Rp,KNOCKOUT:_q,SINGLE_ELIMINATION:on,DOUBLE_ELIMINATION:Ys,CURTIS:ch,FICSF:fE,FICQF:gE,FICR16:IE,MFIC:Rb,VOLUNTARY_CONSOLATION:Qe,FIRST_MATCH_LOSER_CONSOLATION:qs,FIRST_ROUND_LOSER_CONSOLATION:Ga,MODIFIED_FEED_IN_CHAMPIONSHIP:Zl,FEED_IN_CHAMPIONSHIP_TO_R16:Xl,FEED_IN_CHAMPIONSHIP_TO_QF:Cp,FEED_IN_CHAMPIONSHIP_TO_SF:bp,FEED_IN_CHAMPIONSHIP:mm,LUCKY_DRAW:di,ADAPTIVE:Ki,ROUND_ROBIN_WITH_PLAYOFF:sn,ROUND_ROBIN:_r,DECIDER:bb,BACKDRAW:Cb,COMPASS_ATTRIBUTES:uh,OLYMPIC_ATTRIBUTES:ph,ADAPTIVE_ATTRIBUTES:dh,DRAW:ln,RANDOM:dm,TOP_DOWN:Je,BOTTOM_UP:$i,CLUSTER:fu,ADJACENT:pm,SEPARATE:Ub,WATERFALL:qi,WIN_RATIO:Ao,ROUND_OUTCOME:As,MULTI_STRUCTURE_DRAWS:Mb,generatedDrawTypes:wq,stageOrder:ka,finishOrder:Db,AGGREGATE_EVENT_STRUCTURES:Nb,FINISHING_POSITIONS:Pb},DF=vb;var Ne="tournamentRecords",mh="policyDefinitions",Z="tournamentRecord",SE="onlineResource",zt="drawDefinition",TE="tieFormatName",tf="matchUpFormat",Ge="participantId",ef="scheduleDates",UF="tournamentId",RF="scheduleDate",bF="roundNumber",Po="structureId",gm="participant",Iu="matchUpIds",yE="entryStage",CF="policyType",Ob="structures",lh="eventType",xr="matchUpId",rf="tieFormat",Mp="inContext",Ec="structure",Im="courtIds",MF="personId",hm="venueIds",fh="matchUps",Oo="courtId",EE="eventId",Cn="matchUp",Ac="drawId",qr="error",me="event",zi="param",gh="uuids",AE="penaltyType",nf="penaltyId",vp="venueId",vF="stage",OF="averageMatchUpMinutes",_F="recoveryMinutes",xF="periodLength",wF="number";var $r="object",Ye="array";var Xe="_validate",PE="_message",wr="_invalid",qe="_ofType",Op="_anyOf",Va="_oneOf";var LF={[SE]:t=>Ht(Object.keys(t),[Ql,Jl,mu]).length===3,[TE]:t=>t&&Eo({namedFormat:t}),[gh]:t=>!t||Array.isArray(t)&&t.every(wt),[rf]:t=>!ur({tieFormat:t}).error,[lh]:t=>[ue,Xt,Ce].includes(t),[yE]:t=>lu.includes(t)},Lq={[Ne]:kt,[Z]:Y,[mh]:Ca,[zt]:K,[Ge]:$e,[tf]:QU,[UF]:Ic,[Po]:mn,[Iu]:Vs,[gm]:Ma,[SE]:vo,[lh]:so,[Ob]:PI,[xr]:cr,[rf]:ai,[Ec]:Hi,[Oo]:MI,[fh]:zn,[EE]:Br,[Cn]:nr,[Im]:nt,[hm]:nt,[AE]:SR,[nf]:TR,[vp]:Hs,[Ac]:Un,[me]:Se,[vF]:UI},Fq={[Ne]:$r,[mh]:$r,[Z]:$r,[zt]:$r,[SE]:$r,[ef]:Ye,[gm]:$r,[Iu]:Ye,[Ob]:Ye,[rf]:$r,[Ec]:$r,[Im]:Ye,[hm]:Ye,[fh]:Ye,[Cn]:$r,[me]:$r,[gh]:Ye};function X(t,e,r){if(!t&&!St(t))return{error:O};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:O};let{paramError:n,errorParam:o}=Vq(t,e);if(!n)return{valid:!0};let i=n[Xe]&&(n[qr]||n[wr])||t?.[o]==null&&(n[qr]||n[wr]||Lq[o]||O)||O,s=o??(n[Va]&&Object.keys(n[Va]).join(", "));return M({info:{param:s,message:n[PE]},result:{error:i},stack:r})}function FF(t,e){let r=Object.keys(t),n=Object.keys(e);return Ht(r,n)}function kq(t,e){if(!e)return;let r=FF(t,e);return r.length!==1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function Gq(t,e){if(!e)return;let r=FF(t,e).filter(n=>t[n]);return r.length<1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function Vq(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let d=s&&kq(t,s);if(d?.error)return d.error;d&&Object.assign(p,d);let m=a&&Gq(t,a);if(m?.error)return m.error;m&&Object.assign(p,m);let l=Object.keys(p).filter(g=>typeof p[g]=="boolean"),f=l.find(g=>{let I=c&&!Vr(c),h=t[g]!==void 0&&!c&&Bq(t,g,i),S=p[g]&&t[g]==null,y=I||h||S||c&&t[g]!==void 0&&!Hq(t[g],c)||LF[g]&&!LF[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function Bq(t,e,r){return r=r||Fq[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function Hq(t,e){return Vr(e)?e(t):!0}var _p="DYNAMIC",co="RANKING",qo="RATING",mi="SCALE",_o="SEEDING",kF={RANKING:co,RATING:qo,SCALE:mi,SEEDING:_o};function Pc(t){let e=X(t,[{[gm]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(mi)&&[co,qo,_o].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=ct(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,d]=a.itemType.split("."),m=d?`${p}.${d}`:p,l=c===_o&&"seedings"||c===co&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:m})}}}return{...P,...n}}function Ps(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()),d=u.concat(...Object.keys(p)),m=d.includes("*");for(let l of c)if(d.indexOf(l)>=0||m){let f=p[l]||l,g=s[f]||m,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]||m&&s[l]!==!1)&&(a[l]=h)}}}}var NE="voluntaryConsolation",gn="competitiveBands",Ih="roundRobinTally",uo="positionActions",Ke="matchUpActions",In="rankingPoints",$o="roundNaming",Ba="participant",xp="progression",No="scheduling",Nc="avoidance",Wq="participant",jq="display",Jr="scoring",Xn="seeding",hu="feedIn",Yq="sanctioning",qq="audit",Su="competition",of="draws",_b="print",GF={POLICY_TYPE_VOLUNTARY_CONSOLATION:NE,POLICY_TYPE_COMPETITIVE_BANDS:gn,POLICY_TYPE_ROUND_ROBIN_TALLY:Ih,POLICY_TYPE_POSITION_ACTIONS:uo,POLICY_TYPE_MATCHUP_ACTIONS:Ke,POLICY_TYPE_RANKING_POINTS:In,POLICY_TYPE_ROUND_NAMING:$o,POLICY_TYPE_PARTICIPANT:Ba,POLICY_TYPE_PROGRESSION:xp,POLICY_TYPE_SCHEDULING:No,POLICY_TYPE_AVOIDANCE:Nc,POLICY_TYPE_COMPETITION:Su,POLICY_TYPE_DISPLAY:jq,POLICY_TYPE_PRIVACY:Wq,POLICY_TYPE_FEED_IN:hu,POLICY_TYPE_SCORING:Jr,POLICY_TYPE_SEEDING:Xn,POLICY_TYPE_SANCTIONING:Yq,POLICY_TYPE_AUDIT:qq,POLICY_TYPE_DRAWS:of,POLICY_TYPE_PRINT:_b};function li({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=q(s,!1,o);if(a){let c=e?.[Ba];if(r?.withScaleValues){let{ratings:u,rankings:p}=Pc({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Ps({template:c.participant,source:a})}return a}var VF="element required",BF="missing name";function Mn(t){if(!t||typeof t!="object")return{error:nt};if(t.element&&typeof t?.element!="object")return{error:O};if(!t?.name)return{error:nt,info:BF};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=Mn({element:r,name:t.name});if(n.error)return M({result:n,stack:"removeExtension"})}return{...P}}return{error:nt,info:VF}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...P}):{...P,info:fe}}function Zn({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 Qt(t){if(typeof t!="object")return{error:nt};let e="addExtension";if(t?.element&&typeof t.element!="object")return M({result:{error:O},stack:e});if(!Zn({extension:t.extension}))return M({result:{error:O,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=Qt({extension:t.extension,element:o});if(i.error)return M({result:i,stack:e})}return{...P}}else return M({result:{error:nt},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),{...P}}function hh(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?Qt({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:Y}}function Sh(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?Qt({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Cr}}function xb(t){return!t||typeof t!="object"?{error:nt}:t.event?Qt({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Br}}function wb(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:$e};let e=t.tournamentRecord?.participants??[],r=li({participantId:t.participantId,tournamentParticipants:e});return r?Qt({creationTime:t.creationTime,extension:t.extension,element:r}):{error:Wt}}function Th(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?Mn({element:t.tournamentRecord,name:t.name}):{error:Y}}function Lb(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?Mn({element:t.drawDefinition,name:t.name}):{error:Cr}}function yh(t){return!t||typeof t!="object"?{error:nt}:t?.event?Mn({element:t.event,name:t.name}):{error:Br}}function Fb(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:$e};let e=t.tournamentRecord?.participants??[],r=li({participantId:t.participantId,tournamentParticipants:e});return r?Mn({element:r,name:t.name}):{error:Wt}}var $q="extensionQueries";function qt({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(d=>d?.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:fe}}return M({result:{error:nt},stack:$q})}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:fe}}var Kq="activeSuspension",wp="appliedPolicies",Ns="competitionState",kb="context",Lp="delegatedOutcome",Gn="disabled",Ks="disableAutoCalc",Fp="disableLinks",sf="display",fi="draftState",Dc="drawDeletions",zq="drawProfile",Qq="eventProfile",Jq="eventWithdrawalRequests",Gb="factory",Kr="flightProfile",DE="groupingAttribute",po="lineUps",Uc="linkedTournamentsIds",an="mutationLocks",UE="participantRepresentatives",Rc="personRequests",Tu="positionActions",Xq="rankingPoints",Zq="registration",Xr="roundTarget",Vb="sanctioningConstraints",bc="scheduleLimits",xo="scheduleTiming",Ha="schedulingProfile",t$="statusDetail",Wa="subOrder",to="tally",af="tieFormatModification",RE={ACTIVE_SUSPENSION:Kq,APPLIED_POLICIES:wp,COMPETITION_STATE:Ns,CONTEXT:kb,DELEGATED_OUTCOME:Lp,DISABLED:Gn,DISABLE_LINKS:Fp,DISABLE_AUTO_CALC:Ks,DISPLAY:sf,DRAFT_STATE:fi,DRAW_DELETIONS:Dc,DRAW_PROFILE:zq,EVENT_PROFILE:Qq,EVENT_WITHDRAWAL_REQUESTS:Jq,FLIGHT_PROFILE:Kr,GROUPING_ATTRIBUTE:DE,LINEUPS:po,LINKED_TOURNAMENTS:Uc,MUTATION_LOCKS:an,PARTICIPANT_REPRESENTATIVES:UE,PERSON_REQUESTS:Rc,POSITION_ACTIONS:Tu,RANKING_POINTS:Xq,REGISTRATION:Zq,ROUND_TARGET:Xr,SANCTIONING_CONSTRAINTS:Vb,SCHEDULE_LIMITS:bc,SCHEDULE_TIMING:xo,SCHEDULING_PROFILE:Ha,STATUS_DETAIL:t$,SUB_ORDER:Wa,TALLY:to,TIE_FORMAT_MODIFICATIONS:af,FACTORY:Gb},Bb=[Lp,Gn,Ks,Fp,Kr,po,Uc,an,UE,Rc,Xr,bc,xo,Ha,Wa,to,af];function cf(t){if(Array.isArray(t?.linkedTournamentIds))return t.linkedTournamentIds;let{extension:e}=qt({element:t,name:Uc});return e?.value?.tournamentIds??[]}function Sm({tournamentRecords:t}){return{tournamentIds:St(t)?Object.keys(t):[],...P}}function bE(t,e){let r=!e.length;cu()&&!r?t.linkedTournamentIds=[...e]:t?.linkedTournamentIds!==void 0&&delete t.linkedTournamentIds,uu()&&!r?hh({tournamentRecord:t,extension:{name:Uc,value:{tournamentIds:[...e]}}}):Th({tournamentRecord:t,name:Uc})}function Hb({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=Sm({tournamentRecords:t}),{tournamentIds:r}=e;if(r?.length>1)for(let n of Object.values(t))bE(n,r);return{...P}}function Wb({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};for(let r of Object.values(t))bE(r,[]);let e=Mn({name:Uc,tournamentRecords:t,discover:!0});return M({result:e,stack:"unlinkTournaments"})}function jb({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:O};if(!e)return{error:Ic};let r=Sm({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:Ic};for(let o of n){let i=t[o],s=cf(i);if(!s?.length||s.length===1&&s.includes(e)||o===e){bE(i,[]);continue}let a=s.filter(c=>c!==e);bE(i,a)}return{...P}}function gt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:Oy};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...P};function a(c){let p=c?.extensions?.find(d=>d.name===wp)?.value;if(p)for(let d of Object.keys(p))(t?e.includes(d):!e.length||e.includes(d))&&(s[d]=q(p[d],!1,!0))}}function Do({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:Oy};let{appliedPolicies:i}=gt({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:lp.message}}function wo(t){let{appliedPolicies:e}=gt({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,event:t.event});return{competitionPolicy:e?.[Su]}}function Qi({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=q(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[m,l]of u.entries())if(c?.[l]){let f=u.slice(m+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],d({targetElement:c,index:m})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function d({targetElement:m,index:l}){if(m&&l===u.length-1&&["string","number"].includes(typeof m)){let f=p?m.slice(0,p):m;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}function Lo({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Ma};if(!St(e))return{error:O};if(r.timeItems??=[],Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[mi,o,i,s].join("."),u=r.timeItems.filter(p=>p?.itemType===a).filter(p=>!t||p?.itemDate).sort((p,d)=>(p.createdAt?new Date(p.createdAt).getTime():0)-(d.createdAt?new Date(d.createdAt).getTime():0)).pop();if(u){let[p,d,m,l]=u.itemType?.split(".")??[];if(p!==mi)return{error:ou};let f=n&&Qi({element:u.itemValue,accessor:n}),g=f?.value||u.itemValue,I={rawValue:f&&u.itemValue,eventType:m,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:d};return{...P,scaleItem:I}}}return{...P,scaleItem:void 0}}function kp({value:t,sourceRange:e,targetRange:r}){if(!Array.isArray(e)||e.length!==2)return 0;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 Yb="NTRP";var qb="DUPR",$b="UTR_P",Kb="UTPR";var zb="SQUASH_LEVELS",Qb="US_SQUASH",Jb="USATT",Xb="ITTF",Zb="USAR";var HF={ELO:"ELO",NTRP:Yb,TRN:"TRN",UTR:"UTR",WTN:"WTN",DUPR:qb,UTR_P:$b,UTPR:Kb,PSA:"PSA",SQUASH_LEVELS:zb,US_SQUASH:Qb,USATT:Jb,ITTF:Xb,USAR:Zb,BWF:"BWF"};var o$={ELO:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!1},[Yb]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!1,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!1,range:[1,16]},WTN:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!0,decimalsCount:2,range:[40,1]},[qb]:{defaultInitialization:3.5,accessors:["duprRating","reliabilityScore"],accessor:"duprRating",attributes:{reliabilityScore:{generator:!0,range:[0,100]}},decimalsCount:3,ascending:!1,range:[2,8]},[$b]:{defaultInitialization:5,accessors:["utrpRating","verified"],accessor:"utrpRating",attributes:{verified:{type:"boolean"},provisional:{type:"string"}},decimalsCount:1,ascending:!1,range:[1,10]},[Kb]:{defaultInitialization:3.5,accessor:"utprRating",decimalsCount:1,ascending:!1,range:[2,5],deprecated:!0},PSA:{defaultInitialization:500,accessor:"psaPoints",decimalsCount:0,ascending:!1,range:[0,3e3],attributes:{tournaments:{generator:!0,range:[1,20]},divisor:{generator:!0,range:[10,20]}}},[zb]:{defaultInitialization:2e3,accessor:"squashLevel",decimalsCount:0,ascending:!1,range:[0,7e3]},[Qb]:{defaultInitialization:3.5,accessor:"usSquashRating",decimalsCount:1,ascending:!1,range:[2,6]},[Jb]:{defaultInitialization:1e3,accessor:"usattRating",decimalsCount:0,ascending:!1,range:[200,3e3]},[Xb]:{defaultInitialization:500,accessor:"ittfPoints",decimalsCount:0,ascending:!1,range:[0,2e4]},[Zb]:{defaultInitialization:1e4,accessor:"usarRanking",decimalsCount:0,ascending:!0,range:[1,25e3]},BWF:{defaultInitialization:5e3,accessor:"bwfPoints",decimalsCount:0,ascending:!0,range:[0,15e4],attributes:{tournaments:{generator:!0,range:[1,10]}}}},Ze=o$;function Gp({sourceRatingType:t,sourceRating:e}){let r=Ze[t]?.range,n=r?.[0]>r?.[1],o=Ze["ELO"].range;return kp({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function jF({targetRatingType:t,sourceRating:e}){let r=Ze[t]?.decimalsCount||0,n=Ze[t]?.range,o=n?.[0]>n?.[1],i=Math.max(...n),s=Ze["ELO"]?.range,a=kp({targetRange:n,sourceRange:s,value:e}),c=Number.parseFloat(a?.toFixed(r))||0;return o?i-c:c}function uf(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,convertToELO:i,adHocRatings:s={}}=t,a=t.scaleAccessor??Ze[n]?.accessor,c=e.participants??[];for(let u of r??[]){let p=c?.find(m=>m.participantId===u),d;i&&(d=tC({scaleName:`${"ELO"}.${_p}`,participant:p,eventType:o})),d||(d=tC({scaleName:`${n}.${_p}`,participant:p,eventType:o}),d&&i&&n!=="ELO"&&(d=Gp({sourceRatingType:n,sourceRating:d}))),!d&&n&&(d=tC({scaleAccessor:a,participant:p,scaleName:n,eventType:o}),d&&i&&n!=="ELO"&&(d=Gp({sourceRatingType:n,sourceRating:d}))),d&&!s[u]&&(s[u]=d)}return s}function tC({scaleType:t=qo,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Lo({scaleAttributes:{eventType:o??Fa,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&St(a)?a[e]:a}function At(t){let e="setFirstClassOrExtension";if(typeof t!="object")return{error:nt};let{element:r,attribute:n,name:o,value:i,creationTime:s}=t;if(!r||typeof r!="object")return M({result:{error:O},stack:e});if(typeof n!="string"||!n)return M({result:{error:O},stack:e});if(typeof o!="string"||!o)return M({result:{error:O},stack:e});if(cu()&&(i==null?delete r[n]:r[n]=i),uu())if(i==null)Mn({element:r,name:o});else{let a=Qt({element:r,extension:{name:o,value:i},creationTime:s});if(a.error)return M({result:a,stack:e})}else Array.isArray(r.extensions)&&r.extensions.some(a=>a?.name===o)&&Mn({element:r,name:o});return{...P}}function eC(t){let{tournamentRecord:e,drawDefinition:r,participantIds:n,event:o}=t;if(!r)return{error:K};if(!n?.length)return{error:nt};let{competitionPolicy:i}=wo({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let s=i.ratingPolicy,a=s.baselineRating.scaleName,c=s.ratingAggregation??"AVERAGE",u=o?.eventType,p=a?uf({tournamentRecord:e,participantIds:n,scaleName:a,eventType:u}):{},d={};for(let l of n){let f=i$({tournamentRecord:e,participantId:l,adHocRatings:p,aggregation:c,eventType:u});d[l]={participantId:l,baselineRating:f,dynamicFormRating:f,pressureRating:0,roundsPlayed:0,wins:0,losses:0,draws:0,totalPointsWon:0,totalPointsLost:0,ratingHistory:[]}}let m={participantStates:d,roundStates:{}};return At({element:r,attribute:"competitionState",name:Ns,value:m}),{competitionState:m,...P}}function i$({tournamentRecord:t,participantId:e,adHocRatings:r,aggregation:n,eventType:o}){if(r[e]!==void 0)return r[e];if(o===Xt){let s=t.participants?.find(a=>a.participantId===e)?.individualParticipantIds;if(s?.length){let a=s.map(c=>r[c]??0);return s$(a,n)}}return 0}function s$(t,e){if(!t.length)return 0;switch(e){case"MIN":return Math.min(...t);case"MAX":return Math.max(...t);case"SUM":return t.reduce((r,n)=>r+n,0);default:return t.reduce((r,n)=>r+n,0)/t.length}}function $t({element:t,attribute:e,name:r}){if(t?.[e]!==void 0)return t[e];let{extension:n}=qt({element:t,name:r});return n?.value}function Ko({drawDefinition:t}){return{competitionState:$t({element:t,attribute:"competitionState",name:Ns})}}function qF(t){let e=t.score?.sets??[];if(!e.length)return YF(t);let r=0,n=0;for(let o of e){let i=o.side1Score??0,s=o.side2Score??0;if(o.side1TiebreakScore!==void 0||o.side2TiebreakScore!==void 0){let a=o.side1TiebreakScore??0,c=o.side2TiebreakScore??0,u=a+c;if(u>0){r+=i-(o.winningSide===1?1:0)+a/u,n+=s-(o.winningSide===2?1:0)+c/u;continue}}r+=i,n+=s}return r>0||n>0?{side1Count:r,side2Count:n}:YF(t)}function YF(t){let{winningSide:e}=t;return e===1?{side1Count:1,side2Count:0}:e===2?{side1Count:0,side2Count:1}:{side1Count:0,side2Count:0}}function rC({pointsWon:t,pointsLost:e,competitionPolicy:r}){let n=t+e;if(n===0)return .5;let o=t/n,i=r.ratingPolicy.pressureRating;if(!i||i.actualOutputMethod==="POINT_SHARE")return o;let s=i.weights??{pointShare:1},a=(t-e)/n,c=0,u=s.pointShare??1,p=s.pointDifferential??0,d=s.contextFactor??0,m=u+p+d;return m===0?o:(u*o+p*a+d*c)/m}function Eh(t,e,r){return 1/(1+Math.pow(10,(e-t)/r))}function Tm(t){let{tournamentRecord:e,drawDefinition:r,matchUp:n,event:o}=t;if(!r)return{error:K};if(!n)return{error:nr};let{competitionPolicy:i}=wo({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let{competitionState:s}=Ko({drawDefinition:r});if(!s)return{...P};let a=n.sides??[],c=a[0]?.participantId,u=a[1]?.participantId;if(!c||!u)return{...P};let p=s.participantStates[c],d=s.participantStates[u];if(!p||!d)return{...P};let{winningSide:m}=n,{side1Count:l,side2Count:f}=qF(n),g=rC({pointsWon:l,pointsLost:f,competitionPolicy:i}),I=rC({pointsWon:f,pointsLost:l,competitionPolicy:i}),h=i.ratingPolicy.dynamicFormRating.logisticScale,S=i.ratingPolicy.dynamicFormRating.kFactor,T=Eh(p.baselineRating,d.baselineRating,h),y=Eh(d.baselineRating,p.baselineRating,h),E=Eh(p.dynamicFormRating,d.dynamicFormRating,h),A=Eh(d.dynamicFormRating,p.dynamicFormRating,h),N=i.ratingPolicy.pressureRating?.enabled,D=N?g-T:0,R=N?I-y:0,U=i.ratingPolicy.dynamicFormRating.enabled,b=U?p.dynamicFormRating+S*(g-E):p.dynamicFormRating,C=U?d.dynamicFormRating+S*(I-A):d.dynamicFormRating,_=n.roundNumber??0;return p.dynamicFormRating=b,p.pressureRating+=D,p.roundsPlayed+=1,p.wins+=m===1?1:0,p.losses+=m===2?1:0,p.draws+=m?0:1,p.totalPointsWon+=l,p.totalPointsLost+=f,p.ratingHistory.push({roundNumber:_,opponentParticipantId:u,dynamicFormRatingBefore:p.dynamicFormRating-S*(g-E),dynamicFormRatingAfter:b,pressureDelta:D,actualOutput:g,expectedOutput:T}),d.dynamicFormRating=C,d.pressureRating+=R,d.roundsPlayed+=1,d.wins+=m===2?1:0,d.losses+=m===1?1:0,d.draws+=m?0:1,d.totalPointsWon+=f,d.totalPointsLost+=l,d.ratingHistory.push({roundNumber:_,opponentParticipantId:c,dynamicFormRatingBefore:d.dynamicFormRating-S*(I-A),dynamicFormRatingAfter:C,pressureDelta:R,actualOutput:I,expectedOutput:y}),At({element:r,attribute:"competitionState",name:Ns,value:s}),{...P}}var Lr="ABANDONED",yu="AWAITING_RESULT";var mo="CANCELLED",ae="COMPLETED",Vp="DEAD_RUBBER",Mt="DEFAULTED",Te="DOUBLE_DEFAULT",Zt="DOUBLE_WALKOVER",vn="IN_PROGRESS",Zr="INCOMPLETE",nC="NOT_PLAYED",ve="RETIRED",Ji="SUSPENDED",Jt="TO_BE_PLAYED",vt="WALKOVER",$F=[yu,ae,Mt,vn,Zr,ve,Ji],CE=[yu,ae,Mt,Zt,Te,vn,Zr,ve,Ji,vt],ME=[Lr,yu,"BYE",mo,ae,Vp,Mt,Zt,Te,vn,Zr,nC,ve,Ji,Jt,vt],vE=["BYE",Zt,Te,ae,Mt,ve,vt],OE=[Lr,yu,mo,Vp,vn,Zr,nC,Ji,Jt,void 0],Rt=[mo,Lr,ae,Vp,Mt,Zt,Te,ve,vt],pf=[Lr,ae,Mt,Zt,Te,vn,ve,vt],_E=[vn,Zr,Ji,Jt],xE={ABANDONED:Lr,AWAITING_RESULT:yu,BYE:"BYE",CANCELLED:mo,COMPLETED:ae,DEAD_RUBBER:Vp,DEFAULTED:Mt,DOUBLE_WALKOVER:Zt,DOUBLE_DEFAULT:Te,IN_PROGRESS:vn,INCOMPLETE:Zr,NOT_PLAYED:nC,RETIRED:ve,SUSPENDED:Ji,TO_BE_PLAYED:Jt,WALKOVER:vt};function oC(t){let{tournamentRecord:e,drawDefinition:r,roundNumber:n,matchUps:o,event:i}=t;if(!r)return{error:K};let{competitionPolicy:s}=wo({tournamentRecord:e,drawDefinition:r,event:i});if(!s)return{...P};let{competitionState:a}=Ko({drawDefinition:r});if(!a)return{...P};if(a.roundStates[n]?.processed)return{...P};let c=o.filter(p=>p.roundNumber===n&&(p.winningSide||Rt.includes(p.matchUpStatus)));for(let p of c)Tm({tournamentRecord:e,drawDefinition:r,matchUp:p,event:i});let{competitionState:u}=Ko({drawDefinition:r});return u&&(u.roundStates[n]={roundNumber:n,processed:!0},At({element:r,attribute:"competitionState",name:Ns,value:u})),{...P}}function iC({drawDefinition:t}){return t?(At({element:t,attribute:"competitionState",name:Ns,value:void 0}),{...P}):{error:K}}var aC={};_t(aC,{getCompetitionLeaderboard:()=>LE,getCompetitionParticipantState:()=>wE,getCompetitionPolicy:()=>wo,getCompetitionState:()=>Ko,getLinkedTournamentIds:()=>Bp,getTournamentIds:()=>Sm});function wE({drawDefinition:t,participantId:e}){let{competitionState:r}=Ko({drawDefinition:t});return{participantState:r?.participantStates?.[e]}}function LE(t){let{tournamentRecord:e,drawDefinition:r,event:n}=t,{competitionPolicy:o}=wo({tournamentRecord:e,drawDefinition:r,event:n}),{competitionState:i}=Ko({drawDefinition:r});if(!i||!o)return{leaderboard:[]};let s=o.victoryPolicy.primaryRanking;return{leaderboard:[...Object.values(i.participantStates)].sort((p,d)=>{let m=KF(d,s)-KF(p,s);if(m!==0)return m;for(let l of o.victoryPolicy.tiebreakOrder??[]){let f=a$(p,d,l,i.participantStates);if(f!==0)return f}return 0}).map((p,d)=>({participantId:p.participantId,rank:d+1,baselineRating:p.baselineRating,dynamicFormRating:p.dynamicFormRating,pressureRating:p.pressureRating,wins:p.wins,losses:p.losses,draws:p.draws,pointsWon:p.totalPointsWon,pointsLost:p.totalPointsLost}))}}function KF(t,e){switch(e){case"PRESSURE_RATING":return t.pressureRating;case"DYNAMIC_FORM_RATING":return t.dynamicFormRating;case"WINS":return t.wins;case"POINTS":return t.totalPointsWon;default:return t.wins}}function a$(t,e,r,n){switch(r){case"POINT_DIFFERENTIAL":return e.totalPointsWon-e.totalPointsLost-(t.totalPointsWon-t.totalPointsLost);case"DYNAMIC_FORM_RATING":return e.dynamicFormRating-t.dynamicFormRating;case"PRESSURE_RATING":return e.pressureRating-t.pressureRating;case"HEAD_TO_HEAD":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.filter(c=>c.actualOutput>.5).length;return i.filter(c=>c.actualOutput>.5).length-s}case"HEAD_TO_HEAD_PRESSURE":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.reduce((c,u)=>c+u.pressureDelta,0);return i.reduce((c,u)=>c+u.pressureDelta,0)-s}case"STRENGTH_OF_OPPOSITION":{let o=t.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),i=e.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),s=o.length?o.reduce((c,u)=>c+u,0)/o.length:0;return(i.length?i.reduce((c,u)=>c+u,0)/i.length:0)-s}default:return 0}}function Bp({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,i=cf(n).filter(s=>s!==o);return{[r]:i}}))}}var EO={};_t(EO,{adHocPositionSwap:()=>kM,addAdHocMatchUps:()=>md,addDrawDefinitionTimeItem:()=>SS,addFinishingRounds:()=>aa,addGoesTo:()=>bs,addLinkedConsolationStructure:()=>gM,addPlayoffStructures:()=>DS,addQualifyingStructure:()=>LM,addVoluntaryConsolationStructure:()=>rS,allPlayoffPositionsFilled:()=>BA,alternateDrawPositionAssignment:()=>hM,assignDrawPosition:()=>WM,assignDrawPositionBye:()=>Mr,attachConsolationStructures:()=>cS,attachPlayoffStructures:()=>uS,attachQualifyingStructure:()=>hS,attachStructures:()=>pS,autoSeeding:()=>OV,automatedPlayoffPositioning:()=>Ja,automatedPositioning:()=>Gu,buildDrawHierarchy:()=>vV,checkValidEntries:()=>ig,deleteAdHocMatchUps:()=>YM,drawMatic:()=>Td,findDrawDefinition:()=>iP,generateAdHocMatchUps:()=>Vc,generateAdHocRounds:()=>hg,generateAndPopulatePlayoffStructures:()=>Xf,generateConsolationStructure:()=>fM,generateDrawDefinition:()=>jc,generateDrawMaticRound:()=>ug,generateDrawStructuresAndLinks:()=>sg,generateDrawTypeAndModifyDrawDefinition:()=>ag,generateQualifyingStructure:()=>Kf,generateSwissRound:()=>CV,generateVoluntaryConsolation:()=>MP,getAssignedParticipantIds:()=>ss,getAvailableMatchUpsCount:()=>Zf,getAvailablePlayoffProfiles:()=>sd,getDraftState:()=>PP,getDrawDefinitionTimeItem:()=>qE,getDrawParticipantRepresentativeIds:()=>eP,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>gd,getEligibleVoluntaryConsolationParticipants:()=>tP,getLuckyDrawRoundStatus:()=>zf,getMatchUpsMap:()=>ye,getParticipantIdFinishingPositions:()=>rg,getPositionAssignments:()=>Bu,getPositionsPlayedOff:()=>wu,getRandomQualifierList:()=>SP,getSeedingThresholds:()=>PA,getSeedsCount:()=>Id,getStructureSeedAssignments:()=>Dr,getSwissChart:()=>AP,getSwissStandings:()=>TP,getTally:()=>EP,getTeamLineUp:()=>oa,getValidGroupSizes:()=>Cm,hasLuckyRounds:()=>Wh,initializeDraft:()=>jM,isAdHoc:()=>De,isCompletedStructure:()=>Bo,isValidForQualifying:()=>yP,luckyDrawAdvancement:()=>GM,luckyLoserDrawPositionAssignment:()=>cM,modifyDrawDefinition:()=>VM,modifyDrawName:()=>US,modifySeedAssignment:()=>DM,mutate:()=>KM,positionActions:()=>hP,predictDrawCompetitiveBands:()=>ld,pruneDrawDefinition:()=>HM,qualifierDrawPositionAssignment:()=>mS,qualifierProgression:()=>SM,query:()=>uv,remapDrawDefinitionMatchUpIds:()=>dS,removeDrawPositionAssignment:()=>od,removeRoundMatchUps:()=>qM,removeSeededParticipant:()=>wM,removeStructure:()=>MM,renameStructures:()=>RM,resetDrawDefinition:()=>BM,resetQualifyingStructure:()=>CM,resetVoluntaryConsolationStructure:()=>hC,resolveDraftPositions:()=>bM,seedWithdrawalCascade:()=>FM,setDrawParticipantRepresentativeIds:()=>uC,setDrawPositionPreferences:()=>IM,setPositionAssignments:()=>pM,setStructureOrder:()=>UM,setSubOrder:()=>$M,shiftAdHocRounds:()=>uM,swapAdHocRounds:()=>dM,swapDrawPositionAssignments:()=>xM,updateTeamLineUp:()=>vs,validatePlayoffGroups:()=>Yf,withdrawParticipantAtDrawPosition:()=>sM});var KM={};_t(KM,{adHocPositionSwap:()=>kM,addAdHocMatchUps:()=>md,addDrawDefinitionTimeItem:()=>SS,addLinkedConsolationStructure:()=>gM,addPlayoffStructures:()=>DS,addQualifyingStructure:()=>LM,addVoluntaryConsolationStructure:()=>rS,alternateDrawPositionAssignment:()=>hM,assignDrawPosition:()=>WM,assignDrawPositionBye:()=>Mr,attachConsolationStructures:()=>cS,attachPlayoffStructures:()=>uS,attachQualifyingStructure:()=>hS,attachStructures:()=>pS,automatedPlayoffPositioning:()=>Ja,automatedPositioning:()=>Gu,deleteAdHocMatchUps:()=>YM,initializeDraft:()=>jM,luckyDrawAdvancement:()=>GM,luckyLoserDrawPositionAssignment:()=>cM,modifyDrawDefinition:()=>VM,modifyDrawName:()=>US,modifySeedAssignment:()=>DM,pruneDrawDefinition:()=>HM,qualifierDrawPositionAssignment:()=>mS,qualifierProgression:()=>SM,remapDrawDefinitionMatchUpIds:()=>dS,removeDrawPositionAssignment:()=>od,removeRoundMatchUps:()=>qM,removeSeededParticipant:()=>wM,removeStructure:()=>MM,renameStructures:()=>RM,resetDrawDefinition:()=>BM,resetQualifyingStructure:()=>CM,resetVoluntaryConsolationStructure:()=>hC,resolveDraftPositions:()=>bM,seedWithdrawalCascade:()=>FM,setDrawParticipantRepresentativeIds:()=>uC,setDrawPositionPreferences:()=>IM,setPositionAssignments:()=>pM,setStructureOrder:()=>UM,setSubOrder:()=>$M,shiftAdHocRounds:()=>uM,swapAdHocRounds:()=>dM,swapDrawPositionAssignments:()=>xM,updateTeamLineUp:()=>vs,withdrawParticipantAtDrawPosition:()=>sM});var FE=t=>e=>t[e],df=(t=[])=>t.map(Pe).filter(Boolean),Ah=(t=[])=>t.map(lt).filter(Boolean),lt=(t={})=>FE(t)("participantId"),zF=(t={})=>FE(t)("drawPosition");var Pe=(t={})=>FE(t)("matchUpId"),Cc=(t={})=>FE(t)("drawId");function uC({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Cr};if(!Array.isArray(t))return{error:O};let r=Ah(e?.entries??[]);return t.length&&Ht(t,r).length<t.length?{error:O}:Sh({drawDefinition:e,extension:{name:UE,value:t}})}function Xi(t,e,r){let n=d=>$t({element:d,attribute:"roundTarget",name:Xr}),o=r?.deprioritizeCompleted,i=r?.mode===Nb&&PF,s=r?.mode===Pb&&Db,a=s||i||ka,c=d=>d?.stage===j&&d?.stageSequence===1,u=d=>c(d)?-1:a[d?.stage],p=d=>d?.matchUps.every(({matchUpStatus:m})=>Rt.includes(m)?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)||(Ph(t)||0)-(Ph(e)||0)}function Ph(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 tt(t){let e=X(t,[{[zt]:!0,[Po]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=hn({drawDefinition:r}),i=o?.flatMap(c=>c.structures?[...c.structures].concat(c):c),s=i?.find(c=>c.structureId===n);if(!s)return{error:Pt};let a=s.structureType===gu?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function hn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&K||!e?.structures&&PI||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=$t({element:f,attribute:"roundTarget",name:Xr});return!o||o===g},p=e?.structures?.filter(m).filter(l).filter(u).sort((f,g)=>Xi(f,g,i))??[],d=t?Object.assign({},...lu.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:d};function m(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 kE({drawDefinition:t}){if(!t)return{error:K};let e={};return{allPositionedParticipantIds:(t.structures??[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=yt({structure:n}),s=i?.map(lt).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function yt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:K};if({structure:r,error:n}=tt({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>yt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=RI,{positionAssignments:o,error:n}}function pe({drawDefinition:t,structureId:e,structure:r}){let n=yt({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}}function at(t,e,r){let n=e.reduce((o,i)=>(o[i]=!0,o),{});return X(t,[n],r)}var Nh="addDrawDefinition",ym="addMatchUps",Oi="addParticipants",Dh="addScaleItems",pC="addEvent",GE="addVenue",Zi="audit",VE="dataIssue",Uh="deleteParticipants",Rh="deleteVenue",bh="deletedDrawIds",Ch="deletedMatchUpIds",Mh="modifyDrawDefinition",dC="modifyDrawEntries",mC="modifyEventEntries",vh="modifyMatchUp",Oe="modifyParticipants",Oh="modifyPositionAssignments",_h="modifySeedAssignments",ko="modifyTournamentDetail",Sn="modifyVenue",mf="mutations",BE="publishEvent",lC="publishEventSeeding",fC="publishOrderOfPlay",gC="publishParticipants",xh="unPublishEvent",wh="unPublishEventSeeding",Lh="unPublishOrderOfPlay",IC="unPublishParticipants",lf="unPublishTournament",Hp="updateInContextMatchUp",QF={ADD_DRAW_DEFINITION:Nh,ADD_MATCHUPS:ym,ADD_PARTICIPANTS:Oi,ADD_SCALE_ITEMS:Dh,ADD_EVENT:pC,ADD_VENUE:GE,AUDIT:Zi,DATA_ISSUE:VE,DELETE_PARTICIPANTS:Uh,DELETE_VENUE:Rh,DELETED_DRAW_IDS:bh,DELETED_MATCHUP_IDS:Ch,MODIFY_DRAW_DEFINITION:Mh,MODIFY_DRAW_ENTRIES:dC,MODIFY_EVENT_ENTRIES:mC,MODIFY_MATCHUP:vh,MODIFY_PARTICIPANTS:Oe,MODIFY_POSITION_ASSIGNMENTS:Oh,MODIFY_SEED_ASSIGNMENTS:_h,MODIFY_TOURNAMENT_DETAIL:ko,MODIFY_VENUE:Sn,MUTATIONS:mf,PUBLISH_EVENT_SEEDING:lC,PUBLISH_EVENT:BE,PUBLISH_ORDER_OF_PLAY:fC,PUBLISH_PARTICIPANTS:gC,UNPUBLISH_EVENT_SEEDING:wh,UNPUBLISH_EVENT:xh,UNPUBLISH_ORDER_OF_PLAY:Lh,UNPUBLISH_PARTICIPANTS:IC,UNPUBLISH_TOURNAMENT:lf,UPDATE_INCONTEXT_MATCHUP:Hp};function HE(t,e){if(!t)return{error:K};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)}),{...P}}function JF(t){if(!t)return;let e=Date.now(),r=t.updatedAt;if(r){let n=typeof r=="string"?new Date(r).getTime():r.getTime();!Number.isNaN(n)&&e<=n&&(e=n+1)}t.updatedAt=new Date(e).toISOString()}function zo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){if(t&&HE(t),Array.isArray(r))for(let o of r)JF(o);return it({payload:{matchUps:r,tournamentId:e,eventId:n},topic:ym}),{...P}}function Vn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&HE(t),it({topic:Ch,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)Vy({key:i});return{...P}}function mt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Lt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),JF(i),it({topic:vh,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...P}):(console.log(nr),{error:nr})}function XF({tournamentId:t,inContextMatchUp:e}){return e?(it({payload:{inContextMatchUp:e,tournamentId:t},topic:Hp,key:e.matchUpId}),{...P}):{error:nr}}function Mc({tournamentId:t,eventId:e,drawDefinition:r}){return r?(HE(r),it({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:Nh,key:r.drawId}),{...P}):(console.log(K),{error:K})}function ZF({tournamentId:t,eventId:e,drawId:r}){return it({payload:{drawId:r,tournamentId:t,eventId:e},topic:bh,key:r}),Vy({key:r}),{...P}}function Lt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(HE(t,r),it({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Mh,key:t.drawId}),{...P}):{error:K}}function ff({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){let o=at({drawDefinition:t,structure:r},[zt,Ec]);if(o.error)return o;let i=r.seedAssignments,s=r.structureId,a=t.drawId;return it({payload:{tournamentId:e,eventId:n,drawId:a,structureId:s,seedAssignments:i},topic:_h,key:t.drawId}),Lt({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:n}),{...P}}function Tn({drawDefinition:t,tournamentId:e,structure:r,event:n}){let o=at({drawDefinition:t,structure:r},[zt,Ec]);if(o.error)return o;let i=yt({structure:r}),s=r.structureId,a=t.drawId,c=n?.eventId;return it({topic:Oh,payload:{positionAssignments:i,tournamentId:e,structureId:s,eventId:c,drawId:a},key:s}),Lt({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:c}),{...P}}function hC({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:K};let o=e.structures?.find(s=>s.stage===Qe);if(!o)return{error:Pt};let i=o.matchUps?.map(({matchUpId:s})=>s)??[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Vn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==Qe)),Lt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...P}}function gf({drawPositions:t,structure:e}){if([rt,j].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=yt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,attribute:"disableLinks",name:Fp,value:!0})})}function vc(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[Tu]===!1)return;let{extension:o}=qt({name:Tu,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===j);if(a){let c=yt({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:d,qualifier:m})=>({drawPosition:u,participantId:p,qualifier:m,bye:d}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:Tu};Qt({element:n,extension:s})}function ts({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(d=>d.structureId))&&u.forEach(d=>s[d.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function Wp(t){let{sides:e,matchUpType:r}=t??{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===Ut?s?.individualParticipantIds??[]:s.participantId).flat():[],o=(e??[]).map(s=>r===Ut&&(s?.participant?.individualParticipantIds??[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Pr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var Eu="SIGN_IN_STATUS",SC="SIGNED_OUT",jp="SIGNED_IN",Fh="PAYMENT_STATUS",tk="REFUNDED",ek="PARTIAL",rk="WAIVED",nk="UNPAID",ok="PAID",WE=[ok,nk,ek,rk,tk],fr="TEAM",ft="INDIVIDUAL",zr="GROUP",dt="PAIR",bt="TEAM",Yp={TEAM_PARTICIPANT:fr,INDIVIDUAL:ft,GROUP:zr,TEAM:bt,PAIR:dt},ik={INDIVIDUAL:ft,GROUP:zr,PAIR:dt,TEAM:bt,SIGN_IN_STATUS:Eu,SIGNED_OUT:SC,SIGNED_IN:jp,PAYMENT_STATUS:Fh,REFUNDED:tk,PARTIAL:ek,WAIVED:rk,UNPAID:nk,PAID:ok};function qp({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?q(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===bt),s=o.filter(c=>c.participantType===zr),a=o.filter(c=>c.participantType===dt);return o.forEach(c=>{if(c.participantType===ft){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds??[]).forEach(d=>{d===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(d=>{d===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds??[]).forEach(d=>{d===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 TC(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function sk(t){let e=Object.assign({},..._i.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return TC(e[t])}var _i=[{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 jE({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=_i.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 ak({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?Ps({template:e,source:s}):s)}}}}function Bn(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:Wt}}function YE(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Bn({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:nt}}function Fr(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=YE(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:O,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:BI};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=q(i.pop(),!1,!0);if(s){let a={timeItem:s,...P};return e&&Object.assign(a,{previousItems:i}),a}else return{info:fe}}function qE({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Un};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Fr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function $p({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Se};if(!n.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Fr({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function If({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Y};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Fr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function $E({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){let i=at({tournamentRecord:e,participantId:r},[Z,Ge]);if(i.error)return i;let s=Bn({tournamentRecord:e,participantId:r});if(s.error)return s;let{participant:a}=s;if(!a?.timeItems)return{info:fe};let{timeItem:c,previousItems:u,info:p}=Fr({element:s.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return c&&{timeItem:c,previousItems:u}||{info:p}}var c$={[zr]:"groupParticipantIds",[dt]:"pairParticipantIds",[bt]:"teamParticipantIds"},u$={[zr]:"groups",[bt]:"teams"};function KE({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,withGroupings:i,internalUse:s,withISO2:a,withIOC:c}){let u=[],p={};for(let m of r.participants??[]){let l=m?.participantId;l&&m$({participantMap:p,participantId:l})}for(let m of r.participants??[]){let l=q(m,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=d$({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=p$(l)),o){let{ratings:h,rankings:S,seedings:T}=Pc({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&jE({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let m=St(t)?t:void 0;ak({participantMap:p,template:m})}let d;return i&&(d=qp({participants:Object.values(p).map(({participant:m})=>m),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:d}}function p$(t){let{timeItem:e}=Fr({itemType:Eu,element:t});return e?.itemValue===jp}function d$({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[c$[n]].push(o),[bt,zr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:d,teamId:m}=e,l=u$[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:d,teamId:m})}if(n===dt){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function m$({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:{[Ct]:{...r},[Ut]:{...r},[bt]:{...r},...r}}}function gi({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return KE({...t,...n,tournamentRecord:r});let i=q(r.participants,!1,!0)??[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>jE({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=qp({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=Pc({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}var zE="WALKOVER",yC="RETIRED",hf="COMPETITIVE",Au="ROUTINE",Pu="DECISIVE",Sf="winRatio";var l$={[gn]:{policyName:"Competitive Bands Default",profileBands:{[Pu]:20,[Au]:50},predictionModel:{competitiveAnchors:[{delta:0,probability:.7},{delta:1.5,probability:.25}],decisiveAnchors:[{delta:0,probability:.1},{delta:1.5,probability:.55}]}}},zs=l$;function lo({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=Do({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[gn]??s?.[gn]??zs[gn];i.policies[gn]=a}return i}function f$(t,e,r,n){if(n==null){t[e]&&(delete t[e][r],Object.keys(t[e]).length===0&&delete t[e]);return}t[e]||(t[e]={}),t[e][r]=n}function g$(t,e){Array.isArray(t.extensions)&&t.extensions.some(r=>r?.name===e)&&Mn({element:t,name:e})}function Tf(t){let e="setGroupLeafOrExtension";if(typeof t!="object")return{error:nt};let{element:r,groupAttribute:n,leafAttribute:o,name:i,value:s,creationTime:a}=t;if(!r||typeof r!="object")return M({result:{error:O},stack:e});if(typeof n!="string"||!n)return M({result:{error:O},stack:e});if(typeof o!="string"||!o)return M({result:{error:O},stack:e});if(typeof i!="string"||!i)return M({result:{error:O},stack:e});if(cu()&&f$(r,n,o,s),uu())if(s==null)Mn({element:r,name:i});else{let c=Qt({element:r,extension:{name:i,value:s},creationTime:a});if(c.error)return M({result:c,stack:e})}else g$(r,i);return{...P}}function Qs({element:t,groupAttribute:e,leafAttribute:r,name:n}){let o=t?.[e]?.[r];return o!==void 0?o:(t?.extensions??[]).find(s=>s?.name===n)?.value}function Uo({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:Y};let{appliedPolicies:i}=gt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:lp?.message}}function Oc({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}=Uo({policyType:No,tournamentRecord:t,event:n}),i=t?Qs({element:t,groupAttribute:"scheduling",leafAttribute:"timing",name:xo}):void 0,a=(n&&qt({name:xo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:i,eventScheduling:a,categoryName:e,categoryType:r,policy:o}}}function QE({tournamentRecord:t,event:e}){if(!t)return{};let{extension:r}=qt({element:t,name:Vb}),n=r?.value;if(!n?.events?.length)return{};let o=e?n.events.find(s=>s.eventType===e.eventType&&(!s.eventName||s.eventName===e.eventName)&&(!s.category?.categoryName||s.category?.categoryName===e.category?.categoryName)):void 0;if(!o)return{};let i={};return o.drawSize!==void 0&&(i.drawSize=o.drawSize),o.maxWildcards!==void 0&&(i.maxWildcards=o.maxWildcards),o.maxAlternates!==void 0&&(i.maxAlternates=o.maxAlternates),o.maxQualifiers!==void 0&&(i.maxQualifiers=o.maxQualifiers),Object.keys(i).length?{constraints:i}:{}}var Nu="GEMscore",ck={GEM_SCORE:Nu};function uk({provisionalPositioning:t,rankBy:e=Nu,finishingPositions:r,groupResults:n,bestOf:o}){let i=[],s=[],a=[...r].sort(ee),c=Math.max(...a);for(let{structureId:m,results:l}of n)for(let[f,g]of Object.entries(l)){let I=g.groupOrder||t&&g.provisionalOrder;if(!I)continue;let h={groupingValue:m,GEMscore:g.GEMscore,isBestFinisher:!1,finishingPosition:I,participantId:f};a.includes(I)?s.push(h):I>c&&i.push(h)}let u=[...s],p=o-s.length;p>0&&i.length>0&&i.toSorted((f,g)=>f.finishingPosition!==g.finishingPosition?f.finishingPosition-g.finishingPosition:e===Nu?(g.GEMscore??0)-(f.GEMscore??0):0).slice(0,p).forEach(f=>{f.isBestFinisher=!0,u.push(f)});let d={};for(let m of u){let l=m.finishingPosition;d[l]=(d[l]||0)+1}return{selectedParticipants:u,consumedPositions:d}}var tn="ALTERNATE",kh="CONFIRMED",Nr="DIRECT_ACCEPTANCE",Kp="FEED_IN",Gh="JUNIOR_EXEMPT",Js="LUCKY_LOSER",Vh="ORGANISER_ACCEPTANCE",yf="QUALIFIER",I$="REGISTERED",Bh="SPECIAL_EXEMPT",kr="UNGROUPED",es="UNPAIRED",zp="WILDCARD",On="WITHDRAWN",Em=[kh,Nr,Gh,Vh,Bh],EC=[Kp,Js,yf],rs=[kh,Nr,Kp,Gh,Vh,Bh,zp],yr=[kh,Nr,Gh,Js,yf,Vh,Bh,zp],AC=[tn,kh,Nr,Kp,Gh,Js,Vh,yf,I$,Bh,kr,es,zp,On],pk={ALTERNATE:tn,CONFIRMED:kh,DIRECT_ACCEPTANCE:Nr,DIRECT_ENTRY_STATUSES:rs,DRAW_SPECIFIC_STATUSES:EC,EQUIVALENT_ACCEPTANCE_STATUSES:Em,FEED_IN:Kp,JUNIOR_EXEMPT:Gh,LUCKY_LOSER:Js,ORGANISER_ACCEPTANCE:Vh,QUALIFIER:yf,SPECIAL_EXEMPT:Bh,STRUCTURE_SELECTED_STATUSES:yr,UNGROUPED:kr,UNPAIRED:es,VALID_ENTRY_STATUSES:AC,WILDCARD:zp,WITHDRAWN:On};function dk({stage:t,drawDefinition:e}){return lu.includes(t)?e?.structures?.some(n=>n.stage===t)||lu.includes(t):!1}function JE({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function ns({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,d)=>{let m=$t({element:d,attribute:"roundTarget",name:Xr}),l=c&&d.entryStage===c||a?.length&&d.entryStage&&a.includes(d.entryStage),f=!o||d.entryStatus&&o.includes(d.entryStatus),g=d.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!m||s===m)?p.concat(d):p},[])??[];if(i&&c===Vt){let{playoffEntries:p,error:d}=h$({provisionalPositioning:t,drawDefinition:r,structureId:i});return d&&console.log("playoff entries error"),(p?.length?p:u).filter(m=>!e||m.placementGroup===e)}return u}function h$({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===fn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s,bestOf:a,rankBy:c}=o.source,{structure:u}=tt({drawDefinition:e,structureId:s});if(u?.structureType===Ie){let d=(u.structures??[]).map(m=>{let l=m.positionAssignments??[],{structureId:f}=m,g=Object.assign({},...l.map(I=>{let{participantId:h}=I,S=$t({element:I,attribute:"tally",name:to});return S&&h?{[h]:S}:void 0}).filter(Boolean));return{structureId:f,results:g}});if(o.source.remainder)S$({provisionalPositioning:t,allGroupResults:d,drawDefinition:e,playoffEntries:n,inboundLink:o,structureId:s});else if(a!==void 0&&i){let{selectedParticipants:m}=uk({groupResults:d,provisionalPositioning:t,finishingPositions:i,bestOf:a,rankBy:c});m.forEach(l=>{let g=i.includes(l.finishingPosition)?[...i].sort(ee).indexOf(l.finishingPosition)+1:[...i].sort(ee).length+1;n.push({isBestFinisher:l.isBestFinisher,groupingValue:l.groupingValue,participantId:l.participantId,GEMscore:l.GEMscore,entryStatus:Kp,entryStage:Vt,placementGroup:g})})}else T$({provisionalPositioning:t,finishingPositions:i,allGroupResults:d,playoffEntries:n})}}return{playoffEntries:n}}function S$({provisionalPositioning:t,allGroupResults:e,drawDefinition:r,playoffEntries:n,inboundLink:o,structureId:i}){let s=new Set,a=(r.links??[]).filter(c=>c.linkType===fn&&c.source.structureId===i&&c.target.structureId!==o.target.structureId&&c.source.bestOf!==void 0);for(let c of a){let{structure:u}=tt({structureId:c.target.structureId,drawDefinition:r});if(u)for(let p of u.positionAssignments??[])p.participantId&&s.add(p.participantId)}e.forEach(({structureId:c,results:u})=>{Object.keys(u).forEach(p=>{if(!s.has(p)){let d=u[p],{groupOrder:m,provisionalOrder:l,GEMscore:f}=d,g=m||t&&l;n.push({groupingValue:c,entryStage:Vt,entryStatus:Kp,placementGroup:g||1,participantId:p,GEMscore:f})}})})}function T$({provisionalPositioning:t,finishingPositions:e,allGroupResults:r,playoffEntries:n}){r.forEach(({structureId:o,results:i})=>{let s=o,c=Object.keys(i).reduce((p,d)=>{let m=i[d],l=m.groupOrder||t&&m.provisionalOrder;return p.includes(l)||p.push(l),p},[]).length===Object.keys(i).length,u=Object.keys(i).filter(p=>{let d=i[p],m=d.groupOrder||t&&d.provisionalOrder;return e?.includes(m)});(!t||c)&&u.forEach(p=>{let d=i[p],{groupOrder:m,provisionalOrder:l,GEMscore:f}=d,g=m||t&&l,I=[...e??[]].sort(ee).indexOf(g)+1;n.push({entryStage:Vt,entryStatus:Kp,placementGroup:I,groupingValue:s,participantId:p,GEMscore:f})})})}function Dr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=tt({drawDefinition:r,structureId:n}));let a=yt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Pt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,d=c===Vt&&r&&ns({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),m=d?d.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=m?.slice(0,e?m.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=kU;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function Qo(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 Am({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 tr({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:Am({item:r,drawDefinition:t,structure:e,event:n})||Am({item:e,drawDefinition:t,structure:e,event:n})||Qo(t)||Qo(n)}}function mk({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 ye({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,d=u.matchUps;r[u.structureId]={matchUps:d,itemStructureIds:[],structureName:p},d&&(n.push(...d),d.forEach(m=>{m.tieMatchUps&&n.push(...m.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 Jo({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(q(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps??[]).concat(...i)}function XE({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:o}){let i=t?.[gn];if(i?.profileBands)return i.profileBands;if(e){let{appliedPolicies:s}=gt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),a=s?.[gn];if(a?.profileBands)return a.profileBands}return zs[gn].profileBands}var y$=(t,e)=>(t||0)+(e||0);function ZE(t,e){let r=Array.isArray(t)?t[0]:t;return r===void 0||Number.isNaN(r)?zE:r<=e[Pu]&&Pu||r<=e[Au]&&Au||hf}function Ef({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(y$)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function E$(t){let e=t?.games;if(!e?.length)return;let r=Math.max(...e);if(r===0)return;let n=Math.min(...e);return Math.round(n/r*100)}function tA(t){return t.map(E$).filter(e=>e!==void 0).sort((e,r)=>e-r).map(e=>parseFloat(e.toFixed(2)))}function Xs({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:nr};let{score:n,winningSide:o}=r;if(!o)return{error:O};let i=e||XE({tournamentRecord:t}),s=Ef({score:n}),a=tA([s]),c=ZE(a,i),u=Array.isArray(a)?a[0]:a;return{...P,competitiveness:c,pctSpread:u}}function eA({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=Ae(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(ee);return n.map(i=>o.indexOf(i)+1)}function Hh(t){if(!St(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 Ur(t){return Array.isArray(t)?t.every(Hh):!1}function A$(t,e){return e?.find(r=>t.includes(r))}function _e({matchUps:t=[],interpolate:e}){if(!Ur(t))return{roundMatchUps:[],error:O};let r=t.reduce((m,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return!l.roundNumber||m.includes(f)?m:m.concat(f)},[]).sort(ee).map(m=>{let l=t.filter(h=>h.roundNumber===m),g=l.find(({matchUpType:h})=>h===xt)?l.filter(({matchUpType:h})=>h===xt):l,I=h=>h.sort((S,T)=>ee(S.roundPosition,T.roundPosition));return{[m]:I(g)}}),n=t.reduce((m,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return m[f]||(m[f]=et({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),m},{}),o=Object.assign({},...r);if(e){let m=Math.max(...Object.keys(o).map(f=>st(f)).filter(f=>!Number.isNaN(f))),l=o[m]?.length;if(l>1&&rn(l)){let f=m+1,g=f+l/2;J(f,g).forEach((h,S)=>{o[h]=J(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(m=>{let l=o[m]?.length,f=o[m]?.filter(I=>!Rt.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[m]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(m=>st(m)).filter(m=>!Number.isNaN(m));u.forEach(m=>{let l=o[m].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.flatMap(g=>g?.drawPositions??[]);if(s[m].roundNumber=m,s[m].roundFactor=s[m].matchUpsCount?i/s[m].matchUpsCount:1,s[m].finishingRound=n[m]?.finishingRound,s[m].roundName=n[m]?.roundName,s[m].abbreviatedRoundName=n[m]?.abbreviatedRoundName,s[m].finishingPositionRange=o[m]?.[0]?.finishingPositionRange,m===1||!s[m-1]){let g=f.sort(ee),I=Ae(g,2);s[m].drawPositions=g,s[m].pairedDrawPositions=I}else{let g=s[m-1],I=g.drawPositions,h=g.matchUpsCount/s[m].matchUpsCount,S=Ae(I,h),T=l.map(y=>{let{roundPosition:E}=y,A=[...y.drawPositions??[],void 0,void 0].slice(0,2);if(!E)return A;let N=A?.filter(Boolean)??[];if(!N?.length)return[void 0,void 0];if(m<3&&N?.length===2)return A?.slice().sort(ee);let D=Ht(I,N).length!==N?.length;if(N?.length&&D)return N?.length===1?[N[0],void 0]:A?.slice().sort(ee);let R=(E-1)*2;return S.slice(R,R+2).map(b=>A$(b,N))});s[m].drawPositions=T?.flat(),s[m].pairedDrawPositions=T}s[m+1]?.matchUpsCount===s[m].matchUpsCount&&(s[m+1].feedRound=!0,s[m+1].feedRoundIndex=c,s[m].preFeedRound=!0,c+=1),s[m]&&!s[m].feedRound&&(s[m].roundIndex=a,a+=1)});let p=!!Object.values(s).some(({matchUpsCount:m})=>!rn(m));return{hasNoRoundPositions:t.some(m=>!m.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...P}}function Af(t){if(!Array.isArray(t))return"";let e=t.filter(He);return e.length?ct([Math.min(...e),Math.max(...e)]).join("-"):""}function lk({drawDefinition:t,structureId:e,matchUpsMap:r}){let n=at({drawDefinition:t,structureId:e},[zt,Po]);if(n.error)return n;let{structure:o}=tt({drawDefinition:t,structureId:e});if(o?.stage!==je)return{error:hc,info:"Structure is not CONSOLATION stage"};let{links:i}=t,s=i?.filter(m=>m.target.structureId===e)??[],a=s?.reduce((m,l)=>{let{structureId:f}=l.source;return m.includes(f)?m:m.concat(f)},[])??[],c=Object.assign({},...a.map(m=>{let l=Jo({structureId:m,matchUpsMap:r}),g=_e({matchUps:l}).roundProfile;return{[m]:g}})),u=Jo({matchUpsMap:r,structureId:e}),{roundProfile:p}=_e({matchUps:u}),d={};return s?.forEach(m=>{let{structureId:l,roundNumber:f}=m.source,{feedProfile:g,groupedOrder:I,positionInterleave:h,roundNumber:S}=m.target,T=c[l],y=T[1]?.drawPositions,A=T[f]?.matchUpsCount;if(!A)return;let N=A?y.length/A:0,D=y.length/N,R=y.slice(),U=eA({roundPositionsCount:D,groupedOrder:I}),b=U?.length||1;if(b<=D){let x=y.length/b,w=Ae(R,x);g===$i&&w.forEach(F=>F.reverse()),R=U?.length&&U?.map(F=>w[F-1]).flat()||w.flat()}let C=Ae(R,N);if(h){let x=J(0,h.interleave).map(()=>{}),w=J(0,h.offset).map(()=>{});C=C.map(L=>[L,...x]),C.unshift(w),C=C.flat(1);let F=C.length-h.offset;C=C.slice(0,F)}d[S]||(d[S]={});let v=p?.[S]?.feedRound?2:1;C.forEach((x,w)=>{let F=1+w*v;d[S][F]||(d[S][F]=Af(x))})}),{sourceDrawPositionRanges:d}}function Pf({drawDefinition:t}){if(typeof t!="object")return{error:Ua};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:d}){s[c]||(s[c]=[]),a==="0"&&[je,Vt].includes(d)||s[c].push(a);let m=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of m){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 fk({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){let o=at({drawDefinition:t,structureId:r},[zt,Po]);if(o.error)return o;if(!e){let u=Jo({matchUpsMap:n,structureId:r});if({roundProfile:e}=_e({matchUps:u}),!e)return{error:nt}}let s=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,a=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(a??[]).map(u=>{let p=e?.[u]?.matchUpsCount,d=e?.[1]?.drawPositions??[],m=Ae(d,d.length/p),l=m.map(Af),f=m.map(T=>T.map(y=>y-s)).map(Af),g=a.map(T=>{if(T>u)return;let y=e?.[T]?.drawPositions??[];return Ae(y,y.length/p)}).filter(Boolean),I=J(0,p).map(T=>g.map(y=>y[T]).flat().filter(Boolean).sort(ee)).map(T=>ct(T)),h=I.map(T=>kL(T).map(Af).join(", ")),S=Object.assign({},...J(0,p).map(T=>({[T+1]:{firstRoundDrawPositionsRange:l[T],firstRoundOffsetDrawPositionsRange:f[T],possibleDrawPositions:I[T],drawPositionsRange:h[T]}})));return{[u]:S}}))}}var P$=new Set([di,Ki]);function cn(t){return!!t&&P$.has(t)}function Wh({structure:t,matchUps:e}){e=e??t?.matchUps??[];let r=_e({matchUps:e}),n=r.roundProfile,o=r.roundNumbers;if(!n||!o?.length||o.length<2)return!1;let i=[...o].sort((s,a)=>s-a);for(let s=0;s<i.length-1;s++){let a=n[i[s]]?.matchUpsCount??0,c=n[i[s+1]]?.matchUpsCount??0;if(a%2===1&&c%2===0)return!0}return!1}function _c({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){return!r||(n=n??r.matchUps??[],t=t??_e({matchUps:n}).roundsNotPowerOf2,!(!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length))||r?.structures)||e?.drawType&&cn(e.drawType)||!t?!1:Wh({structure:r,matchUps:n})}function De({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?.stage===Qe?t?.structures||t?.structureType===gu&&n?!1:t?.finishingPosition===Ao:!t?.structures&&(!e.length||!r&&!n)}var jh={[$o]:{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:{[j]:"",[Vt]:"P",[rt]:"Q",[je]:"C"}}},gk=jh;function rA({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=_e({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=De({structure:r}),u=_c({structure:r}),p=r.structures,d={},m=jh[$o],l=r.stage===rt,f=l?Math.max(...(e?.structures??[]).filter(_=>_.stage===rt).map(({stageSequence:_})=>_??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||m.affixes.preQualifying)||"",h=t?.roundNamingMap||(m.roundNamingMap??{}),S=t?.abbreviatedRoundNamingMap||(m.abbreviatedRoundNamingMap??{}),T=t?.affixes?.preFeedRound||m.affixes.preFeedRound,y=t?.affixes?.roundNumber||m.affixes.roundNumber,A=(t?.namingConventions||m.namingConventions).round,N=a&&a!==j?a[0]:"",D=t?.stageConstants||m.stageConstants,R=a&&D?.[a]||N,U=`${I}${R}${g}`,b=o?Object.keys(o):[],C=l&&D?.[rt]?`${D?.[rt]}-`:"";if(p||c||u)Object.assign(d,...b.map(_=>{let v=`${C}${A} ${_}`,x=`${y}${_}`;return{[_]:{roundName:v,abbreviatedRoundName:x}}}));else{let _=l&&(t?.qualifyingFinishMap||(m?.qualifyingFinishMap??{}));Object.assign(d,...b.map(v=>{if(!o?.[v])return;let{matchUpsCount:x,preFeedRound:w}=o[v],F=x*2,L=_?.[o?.[v].finishingRound]||_&&`${y}${F}`||h[x]||`${y}${F}`,k=w?`-${T}`:"",G=`${L}${k}`,V=[U,s,G].filter(Boolean).join("-"),$=`${S[x]||`${y}${F}`}${k}`,H=[U,s,$].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:H,roundName:V}}}))}return{roundNamingProfile:d,roundProfile:o,roundMatchUps:i}}function nA({matchUp:t}){if(!t)return{error:nr};if(t&&!t.sides)return{error:mr};if(t&&!t.hasContext)return{error:hp};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===ft).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=ct(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...P}}var Nf="CHECK_IN",Df="CHECK_OUT",N$="SCHEDULE",Ii="SCHEDULE.ASSIGNMENT.VENUE",Hn="SCHEDULE.ALLOCATION.COURTS",Ro="SCHEDULE.ASSIGNMENT.COURT",Ds="SCHEDULE.COURT.ORDER",Us="SCHEDULE.COURT.ANNOTATION",hi="SCHEDULE.DATE",D$="COMPLETED.DATE",xc="HOME_PARTICIPANT_ID",Du="SCHEDULE.ASSIGNMENT.OFFICIAL",Si="SCHEDULE.TIME.SCHEDULED",Ti="SCHEDULE.TIME.START",ja="SCHEDULE.TIME.STOP",Zs="SCHEDULE.TIME.RESUME",Rs="SCHEDULE.TIME.END",Ya="SCHEDULE.TIME.MODIFIERS",Ik="TO_BE_ANNOUNCED",hk="NEXT_AVAILABLE",Sk="FOLLOWED_BY",Tk="AFTER_REST",yk="RAIN_DELAY",U$="NOT_BEFORE",oA=[Ik,hk,Sk,Tk,yk],R$="ELIGIBILITY",b$="REGISTRATION",C$="SUSPENSION",M$="MEDICAL",v$="PENALTY",PC="SCALE",NC="RATING",DC="RANKING",Yh="SEEDING",Xo="PUBLISH",Rr="PUBLIC",Zo="STATUS",O$="MODIFICATION",_$="RETRIEVAL",x$="other",Ek={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:oA,AFTER_REST:Tk,ALLOCATE_COURTS:Hn,ASSIGN_COURT:Ro,ASSIGN_OFFICIAL:Du,ASSIGN_VENUE:Ii,CHECK_IN:Nf,CHECK_OUT:Df,COMPLETED_DATE:D$,COURT_ANNOTATION:Us,COURT_ORDER:Ds,ELIGIBILITY:R$,END_TIME:Rs,FOLLOWED_BY:Sk,MEDICAL:M$,MODIFICATION:O$,NEXT_AVAILABLE:hk,NOT_BEFORE:U$,OTHER:x$,PENALTY:v$,PUBLIC:Rr,PUBLISH:Xo,RANKING:DC,RATING:NC,RAIN_DELAY:yk,REGISTRATION:b$,RESUME_TIME:Zs,RETRIEVAL:_$,SCALE:PC,SCHEDULE:N$,SCHEDULED_DATE:hi,SCHEDULED_TIME:Si,SEEDING:Yh,START_TIME:Ti,STATUS:Zo,STOP_TIME:ja,SUSPENSION:C$,TIME_MODIFIERS:Ya,TO_BE_ANNOUNCED:Ik};function ta({matchUp:t}){if(!t)return{error:nr};if(!t.hasContext)return{error:hp};if(!t.sides||t?.sides.filter(Boolean).length!==2)return{error:mr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=nA({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Nf,Df].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===Nf);e?.forEach((u,p)=>{let d=n?.[p],m=u?.length&&u.every(l=>a.includes(l));d&&m&&!a.includes(d)&&a.push(d)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(d=>{d&&!a.includes(d)&&a.push(d)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...P}}var oe=t=>e=>{let r=St(e)&&e?.matchUpType||wt(e)&&e;return r&&yy[t].includes(r)};function Pm(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 Nm(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 iA({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 Ak({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Nm({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Nm({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Nm({...a,averageMinutes:r,matchUpFormat:o}),d=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return iA({categoryName:i,categoryType:s,timesBlockArray:d})}function Pk({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Pm({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Pm({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Pm({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return iA({categoryName:e,categoryType:r,timesBlockArray:p})}var UC="ADULT",RC="JUNIOR",sA="WHEELCHAIR",qh={[No]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[Ut]:30,default:60}}]},defaultDailyLimits:{[Ct]:2,[Ut]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[kn],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[sA],minutes:{default:120}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:85}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:70}}]},{matchUpFormatCodes:["SET3-S:4NOAD-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB7"],averageTimes:[{categoryNames:[],minutes:{default:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:50}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB5@3"],averageTimes:[{categoryNames:[],minutes:{default:45}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7"],averageTimes:[{categoryNames:[],minutes:{default:40}}]},{matchUpFormatCodes:["SET1-S:5/TB9@4"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6/TB7"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6NOAD"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB7","SET1-S:4/TB5@3","SET3-S:TB10","SET1-S:T20"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:4NOAD"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:TB10"],averageTimes:[{categoryNames:[],minutes:{default:10}}]}],matchUpRecoveryTimes:[{matchUpFormatCodes:["SET3-S:6/TB7","SET3-S:6/TB7-F:TB10","SET3-S:6/TB7-F:TB7"],recoveryTimes:[{categoryTypes:[UC,sA],minutes:{default:60,[Ut]:30}},{categoryTypes:[RC],minutes:{default:60,[Ut]:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7","SET3-S:4/TB7-F:TB10","SET3-S:4NOAD-F:TB7","SET3-S:4/TB7","SET3-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[UC,sA],minutes:{default:30}},{categoryTypes:[RC],minutes:{default:60}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7","SET1-S:5/TB9@4","SET1-S:6/TB7","SET1-S:6NOAD","SET1-S:4/TB7","SET1-S:4NOAD","SET3-S:TB10","SET1-S:T20"],recoveryTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[UC,RC],minutes:{default:30}},{categoryTypes:[sA],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},Nk=qh;var bC="DOUBLES_SINGLES",CC="SINGLES_DOUBLES",fo="total",aA="participantConflict",cA="potentialParticipantConflict",yi="matchUpConflict",MC="courtDoubleBooking",vC="positionLinkConflict",OC="ISSUE_IDS",ea="CONFLICT",ra="WARNING",Uf="ERROR",Rf="ISSUE",$h="STATE",w$="BLOCKED",Kh="PRACTICE",L$="MAINTENANCE",Dk={SINGLES_DOUBLES:CC,DOUBLES_SINGLES:bC,TOTAL:fo,CONFLICT_MATCHUP_ORDER:yi,CONFLICT_PARTICIPANTS:aA,CONFLICT_POTENTIAL_PARTICIPANTS:cA,CONFLICT_COURT_DOUBLE_BOOKING:MC,CONFLICT_POSITION_LINK:vC,SCHEDULE_ISSUE_IDS:OC,SCHEDULE_CONFLICT:ea,SCHEDULE_WARNING:ra,SCHEDULE_ERROR:Uf,SCHEDULE_ISSUE:Rf,SCHEDULE_STATE:$h,BLOCKED:w$,PRACTICE:Kh,MAINTENANCE:L$};function Qp({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:Y};s=s??a?.eventType??Fa;let c=ne(n),u=F$(c),d={averageTimes:[{minutes:{default:u??t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:m}=Oc({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),l=m.policy??qh[No];typeof u=="number"&&l&&(l={...l,defaultTimes:{...l.defaultTimes,averageTimes:[{minutes:{default:u}}]}});let f={...m,policy:l,matchUpFormat:n,categoryType:i,defaultTiming:d};return Dm({eventType:s,timingDetails:f})}function F$(t){if(!t)return;let e=t.matchUpConstraint?.timed?t.matchUpConstraint.minutes:void 0;if(typeof e=="number")return e;let r=t.setFormat?.timed&&typeof t.setFormat.minutes=="number"?t.setFormat.minutes:void 0;if(typeof r!="number")return;let n=t.bestOf??1,o=t.finalSetFormat?.timed&&typeof t.finalSetFormat.minutes=="number"?t.finalSetFormat.minutes:void 0;return n<=1?r:typeof o=="number"?(n-1)*r+o:n*r}function Dm({timingDetails:t,eventType:e}){let r=Pk(t),n=Object.keys(r?.minutes??{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Ak({...t,averageMinutes:o}),s=Object.keys(i?.minutes??{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=oe(Fa)(e)?CC:bC,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function _C(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Ei({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>_C(o)-_C(i)).pop(),n=r&&_C(r);return{itemValue:r?.itemValue,timeStamp:n}}function bf({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ei({timeItems:r?.timeItems??[],itemType:Si});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function na({timeStamp:t,schedule:e,matchUp:r}){let n=r?.schedule?.scheduledDate,{itemValue:o,timeStamp:i}=Ei({timeItems:r?.timeItems??[],itemType:hi}),s=n??o;return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{scheduledDate:s}:e}function Um(t){if(jy.test(t)){let e=nh();return new Date(`${e}T${t}`)}else return new Date(t)}function Uk({matchUp:t}){if(!t)return{error:nr};if(!t.timeItems)return{error:BI};let e=t.timeItems.filter(n=>[Ti,ja,Zs,Rs].includes(n?.itemType)).sort((n,o)=>Um(n.itemValue).getTime()-Um(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 Ti:i=0;break;case Rs:if(n.lastValue&&[Ti,Zs].includes(n.lastType)){let u=Um(o.itemValue).getTime()-Um(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case ja:if([Ti,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=Um(o.itemValue).getTime()-Um(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([Ti,Zs].includes(r.lastType)){let n=new Date().getTime()-Um(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:k$(r.milliseconds),relevantTimeItems:e}}function k$(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 Rk({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===Ti&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function uA(t){return parseInt(t)}function Cf({startTime:t="",endTime:e=""}={}){if(!t||!e||!du.test(t)||!du.test(e))return!1;let[r,n]=t.split(":").map(uA),[o,i]=e.split(":").map(uA);return o<r?!1:!(r===o&&i<n)}function bk(t,e){let[r,n]=t.startTime.split(":").map(uA),[o,i]=e.startTime.split(":").map(uA);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function Jp({dateAvailability:t}){if(!t)return{error:nR};if(!Array.isArray(t))return{error:OI};for(let e of t){if(typeof e!="object")return{error:OI};let{date:r,startTime:n,endTime:o,bookings:i=[]}=e;if(!n||!o)return{error:OI};let s=V$(r);if(s)return s;let a=Mk(n,o);if(a)return a;if(i){let c=B$(i);if(c)return c}}return{valid:!0}}var G$="Dates must be formated => YYYY-MM-DD",Ck="Times must be 24 hour => 00:00";function V$(t){if(t&&!Yo.test(t))return{error:de,dateAvailability:{date:t},info:G$}}function Mk(t,e){if(!du.test(t))return{error:Bs,dateAvailability:{startTime:t},info:Ck};if(!du.test(e))return{error:Bs,dateAvailability:{endTime:e},info:Ck};if(t===e)return{error:Bs,dateAvailability:{startTime:t,endTime:e},info:"startTime and endTime are equivalent"};if(!Cf({startTime:t,endTime:e}))return{error:Bs,dateAvailability:{startTime:t,endTime:e},info:"endTime must be after startTime"}}function B$(t){if(!Array.isArray(t))return{error:kl};for(let e of t){if(typeof e!="object")return{error:kl};let{startTime:r,endTime:n}=e,o=Mk(r,n);if(o)return o}}function pA({tournamentRecord:t}){for(let e of t.venues??[])e.isPrimary&&delete e.isPrimary}function Uu(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:O};let o=Pr(t);r.venueId??=ot();let i;for(let s of Object.values(o)){let a=H$({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||it({topic:GE,payload:{venue:r}}),et({...P,venue:i})}function H$({tournamentRecord:t,disableNotice:e,context:r,venue:n}){let o=at({tournamentRecord:t},[Z]);if(o.error)return o;if(!n)return{error:nt,info:"missing venue"};if(t.venues??=[],n.venueId??=ot(),t.venues.reduce((s,a)=>s||a.venueId===n.venueId,void 0))return{error:NR};if(n.dateAvailability?.length){let s=Jp({dateAvailability:n.dateAvailability});if(s.error)return s}if(n.defaultStartTime||n.defaultEndTime){if(!n.defaultStartTime||!n.defaultEndTime)return{error:O,info:"both defaultStartTime and defaultEndTime are required"};if(!Cf({startTime:n.defaultStartTime,endTime:n.defaultEndTime}))return{error:O,info:"defaultEndTime must be after defaultStartTime"}}return r&&Qt({element:n,extension:{value:r,name:kb}}),n.isPrimary&&pA({tournamentRecord:t}),t.venues.push(n),e||it({payload:{venue:n,tournamentId:t.tournamentId},topic:GE}),{...P,venue:q(n)}}function Wn({tournamentRecords:t,tournamentRecord:e,venueId:r}){let n=at({tournamentRecord:e,venueId:r},[Z,vp]);if(n.error)return n;let i=(e.venues??[]).reduce((s,a)=>a.venueId===r?a:s,void 0);if(!i&&t){let a=(Bp({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=Wn({tournamentRecord:u,venueId:r});if(p.success&&p.venue)return Uu({tournamentRecord:e,venue:p.venue}),{...P,venue:i}}}return i?{...P,venue:i}:{error:ji}}function dA({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Wn({tournamentRecords:r,tournamentRecord:n,venueId:o});return q(i,t,!0)}function Go({tournamentRecords:t,tournamentRecord:e,courtId:r}){let n=at({tournamentRecord:e,courtId:r},[Z,Oo]);if(n.error)return n;let o="findCourt",i,s;if((e.venues??[]).forEach(a=>{(a.courts??[]).forEach(c=>{c.courtId===r&&(i=c,s=a)})}),i)return{...P,court:i,venue:s};if(t){let c=(Bp({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let u of c){let p=t[u],d=Go({tournamentRecord:p,courtId:r});if(d.success)return d.venue&&Uu({tournamentRecord:e,venue:d.venue}),{...P,court:i,venue:s}}}return M({result:{error:So},stack:o})}function mA(t){return q(Go(t),!1,!0)}function Mf({tournamentRecord:t,internalUse:e,courtId:r}){let n=at({tournamentRecord:t,courtId:r},[Z,Oo]);if(n.error)return n;let o=Go({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.court&&(({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:d,surfaceCategory:m,surfaceType:l,surfacedDate:f,pace:g,notes:I})=>({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:d,surfaceCategory:m,surfaceType:l,surfacedDate:f,pace:g,notes:I}))(o.court);return{...P,courtInfo:q(i,!1,e)}}function Ru(t){let e=X(t,[{[Z]:!0},{venueId:!0,[qr]:Hs}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=Wn({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(Mf({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:d})=>({venueAbbreviation:d,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...P,venueData:q(c,!1,!0)}}function vk({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===Rs&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Gt({event:t,eventId:e}){if(!t)return{error:Se};let r=$t({element:t,attribute:"flightProfile",name:Kr}),n=e?q(r,!1,!0):r;return e&&t.drawDefinitions?.forEach(o=>{n?.flights?.forEach(i=>{i.drawId===o.drawId&&Object.assign(i,{drawDefinition:o})})}),{flightProfile:n}}function Ve(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(d=>{i[d.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(d=>{let l=(d?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[d.eventId].tournamentId;else{let g=(d&&Gt({event:d})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[d.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,...M({result:{error:Br},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,...M({result:{error:Cr},context:{drawId:n,eventId:r},stack:o})}}function vf(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:nr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let N=t.drawDefinition||e?.drawDefinitions?.find(R=>R.drawId===p.drawId);!N&&i&&({drawDefinition:N,event:e}=Ve({drawId:p.drawId,tournamentRecord:i}));let D=p.structureId?N?.structures?.find(({structureId:R})=>R===p.structureId):void 0;r=t.matchUpType||D?.matchUpType||N?.matchUpType||e?.eventType!==Ce&&e?.eventType}let{milliseconds:d,time:m}=Uk({matchUp:p}),{startTime:l}=Rk({matchUp:p}),{endTime:f}=vk({matchUp:p}),{eventIds:g,drawIds:I}=n??{},S=(!g||g.includes(p.eventId))&&(!I||I.includes(p.drawId))?W$({tournamentRecord:i,scheduleTiming:a,afterRecoveryTimes:o,matchUpFormat:c,matchUpType:r,matchUp:p,endTime:f,startTime:l,milliseconds:d,time:m}):et({milliseconds:d,startTime:l,endTime:f,time:m}),{scheduledDate:T}=na({matchUp:p}),{scheduledTime:y}=bf({matchUp:p});if(s&&u?.displaySettings?.draws){let N=u.displaySettings.draws,D=(N?.[p.drawId]??N?.default)?.scheduleDetails;if(D){let R=(D.find(U=>T&&U.dates?.includes(T))??D.find(U=>!U.dates?.length))?.attributes;if(R){let U=Object.assign({},...Object.keys(S).map(b=>({[b]:!0})),R);S=Ps({source:S,template:U})}}}let A=p.matchUpStatus&&Rt.includes(p.matchUpStatus)&&(ut(f)||ut(T)||ut(y))||void 0;return{schedule:S,endDate:A}}function W$({tournamentRecord:t,scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,startTime:a,milliseconds:c,time:u}){let p=_=>_.createdAt?new Date(_.createdAt).getTime():0,d=new Map,m=i.timeItems?.toSorted((_,v)=>p(_)-p(v))??[];for(let _ of m)d.set(_.itemType,_.itemValue);let l=i.schedule??{},f=l.homeParticipantId??d.get(xc),g=l.courtAnnotation??d.get(Us),I=l.allocatedCourts??d.get(Hn),h=l.scheduledTime??d.get(Si),S=l.timeModifiers??d.get(Ya),T=l.scheduledDate??d.get(hi),y=l.official??d.get(Du),E=l.courtOrder??d.get(Ds),A=l.venueId??d.get(Ii),N=l.courtId??d.get(Ro),D=j$({scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,scheduledTime:h});!T&&h&&(T=ut(h));let R=Kl({scheduledDate:T,scheduledTime:h}),{venueName:U,venueAbbreviation:b,courtName:C}=Y$({tournamentRecord:t,allocatedCourts:I,venueId:A,courtId:N});return et({typeChangeTimeAfterRecovery:D.typeChangeTimeAfterRecovery,typeChangeRecoveryMinutes:D.typeChangeRecoveryMinutes,timeAfterRecovery:D.timeAfterRecovery,recoveryMinutes:D.recoveryMinutes,averageMinutes:D.averageMinutes,homeParticipantId:f,courtAnnotation:g,venueAbbreviation:b,allocatedCourts:I,scheduledDate:T,scheduledTime:h,isoDateString:R,timeModifiers:S,venueName:U,venueId:A,courtOrder:E,courtName:C,courtId:N,official:y,milliseconds:c,startTime:a,endTime:s,time:u})}function j$({scheduleTiming:t,afterRecoveryTimes:e,matchUpFormat:r,matchUpType:n,matchUp:o,endTime:i,scheduledTime:s}){let a,c,u,p,d,m=o.matchUpType??n;if(t&&s&&e&&m){let l={matchUpFormat:o.matchUpFormat??r,...t};({averageMinutes:c=0,recoveryMinutes:u=0,typeChangeRecoveryMinutes:p=0}=Dm({timingDetails:l,eventType:m})),(c||u)&&(a=i?Yr(Kt(i),u):Yr(s,c+u)),p&&(d=i?Yr(Kt(i),p):Yr(s,c+p))}return{timeAfterRecovery:a,averageMinutes:c,recoveryMinutes:u,typeChangeRecoveryMinutes:p,typeChangeTimeAfterRecovery:d}}function Y$({tournamentRecord:t,allocatedCourts:e,venueId:r,courtId:n}){let o={},i=(t&&r&&Ru({tournamentRecord:t,venueId:r}))?.venueData??{};r&&(o[r]=i);let{venueName:s,venueAbbreviation:a,courtsInfo:c}=i,p=(n&&c?.find(d=>d.courtId===n))?.courtName;for(let d of e??[]){if(!t)break;d.venueId&&!o[d.venueid]&&(o[d.venueId]=Ru({venueId:d.venueId,tournamentRecord:t})?.venueData);let m=o[d.venueId];d.venueName=m?.venueName;let l=m?.courtsInfo?.find(f=>f.courtId===d.courtId);d.courtName=l?.courtName}return{venueName:s,venueAbbreviation:a,courtName:p}}function Ok({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(Uy(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>we(c??[],t.filter(Boolean)))??n,a=o?.feedRound;if(Dy(t)){let c=[...t].sort(ee);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(st(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Rm({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(d=>d.collectionPosition===t&&d.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(d=>d!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function yn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:Y};if(!Array.isArray(r)||r.length>2)return{error:vr};if(!r.length)return M({result:{error:jo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===dt&&Ht(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return M({result:{error:Wt},stack:n});let s=q(o.slice(1),!1,!0);return{participant:q(i),duplicatedPairParticipants:s,...P}}function oa({drawDefinition:t,participantId:e}){return typeof t!="object"?{error:K}:typeof e!="string"?{error:$e}:{lineUp:($t({element:t,attribute:"lineUps",name:po})??{})[e]}}function _k({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:d,lineUp:m,teamParticipant:l})=>{let{assignedParticipantIds:f,substitutions:g}=Rm({collectionPosition:r,collectionId:s,lineUp:m});if(c===Ut){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||yn({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[d]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[d]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[d]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let d=a?.map(m=>{let{teamParticipant:l,sideNumber:f}=m,g=m.lineUp||oa({participantId:l.teamParticipantId,drawDefinition:i})?.lineUp;return u({attribute:f,lineUp:g,teamParticipant:l})}).filter(Boolean)??{};return{sideNumberCollectionAssignment:Object.assign({},...d)}}let p=n?.map(d=>{let m=e.find(I=>I.drawPosition===d)?.participantId,l=a?.find(I=>I?.drawPosition===d),f=l?.teamParticipant||m&&o?.[m]?.participant||t?.find(({participantId:I})=>I===m),g=l?.lineUp||oa({participantId:m,drawDefinition:i})?.lineUp;return u({attribute:d,lineUp:g,teamParticipant:f})}).filter(Boolean)??{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function Of(t){let e=X(t,[{[Cn]:!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===ft&&Ct||s===dt&&Ut||s===bt&&bt||void 0}return{matchUpType:n}}function xk({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,d=u?u[i]?.participantId:c?.participantId,m=c?q$({displaySideNumber:n,seedAssignments:o,participantId:d,assignment:c,sideNumber:a}):{...p?.[a]};if(s&&(a===1?Object.assign(m,{participantFed:!0}):Object.assign(m,{participantAdvanced:!0})),i&&u){let l=u[i]?.teamParticipant,f=u[i]?.participant,g=u[i]?.substitutions;f&&(m.participant=f),g&&(m.substitutions=g),l&&(m.teamParticipant=l)}return m}function q$({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=$$({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 $$({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function Vo(t){let e=t?.embargo;return!e||!ys(e)?!1:new Date(e).getTime()>Date.now()}function go(t){return!!t?.published&&!Vo(t)}function K$({publishStatus:t,drawDefinition:e,structure:r,matchUp:n,schedule:o}){if(!t||!e?.drawId||!r?.structureId)return o;let i=t?.drawDetails?.[e.drawId]?.structureDetails?.[r.structureId];if(!i)return o;let s=n.roundNumber;if(!It(s))return o;let a=i.scheduledRounds?.[s];if(!(a&&Vo(a)))return o}function z$({matchUp:t,collectionDefinition:e,structure:r,drawDefinition:n,event:o,tournamentRecord:i}){return t.processCodes?.length&&t.processCodes||e?.processCodes?.length&&e?.processCodes||r?.processCodes?.length&&r?.processCodes||n?.processCodes?.length&&n?.processCodes||o?.processCodes?.length&&o?.processCodes||i?.processCodes}function xC({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:d,appliedPolicies:m,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,publishStatus:E,scoringActive:A,matchUpTieId:N,isRoundRobin:D,roundProfile:R,sideLineUps:U,structure:b,context:C,matchUp:_,event:v}){c=c??{};let x=tr({drawDefinition:y,structure:b,matchUp:_,event:v})?.tieFormat,{roundOffset:w,structureId:F,structureName:L,stage:k,stageSequence:G}=b,{drawId:V,drawName:B,drawType:$}=y??{},H=x?.collectionDefinitions,z=_.collectionId&&H?.find(io=>io.collectionId===_.collectionId),W=_.collectionId?z?.matchUpFormat:_.matchUpFormat??b?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,Q=_.matchUpType||z?.matchUpType||b?.matchUpType||y?.matchUpType||!oe(Ce)(v?.eventType)&&v?.eventType,pt=l?"BYE":_.matchUpStatus,{schedule:Tt,endDate:Ot}=vf({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:W,publishStatus:E,matchUpType:Q,matchUp:_,event:v});g&&Tt&&(Tt=K$({publishStatus:E,drawDefinition:y,structure:b,matchUp:_,schedule:Tt}));let Et=d??_.drawPositions??[],{collectionPosition:Bt,collectionId:ce,roundPosition:ge}=_,he=_.roundNumber??c.roundNumber,oo=ce?_k({tournamentParticipants:r,positionAssignments:n,collectionPosition:Bt,participantMap:I,drawDefinition:y,drawPositions:Et,collectionId:ce,sideLineUps:U,matchUpType:Q}):void 0,Ln=u?.[he]?.roundName||c.roundName,Fn=u?.[he]?.abbreviatedRoundName||c.abbreviatedRoundName,Ui=R?.[he]?.feedRound,ii=R?.[he]?.preFeedRound,Pa=R?.[he]?.roundFactor,Fs=o?.[he],cp=ge?Fs?.[ge]:void 0,mc=e?.[he],Ol=z?.category?{...C?.category,...z.category}:C?.category??v?.category,lc=z$({matchUp:_,collectionDefinition:z,structure:b,drawDefinition:y,event:v,tournamentRecord:p}),Me=T?.withCompetitiveness&&Xs({...h,matchUp:_}),Ri=_.finishingPositionRange??c.finishingPositionRange,gs=k!==rt&&It(a)&&a+(he||0),fc=io=>et(io,void 0,!0),Nn={...fc(C),...fc({matchUpFormat:Q===Ce?void 0:W,tieFormat:Q===Ce?x:void 0,gender:z?.gender??v?.gender,endDate:_.endDate??Ot,discipline:v?.discipline,category:Ol,finishingPositionRange:Ri,abbreviatedRoundName:Fn,drawPositionsRange:cp,competitiveProfile:Me,structureName:L,stageSequence:G,drawPositions:Et,matchUpStatus:pt,processCodes:lc,isRoundRobin:D,matchUpTieId:N,preFeedRound:ii,matchUpType:Q,roundFactor:Pa,roundOffset:w,structureId:F,roundNumber:he,roundOfPlay:gs,feedRound:Ui,roundName:Ln,drawName:B,drawType:$,schedule:Tt,drawId:V,stage:k}),...q(fc(_),!0,!0)};if(W&&_.score?.scoreStringSide1&&Q$(Nn,W),Array.isArray(Et)){let io=J$({sourceDrawPositionRoundRanges:mc,collectionAssignmentDetail:oo,positionAssignments:n,seedAssignments:f,drawPositions:Et,roundPosition:ge,roundProfile:R,roundNumber:he,onlyDefined:fc,matchUp:_});Object.assign(Nn,q({sides:io},!0,!0))}if(r&&Nn.sides){if(X$({tournamentParticipants:r,hydrateParticipants:i,positionAssignments:n,appliedPolicies:m,drawDefinition:y,participantMap:I,contextProfile:T,matchUpWithContext:Nn,event:v}),!Nn.matchUpType){let{matchUpType:io}=Of({matchUp:Nn});io&&Object.assign(Nn,{matchUpType:io})}t3({contextProfile:T,matchUpWithContext:Nn})}Nn.tieMatchUps&&e3({matchUpWithContext:Nn,abbreviatedRoundName:Fn,roundNumber:he,roundName:Ln,drawPositions:Et,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,appliedPolicies:m,usePublishState:g,publishStatus:E,isRoundRobin:D,roundProfile:R,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:A,structure:b,context:C});let Qc=Nn.sides?.filter(io=>io?.participantId).length===2,up=!Nn.winningSide;if(Object.assign(Nn,{readyToScore:A&&Qc&&up,hasContext:!0}),Qc){let{allParticipantsCheckedIn:io,checkedInParticipantIds:_l}=ta({matchUp:Nn});Object.assign(Nn,{allParticipantsCheckedIn:io,checkedInParticipantIds:_l})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(io=>delete Nn[io]),Nn}function Q$(t,e){let r=ne(e),{bestOf:n,finalSetFormat:o,setFormat:i}=r??{};!o?.tiebreakSet&&!i?.tiebreakSet&&!i?.timed||(t.score.sets=t.score.sets.sort((s,a)=>s.setNumber-a.setNumber).map((s,a)=>{let p=a+1===n&&o?o:i,d=p?.tiebreakSet&&!p?.timed,m=p?.timed;return d?(s.tiebreakSet=!0,[1,2].includes(s.winningSide)&&(s.side1Score=s.winningSide===1?1:0,s.side2Score=s.winningSide===2?1:0)):m&&(s.timed=!0),s}))}function J$({sourceDrawPositionRoundRanges:t,collectionAssignmentDetail:e,positionAssignments:r,seedAssignments:n,drawPositions:o,roundPosition:i,roundProfile:s,roundNumber:a,onlyDefined:c,matchUp:u}){let{orderedDrawPositions:p,displayOrder:d}=Ok({drawPositions:o,roundProfile:s,roundNumber:a}),m=s?.[a]?.feedRound,l=d[0]!==p[0];return p.concat(void 0,void 0).slice(0,2).map((g,I)=>{let h=I+1,S=l?3-h:h,T=xk({...e,positionAssignments:r,displaySideNumber:S,seedAssignments:n,drawPosition:g,isFeedRound:m,sideNumber:h}),y=u.sides?.find(N=>N.sideNumber===h),E=i?(i-1)*2+I+1:void 0,A=E?t?.[E]:void 0;return c({sourceDrawPositionRange:A,...y,...T})})}function X$({tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,participantMap:i,contextProfile:s,matchUpWithContext:a,event:c}){let u=n?.[Ba],p=d=>{let m=i?.[d]?.participant;return m&&Ps({template:u?.participant,source:m})};a.sides.filter(Boolean).forEach(d=>{if(Z$({side:d,getMappedParticipant:p,tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,contextProfile:s,event:c}),d?.participant?.individualParticipantIds?.length&&!d.participant.individualParticipants?.length){let m=d.participant.individualParticipantIds.map(l=>p(l)||(t?li({policyDefinitions:n,tournamentParticipants:t,internalUse:!0,contextProfile:s,participantId:l}):void 0));e!==!1&&Object.assign(d.participant,{individualParticipants:m})}})}function Z$({side:t,getMappedParticipant:e,tournamentParticipants:r,hydrateParticipants:n,positionAssignments:o,appliedPolicies:i,drawDefinition:s,contextProfile:a,event:c}){if(!t.participantId)return;let u=q(e(t.participantId)||(r?li({policyDefinitions:i,participantId:t.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:a}):void 0),void 0,!0);if(!u)return;let p,d;if(s?.entries){let l=s.entries.find(g=>g.participantId===t.participantId),f=c?.entries?.find(g=>g.participantId===t.participantId);p=l?.entryStatus||f?.entryStatus,u.entryStatus=p,l?.entryStage&&(d=l.entryStage,u.entryStage=d)}let m;t.drawPosition&&o&&o.find(f=>f.drawPosition===t.drawPosition)?.extensions?.some(f=>f.name==="luckyAdvancement")&&(m=!0,u.luckyAdvancement=!0),n===!1?Object.assign(t,{participant:{entryStage:d,entryStatus:p,luckyAdvancement:m}}):Object.assign(t,{participant:u})}function t3({contextProfile:t,matchUpWithContext:e}){if(!(t?.inferGender&&(!e.gender||e.gender===Ss)&&e.sides?.length===2&&e.matchUpType!==Ce))return;let n=e.sides.map(o=>{if(oe(Ct)(e.matchUpType))return o.participant?.person?.sex;if(o.participant?.individualParticipants?.length===2){let i=ct(o.participant.individualParticipants.map(s=>s.person?.sex)).filter(Boolean);if(i.length===1)return i[0]}});n.filter(Boolean).length===2&&ct(n).length===1&&(e.inferredGender=n[0])}function e3(t){let{matchUpWithContext:e}=t,r=e.matchUpStatus==="BYE",n=e.sides?.map(({participant:o,drawPosition:i,sideNumber:s,lineUp:a})=>{let c=o?.participantType===Ce&&o;return{teamParticipant:c&&et({participantRoleResponsibilities:c.participantRoleResponsibilities,participantOtherName:c.participantOtherName,participantName:c.participantName,participantId:c.participantId,teamId:c.teamId}),drawPosition:i,sideNumber:s,lineUp:a}});e.tieMatchUps=e.tieMatchUps.map(o=>{let i=e.matchUpId,a={finishingPositionRange:e.finishingPositionRange,abbreviatedRoundName:t.abbreviatedRoundName,roundNumber:t.roundNumber,roundName:t.roundName};return xC({tieDrawPositions:t.drawPositions,scheduleVisibilityFilters:t.scheduleVisibilityFilters,sourceDrawPositionRanges:t.sourceDrawPositionRanges,sideLineUps:n,drawPositionsRanges:t.drawPositionsRanges,initialRoundOfPlay:t.initialRoundOfPlay,roundNamingProfile:t.roundNamingProfile,additionalContext:a,appliedPolicies:t.appliedPolicies,isCollectionBye:r,usePublishState:t.usePublishState,publishStatus:t.publishStatus,matchUpTieId:i,isRoundRobin:t.isRoundRobin,roundProfile:t.roundProfile,matchUp:o,event:t.event,tournamentParticipants:t.tournamentParticipants,positionAssignments:t.positionAssignments,tournamentRecord:t.tournamentRecord,seedAssignments:t.seedAssignments,participantMap:t.participantMap,contextContent:t.contextContent,scheduleTiming:t.scheduleTiming,contextProfile:t.contextProfile,drawDefinition:t.drawDefinition,scoringActive:t.scoringActive,structure:t.structure,context:t.context})})}function wk({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ei({timeItems:r?.timeItems??[],itemType:Hn});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:q(n,!1,!0)}:e}function Lk({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ei({timeItems:r?.timeItems??[],itemType:Ro});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function Fk({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ei({timeItems:r?.timeItems??[],itemType:Ii});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function os(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:d,roundNumbers:m,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:E,tournamentIds:A,matchUpTypes:N,structureIds:D,readyToScore:R,courtIds:U,eventIds:b,venueIds:C,drawIds:_,stages:v}=t,x=Array.isArray(y)?y.filter(Boolean):[],w=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],L=Array.isArray(v)?v.filter(Boolean):[],k=Array.isArray(h)?h.filter(Boolean):[],G=Array.isArray(p)?p.filter(Boolean):[],V=Array.isArray(f)?f.filter(Boolean):[],B=Array.isArray(m)?m.filter(Boolean):[],$=Array.isArray(c)?c.filter(Boolean):[],H=Array.isArray(l)&&I?l.filter(Boolean):[],z=Array.isArray(N)&&g?N.filter(Boolean):[],W=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(C)?C.filter(Boolean):[],pt=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],Tt=Array.isArray(S)&&S.filter(Boolean).length&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],Ot=Array.isArray(A)?A.filter(Boolean):[],Et=Array.isArray(b)?b.filter(Boolean):[],Bt=Array.isArray(_)?_.filter(Boolean):[],ce=Array.isArray(D)?D.filter(Boolean):[];return e.filter(ge=>!(!r3({matchUp:ge,readyToScore:R,hasWinningSide:s,isMatchUpTie:d,isCollectionMatchUp:o})||!n3({matchUp:ge,targetStages:L,targetStageSequences:k,targetCollectionIds:G,targetRoundNames:V,targetRoundNumbers:B,targetRoundPositions:$,targetMatchUpStatuses:w,excludeTargetMatchUpStatuses:F,targetMatchUpIds:H,targetMatchUpTypes:z,targetMatchUpFormats:pt})||!o3({matchUp:ge,targetScheduledDates:Tt,targetCourtIds:W,targetVenueIds:Q})||E&&!i3({matchUp:ge,targetTournamentIds:Ot,targetEventIds:Et,targetDrawIds:Bt,targetStructureIds:ce,targetParticipantIds:x,hasParticipantsCount:n})))}function r3({matchUp:t,readyToScore:e,hasWinningSide:r,isMatchUpTie:n,isCollectionMatchUp:o}){return!(e&&!oe(hr)(t)&&!t.readyToScore||t.winningSide&&r&&![1,2].includes(t.winningSide)||n!==void 0&&(n&&!t.tieMatchUps||!n&&t.tieMatchUps)||o!==void 0&&(o&&!t.collectionId||!o&&t.collectionId))}function n3({matchUp:t,targetStages:e,targetStageSequences:r,targetCollectionIds:n,targetRoundNames:o,targetRoundNumbers:i,targetRoundPositions:s,targetMatchUpStatuses:a,excludeTargetMatchUpStatuses:c,targetMatchUpIds:u,targetMatchUpTypes:p,targetMatchUpFormats:d}){return!(e.length&&!e.includes(t.stage)||r.length&&!r.includes(t.stageSequence)||n.length&&(!t.collectionId||!n.includes(t.collectionId))||o.length&&(!t.roundName||!o.includes(t.roundName))||i.length&&(!t.roundNumber||!i.includes(t.roundNumber))||s.length&&(!t.roundPosition||!s.includes(t.roundPosition))||a.length&&(!t.matchUpStatus||!a.includes(t.matchUpStatus))||c.length&&t.matchUpStatus&&c.includes(t.matchUpStatus)||u.length&&!u.includes(t.matchUpId)||p.length&&(!t.matchUpType||!Gs(p,t.matchUpType))||d.length&&(!t.matchUpFormat||!d.includes(t.matchUpFormat)))}function o3({matchUp:t,targetScheduledDates:e,targetCourtIds:r,targetVenueIds:n}){if(e?.length){let{scheduledTime:o}=bf({matchUp:t}),{scheduledDate:i}=na({matchUp:t}),a=ut(o)||i;if(!e.some(c=>nn(c,a)))return!1}if(r.length){let{courtId:o}=Lk({matchUp:t}),{allocatedCourts:i}=wk({matchUp:t}),s=i?.map(({courtId:a})=>a);if(!r.filter(Boolean).includes(o)||s?.includes(o))return!1}if(n.length){let{venueId:o}=Fk({matchUp:t});if(!n.filter(Boolean).includes(o))return!1}return!0}function i3({matchUp:t,targetTournamentIds:e,targetEventIds:r,targetDrawIds:n,targetStructureIds:o,targetParticipantIds:i,hasParticipantsCount:s}){if(e.length&&!e.includes(t.tournamentId)||r.length&&!r.includes(t.eventId)||n.length&&!n.includes(t.drawId)||o.length&&!o.includes(t.structureId))return!1;let a=t.sides?.map(({participantId:c})=>c).filter(Boolean)??[];return!(s&&a.length<s||i.length&&!i.some(u=>a.includes(u)))}function ht(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:d,contextContent:m,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:Hi,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),E=!S?.length||S.includes(c.structureId),A=!s||!T?.length||T.includes(s.drawId);if(!y||!E||!A)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!m&&(m=lo({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:N}=gt({drawDefinition:s}),D={...t.tournamentAppliedPolicies,...N,...t.policyDefinitions},R=D?.scoring?.structures,U=c.stage&&R?.stage?.[c.stage],b=c.stageSequence&&U?.stageSequence?.[c.stageSequence],C=D?.scoring?.requireAllPositionsAssigned||U?.requireAllPositionsAssigned||b?.requireAllPositionsAssigned;f??=ye({drawDefinition:s,structure:c});let{positionAssignments:_,allPositionsAssigned:v}=pe({structure:c}),x=!C||v,{seedAssignments:w}=Dr({provisionalPositioning:e,drawDefinition:s,structure:c});d=d??w;let{structureId:F}=c;l=l||s&&Pf({drawDefinition:s}).exitProfiles;let L=l?.[F],k=L?.length&&(L[0].split("-").map(W=>Number.parseInt(W)).reduce((W,Q)=>W+Q,0)||0),G=!!c.structures,V=Jo({matchUpsMap:f,structureId:F,inContext:u}),B=D?.[$o],$=rA({roundNamingPolicy:B,drawDefinition:s,structure:c,matchUps:V}),{roundNamingProfile:H,roundProfile:z}=$;if(I=$?.roundMatchUps??[],o){let W=new Set(V.filter(Q=>Array.isArray(Q.tieMatchUps)).map(Q=>Q.matchUpId));V=os({matchUps:W.size?V.filter(Q=>!W.has(Q.matchUpId)):V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1}).concat(W.size?V.filter(Q=>W.has(Q.matchUpId)):[])}return u?V=a3({positionAssignments:_,initialRoundOfPlay:k,roundNamingProfile:H,tournamentRecord:r,appliedPolicies:D,seedAssignments:d,contextContent:m,contextProfile:i,drawDefinition:s,contextFilters:n,scoringActive:x,isRoundRobin:G,roundProfile:z,matchUpsMap:f,structureId:F,structure:c,context:a,params:t,event:p,matchUps:V}):(V=kk(V),i?.withCompetitiveness&&(V=s3({policyDefinitions:t.policyDefinitions,tournamentRecord:r,drawDefinition:s,structure:c,matchUps:V,event:p}))),o&&(V=os({matchUps:V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(V=os({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:V})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=_e({matchUps:V}).roundMatchUps??[]),tr({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=mk({matchUps:V})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:G,roundProfile:z,matchUpsMap:f,matchUps:V}}function kk(t){let e=t?.filter(n=>Array.isArray(n.tieMatchUps)),r=t;return e.forEach(n=>{r=r.concat(...n.tieMatchUps)}),r}function s3({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,matchUps:o,event:i}){let s=XE({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:i});return o.map(a=>{if(a.competitiveProfile||!a.winningSide)return a;let c=Xs({profileBands:s,matchUp:a});return c.error?a:{...a,competitiveProfile:c}})}function a3({positionAssignments:t,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,contextProfile:a,drawDefinition:c,contextFilters:u,scoringActive:p,isRoundRobin:d,roundProfile:m,matchUpsMap:l,structureId:f,structure:g,context:I,params:h,event:S,matchUps:T}){let{sourceDrawPositionRanges:y}=lk({drawDefinition:c,matchUpsMap:l,structureId:f}),E=c?fk({drawDefinition:c,roundProfile:m,matchUpsMap:l,structureId:f}).drawPositionsRanges:void 0,A=h.tournamentParticipants,N=h.participantMap;!A?.length&&!N&&n&&({participants:A=[],participantMap:N}=gi({participantsProfile:h.participantsProfile,useParticipantMap:h.useParticipantMap,policyDefinitions:h.policyDefinitions,tournamentRecord:n,contextProfile:a,inContext:!0}));let D=T.map(R=>xC({scheduleVisibilityFilters:h.scheduleVisibilityFilters,hydrateParticipants:h.hydrateParticipants,afterRecoveryTimes:h.afterRecoveryTimes,usePublishState:h.usePublishState,scheduleTiming:h.scheduleTiming,publishStatus:h.publishStatus,sourceDrawPositionRanges:y,tournamentParticipants:A,positionAssignments:t,drawPositionsRanges:E,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,participantMap:N,contextProfile:a,drawDefinition:c,scoringActive:p,isRoundRobin:d,roundProfile:m,structure:g,context:I,matchUp:R,event:S}));return D=kk(D),u&&(D=os({processContext:!0,...u,matchUps:D})),D}function ia({matchUp:t}){return t?Rt.includes(t?.matchUpStatus)||t?.winningSide:!1}function Xp({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:d,participantMap:m,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structureId:T,inContext:y,structure:E,context:A,event:N}){!E&&T&&({structure:E}=tt({drawDefinition:I,structureId:T}));let D=ht({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:d,participantMap:m,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structure:E,inContext:y,context:A,event:N}),R=[],U=[],b=[],C=[],_=[];if(D.error)return D;let{matchUps:v}=D,{assignedPositions:x}=pe({structure:E}),w=x?.filter(L=>L.participantId).map(L=>L.drawPosition),F;return v.filter(L=>{let k=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===xt;return!(L.matchUpType!==xt&&k)}).forEach(L=>{if(L.matchUpStatus===Lr){R.push(L);return}L.matchUpType===xt&&(F=!0);let k=!!L.collectionId,G=k&&L.sides?.every(Q=>Q.participantId),V=!k&&L.drawPositions?.filter(Boolean).length===2,B=!k&&L.drawPositions?.every(Q=>w?.includes(Q)),$=x?.filter(Q=>Q.bye).map(Q=>Q.drawPosition),H=!k&&L.drawPositions?.find(Q=>$?.includes(Q)),W=_E.includes(L.matchUpStatus)&&(G||V&&(!t||B));return H?_.push(L):ia({matchUp:L})?U.push(L):W?b.push(L):C.push(L)}),{includesTeamMatchUps:F,abandonedMatchUps:R,completedMatchUps:U,upcomingMatchUps:b,pendingMatchUps:C,byeMatchUps:_,structure:E}}function Gk({drawDefinition:t,roundNumber:e,structureId:r}){let n=at({drawDefinition:t,structureId:r},[zt,Po]);if(n.error)return n;let{links:o}=qa({drawDefinition:t,structureId:r}),i=o.source.reduce((a,c)=>!c.source.roundNumber||c.source.roundNumber===e?a.concat(c):a,[]),s=o.target.reduce((a,c)=>!c.target.roundNumber||c.target.roundNumber===e?a.concat(c):a,[]);return{links:{source:i,target:s}}}function lA({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||we(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Ar,pr].includes(o?.linkType)&&!o?.source?.roundNumber?M({result:{error:O},stack:"getTargetLink",context:o}):o}function qa({drawDefinition:t,structureId:e,roundNumber:r}){let n=at({drawDefinition:t,structureId:e},[zt,Po]);return n.error?n:{links:(t.links??[]).filter(Boolean).reduce((s,a)=>(a.source?.structureId===e&&(!r||a.source.roundNumber===r)&&(s.source=s.source.concat(a)),a.target?.structureId===e&&(!r||a.target.roundNumber===r)&&(s.target=s.target.concat(a)),s),{source:[],target:[]})}}function Vk({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 fA({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:AI};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=tt({drawDefinition:n,structureId:i}),{positionAssignments:d}=yt({structure:p}),l=(e?.filter(U=>U.structureId===p?.structureId)).filter(U=>U.roundNumber===c&&!U.matchUpTieId),f=l.length,g=J(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let U=u.offset+(r-1)*u.interleave,b=r+U;h=Math.ceil(b/2),S=1-b%2}let T=g,y=g[h-1],E=eA({roundPositionsCount:g.length,groupedOrder:a}),A=E?.length||1;if(A<=g.length){let U=f/A,b=Ae(g,U);s===$i&&b.forEach(C=>C.reverse()),T=E?.length&&E?.map(C=>b[C-1]).flat()||T}s===Je?y=T[h-1]:s===$i?((!E?.length||A>g.length)&&(h=l.length+1-h),y=T[h-1]):s===dm&&We()&&console.log(jI,{feedProfile:s});let N=y&&l.reduce((U,b)=>b.roundPosition===y?b:U,void 0),D;N?.feedRound?(S=0,D=Math.min(...(N.drawPositions??[]).filter(Boolean))):D=N?.drawPositions?.length===2&&N?.drawPositions[S];let R=d?.find(({drawPosition:U})=>U===D);return R&&$t({element:R,attribute:"disableLinks",name:Fp})?{disabledDrawPosition:D}:{matchUp:N,targetDrawPosition:D,matchUpDrawPositionIndex:S}}function ir({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}=tt({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===As?c3({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):u3({matchUp:i})}function c3({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=Gk({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=lA({source:c,linkType:Ar}),p=lA({linkCondition:Jn,linkType:pr,source:c}),d=lA({source:c,linkType:pr}),m=p&&d;d||(d=p);let l=u?.target?.feedProfile,f=d?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,E,A,N,D,R;if(e&&(i||s)&&(A=i&&l!==ln&&t.find(({matchUpId:C})=>C===i),T=s&&f!==ln&&t.find(({matchUpId:C})=>C===s),A||T))return{matchUp:o,targetLinks:{loserTargetLink:d,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:A}};let{roundPosition:U}=o;R=R||t.filter(C=>C.structureId===n.structureId);let b=R.reduce((C,_)=>_.roundNumber===o.roundNumber&&!_.matchUpTieId?C+1:C,0);return d&&!T&&f!==ln&&({matchUpDrawPositionIndex:E,targetDrawPosition:y,matchUp:T}=fA({targetLink:d,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),m&&g!==ln&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=fA({targetLink:p,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),u&&!A&&l!==ln&&({matchUpDrawPositionIndex:D,targetDrawPosition:N,matchUp:A}=fA({targetLink:u,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),A||(R=R||t.filter(C=>C.structureId===n.structureId),{matchUp:A}=Vk({structureMatchUps:R,matchUp:o})),et({matchUp:o,targetLinks:{loserTargetLink:d,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:D,loserMatchUpDrawPositionIndex:E,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:N,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:A,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function u3({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Hk({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=tt({drawDefinition:t,structureId:i});a?.finishingPosition===Ao?p3({inContextMatchUp:n,structure:a,drawPositions:s}):d3({scheduleConflictMatchUpIds:r,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o})}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function p3({inContextMatchUp:t,structure:e,drawPositions:r}){let{roundNumber:n}=t,o=n&&st(n)+1,i=e.matchUps??[],{roundMatchUps:s}=_e({matchUps:i});if(o&&s?.[o]){let a=[...r].sort(ee).map((c,u)=>{let p=s[o].find(d=>d.drawPositions?.includes(c));return{matchUpId:p?.matchUpId,roundNumber:o,schedule:p?.schedule,sideNumber:u+1,structureName:e.structureName}});Object.assign(t,{sidesTo:a})}}function d3({scheduleConflictMatchUpIds:t,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=ir({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}),{winnerMatchUp:s}=i.targetMatchUps,{loserMatchUp:a}=i.targetMatchUps;!r.winnerMatchUpId&&s&&(r.winnerMatchUpId=s.matchUpId),!r.loserMatchUpId&&a&&(r.loserMatchUpId=a.matchUpId);let c=wC({upcomingMatchUp:s}),u=wC({upcomingMatchUp:a});if(r.matchUpStatus!=="BYE"&&a?.matchUpStatus==="BYE"){let{matchUp:d}=Wk({matchUp:a,drawDefinition:n,inContextDrawMatchUps:e})??{};u=d&&wC({upcomingMatchUp:d})||u}let p=r.schedule?.timeAfterRecovery;p&&(Bk({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:c}),Bk({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:u})),Object.assign(r,{winnerTo:c,loserTo:u}),r.drawPositions?.filter(Boolean).length&&m3({inContextDrawMatchUps:e,inContextMatchUp:r,winnerMatchUp:s,loserMatchUp:a,targetData:i})}function Bk({scheduleConflictMatchUpIds:t,inContextMatchUp:e,timeAfterRecovery:r,upcomingTo:n}){n?.schedule?.scheduledTime&&Yt(n.schedule.scheduledTime)<Yt(r)&&(t[n.matchUpId]=e.matchUpId,n.schedule.scheduleConflict=e.matchUpId)}function m3({inContextDrawMatchUps:t,inContextMatchUp:e,winnerMatchUp:r,loserMatchUp:n,targetData:o}){let s=o.targetLinks?.loserTargetLink?.linkCondition===Jn,a=l3(e);if(!a.length)return;let c=Ah(r?.sides),u=Ah(n?.sides),d=a.find(({participantId:f})=>c.includes(f))?[]:a,l=a.find(({participantId:f})=>u.includes(f))?[]:a;n&&s&&l.length<2&&l.push({bye:!0,tbd:!0}),d?.length&&r&&(!o.targetMatchUpIds&&r&&(r=t.find(({matchUpId:f})=>f===r.matchUpId)),r.potentialParticipants??=[],r.potentialParticipants.push(d)),l?.length&&n&&(o.targetMatchUpIds||(r=t.find(({matchUpId:f})=>f===n.matchUpId)),n.potentialParticipants||(n.potentialParticipants=[]),n.potentialParticipants.push(l))}function l3(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)??[]}function Wk({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==="BYE"){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=ir({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps??{},Wk({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function wC(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 re(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=$a(t);if(r.error)return M({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 $a(t){if(!t?.drawDefinition)return{error:K};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:d,contextFilters:m,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:y,context:E,event:A}=t,N=[],D=[],R=[],U=[],b=[];h&&!r&&(r=lo({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:A}));let C;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:C}=qp({participants:e,participantsProfile:a})));let{structures:_}=hn({drawDefinition:S});if(!_)return{error:Pt};n||(n=ye({drawDefinition:S}));let v=S&&Pf({drawDefinition:S}).exitProfiles;_.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:k=[],upcomingMatchUps:G=[],completedMatchUps:V=[],abandonedMatchUps:B=[]}=Xp({matchUpFilters:T?void 0:l,contextFilters:T?void 0:m,inContext:y||T||m,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:d,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:v,matchUpsMap:n,structure:F,context:E,event:A});N=N.concat(...B),D=D.concat(...V),R=R.concat(...G),U=U.concat(...k),b=b.concat(...L)});let x=F=>(!l&&!T&&!m||(l&&(F=os({matchUps:F,...l})),m&&(F=os({matchUps:F,...m,processContext:!0}))),F),w={abandonedMatchUps:x(N),completedMatchUps:x(D),upcomingMatchUps:x(R),pendingMatchUps:x(U),byeMatchUps:x(b),matchUpsMap:n,...P,groupInfo:C};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:k,upcoming:G,pending:V,bye:B}=F,$=[].concat(...(L&&N)??[],...(k&&D)??[],...(G&&R)??[],...(V&&U)??[],...(B&&b)??[]);Hk({inContextDrawMatchUps:$,drawDefinition:S})}return w}function _n(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:d,contextFilters:m,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:h,event:S}=t;if(!S)return{error:Se};let{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:D,matchUpFormat:R}=S??{},U={...h,...et({indoorOutDoor:S.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:S.surfaceCategory??p?.surfaceCategory,endDate:S.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:R,eventName:y,eventType:A,category:N,eventId:T,gender:D})};E&&(U.endDate=E),f&&!r&&(r=lo({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:S}));let b;if(!e?.length&&!n&&p){let x=gi({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=x.participantMap,e=x.participants??[],b=x.groupInfo}let C=S.drawDefinitions??[],_=Oc({tournamentRecord:p,event:S}).scheduleTiming;return{matchUps:C.flatMap(x=>{let{matchUps:w}=re({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:U,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:d,contextFilters:m,contextProfile:f,drawDefinition:x,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:_,nextMatchUps:g,inContext:I,event:S});return w??[]}),groupInfo:b}}function jt(t){let e=X(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:Y};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:d,contextProfile:m,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,h=t.tournamentId??u.tournamentId,S=u?.events??[];n||({participants:n,participantMap:r}=gi({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:T}=gt({tournamentRecord:u}),y={...I,tournamentId:h,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},E=lo({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:S.flatMap(N=>(y.eventDrawsCount=N.drawDefinitions?.length??0,_n({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:d,contextContent:E,contextFilters:f,contextProfile:m,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:N}).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:kt};let d=Object.keys(n).map(m=>{let l=n[m];return jt({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...P,matchUps:d}}function sa(t,e){return f3(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function f3(t,e){return(ka[t?.stage]||0)-(ka[e?.stage]||0)}function sr(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:d,contextFilters:m,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:D,matchUpFormat:R}=S??{},U={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:R,eventType:A,eventName:y,category:N,eventId:T,endDate:E,gender:D},b;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:b}=gi({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=lo({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...re({context:U,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:m,contextProfile:l,matchUpFilters:d,participantMap:r,nextMatchUps:g,inContext:I,event:S}),groupInfo:b}}var LC=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Qi({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Qi({element:e,accessor:r})?.value}))||(typeof t=="string"&&Qi({element:e,accessor:t}))?.value,Gr=LC;function aa({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Ur(i))return[];let{roundProfile:c,roundNumbers:u=[]}=_e({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,d=p&&c?.[n-p]?.matchUpsCount,m=c&&Object.values(c).map(Gr("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);d&&h&&S===1&&(S=d);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=m?.slice(I-1).reduce((C,_)=>C+(_||0),0),E=a&&I!==1,A=1+t+(E?r??0:0),N=1,D=J(A,s?A+S*2:y+A+N),R=y+N-S,U=l(D.slice(R)),b=l(D.slice(0,R),!0);return T.finishingPositionRange={loser:U,winner:b},{[I]:T}})),g=We({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 bs({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:K};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=re({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];aa({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=ir({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,d=u?.matchUpId,m=p?.matchUpId,f=Jo({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(d&&(n.winnerMatchUpIds[f.matchUpId]=d,Object.assign(f,{winnerMatchUpId:d}),Object.assign(i,{winnerMatchUpId:d})),m&&(n.loserMatchUpIds[f.matchUpId]=m,i.loserMatchUpId=m,f.loserMatchUpId=m,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 en(t){let e=Pr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:zn};if(!Array.isArray(n))return{error:Un};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:Vs};let c={},u={},p={},d={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let m=Object.values(e),f=m.reduce((T,y)=>T.concat(y.events??[]).map(E=>(E.drawDefinitions??[]).map(A=>A.links??[])).flat(1/0),[]).filter(({linkType:T})=>T===fn),g=r;f.length&&(g=un({nextMatchUps:!0,tournamentRecords:e}).matchUps,g3({positionLinks:f,sourceStructureIdMap:p,positionDependencies:c,matchUps:g}));let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},d[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(A=>{u[y].matchUpIds.push(A)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(A=>u[y].participantIds.push(A))},S=T=>{let y=Object.keys(c).length;for(let E of T??[]){let{matchUpId:A,winnerMatchUpId:N,loserMatchUpId:D}=E;if(!a.length||a.includes(A)){if(I(A),o){let{individualParticipantIds:b}=Wp(E);u[A].participantIds=b}N&&(I(N),h(A,N),d[N].push(A)),D&&(I(D),h(A,D),d[D].push(A)),u[A].sources.push(d[A]);let R=d[A].map(b=>u[b].sources[0]).flat(),U=d[A].map(b=>u[b].sources[1]).flat();if(u[A].sources.push(R,U),y){let b=E.containerStructureId||E.structureId,C=p[b];if(c[C])for(let _ of c[C])I(_),h(_,A),d[_].push(A)}}}};if(s)bs({drawDefinition:s}),g?.length||(g=sr({drawDefinition:s}).matchUps),S(g);else{g?.length||(g=un({nextMatchUps:!0,tournamentRecords:e}).matchUps),n.length||(n=I3(m));for(let T of n)h3({matchUps:g,drawId:T,tournamentRecords:e,processMatchUps:S})}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:d,matchUps:g,...P}}function g3({positionLinks:t,sourceStructureIdMap:e,positionDependencies:r,matchUps:n}){let o=t.reduce((i,s)=>{let a=s.source?.structureId,c=s.target?.structureId;return a&&c&&(e[c]=a),a&&!i.includes(a)&&i.push(a),i},[]);for(let i of o)r[i]=[];for(let i of n??[]){let s=i.containerStructureId||i.structureId;o.includes(s)&&r[s].push(i.matchUpId)}}function I3(t){return t?.length?t.map(({events:e=[]})=>e.map(({drawDefinitions:r=[]})=>r.map(({drawId:n})=>n))).flat(1/0):[]}function h3({matchUps:t,drawId:e,tournamentRecords:r,processMatchUps:n}){let o=t?.filter(s=>s.drawId===e).sort(sa);if(!o?.find(({roundPosition:s})=>!s)){let s=o?.find(({tournamentId:c})=>c),{drawDefinition:a}=Ve({tournamentRecord:r[s?.tournamentId],drawId:e});a&&bs({drawDefinition:a})}n(o)}function le(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 Ka({matchUpStatus:t}){return vE.includes(t)}function jk({matchUpStatus:t}){return pf.includes(t)}function zh({matchUpStatus:t}){return OE.includes(t)}function Qh({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(Qh)?.length;return le({score:o})||s||e&&i||t&&jk({matchUpStatus:t})&&![Mt,vt,vn].includes(t)}function is(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=ts({drawDefinition:e}),a=n?s[n]??[]:[],c={isCollectionMatchUp:!1};if(!i){let N=tt({drawDefinition:e,structureId:n});if(N.error)return N;i=r?N.containingStructure??N.structure:N.structure}if(De({structure:i}))return{structure:i,isAdHoc:!0,error:hs};let{matchUps:u}=re({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(N=>N.structureId===n||a.includes(N.structureId)),{matchUpDependencies:d}=en({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),m=[],l=[],f={},g=[];for(let N of u??[]){if(N.structureId===n||a.includes(N.structureId)){l.push(...N.drawPositions??[]);let D=N.roundNumber;for(let R of(N.drawPositions??[]).filter(Boolean))(!f[R]||D&&f[R]>D)&&(f[R]=D)}Qh(N)&&(g.push(N),m.push(N.matchUpId,...d?.[N?.matchUpId]?.matchUpIds??[]))}let I=ct(l.filter(Boolean)).sort(ee),h=ct(m),S=ct(p?.map(({matchUpId:N,drawPositions:D})=>h.includes(N)?D:[]).flat().filter(Boolean)).sort(ee),{positionAssignments:T}=yt({drawDefinition:e,structure:i}),y=T?.filter(N=>N.bye).map(N=>N.drawPosition),E=T?.filter(N=>N.qualifier).map(N=>N.drawPosition),A=I?.filter(N=>!S.includes(N))??[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:E,inactiveDrawPositions:A,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function ca({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(ee)[0]}}var wc={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 gA=[];function Ue(t,e){wt(t)&&(t={method:t}),(e||We())&&gA.push(t)}function S3(t){let e=gA.slice();return t&&(gA.length=0),e}function Yk(t){let r=S3(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(wc).includes(o)?wc[o]:wc.cyan,p=Object.keys(n).filter(m=>!["color","keyColors","method","newline"].includes(m)).map(m=>{let l=i&&Object.keys(i).includes(m)&&wc[i[m]]?wc[i[m]]:wc.brightwhite;return`${wc.white}${m}: ${l}${n[m]}`}).join(", "),d=s?.length<15?" ":" ";return[a?`
|
|
2
2
|
`:"",c,s,d,wc.white,p,wc.reset,`
|
|
3
3
|
`].join("")});r?.length&&console.log(...r)}function qk(){gA.length=0}function _f(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,containsParticipant:n,filled:e||r||n}}function ze(t){return[Mt,vt,ve].includes(t)}function Mr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,loserMatchUp:i,matchUpsMap:s,structureId:a,structure:c,event:u}){if(!n)return{error:K};if(c||({structure:c}=tt({drawDefinition:n,structureId:a})),!c)return{error:Pt};a||({structureId:a}=c);let p="assignDrawPositionBye";Ue({method:p,color:"cyan",drawPosition:o}),s??=ye({drawDefinition:n});let{positionAssignments:d}=yt({structure:c}),{activeDrawPositions:m}=is({drawDefinition:n,structureId:a});if(d?.find(v=>v.drawPosition===o)?.bye)return{...P};if(cn(n.drawType)&&d?.filter(x=>x.bye&&x.drawPosition!==o)?.length)return M({result:{error:KU},stack:p});let f=!!(i&&s.drawMatchUps.some(v=>v.loserMatchUpId===i?.matchUpId&&ze(v.matchUpStatus)));if(m?.includes(o)&&!f)return{error:eu};let I=d?.find(v=>v.drawPosition===o);I||(I={drawPosition:o},d?.push(I));let{filled:h,containsBye:S,containsParticipant:T}=_f(I);if(S)return{...P};if(h&&!S&&!f)return M({result:{error:Zc},stack:p});let y=gt({tournamentRecord:r,drawDefinition:n,event:u}).appliedPolicies??{},E=re({inContext:!0,drawDefinition:n,matchUpsMap:s}).matchUps??[],A={isCollectionMatchUp:!1},{matchUps:N}=ht({provisionalPositioning:t,drawDefinition:n,matchUpFilters:A,matchUpsMap:s,structure:c});if(d?.forEach(v=>{v.drawPosition===o&&(v.bye=!0,f&&(v.participantId=void 0))}),c.structureType===Ie)return T3({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:N}),Tn({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),$k({assignedParticipantId:T,isPositionAction:e,appliedPolicies:y,drawDefinition:n,drawPosition:o,structureId:a,stack:p});let{roundProfile:D,roundMatchUps:R}=_e({matchUps:N}),b=(D&&Object.keys(D).map(v=>Number.parseInt(v)).reverse())?.find(v=>D?.[v].drawPositions?.includes(o)),C=b?R?.[b].find(({drawPositions:v})=>v?.includes(o)):void 0;C&&Kk({tournamentRecord:r,drawDefinition:n,matchUp:C,event:u});let _=C?.drawPositions?.find(v=>v!==o);if(C&&_){let v=IA({sourceDrawPositions:C.drawPositions,matchUpId:C.matchUpId,inContextDrawMatchUps:E,drawPositionToAdvance:_,tournamentRecord:r,drawDefinition:n,matchUpsMap:s});if(v.error)return v}return Tn({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),$k({assignedParticipantId:T,isPositionAction:e,appliedPolicies:y,drawDefinition:n,drawPosition:o,structureId:a,stack:p})}function $k({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&vc({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),M({result:{...P},stack:s})}function Kk({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:"BYE",score:void 0,winningSide:void 0}),mt({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function T3({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&Kk({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function IA({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Ue({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(N=>N.matchUpId===s),d=e.find(N=>N.matchUpId===s)?.structureId,{structure:m}=tt({drawDefinition:o,structureId:d}),{positionAssignments:l}=yt({structure:m}),f=l?.filter(N=>N.bye).map(N=>N.drawPosition),g=u?.drawPositions?.find(N=>N!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserTargetDrawPosition:y}}=ir({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s}),E=cn(o?.drawType),A=!E||!u?.roundNumber||!m?.matchUps?!1:m.matchUps.filter(D=>D.roundNumber===u.roundNumber).length%2!==0;if(T&&T.structureId===m?.structureId&&(!E||!A)&&y3({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),S&&I&&S.structureId!==m?.structureId){let{roundNumber:N}=S;if(N===1){let D=Mr({structureId:h.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(D.error)return D}else zk({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...P}}function y3({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(L=>L.matchUpId===i.matchUpId),d=e.find(L=>L.matchUpId===i.matchUpId)?.structureId,{structure:m}=tt({drawDefinition:o,structureId:d}),{positionAssignments:l}=yt({structure:m}),g=l?.find(({drawPosition:L})=>L===t)?.bye,I=u.drawPositions?.filter(Boolean),h=l?.filter(L=>I?.includes(L.drawPosition)),S=l?.find(({drawPosition:L})=>L===t),T=r?.find(L=>L!==t),E=(T&&h?.find(({drawPosition:L})=>L===T))?.bye,A=g&&E;if(A&&console.log({isByeAdvancedBye:A}),I?.length>1&&g&&!E)return M({result:{error:Zc},stack:c});let N=I?.find(L=>L!==t),D=A,R=[...(u.drawPositions??[]).filter(Boolean),void 0,void 0].slice(0,2),U=R.map(L=>!L&&!D||L===t?(D=!0,t):L).sort(ee);if(!D)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),M({result:{error:Zc},stack:c});let b=l?.find(({drawPosition:L})=>L===N)?.bye,C=l?.find(({drawPosition:L})=>L===t)?.bye;Object.assign(u,{matchUpStatus:C||b?"BYE":Jt,score:void 0,winningSide:void 0,drawPositions:U});let v=u.drawPositions.find(L=>!R.includes(L));Ue({method:c,color:"brightyellow",changedDrawPosition:v,pairedDrawPositionIsBye:b,drawPositionIsBye:C}),mt({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:x},targetMatchUps:{loserMatchUp:w,loserTargetDrawPosition:F}}=ir({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(b||C){let L=b?t:N;if(L)IA({drawPositionToAdvance:L,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(C&&x&&w)if(w.feedRound)zk({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:x,drawDefinition:o,loserMatchUp:w,matchUpsMap:s});else{let G=1-i.roundPosition%2,V=w.drawPositions[G],B=Mr({structureId:x.target.structureId,drawPosition:V,tournamentRecord:n,drawDefinition:o,event:a});if(B.error)return B}}}function zk({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Ue({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps??{})[o.structureId].matchUps,{initialRoundNumber:d}=ca({drawPosition:t,matchUps:p});if(d===a){let m=Mr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(m.error)return m}}function hA({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=ht({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?"BYE":Jt}),mt({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function bu(t){let{inContextDrawMatchUps:e,participantId:r,drawPosition:n}=t,{tournamentRecord:o,drawDefinition:i,structureId:s,matchUpsMap:a,event:c}=t,{structure:u}=tt({drawDefinition:i,structureId:s}),d=(pe({drawDefinition:i,structure:u}).positionAssignments??[]).find(g=>r&&g.participantId===r||n&&g.drawPosition===n);if(d&&r&&!n&&(n=d?.drawPosition),!n)return{error:Ra};r||(r=d?.participantId);let{activeDrawPositions:m}=is({drawDefinition:i,structureId:s});return m.includes(n)?{error:eu}:(e||({matchUps:e}=re({inContext:!0,drawDefinition:i,matchUpsMap:a})),FC({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(Tn({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...P,participantId:r}):{error:OU})}function FC({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:i,event:s}){let{structure:a}=tt({drawDefinition:r,structureId:i});if(!a)return{error:Pt};let c=pe({drawDefinition:r,structure:a}).positionAssignments??[],u=c.some(S=>{if(S.drawPosition===n)return delete S.participantId,delete S.qualifier,delete S.bye,!0});if(a.structureType===Ie)return hA({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...P};let p={isCollectionMatchUp:!1},{matchUps:d}=ht({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:m,roundMatchUps:l}=_e({matchUps:d}),g=(m&&Object.keys(m))?.map(S=>st(S)),I=A3({roundNumbers:g,roundProfile:m,positionAssignments:c,drawPosition:n}),h=P3(I);return h?.forEach(({roundNumber:S,targetDrawPosition:T,relevantPair:y})=>{let E=l?.[S].find(A=>we(A.drawPositions?.filter(Boolean),y.filter(Boolean)));E&&(E3({inContextDrawMatchUps:t,targetDrawPosition:T,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:S,matchUpsMap:o}),Qk({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:E,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:h,drawPositionCleared:u,positionAssignments:c}}function E3({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,roundNumber:i,structureId:s}){let{structure:a}=tt({drawDefinition:n,structureId:s});if(!a)return{error:Pt};if(a.structureType===Ie)return;o=o||ye({drawDefinition:n});let u=(o?.mappedMatchUps??{})[s].matchUps,{initialRoundNumber:p}=ca({drawPosition:e,matchUps:u}),d=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),m=yt({drawDefinition:n,structureId:s}).positionAssignments??[];return d?.forEach(l=>Qk({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:m,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...P}}function Qk({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(),d=o.matchUpStatus,m=o.winningSide;s=s??ye({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=ca({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let A=(o.drawPositions??[]).map(N=>N===i?void 0:N);o.drawPositions=A}N3({inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,event:c,stack:u});let I=ir({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,E=D3({initialDrawPositions:p,initialMatchUpStatus:d,initialWinningSide:m,positionAssignments:e,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,event:c,stack:u});if(S&&S.structureId!==I.matchUp.structureId&&!E){let A=U3({loserMatchUpDrawPositionIndex:y,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:S,matchUpsMap:s,event:c,stack:u});if(A?.error)return A}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,ln),{...P}}function A3({roundNumbers:t,roundProfile:e,positionAssignments:r,drawPosition:n}){let o=n;return t?.map(i=>{let a=e?.[i]?.pairedDrawPositions?.find(I=>I.includes(o)),c=a?.find(I=>I!==o),u=r.find(I=>I.drawPosition===c),p=e?.[i+1],d=u?.bye,m=p?.pairedDrawPositions?.find(I=>I.includes(c)),l=d&&m&&p?.drawPositions?.includes(c),g=a&&{pairedDrawPositionByeAdvancedPair:!l&&m,pairedDrawPosition:c,targetDrawPosition:o,relevantPair:a,roundNumber:i};return l&&(o=c),g}).filter(i=>i?.targetDrawPosition)}function P3(t){return t?.reduce((e,r)=>{let{roundNumber:n,relevantPair:o,targetDrawPosition:i,pairedDrawPosition:s,pairedDrawPositionByeAdvancedPair:a}=r,c={roundNumber:n,targetDrawPosition:i,relevantPair:o},u=a&&{roundNumber:n+1,targetDrawPosition:s,relevantPair:a,subsequentRoundRemoval:!0},p=[c,u].filter(Boolean);return e.concat(...p)},[])}function N3({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUp:n,drawPosition:o,event:i,stack:s}){if(n.matchUpType!==xt)return;let u=(t?.find(p=>p.matchUpId===n.matchUpId)?.sides??[]).reduce((p,d,m)=>d.drawPosition===o?m:p,void 0);u!==void 0&&n.sides?.[u]?.lineUp&&(delete n.sides?.[u].lineUp,mt({tournamentId:e?.tournamentId,context:`${s}-TEAM`,eventId:i?.eventId,matchUp:n,drawDefinition:r}))}function D3({initialDrawPositions:t,initialMatchUpStatus:e,initialWinningSide:r,positionAssignments:n,tournamentRecord:o,drawDefinition:i,targetMatchUp:s,drawPosition:a,event:c,stack:u}){let d=n.filter(({drawPosition:g})=>s.drawPositions?.includes(g)).filter(g=>g.bye).length,m=d&&"BYE"||s.matchUpStatus&&ze(s.matchUpStatus)&&s.matcHUpStatus||Jt;s.matchUpStatus=m,s.matchUpStatus&&ze(s.matchUpStatus)&&(s.winningSide=void 0);let l=t?.find(g=>!s.drawPositions?.includes(g));return t?.includes(a)&&e===s.matchUpStatus&&r===s.winningSide||(l&&Ue({method:u,color:"brightyellow",removedDrawPosition:l}),mt({tournamentId:o?.tournamentId,context:`${u}-${a}`,eventId:c?.eventId,matchUp:s,drawDefinition:i})),d}function U3({loserMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s,stack:a}){let{drawPositions:c,roundNumber:u}=o;if(u===1){let g=c[t];FC({structureId:o.structureId,drawPosition:g,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});return}let p=Math.min(...c.filter(Boolean)),d=R3({loserMatchUpDrawPosition:p,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s});if(d.error)return M({result:d,stack:a});let l=(i?.mappedMatchUps??{})[o.structureId].matchUps,{initialRoundNumber:f}=ca({drawPosition:p,matchUps:l});f===1&&(Ue({method:a,color:"brightyellow",loserMatchUpDrawPosition:p}),FC({structureId:o.structureId,drawPosition:p,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i}))}function R3({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=tt({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=yt({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=bu({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...P}}function ss({drawDefinition:t,stages:e}){if(!t)return{error:K};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=ct(r.map(o=>{let{positionAssignments:i}=yt({structure:o});return i?i.map(lt):[]}).flat().filter(Boolean));return{...P,assignedParticipantIds:n}}function Io(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||j}${s||""}`;return n[a]||(n[a]=[]),n[a].push(o),n},{}),r=n=>Number.isNaN(Number(n))?1/0:n;return Object.keys(e).flatMap(n=>e[n].sort((o,i)=>r(o.entryPosition)-r(i.entryPosition)).map((o,i)=>{let s=i+1;return{...o,entryPosition:s}}))}function ua(t){return[es,kr].includes(t)}function xf({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:r,drawDefinition:n,participantIds:o,entryStatus:i,entryStage:s,extension:a,eventSync:c,drawId:u,stage:p,event:d}){let m=b3({participantIds:o,drawDefinition:n,entryStatus:i,entryStage:s,extension:a,event:d});if(m)return m;let l="modifyEntriesStatus",f=[],g=C3({event:d,stage:p}),I=r?.participants??[];if(!M3({participantIds:o,tournamentParticipants:I,entryStatus:i,event:d}))return{error:wI};let h=d&&Gt({event:d}).flightProfile,S=h?.flights?.find(U=>U.drawId===u),T=v3({assignedParticipantIds:g,ignoreAssignment:e,participantIds:o,entryStatus:i,entryStage:s,extension:a,stage:p}),y=({flight:U,drawDefinition:b})=>{d&&(d.entries=Io({entries:d.entries??[]})),U&&(U.drawEntries=Io({entries:U.drawEntries})),b&&(b.entries=Io({entries:b.entries}))},E=({flight:U,drawDefinition:b})=>{let C="updateDrawEntries";if(U){let _=T(U.drawEntries);if(_.error)return M({result:_,stack:C})}if(b){let _=T(b.entries);if(_.error)return M({result:_,stack:C});f.includes(b.drawId)||f.push(b.drawId)}return{...P}},A=d?.entries?.find(({entryPosition:U})=>U)??(S?.drawEntries?.find(({entryPosition:U})=>U)||n?.entries?.find(({entryPosition:U})=>U));if(t&&!A&&y({flight:S,drawDefinition:n}),S||n){let U=E({flight:S,drawDefinition:n});if(U.error)return M({result:U,stack:l})}let N=d?.drawDefinitions?.map(({drawId:U})=>U)??[],D=h?.flights?.filter(U=>!N.includes(U.drawId))??[];for(let U of D){let b=U&&E({flight:U,drawDefinition:void 0});if(b?.error)return M({result:b,stack:l})}let R=h?.flights?.length===1&&(d?.drawDefinitions?.length??0)<=h?.flights?.length;if(!S&&!n&&i&&EC.includes(i))return{error:hR};if(!S&&!n||i===On||c&&R){let U=T(d?.entries);if(U?.error)return M({result:U,stack:l});if(i===On){let b=O3({updateEntryStatus:T,participantIds:o,flightProfile:h,event:d});if(b)return M({result:{error:b},stack:l})}}t&&y({flight:S,drawDefinition:n});for(let U of d?.drawDefinitions??[])f.length&&!f.includes(U.drawId)||Lt({tournamentId:r.tournamentId,eventId:d?.eventId,drawDefinition:U});return{...P}}function b3({participantIds:t,drawDefinition:e,entryStatus:r,entryStage:n,extension:o,event:i}){if(!t||!Array.isArray(t))return{error:Hr,method:"modifyEntriesStatus",participantIds:t};if(!e&&!i)return{error:Se};if(r&&!AC.includes(r))return{error:wI};if(n&&!lu.includes(n))return{error:hc};let s="modifyEntriesStatus";if(!r&&!o)return M({result:{error:nt},info:"Missing entryStatus",stack:s});if(o&&!Zn({extension:o,requiredAttributes:["name"]}))return M({result:{error:O},info:"Invalid extension",context:{extension:o},stack:s})}function C3({event:t,stage:e}){let r=[];return t?.drawDefinitions?.forEach(n=>{let o=ss({stages:e&&[e],drawDefinition:n}).assignedParticipantIds??[];r.push(...o)}),r}function M3({participantIds:t,tournamentParticipants:e,entryStatus:r,event:n}){return t.every(o=>{let i=li({tournamentParticipants:e,participantId:o})?.participantType;return!(i&&[dt,fr].includes(i)&&ua(r))&&!(r&&n?.eventType&&i===ft&&[Xt,Tr].includes(n.eventType)&&[tn,...Em].includes(r))})}function v3({assignedParticipantIds:t,ignoreAssignment:e,participantIds:r,entryStatus:n,entryStage:o,extension:i,stage:s}){return a=>{let c=(a??[]).filter(d=>!s||!d.entryStage||s===d.entryStage).filter(({participantId:d})=>r.includes(d)),u=d=>n&&t.includes(d.participantId)&&!(Em.includes(d.entryStatus)&&Em.includes(n));return c.every(d=>u(d)&&!e?!1:(n&&(d.entryStatus=n,delete d.entryPosition),o&&(d.entryStage=o,delete d.entryPosition),i&&(i.value?Qt({element:d,extension:i}):Mn({element:d,name:i.name})),!0))?{...P}:{error:Oa}}}function O3({updateEntryStatus:t,participantIds:e,flightProfile:r,event:n}){let o=new Set(e);for(let i of r?.flights??[]){let s=t(i.drawEntries);if(s.error)return s.error;i.drawEntries=i.drawEntries.filter(({participantId:a})=>!o.has(a))}for(let i of n?.drawDefinitions??[]){let s=t(i.entries);if(s.error)return s.error;i.entries=i.entries?.filter(({participantId:a})=>!o.has(a))}}function kC(t){let e=X(t,[{ratings:!0,[qe]:$r}]);if(e.error)return e;let r=t.matchUpType&&[Ct,Ut].includes(t.matchUpType)?t.matchUpType:Ct,n=Object.keys(Ze),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:"ELO",i=t.ratings[r]?t.ratings[r].reduce((m,l)=>m.includes(l.scaleName)?m:m.concat(l.scaleName),[]):[];if(!i)return{error:fe};let s=t.ratings[r]?.find(m=>m.scaleName===o)??t.ratings[r]?.[0];if(i[0]===o)return s;let a=s?.scaleName,c=Ze[s?.scaleName]?.accessor,u=c&&s.scaleValue[c]||s?.scaleValue,p=Gp({sourceRatingType:a,sourceRating:u}),d=jF({targetRatingType:o,sourceRating:p});return d?{convertedRating:d,sourceRating:u}:{error:O}}function Jk({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?.[Ct]&&s?.[Ct]){let a="ELO",{convertedRating:c}=kC({ratings:i,targetRatingType:a}),{convertedRating:u}=kC({ratings:s,targetRatingType:a}),{side1pressure:p,side2pressure:d}=_3({side1ConvertedRating:c,side2ConvertedRating:u,score:r});p&&t[n?.participantId].pressureScores.push(p),d&&t[o?.participantId].pressureScores.push(d);let m=Math.max(...Ze["ELO"].range),l=SI((u-c)/m),f=SI((c-u)/m);t[n?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(f)}}function _3({side1ConvertedRating:t,side2ConvertedRating:e,score:r}){let n=Math.max(t,e),o=Math.min(t,e),i=Math.abs(t-e),s=Ze["ELO"].range,a=Math.max(...s),c=(a-n)*0,p=(n+c)/a*i,d=r?.sets?.reduce((T,y)=>T+(y?.side1Score??0),0),m=r?.sets?.reduce((T,y)=>T+(y.side2Score??0),0),l=t>e?2:1,f=(d||0)*(o+(l===1?p:0)),g=(m||0)*(o+(l===2?p:0)),I=f+g,h=I?SI(f/I):0,S=I?SI(g/I):0;return{side1pressure:h,side2pressure:S}}function Jh({winningSide:t,matchUpFormat:e=kn,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=ne(e),u=GC(c?.bestOf??1);if(typeof a=="number"&&(r===Mt&&n?.setsCreditForDefaults||r===vt&&n?.setsCreditForWalkovers))i[a]=u;else for(let p of s??[]){let{winningSide:d}=p;d&&(i[d-1]+=1)}return typeof a=="number"&&r===ve&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function SA({matchUpFormat:t=kn,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=ne(t),c=a?.bestOf??1,u=GC(c),p=a?.setFormat?.tiebreakAt||0,d=[[],[]];if(typeof s=="number"&&(r===Mt&&n?.gamesCreditForDefaults||r===vt&&n?.gamesCreditForWalkovers)){let m=a?.setFormat?.setTo||0,l=u*m;d[s].push(l)}else i.forEach((m,l)=>{let g=(m.setNumber||l+1)>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",I=a?.[g]?.based,h=a?.[g].tiebreakSet,{side1Score:S,side2Score:T}=m;Xk(I)&&!h&&(d[0].push(st(S||0)),d[1].push(st(T||0))),h&&m.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&d[m.winningSide-1].push(1)});if(r===ve&&typeof s=="number"){let m=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[m];if(Xk(l.based)){let f=l?.setTo||0,g=S=>{if(!(!a||S===""))return+S===p-1||+S===p?st(p||0)+1:+S<p?f:p},I=Jh({winningSide:e,score:{sets:i},matchUpStatus:r,matchUpFormat:t,tallyPolicy:n});if(d.map(S=>S[s]<=S[1-s]).reduce((S,T)=>S+(T?1:0),0)>I[1-s]){let S=d[s].length,T=g(d[1-s][S-1]);T&&(d[s][S-1]=T)}u>d[s].length&&n?.gamesCreditForRetirements&&d[s].push(f)}}return[d[0].reduce((m,l)=>m+l,0),d[1].reduce((m,l)=>m+l,0)]}function TA({matchUpFormat:t,score:e}){let r=t?ne(t):void 0,n=r?.bestOf??1,o=GC(n),i=[0,0],s=[0,0];return e?.sets?.forEach((a,c)=>{let p=(a.setNumber||c+1)>o&&r?.finalSetFormat?"finalSetFormat":"setFormat",d=r?.[p]?.based;if(Zk(d)){let{side1Score:m,side2Score:l}=a;m&&(s[0]+=st(m||0)),l&&(s[1]+=st(l||0))}else a.side1TiebreakScore&&(s[0]+=st(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=st(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function GC(t){return t&&Math.ceil(t/2)||1}function Zk(t){return t==="P"}function Xk(t){return!Zk(t)}function t0({participantResults:t,groupingTotal:e,matchUpFormat:r,tallyPolicy:n,totalGames:o,perPlayer:i,totalSets:s}){let a=(r&&ne(r))??{},c=a.bestOf,u=c&&Math.ceil(c/2)||1,p=a.setFormat?.setTo,d=Math.pow(10,n?.precision||3);Object.keys(t).forEach(m=>{let l=t[m].setsWon,f=t[m].setsLost,g=n?.groupTotalSetsPlayed||e==="setsPct"?s:i*(u||0)||l+f,I=Math.round(l/g*d)/d;(I===1/0||Number.isNaN(I))&&(I=g);let h=t[m].tieMatchUpsWon,S=t[m].tieMatchUpsLost,T=h+S,y=Math.round(h/T*d)/d;(y===1/0||Number.isNaN(y))&&(y=h);let E=t[m].matchUpsWon,A=t[m].matchUpsLost,N=E+A,D=Math.round(E/N*d)/d;(D===1/0||Number.isNaN(D))&&(D=E);let R=t[m].gamesWon||0,U=t[m].gamesLost||0,b=(i||0)*(u||0)*(p||0),C=n?.groupTotalGamesPlayed||e==="gamesPct"?o:Math.max(b,R+U),_=Math.round(R/C*d)/d;(_===1/0||Number.isNaN(_))&&(_=0);let v=t[m].pointsWon+t[m].pointsLost,x=Math.round(t[m].pointsWon/v*d)/d;(x===1/0||Number.isNaN(x))&&(x=0),t[m].setsWon=l,t[m].setsLost=f,t[m].setsPct=I,t[m].tieMatchUpsWon=h,t[m].tieMatchUpsPct=y,t[m].matchUpsPct=D,t[m].gamesWon=R,t[m].gamesLost=U,t[m].gamesPct=_,t[m].pointsPct=x,t[m].result=`${t[m].matchUpsWon}/${t[m].matchUpsLost}`})}function Zp({participantIds:t,pressureRating:e,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,perPlayer:i,matchUps:s}){let a={},c=o?.excludeMatchUpStatuses??[],u=x3({matchUps:s,excludeMatchUpStatuses:c,participantIds:t}),{totalSets:p,totalGames:d}=w3({filteredMatchUps:u,excludeMatchUpStatuses:c});for(let m of u??[]){let{matchUpStatus:l,tieMatchUps:f,tieFormat:g,score:I,winningSide:h,sides:S}=m,T=g&&m._disableAutoCalc&&g.collectionDefinitions.every(({scoreValue:A})=>A),y=h&&B3(m),E=h&&H3(m);!y&&!E?i=L3({participantResults:a,manualGamesOverride:T,matchUpStatus:l,tieMatchUps:f,perPlayer:i,score:I,sides:S}):(Cu(a,y),Cu(a,E),i=k3({winningParticipantId:y,losingParticipantId:E,manualGamesOverride:T,participantResults:a,pressureRating:e,matchUpFormat:n,matchUpStatus:l,tieMatchUps:f,tallyPolicy:o,winningSide:h,perPlayer:i,matchUp:m,score:I,sides:S})),T&&V3({participantResults:a,score:I,sides:S})}return t0({participantResults:a,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,totalGames:d,perPlayer:i,totalSets:p}),{participantResults:a}}function x3({matchUps:t,excludeMatchUpStatuses:e,participantIds:r}){return t?.filter(n=>(n.tieMatchUps||!e.includes(n.matchUpStatus))&&(!r?.length||Ht(r,[wf(n,0),wf(n,1)]).length===2))}function w3({filteredMatchUps:t,excludeMatchUpStatuses:e}){let n=t?.flatMap(({score:a,tieMatchUps:c})=>c?c.filter(({matchUpStatus:u})=>!e.includes(u)).flatMap(({score:u})=>u?.sets?.length??0):a?.sets?.length??0)?.reduce((a,c)=>a+c,0),o=a=>a?.sets?.reduce((c,u)=>c+(u?.side1Score??0)+(u?.side2Score??0),0)??0,s=t?.flatMap(({score:a,tieMatchUps:c})=>c?c.filter(({matchUpStatus:u})=>!e.includes(u)).flatMap(({score:u})=>o(u)):o(a))?.reduce((a,c)=>a+c,0);return{totalSets:n,totalGames:s}}function L3({participantResults:t,manualGamesOverride:e,matchUpStatus:r,tieMatchUps:n,perPlayer:o,score:i,sides:s}){if(r&&Rt.includes(r)){let a=wf({sides:s},0),c=wf({sides:s},1);a&&(Cu(t,a),t[a].matchUpsCancelled+=1),c&&(Cu(t,c),t[c].matchUpsCancelled+=1)}else if(n?.length){o=0;for(let a of n)a.winningSide&&F3({participantResults:t,tieMatchUp:a,sides:s}),r0({score:a.score,manualGamesOverride:e,participantResults:t,sides:s})}else r0({manualGamesOverride:e,participantResults:t,score:i,sides:s});return o}function F3({participantResults:t,tieMatchUp:e,sides:r}){let n=r?.find(({sideNumber:i})=>i===e.winningSide)?.participantId,o=r?.find(({sideNumber:i})=>i===e.winningSide)?.participantId;n&&o&&(Cu(t,n),Cu(t,o),t[n].tieMatchUpsWon+=1,t[o].tieMatchUpsLost+=1,oe(Ct)(e.matchUpType)?(t[n].tieSinglesWon+=1,t[o].tieSinglesLost+=1):oe(Ut)(e.matchUpType)&&(t[n].tieDoublesWon+=1,t[o].tieDoublesLost+=1))}function k3({winningParticipantId:t,losingParticipantId:e,manualGamesOverride:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,tieMatchUps:a,tallyPolicy:c,winningSide:u,perPlayer:p,matchUp:d,score:m,sides:l}){if(a?.length){p=0;for(let f of a)f.winningSide&&G3({winningParticipantId:t,losingParticipantId:e,participantResults:n,tieMatchUp:f,winningSide:u}),n0({matchUpFormat:f.matchUpFormat,matchUpStatus:f.matchUpStatus,matchUpType:f.matchUpType,score:f.score,sides:f.sides,winningParticipantId:t,losingParticipantId:e,manualGamesOverride:r,participantResults:n,isTieMatchUp:!0,pressureRating:o,tallyPolicy:c,winningSide:u});o0({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:s})}else n0({matchUpFormat:d.matchUpFormat??i,matchUpType:d.matchUpType,isTieMatchUp:void 0,winningParticipantId:t,manualGamesOverride:r,losingParticipantId:e,participantResults:n,pressureRating:o,matchUpStatus:s,tallyPolicy:c,winningSide:u,score:m,sides:l});return p}function G3({winningParticipantId:t,losingParticipantId:e,participantResults:r,tieMatchUp:n,winningSide:o}){let{matchUpType:i}=n,s=oe(Ut)(i),a=oe(Ct)(i),c=n.winningSide===o,u=c?t:e,p=c?e:t;e0(r,u,"Won",a,s),e0(r,p,"Lost",a,s)}function e0(t,e,r,n,o){e&&(t[e][`tieMatchUps${r}`]+=1,n&&(t[e][`tieSingles${r}`]+=1),o&&(t[e][`tieDoubles${r}`]+=1))}function V3({participantResults:t,score:e,sides:r}){let n=e?.sets?.reduce((a,c)=>a+(c?.side1Score??0),0),o=e?.sets?.reduce((a,c)=>a+(c.side2Score??0),0),i=r?.find(({sideNumber:a})=>a===1)?.participantId,s=r?.find(({sideNumber:a})=>a===2)?.participantId;Cu(t,i),Cu(t,s),i&&(t[i].gamesWon+=n,t[i].gamesLost+=o),s&&(t[s].gamesWon+=o,t[s].gamesLost+=n)}function B3(t){let e=t.winningSide-1;return wf(t,e)}function H3(t){let e=1-(t.winningSide-1);return wf(t,e)}function wf(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 Cu(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 r0({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:d}=c;u&&(s[u-1]+=1),i[0].push(st(p||0)),i[1].push(st(d||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&&(Cu(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 n0({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,isTieMatchUp:a,matchUpType:c,tallyPolicy:u,winningSide:p,score:d,sides:m}){let l=p&&p-1,f=1-l;o&&c===Ct&&Jk({participantResults:n,sides:m,score:d}),a||o0({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let g=Jh({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:d}),I=SA({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:d}),{pointsTally:h}=TA({score:d,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 o0({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===vt&&(r[e].walkovers+=1),n===Mt&&(r[e].defaults+=1),n===ve&&(r[e].retirements+=1),ze(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 W3(t,e,r,n){t.groups&&Object.keys(t.groups).sort(n).forEach(o=>{let i=t.groups[o].map(a=>e[a]).join(", "),s=`${o} ${t.attribute}: ${i}`;r.push(s)})}function j3(t,e,r,n){if(t.excludedDirectives?.length){let o=t.excludedDirectives.map(({attribute:a})=>a).join(", "),i=`${o.length} directives were excluded due to participants limit}`;n.push(i);let s=`Excluded: ${o}`;n.push(s)}else{let o=(u,p)=>Number.parseFloat(t.reversed?u:p)-Number.parseFloat(t.reversed?p:u),i=t.groups?Object.values(t.groups).flat(1/0).length:t.participantIds?.length??0,s=t.reversed?" in reverse order":"",a=t.groups?"grouped":"separated",c=`Step ${e+1}: ${i} particiants were ${a}${s} by ${t.attribute}`;if(n.push(c),t.idsFilter){let u=`${t.attribute} was calculated considering ONLY TIED PARTICIPANTS`;n.push(u)}W3(t,r,n,o)}n.push("----------------------")}function i0({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)=>{j3(i,s,n,o)}),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 VC({participantResults:t,participantIds:e,attribute:r}){return BC({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 BC(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var Y3=[{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}],HC={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function WC(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!q3(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=VC({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let p=Object.keys(a).map(S=>Number.parseFloat(S)).sort((S,T)=>T-S).map(S=>a[S]).map(S=>{let T=s0({participantIds:S,...t});return i.push(...T.report??[]),T.order}).flatMap((S,T)=>S.map(y=>y.resolved?y:{...y,subGroup:[T].concat(...y.subGroup??[])})),d,m=0,l=1,f;p.forEach((S,T)=>{T&&(S.resolved||f&&!S.resolved)&&(l+=1),f=S.resolved;let y=Number.parseInt(S.subGroup?.join("")||0);S.resolved?(S.position=T+1,l=S.position):(d&&y>d&&(l+=m,m=0),S.position=l,m+=1),d=y});let g=p.map(({position:S})=>S),I=dn(g);return p.forEach(S=>{let{participantId:T,position:y}=S??{},E=r[T];S.GEMscore=h(E);let A=I[y];S?.position!==void 0&&(A>1&&(S.ties=A,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(HC).filter(E=>o.GEMscore.includes(E)):Object.keys(HC)).map(E=>(S[E]||0)*Math.pow(10,HC[E].toFixed(3))).reduce((E,A)=>E+A,0)}}function q3({participantResults:t,participantsCount:e}){let n=BC({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function $3({disableHeadToHead:t,participantIds:e,matchUpFormat:r,groupTotals:n,tallyPolicy:o,attribute:i,idsFilter:s,matchUps:a,reversed:c}){let{participantResults:u}=Zp({participantIds:s&&e,groupingTotal:n&&i,matchUpFormat:r,tallyPolicy:o,matchUps:a}),p=VC({participantResults:u,participantIds:e,attribute:i}),d=[{attribute:i,reversed:c,groups:p,idsFilter:s,groupTotals:n}],m;return Object.keys(p).length>1&&e.length&&(m=Object.keys(p).map(g=>Number.parseFloat(g)).sort((g,I)=>c?g-I:I-g).map(g=>p[g]).map(g=>{let I=s0({participantResults:u,disableHeadToHead:t,participantIds:g,matchUpFormat:r,tallyPolicy:o,matchUps:a});return d.push(...I.report??[]),I.order}).flatMap((g,I)=>g.map(h=>h.resolved?h:{...h,subGroup:[I].concat(...h.subGroup??[])}))),{order:m,report:d}}function s0({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 d=K3({participantIds:r,participantResults:t});if(d){let m=d[0].participantId;return a.push({attribute:"head2Head",participantIds:r,headToHeadWinner:m}),{order:d,headToHeadWinner:m,report:a}}}let p=(o?.tallyDirectives||Y3).filter(d=>{let m=!(He(d.maxParticipants)&&r?.length>d.maxParticipants);return m||s.push(d),m});return s.length&&a.push({excludedDirectives:s,participantIds:r}),p.every(({attribute:d,reversed:m,idsFilter:l,groupTotals:f,disableHeadToHead:g})=>(c=$3({disableHeadToHead:g,participantIds:r,matchUpFormat:n,groupTotals:f,tallyPolicy:o,attribute:d,idsFilter:l,matchUps:i,reversed:m}),a.push(c.report),!c.order)),c.order?{order:c.order,report:a}:{order:r?.map(d=>({participantId:d})),report:a}}function K3({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 pa({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Ur(o))return{error:zn};let a=ct(o.map(({structureId:y})=>y));if(a.length!==1)return M({result:{error:O,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!=="BYE"),u=c.length&&ct(c.flatMap(({drawPositions:y})=>y)).length,p=c.filter(y=>ia({matchUp:y})).length===c.length;p||(s=0);let d=o.every(({matchUpType:y,tieMatchUps:E})=>y===xt&&E?.every(A=>ia({matchUp:A}))),m=t?.[Ih],l=o.filter(y=>ia({matchUp:y})??y.matchUpType===xt),{participantResults:f}=Zp({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:m,perPlayer:s}),g,I,{groupOrder:h,report:S}=WC({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,subOrderMap:i,tallyPolicy:m});if(r&&z3({participantResults:f}),p&&h)g=S,I=h,h.forEach(y=>{let{participantId:E,groupOrder:A,rankOrder:N,subOrder:D,ties:R,GEMscore:U}=y,b=f[E];Object.assign(b,{groupOrder:A,rankOrder:N,GEMscore:U,subOrder:D,ties:R})});else{let{groupOrder:y,report:E}=WC({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:m,subOrderMap:i,matchUps:o});g=E,I=y,y&&y.forEach(A=>{let{participantId:N,groupOrder:D,subOrder:R,ties:U,GEMscore:b}=A,C=f[N];Object.assign(C,{provisionalOrder:D,GEMscore:b,subOrder:R,ties:U})})}let T={completedTieMatchUps:d,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||d)&&(T.order=I),e||We({tally:!0})){let y=i0({matchUps:o,report:g,order:I});We({tally:!0})&&console.log(y),T.readableReport=y}return T}function z3({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 a0({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=d=>[mi,_o,o.eventType,d].join("."),a=Object.assign({},...(n.timeItems??[]).filter(({itemType:d})=>d.split(".")[1]===_o).map(({itemType:d,itemValue:m})=>({[d]:m}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=Ht(Object.keys(a),c);if(!!(!e||!Object.keys(a).length&&!t?.drawIds?.length||u.length)&&u.length){if(t?.stageSeedingScaleNames){let d=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]}})),m=Object.assign({},...d);i.seedAssignments=m}else if(u){let d=u.map(m=>a[m]);i.seedValue=d.pop()}}else if(!e&&typeof r=="object"){let d=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]}})),m=Object.assign({},...d);i.seedAssignments=m}else{let{categoryName:d,ageCategoryCode:m}=o.category??{},l=[m,o.eventId,d].filter(Boolean),f;for(let g of l){let I={eventType:o.eventType,scaleType:_o,scaleName:g},h=Lo({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 Lf({positionAssignments:t}){let e=(t??[]).filter(Gr(Ge)).map(i=>{let s=st($t({element:i,attribute:"subOrder",name:Wa})),a=!isNaN(s)&&s;return a&&{participantId:i.participantId,subOrder:a}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=dn(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function c0({convertExtensions:t,seedAssignments:e,participant:r,withSeeding:n,seedValue:o,eventId:i,ranking:s,entry:a}){let{entryStatus:c,entryStage:u,entryPosition:p,extensions:d}=a,m=d?.length&&t?Object.assign({},...ih(d??[])):{},l=Object.assign(m,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=et(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function Lc(t){let e=X(t,[{[Z]:!0}]);if(e.error)return e;let{tournamentRecord:r,status:n=Rr}=t,o=`${Xo}.${Zo}`;return q(If({tournamentRecord:r,itemType:o})?.timeItem?.itemValue?.[n],!1,!0)}function u0(t){let{tournamentId:e}=t??{};return!!e}function br({event:t,status:e=Rr}){let r=`${Xo}.${Zo}`;return $p({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function td({drawDetails:t,drawId:e,ignoreEmbargo:r=!1}){let n=t?.[e]?.publishingDetail;return r?!!n?.published:go(n)}function da(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!u0(e))return{error:O};if(o&&!a)return{error:Br};if(Array.isArray(n)&&n?.length){let m={};for(let l of n){if(!wt(l))return{error:O};let f=Ve({tournamentRecord:e,eventId:l})?.event;if(!f)return{error:Br};let g=jC({event:f});m[l]=g}return{...P,publishState:m}}if(a)return Q3({event:a,drawId:s,drawIds:i,drawDefinition:r});let c={},{publishedEventIds:u,tournamentPublished:p}=J3({publishState:c,tournamentRecord:e}),d=[];return e&&X3({tournamentPublished:p,publishedEventIds:u,tournamentRecord:e,publishState:c,embargoes:d}),Z3({tournamentRecord:e,embargoes:d}),d.length&&(c.embargoes=d),{...P,publishState:c}}function Q3({event:t,drawId:e,drawIds:r,drawDefinition:n}){let o=jC({event:t}),i={};if(e)return n?{publishState:{status:{published:!!o.status.publishedDrawIds?.includes(e),drawDetail:o.status.drawDetails?.[e]},...P}}:{error:Cr};if(Array.isArray(r)&&r?.length){let s=t.drawDefinitions?.map(Cc)??[];for(let a of r){if(!wt(a))return{error:O};if(!s.includes(a))return{error:Cr};i[a]={status:{published:!!o.status.publishedDrawIds.includes(a),drawDetail:o.status.drawDetails?.[a]}}}}else i=o;return{...P,publishState:i}}function J3({publishState:t,tournamentRecord:e}){let r=[],n=!1;for(let o of e?.events??[]){let i=jC({event:o});t[o.eventId]=i,i.status.published&&(r.push(o.eventId),n=!0);for(let{drawId:s}of o.drawDefinitions??[]){let a=i.status?.publishedDrawIds?.includes(s);a&&(t[s]={status:{published:a}})}}return{publishedEventIds:r,tournamentPublished:n}}function X3({publishState:t,tournamentRecord:e,tournamentPublished:r,publishedEventIds:n,embargoes:o}){let i=Lc({tournamentRecord:e});return t.tournament=i??{},(i?.orderOfPlay?.published||i?.participants?.published)&&(r=!0),t.tournament.status={published:r,publishedEventIds:n},i?.orderOfPlay?.embargo&&o.push({type:"orderOfPlay",embargo:i.orderOfPlay.embargo,embargoActive:Vo(i.orderOfPlay)}),i?.participants?.embargo&&o.push({type:"participants",embargo:i.participants.embargo,embargoActive:Vo(i.participants)}),r}function Z3({tournamentRecord:t,embargoes:e}){for(let r of t?.events??[]){let o=br({event:r})?.drawDetails??{};for(let[i,s]of Object.entries(o))tK({drawId:i,detail:s,embargoes:e})}}function tK({drawId:t,detail:e,embargoes:r}){e?.publishingDetail?.embargo&&r.push({type:"draw",id:t,embargo:e.publishingDetail.embargo,embargoActive:Vo(e.publishingDetail)});for(let[n,o]of Object.entries(e?.stageDetails??{}))o?.embargo&&r.push({type:"stage",id:`${t}:${n}`,embargo:o.embargo,embargoActive:Vo(o)});for(let[n,o]of Object.entries(e?.structureDetails??{}))o?.embargo&&r.push({type:"structure",id:n,embargo:o.embargo,embargoActive:Vo(o)}),eK({structureId:n,structureDetail:o,embargoes:r})}function eK({structureId:t,structureDetail:e,embargoes:r}){if(e?.scheduledRounds)for(let[n,o]of Object.entries(e.scheduledRounds))o?.embargo&&r.push({type:"scheduledRound",id:`${t}:round${n}`,embargo:o.embargo,embargoActive:Vo(o)})}function jC({event:t}){let e=br({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(Cc)??[])n[a]||(n[a]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(a=>td({drawDetails:n,drawId:a,ignoreEmbargo:!0})),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 yA(t){let{participantMap:e,participantId:r,matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,schedule:p,drawId:d,score:m}=t;if(!p||!Object.keys(p).length)return;n==="BYE"||e[r].scheduleItems.push({...p,scheduledDate:ut(p?.scheduledDate),scheduledTime:Kt(p?.scheduledTime),checkScoreHasValue:le({score:m}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:d})}function p0({finishingPositionRange:t={winner:[],loser:[]},collectionPosition:e,participantMap:r,finishingRound:n,participantWon:o,collectionId:i,matchUpStatus:s,participantId:a,stageSequence:c,roundNumber:u,structureId:p,matchUpId:d,drawId:m,stage:l}){let f=r[a],g=y=>Math.abs(y[0]-y[1]);f.structureParticipation[p]||(f.structureParticipation[p]={rankingStage:l,walkoverWinCount:0,defaultWinCount:0,stageSequence:c,winCount:0,structureId:p,drawId:m});let I=f.structureParticipation[p],{winner:h,loser:S}=t,T=o?h:S;o&&(I.winCount+=1,s===vt&&(I.walkoverWinCount+=1),s===Mt&&(I.defaultWinCount+=1)),T&&(!I.finishingPositionRange||g(T)<g(I.finishingPositionRange))&&(I.finishingPositionRange=T),n&&((!I.finishingRound||n<I.finishingRound)&&(I.finishingMatchUpId=d,I.finishingRound=n,I.roundNumber=u),n===1&&(I.participantWon=o)),e&&(I.lineParticipation||(I.lineParticipation=[]),I.lineParticipation.push({collectionPosition:e,collectionId:i,won:o}))}function YC(t){let{withScheduleItems:e,scheduleAnalysis:r,withTeamMatchUps:n,participantMap:o,withOpponents:i,withMatchUps:s,withEvents:a,withDraws:c,finishingPositionRange:u,finishingRound:p,matchUpStatus:d,stageSequence:m,roundNumber:l,structureId:f,score:g,stage:I,withRankingProfile:h,collectionPosition:S,tieWinningSide:T,roundPosition:y,matchUpTieId:E,matchUpSides:A,collectionId:N,matchUpType:D,winningSide:R,matchUpId:U,schedule:b,eventId:C,drawId:_,sides:v}=t,x=i&&v?.length===2&&Object.assign({},...v.map(({sideNumber:w},F)=>{let L=v[1-F].participantId;return w&&{[w]:L}}).filter(Boolean));for(let w of v){let{participantId:F,sideNumber:L,bye:k}=w;if(k)continue;let G=R===L,V=H=>{let z=o[H]?.participant,W=z?.participantType,Q=[{participantId:H,participantType:W}];if(W!==fr)for(let pt of z?.individualParticipantIds??[]){let Tt=o[pt]?.participant;Q.push({participantType:Tt?.participantType,participantId:pt})}return Q},B=(H,z)=>{if(s){if(o[H].matchUps[U]={participantWon:G,matchUpType:D,structureId:f,sideNumber:L,matchUpId:U,eventId:C,drawId:_,stage:I},i){let W=V(z);o[H].matchUps[U].opponentParticipantInfo=W}N&&(o[H].matchUps[U].collectionId=N)}i&&z&&(o[H].opponents[z]={participantId:z,matchUpId:U,eventId:C,drawId:_}),h&&R&&p0({finishingPositionRange:u,collectionPosition:S,participantMap:o,participantWon:G,collectionId:N,finishingRound:p,matchUpStatus:d,participantId:H,stageSequence:m,roundNumber:l,structureId:f,matchUpId:U,drawId:_,stage:I}),(r||e)&&yA({participantMap:o,participantId:H,matchUpStatus:d,roundPosition:y,matchUpType:D,roundNumber:l,structureId:f,matchUpId:U,schedule:b,drawId:_,score:g})},$=({participant:H,partnerParticipantId:z})=>{let W=(Q,pt)=>{Q&&(Q.partnerParticipantIds??=[],Q.partnerParticipantIds.includes(pt)||Q.partnerParticipantIds.push(pt))};c&&W(H?.draws?.[_],z),a&&W(H?.events?.[C],z),s&&W(H?.matchUps?.[U],z)};if(F&&o[F]){let H=x?.[L];B(F,H);let z=o[F]?.participant.participantType===dt,W=o[F]?.participant.individualParticipantIds??[];E&&rK({individualParticipantIds:W,tieWinningSide:T,withTeamMatchUps:n,participantMap:o,matchUpSides:A,matchUpTieId:E,sideNumber:L,participantId:F,withDraws:c,eventId:C,drawId:_}),z&&nK({individualParticipantIds:W,opponentParticipantId:H,participantMap:o,matchUpSides:A,participantId:F,sideNumber:L,withEvents:a,addMatchUp:B,addPartner:$,eventId:C}),R&&oK({individualParticipantIds:W,participantMap:o,participantWon:G,matchUpStatus:d,participantId:F,matchUpType:D})}}}function rK({individualParticipantIds:t,tieWinningSide:e,withTeamMatchUps:r,participantMap:n,matchUpSides:o,matchUpTieId:i,sideNumber:s,participantId:a,withDraws:c,eventId:u,drawId:p}){if(r){let d=m=>n[m].matchUps[i]={participantWon:e===s,matchUpId:i,matchUpType:xt,sideNumber:s};d(a),t.forEach(d)}if(c&&!n[a].draws[p]){let d=o.find(f=>f.sideNumber===s)?.participant?.participantId,m=n[d]?.draws?.[p]?.entryStatus,l=f=>n[f].draws[p]={entryStatus:m,eventId:u,drawId:p};l(a),t.forEach(l)}}function nK({individualParticipantIds:t,opponentParticipantId:e,participantMap:r,matchUpSides:n,participantId:o,sideNumber:i,withEvents:s,addMatchUp:a,addPartner:c,eventId:u}){if(t.forEach(p=>r[p]&&a(p,e)),t.forEach((p,d)=>{let m=t[1-d],l=r[p];l&&c({participant:l,partnerParticipantId:m})}),s&&n){let p=n.find(d=>d.sideNumber===i)?.participant?.participantId;if(p){let d=r[p]?.events[u];d?(r[o].events[u]={...d},t.forEach(m=>r[m].events[u]={...d})):console.log("Missing teamEntry",{eventId:u,teamParticipantId:p})}}}function oK({individualParticipantIds:t,participantMap:e,participantWon:r,matchUpStatus:n,participantId:o,matchUpType:i}){let s=a=>{r?(e[a].counters[i].wins+=1,e[a].counters.wins+=1,n===vt&&(e[a].counters[i].walkoverWins+=1,e[a].counters.walkoverWins+=1),n===Mt&&(e[a].counters[i].defaultWins+=1,e[a].counters.defaultWins+=1)):(e[a].counters[i].losses+=1,e[a].counters.losses+=1,n===vt&&(e[a].counters[i].walkovers+=1,e[a].counters.walkovers+=1),n===Mt&&(e[a].counters[i].defaults+=1,e[a].counters.defaults+=1))};s(o),t.forEach(s)}function ed(t,e){return(t||"").localeCompare(e||"")}function m0(t){let{participantFilters:e,convertExtensions:r,policyDefinitions:n,tournamentRecord:o,usePublishState:i,contextFilters:s,matchUpFilters:a,participantMap:c,contextProfile:u,withPotentialMatchUps:p,withRankingProfile:d,withScheduleItems:m,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,withOpponents:I,withMatchUps:h,withSeeding:S,withEvents:T,withDraws:y}=t,E=e?.participantIds,A=L=>{let k=[L];return c[L]?.participant.individualParticipantIds?.forEach(G=>k.push(G)),k.some(G=>!E?.length||E.includes(G))?k:[]},N={withMatchUps:h||d,withEvents:T||d,withDraws:y||d,withPotentialMatchUps:p,withRankingProfile:d,withScheduleItems:m,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,participantMap:c,withOpponents:I,withSeeding:S},D=[],R={},U=[],b={},C={},_={},v={},x={},w=({eventType:L,scaleNames:k,participantId:G})=>c[G]?.participant?.rankings?.[L]?.find(V=>k.includes(V.scaleName))?.scaleValue;for(let L of o?.events??[])e?.eventIds&&!e.eventIds.includes(L.eventId)||iK({convertExtensions:r,eventsPublishStatuses:b,derivedEventInfo:C,derivedDrawInfo:_,participantMap:c,getRanking:w,withOpts:N,event:L,getRelevantParticipantIds:A,withPotentialMatchUps:p,withRankingProfile:d,withScheduleItems:m,scheduleAnalysis:l,withTeamMatchUps:f,policyDefinitions:n,tournamentRecord:o,withStatistics:g,rrContainerInfo:x,rrGroupMatchUps:v,mappedMatchUps:R,contextFilters:s,matchUpFilters:a,contextProfile:u,withOpponents:I,usePublishState:i,withMatchUps:h,withSeeding:S,withEvents:T,withDraws:y,matchUps:U});let F=mK(v,x,d);if(g||d||l){let L=fK({rrFinishingPositions:F,withRankingProfile:d,scheduleAnalysis:l,withStatistics:g,derivedDrawInfo:_,participantMap:c});D.push(...L)}return{participantIdsWithConflicts:D,eventsPublishStatuses:b,derivedEventInfo:C,derivedDrawInfo:_,mappedMatchUps:R,participantMap:c,matchUps:U}}function iK({convertExtensions:t,eventsPublishStatuses:e,derivedEventInfo:r,derivedDrawInfo:n,participantMap:o,getRanking:i,withOpts:s,event:a,getRelevantParticipantIds:c,withPotentialMatchUps:u,withRankingProfile:p,withScheduleItems:d,scheduleAnalysis:m,withTeamMatchUps:l,policyDefinitions:f,tournamentRecord:g,withStatistics:I,rrContainerInfo:h,rrGroupMatchUps:S,mappedMatchUps:T,contextFilters:y,matchUpFilters:E,contextProfile:A,withOpponents:N,usePublishState:D,withMatchUps:R,withSeeding:U,withEvents:b,withDraws:C,matchUps:_}){let{drawDefinitions:v=[],extensions:x=[],wheelchairClass:w,eventType:F,eventName:L,category:k,entries:G,eventId:V,gender:B}=a,{flightProfile:$}=Gt({event:a}),H=$?.flights??[],z=da({event:a}).publishState;z&&(e[V]=z);let W=z?.status?.publishedSeeding;if(b||U||p){let pt=t?Object.assign({},...ih(x??[])):{};r[V]={...pt,wheelchairClass:w,eventName:L,eventType:F,category:k,eventId:V,gender:B};let Tt=[k?.categoryName,k?.ageCategoryCode].filter(Boolean);for(let Ot of G){let{participantId:Et}=Ot;if(!Et||!o[Et])continue;let Bt=i({eventType:F,scaleNames:Tt,participantId:Et}),ce,ge;if(U){let Ln=o[Et].participant;({seedAssignments:ce,seedValue:ge}=a0({publishedSeeding:W,usePublishState:D,withSeeding:U,participant:Ln,event:a}))}let he=Ln=>{if(o[Ln]?.events?.[V])return;let Fn=o[Ln];c0({convertExtensions:t,seedAssignments:ce,participant:Fn,withSeeding:U,seedValue:ge,eventId:V,ranking:Bt,entry:Ot})};he(Et),(o[Et].participant.individualParticipantIds??[]).forEach(he)}}let Q=e?.[V]?.publishedSeeding;if(C||p||U){let pt=ct([...v.map(Cc),...H.map(Cc)]);for(let Tt of pt)aK({drawDefinitions:v,participantMap:o,derivedDrawInfo:n,eventPublishedSeeding:Q,usePublishState:D,withRankingProfile:p,withSeeding:U,withDraws:C,eventType:F,category:k,eventId:V,flights:H,drawId:Tt,getRanking:i})}if(p||m||l||I||N||R||C){let pt=!!m||u,Tt=_n({afterRecoveryTimes:!!m,policyDefinitions:f,tournamentRecord:g,inContext:!0,participantMap:o,contextFilters:y,matchUpFilters:E,contextProfile:A,nextMatchUps:pt,event:a})?.matchUps??[];for(let Ot of Tt)cK({getRelevantParticipantIds:c,withScheduleItems:d,tournamentRecord:g,drawDefinitions:v,scheduleAnalysis:m,withRankingProfile:p,rrContainerInfo:h,rrGroupMatchUps:S,mappedMatchUps:T,participantMap:o,nextMatchUps:pt,withOpts:s,matchUp:Ot});_.push(...Tt)}}function d0(t){return t?Object.assign({},...t.map(({participantId:e,seedValue:r,seedNumber:n})=>({[e]:{seedValue:r,seedNumber:n}}))):void 0}function sK({participantMap:t,id:e,participantId:r,eventId:n,eventType:o,drawId:i,mainSeedingMap:s,qualifyingSeedingMap:a,seedingPublished:c,withSeeding:u}){let p=u&&c,d=p?{}:void 0,m=p?s?.[r]?.seedValue||s?.[r]?.seedNumber:void 0,l=m?s?.[r]:void 0,f=p?a?.[r]?.seedValue||a?.[r]?.seedNumber:void 0,g=f?a?.[r]:void 0;d&&m&&(d[j]=l),d&&f&&(d[rt]=g);let I=m||f;return I&&(t[e].participant.seedings[o]||(t[e].participant.seedings[o]=[]),l&&t[e].participant.seedings[o].push({...l,scaleName:i}),g&&t[e].participant.seedings[o].push({...g,scaleName:i}),d&&(t[e].events[n].seedAssignments||(t[e].events[n].seedAssignments={}),Object.keys(d).forEach(h=>t[e].events[n].seedAssignments[h]=d[h]))),{seedAssignments:d,seedValue:I}}function aK({drawDefinitions:t,participantMap:e,derivedDrawInfo:r,eventPublishedSeeding:n,usePublishState:o,withRankingProfile:i,withSeeding:s,withDraws:a,eventType:c,category:u,eventId:p,flights:d,drawId:m,getRanking:l}){let f=t.find(G=>G.drawId===m),g=[u?.categoryName,u?.ageCategoryCode].filter(Boolean),{structures:I=[],drawOrder:h,drawName:S,drawType:T}=f??{},y=d?.find(G=>G.drawId===m),E=f?.entries||y?.drawEntries,A=y?.flightNumber,N=(f?.structures??[]).sort((G,V)=>Xi(G,V)).map(({structureId:G,structures:V})=>[G,...(V??[]).map(({structureId:B})=>B)]).flat(1/0),D,R,U,b,C=0,_=new Set(I.filter(({stage:G,stageSequence:V})=>G===j&&V===1||G===rt).flatMap(G=>{let{positionAssignments:V}=yt({structure:G}),{seedAssignments:B,stageSequence:$,stage:H}=G;return H===j?(C=V?.length??0,U=V,b=B):$===1&&(D=V,R=B),V}).map(({participantId:G})=>G).filter(Boolean)),v=d0(b),x=d0(R),w=f?E.filter(({participantId:G})=>_.has(G)):E,F=!o||n?.published&&(n?.drawIds?.length===0||n?.drawIds?.includes(m));for(let G of w){if(!e[G.participantId])continue;let{entryStatus:V,entryStage:B,entryPosition:$,participantId:H}=G,z=l({participantId:H,scaleNames:g,eventType:c}),W=Q=>{if(!e[Q]||e[Q].draws?.[m])return;let{seedAssignments:pt,seedValue:Tt}=sK({participantMap:e,id:Q,participantId:H,eventId:p,eventType:c,drawId:m,mainSeedingMap:v,qualifyingSeedingMap:x,seedingPublished:F,withSeeding:s});(a||i)&&(e[Q].draws[m]=et({seedAssignments:pt,entryPosition:$,entryStatus:V,entryStage:B,seedValue:Tt,eventId:p,ranking:z,drawId:m},!1,!1,!0))};[kr,es].includes(V)||(W(H),(e[H].participant.individualParticipantIds??[])?.forEach(W))}let L=(f?.structures??[]).reduce((G,V)=>(G.includes(V.stage)||G.push(V.stage),G),[]),k=(f?.links??[]).length;r[m]={qualifyingPositionAssignments:D,qualifyingSeedAssignments:R,mainPositionAssignments:U,qualifyingSeedingMap:x,mainSeedAssignments:b,orderedStructureIds:N,mainSeedingMap:v,flightNumber:A,linksCount:k,drawOrder:h,drawName:S,drawType:T,drawSize:C,drawId:m,stages:L}}function cK({getRelevantParticipantIds:t,withScheduleItems:e,tournamentRecord:r,drawDefinitions:n,scheduleAnalysis:o,withRankingProfile:i,rrContainerInfo:s,rrGroupMatchUps:a,mappedMatchUps:c,participantMap:u,nextMatchUps:p,withOpts:d,matchUp:m}){let{finishingPositionRange:l,potentialParticipants:f,tieMatchUps:g=[],sides:I=[],winningSide:h,matchUpType:S,matchUpId:T,eventId:y,drawId:E,collectionId:A,containerStructureId:N,stageSequence:D,finishingRound:R,matchUpStatus:U,roundPosition:b,roundNumber:C,structureId:_,schedule:v,score:x,stage:w}=m;if(c[T]=m,i&&N&&_&&E&&(a[_]||(a[_]=[]),a[_].push(m),!s[N])){let L=n.find(k=>k.drawId===E);L&&(s[N]={drawDefinition:L,drawId:E})}let F={finishingPositionRange:l,containerStructureId:N,finishingRound:R,stageSequence:D,roundPosition:b,collectionId:A,roundNumber:C,structureId:_,schedule:v,eventId:y,drawId:E,score:x,stage:w};YC({tournamentRecord:r,drawDefinitions:n,...F,...d,matchUpStatus:U,winningSide:h,matchUpType:S,matchUpId:T,sides:I});for(let L of g){let{winningSide:k,sides:G=[],matchUpId:V,collectionPosition:B,collectionId:$,matchUpStatus:H,matchUpType:z}=L;YC({...F,...d,winningSide:k,tieWinningSide:h,matchUpTieId:T,matchUpId:V,sides:G,collectionId:$,collectionPosition:B,matchUpSides:I,matchUpStatus:H,matchUpType:z})}Array.isArray(f)&&(p||o||e)&&uK({getRelevantParticipantIds:t,potentialParticipants:f,withScheduleItems:e,tournamentRecord:r,scheduleAnalysis:o,participantMap:u,matchUpStatus:U,roundPosition:b,structureId:_,matchUpType:S,roundNumber:C,matchUpId:T,schedule:v,eventId:y,drawId:E,score:x})}function uK({getRelevantParticipantIds:t,potentialParticipants:e,withScheduleItems:r,tournamentRecord:n,scheduleAnalysis:o,participantMap:i,matchUpStatus:s,roundPosition:a,structureId:c,matchUpType:u,roundNumber:p,matchUpId:d,schedule:m,eventId:l,drawId:f,score:g}){e.flat().map(lt).filter(Boolean)?.forEach(h=>{t(h)?.forEach(T=>{i[T]&&(i[T].potentialMatchUps[d]=et({tournamentId:n?.tournamentId,matchUpId:d,eventId:l,drawId:f}))}),(o||r)&&yA({potential:!0,participantMap:i,participantId:h,matchUpStatus:s,roundPosition:a,structureId:c,matchUpType:u,roundNumber:p,matchUpId:d,schedule:m,drawId:f,score:g})})}function pK({drawPositionsCount:t,containerStructureId:e,bracketsCount:r,playoffStructure:n,drawDefinition:o,bracketSize:i,order:s}){if(t===i&&s)return[s,s];if(r>1&&s&&!n)return[1,r];if(r>1&&s&&n){let a=o.links?.find(c=>c.source.structureId===e)?.source?.finishingPositions;if(a){let c=a.length*r;if(a.includes(s))return[1,c];let u=(i-s)*r;return[c+1,t-u]}}}function dK({containedStructure:t,rrGroupMatchUps:e,drawPositionsCount:r,containerStructureId:n,bracketsCount:o,playoffStructure:i,drawDefinition:s,drawPositions:a}){let c=t.structureId,u=e[c];if(!u?.length)return;let p=t.positionAssignments?.length,{subOrderMap:d}=Lf({positionAssignments:t.positionAssignments}),m=pa({matchUps:u,subOrderMap:d});if(m?.participantResults)for(let[l,f]of Object.entries(m.participantResults)){let g=f.groupOrder||f.provisionalOrder;if(!g)continue;let I=pK({drawPositionsCount:r,containerStructureId:n,bracketsCount:o,playoffStructure:i,drawDefinition:s,bracketSize:p,order:g});I&&(a[l]=I)}}function mK(t,e,r){let n={};if(!r)return n;for(let[o,i]of Object.entries(e)){let{drawDefinition:s,drawId:a}=i,c=s.structures?.find(l=>l.structureType===Ie&&l.stage===j&&l.stageSequence===1);if(!c?.structures)continue;let u=c.structures,p=u.length,d=u.reduce((l,f)=>l+(f.positionAssignments?.length||0),0),m=s.structures?.find(l=>l.stage===Vt);n[a]||(n[a]={});for(let l of u)dK({containedStructure:l,rrGroupMatchUps:t,drawPositionsCount:d,containerStructureId:o,bracketsCount:p,playoffStructure:m,drawDefinition:s,drawPositions:n[a]})}return n}function lK({scheduleItems:t,potentialMatchUps:e,scheduleAnalysis:r}){let n=St(r)?r.scheduledMinutesDifference:0,o={},i=t.reduce((s,a)=>{let{scheduledDate:c,scheduledTime:u}=a;return s[c]||(s[c]=[]),u&&s[c].push(a),s},{});Object.values(i).forEach(s=>s.sort(Ky));for(let s of t){let{typeChangeTimeAfterRecovery:a,timeAfterRecovery:c,scheduledDate:u,scheduledTime:p}=s,d=i[u],m=Yt(p);for(let l of d){if(l.matchUpId===s.matchUpId||ze(l.matchUpStatus)&&!l.checkScoreHasValue)continue;let I=s.matchUpType!==l.matchUpType&&a||c,h=s.drawId===l.drawId,S=e[s.matchUpId]&&e[l.matchUpId],T=Yt(l.scheduledTime),y=Math.abs(T-m),E=T>=m;if((n&&!Number.isNaN(n)?y<=n:E&&Yt(l.scheduledTime)<Yt(I))&&!(S&&h)&&E){let N=[s.matchUpId,l.matchUpId].sort(ed).join("|");o[N]={priorScheduledMatchUpId:s.matchUpId,matchUpIdWithConflict:l.matchUpId}}}}return o}function fK({rrFinishingPositions:t,withRankingProfile:e,scheduleAnalysis:r,withStatistics:n,derivedDrawInfo:o,participantMap:i}){let s=[],a=Object.values(i);for(let c of a){let{wins:u,losses:p,[Ct]:{wins:d,losses:m},[Ut]:{wins:l,losses:f}}=c.counters,g=(I,h,S)=>{let T=h+S,y=h,E=T&&y/T;c.statistics[I]={denominator:T,numerator:y,statValue:E,statCode:I}};n&&(g(Sf,u,p),g(`${Sf}.${Ct}`,d,m),g(`${Sf}.${Ut}`,l,f)),e&&gK({participantAggregator:c,derivedDrawInfo:o,rrFinishingPositions:t}),r&&IK({participantAggregator:c,scheduleAnalysis:r,participantMap:i,participantIdsWithConflicts:s})}return s}function gK({participantAggregator:t,derivedDrawInfo:e,rrFinishingPositions:r}){let n=(o=[])=>Math.abs(o[0]-o[1]);for(let o of Object.keys(t.draws)){let{orderedStructureIds:i=[],flightNumber:s}=e[o]??{};if(!t.structureParticipation||!i.length)continue;let a,c=0,u=i.map(p=>{let d=t.structureParticipation[p];if(!d)return;a||(a=d?.finishingPositionRange),n(a)>n(d?.finishingPositionRange)&&(a=d?.finishingPositionRange);let m=d.stage!==rt;return m&&(c+=1),et({...d,participationOrder:m?c:void 0,flightNumber:s})}).filter(Boolean);if(t.draws[o]){let p=t.participant.participantId,d=r[o]?.[p];d&&(a=d),t.draws[o].finishingPositionRange=a,t.draws[o].structureParticipation=u}}}function IK({participantAggregator:t,scheduleAnalysis:e,participantMap:r,participantIdsWithConflicts:n}){let o=t.scheduleItems??[],i=t.potentialMatchUps??{};t.scheduleConflicts=lK({scheduleAnalysis:e,scheduleItems:o,potentialMatchUps:i});let s=t.participant.participantId;Object.keys(t.scheduleConflicts).length&&n.push(s),r[s].scheduleConflicts=t.scheduleConflicts}function rd({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:d,enableOrFiltering:m,eventIds:l,genders:f}=t,g=za(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&hK({drawEntryStatuses:o,tournamentEvents:g}),h=s&&SK({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,E)=>y.concat(...(E.drawDefinitions??[]).map(A=>kE({drawDefinition:A}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((E,A)=>{let{accessor:N,value:D}=A,{values:R}=Qi({element:y,accessor:N});return E&&R?.includes(D)},!0);if(r=r?.filter(y=>{let E=Fr({element:y,itemType:Eu})?.timeItem?.itemValue,{participantRoleResponsibilities:A,participantType:N,participantRole:D,participantId:R,person:U}=y,b=Array.isArray(f)&&f?.length&&U?.sex&&f.includes(U.sex);return m?f&&b||i&&S.includes(R)||i===!1&&!S.includes(R)||I?.includes(R)||h?.includes(R)||p?.includes(R)||d&&E===d||u&&N&&za(u)&&u.includes(N)||a&&D&&za(a)&&a.includes(D)||c&&za(A)&&za(c)&&c.find(C=>A?.includes(C))||n?.length&&za(n)&&T(y):(!f||b)&&(i===void 0||i&&S.includes(R)||i===!1&&!S.includes(R))&&(!I||I.includes(R))&&(!h||h.includes(R))&&(!p||p.includes(R))&&(!d||E===d)&&(!u||N&&za(u)&&u.includes(N))&&(!a||D&&za(a)&&a.includes(D))&&(!c||za(A)&&za(c)&&c.find(C=>A?.includes(C)))&&(!n?.length||za(n)&&T(y))}),g.length&&l){let y=new Set(g.filter(E=>l.includes(E.eventId)).flatMap(E=>{let A=(E.entries??[]).map(D=>D.participantId);if(oe(ue)(E.eventType))return A;let N=(e?.participants??[]).filter(D=>A.includes(D.participantId)).flatMap(D=>D.individualParticipantIds);return A.concat(...N)}));r=r?.filter(E=>y.has(E.participantId))}return r}function za(t){return t&&Array.isArray(t)&&t.length}function hK({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return ct(e.reduce((n,o)=>{let{flightProfile:i}=Gt({event:o}),s=i?.flights?.flatMap(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(lt):[])??[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(lt):[])??[];return n.concat(...s,...a)},[]))}function SK({eventEntryStatuses:t,tournamentEvents:e}){return ct(e.reduce((r,n)=>{let o=(n.entries??[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(lt);return r.concat(...o)},[]))}function Nt(t){let{withIndividualParticipants:e,participantFilters:r={},withPotentialMatchUps:n,withRankingProfile:o,convertExtensions:i,policyDefinitions:s,withScheduleItems:a,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:p,withTeamMatchUps:d,withScaleValues:m,usePublishState:l,withStatistics:f,contextFilters:g,matchUpFilters:I,contextProfile:h,withOpponents:S,withMatchUps:T,internalUse:y,withSeeding:E,withEvents:A,withDraws:N,withISO2:D,withIOC:R}=t,U="getParticipants";if(!c)return M({stack:U,result:{error:Y}});(T||o)&&en({tournamentRecord:c});let b=KE({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:m,internalUse:y,withISO2:D,withIOC:R}),{participantMap:C}=b,_=m0({withMatchUps:T??o,withEvents:A??o,withDraws:N??o,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:o,convertExtensions:i,withScheduleItems:a,policyDefinitions:s,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:d,usePublishState:l,withStatistics:f,contextFilters:g,matchUpFilters:I,participantMap:C,withOpponents:S,contextProfile:h,withSeeding:E}),{participantIdsWithConflicts:v,eventsPublishStatuses:x,derivedEventInfo:w,derivedDrawInfo:F,mappedMatchUps:L}=_,k=_.matchUps;C=_.participantMap;let G=u??n,V=({potentialMatchUps:pt,scheduleConflicts:Tt,scheduleItems:Ot,participant:Et,statistics:Bt,opponents:ce,matchUps:ge,events:he,draws:oo})=>{let Ln=Object.values(oo),Fn=Object.values(ce);return S&&Ln?.forEach(Ui=>{Ui.opponents=Fn.filter(ii=>ii.drawId===Ui.drawId)}),et({...Et,scheduleConflicts:u?Object.values(Tt):void 0,draws:N||o?Ln:void 0,events:A||o?Object.values(he):void 0,matchUps:T||o?Object.values(ge):void 0,opponents:S?Fn:void 0,potentialMatchUps:G?Object.values(pt):void 0,statistics:f?Object.values(Bt):void 0,scheduleItems:a?Ot:void 0},!1,!1,!0)},B=new Map;for(let pt of Object.keys(C))B.set(pt,V(C[pt]));let $=[...B.values()],z=s?.[Ba]?.participant,W=rd({participants:$,participantFilters:r,tournamentRecord:c});if(e){let pt=St(e)?e:void 0;for(let Tt of W)for(let Ot of Tt.individualParticipantIds??[]){Tt.individualParticipants??=[];let Et=B.get(String(Ot)),Bt=pt?Ps({template:pt,source:Et}):Et;Tt.individualParticipants.push(Bt)}}let Q=z?W.map(pt=>Ps({source:pt,template:z})):W;return{participantMap:t.returnParticipantMap!==!1?C:void 0,mappedMatchUps:t.returnMatchUps!==!1?L:void 0,matchUps:t.returnMatchUps!==!1?k:void 0,missingParticipantIds:b.missingParticipantIds,participantIdsWithConflicts:v,eventsPublishStatuses:x,derivedEventInfo:w,derivedDrawInfo:F,participants:Q,...P}}function as(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:$e};let{participant:i,tournamentId:s}=Bn({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...Lo({participant:i,scaleAttributes:r}),tournamentId:s}:{error:Wt}}function I0(t,e){let r=t.startDate||e?.startDate,n=t.endDate||e?.endDate;return!r||!n?{error:WL}:!Fe(r)||!Fe(n)?{error:de}:{startDate:r,endDate:n}}function l0(t,e){return Number(ut(e).split("-")[0])-t}function f0(t,e){let r=new Date(ut(t)),n=new Date(ut(e)),o=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return(i<0||i===0&&n.getDate()<r.getDate())&&o--,o}function g0(t,e,r){return!(e!==void 0&&t<e||r!==void 0&&t>r)}function TK(t){return/^C\d{1,2}-\d{1,2}$/.test(t.ageCategoryCode||"")}function yK(t,e,r,n){if(TK(e))return{valid:!0};let o=e.ageMin,i=e.ageMax;if(e.ageCategoryCode&&!o&&!i){let l=Es({consideredDate:r,category:e});l.error||(o=l.ageMin,i=l.ageMax)}if(!o&&!i)return{valid:!0};let s=t.person?.birthDate,a=t.person?.birthYear;if(!s&&a===void 0)return{valid:!1,reason:"Missing birthDate or birthYear",details:{requiredMin:o,requiredMax:i}};let c=s?{birthDate:s}:{birthYear:a},u=s?f0(s,r):l0(a,r),p=s?f0(s,n):l0(a,n),d=g0(u,o,i),m=g0(p,o,i);if(!d){let l=[o===void 0?null:`min: ${o}`,i===void 0?null:`max: ${i}`].filter(Boolean).join(", ");return{valid:!1,reason:`Age ${u} at event start (${r}) outside range [${l}]`,details:{...c,ageAtStart:u,ageAtEnd:p,requiredMin:o,requiredMax:i}}}if(!m){let l=[o===void 0?null:`min: ${o}`,i===void 0?null:`max: ${i}`].filter(Boolean).join(", ");return{valid:!1,reason:`Age ${p} at event end (${n}) outside range [${l}]`,details:{...c,ageAtStart:u,ageAtEnd:p,requiredMin:o,requiredMax:i}}}return{valid:!0}}function EK(t,e,r,n){if(!e.ratingMin&&!e.ratingMax)return{valid:!0};if(!e.ratingType)return{valid:!0};let o={scaleType:"RATING",scaleName:e.ratingType,eventType:r.eventType},{scaleItem:i}=as({tournamentRecord:n,participantId:t.participantId,scaleAttributes:o});if(!i?.scaleValue)return{valid:!1,reason:`Missing ${e.ratingType} rating`,details:{ratingType:e.ratingType,requiredMin:e.ratingMin,requiredMax:e.ratingMax}};let s;if(typeof i.scaleValue=="object"){let a=Qi({element:i.scaleValue,accessor:i.scaleValue?.accessor});if(a===void 0)return{valid:!1,reason:`Cannot extract rating value from ${e.ratingType} scale item`,details:{ratingType:e.ratingType,requiredMin:e.ratingMin,requiredMax:e.ratingMax}};s=a}else s=i.scaleValue;return e.ratingMin!==void 0&&s<e.ratingMin?{valid:!1,reason:`${e.ratingType} rating ${s} below minimum ${e.ratingMin}`,details:{ratingType:e.ratingType,ratingValue:s,requiredMin:e.ratingMin,requiredMax:e.ratingMax}}:e.ratingMax!==void 0&&s>e.ratingMax?{valid:!1,reason:`${e.ratingType} rating ${s} above maximum ${e.ratingMax}`,details:{ratingType:e.ratingType,ratingValue:s,requiredMin:e.ratingMin,requiredMax:e.ratingMax}}:{valid:!0}}function qC(t){let e=t.person;if(!e)return t.participantOtherName||t.participantName||"Unknown";let r=e.standardGivenName||e.passportGivenName,n=e.standardFamilyName||e.passportFamilyName;return[r,n].filter(Boolean).join(" ")||t.participantOtherName||t.participantName||"Unknown"}function $C(t,e,r,n,o,i){let s=yK(t,e,n,o),a=EK(t,e,r,i);if(!s.valid||!a.valid){let c={participantId:t.participantId,participantName:qC(t),rejectionReasons:[]};return s.valid||c.rejectionReasons.push({type:"age",reason:s.reason,details:s.details??{}}),a.valid||c.rejectionReasons.push({type:"rating",reason:a.reason,details:a.details??{}}),c}return null}function Mu({participantId:t,drawDefinition:e,entryStatus:r,entryStage:n}){if(!e)return{error:K};let o=e.entries?.find(i=>i.participantId===t&&(!r||r===i.entryStatus)&&(!n||n===i.entryStage));return t&&o}function KC({stage:t,drawDefinition:e}){return!!(t===Qe||dk({stage:t,drawDefinition:e}))}function AK({relevantLinks:t,drawDefinition:e,provisionalPositioning:r,roundQualifiersCounts:n}){let o=0;for(let i of t){let s=tt({structureId:i.source.structureId,drawDefinition:e})?.structure;if(s?.stage===rt){let a=i.source.roundNumber,c=i.target.roundNumber,u;if(s.structureType===Ie){let p=s.structures?.length??0,d=i.source.finishingPositions?.length??0;u=p*d}else a===0&&i.source.qualifyingPositions?u=i.source.qualifyingPositions:u=ht({matchUpFilters:{roundNumbers:[a]},structure:s,afterRecoveryTimes:!1,provisionalPositioning:r,inContext:!1}).matchUps?.length||0;n[c]||(n[c]=0),n[c]+=u,o+=u}}return o}function nd(t){let{provisionalPositioning:e,drawDefinition:r,structureId:n}=t;if(!r)return{error:K};let o={};if(!n)return{qualifiersCount:0,roundQualifiersCounts:o};let{structure:i}=tt({drawDefinition:r,structureId:n}),s=r.links?.filter(c=>c?.target?.structureId===i?.structureId),a=0;return s?.length&&(a=AK({relevantLinks:s,drawDefinition:r,provisionalPositioning:e,roundQualifiersCounts:o})),{qualifiersCount:a,roundQualifiersCounts:o}}function zC({stage:t,drawDefinition:e,stageSequence:r,tournamentRecord:n,event:o}){let i=e?.structures?.filter(s=>s.stage===t&&(!r||s.stageSequence===r));if(i?.length)return i.reduce((s,a)=>a.structureType===Ie?s+(a.structures?.reduce((c,u)=>c+(u.positionAssignments?.length??0),0)??0):s+(a.positionAssignments?.length??0),0);if(t===j&&n){let{constraints:s}=QE({tournamentRecord:n,event:o});if(s?.drawSize)return s.drawSize}return 0}function h0(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o,tournamentRecord:i,event:s}=t,a=zC({stage:o,drawDefinition:r,stageSequence:n,tournamentRecord:i,event:s}),c=r?.structures?.find(p=>p.stage===o&&(!n||p.stageSequence===n)),{qualifiersCount:u}=nd({structureId:c?.structureId,provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return a&&a-(u??0)}function QC({entryStatus:t=Nr,tournamentRecord:e,drawDefinition:r,stageSequence:n,event:o,stage:i}){let{constraints:s}=QE({tournamentRecord:e,event:o});if(t===tn){if(!s)return{positionsAvailable:1/0,...P};if(s.maxAlternates===void 0)return{positionsAvailable:1/0,...P};let f=JE({entryStatus:tn,drawDefinition:r,stage:i});return f<s.maxAlternates?{positionsAvailable:s.maxAlternates-f,...P}:{error:IR}}if(!r?.structures?.some(f=>f.stage===i))return{positionsAvailable:1/0,...P};let c=h0({drawDefinition:r,stageSequence:n,stage:i}),u=JE({entryStatus:zp,drawDefinition:r,stage:i}),p=JE({entryStatus:Nr,drawDefinition:r,stage:i}),d=u+p,m=c>0&&d>=c,l=c-d;if(i!==Qe&&m)return{error:LI};if(t===zp){if(!s)return d<c?{...P}:{error:LI};let f=s.maxWildcards??c;return u<f?{...P}:{error:LI}}return{positionsAvailable:l,...P}}var PK=new Set([vi,$s]);function En(t){return!!t&&PK.has(t)}function Ff(t){let e=X(t,[{[zt]:!0,[yE]:!0}]);if(e.error)return e;let{suppressDuplicateEntries:r=!0,entryStatus:n=Nr,entryStageSequence:o,entryStage:i=j,ignoreStageSpace:s,drawDefinition:a,entryPosition:c,participant:u,roundTarget:p,extensions:d,extension:m,drawType:l,event:f}=t,g="addDrawEntry";if(!En(l)&&!KC({stage:i,drawDefinition:a}))return M({result:{error:hc},stack:g});let I=QC({stageSequence:o,stage:i,drawDefinition:a,entryStatus:n});if(!s&&!I.success&&(!l||!En(l)))return{error:I.error};if(m&&!Zn({extension:m}))return M({result:{error:O},info:"Invalid extension",context:{extension:m},stack:g});let h=t.participantId||u?.participantId;if(!h)return M({result:{error:$e},stack:g});let S=n===Js&&Mu({participantId:h,drawDefinition:a,entryStatus:n}),T=i===Qe&&Mu({participantId:h,drawDefinition:a,entryStage:i}),y=Mu({participantId:h,drawDefinition:a}),E=n!==Js&&i!==Qe&&y;if(E)return r?(it({payload:{drawId:a.drawId,eventId:f?.eventId,error:Ll,participantId:h},topic:VE}),{...P}):M({result:{error:Ll},context:{participantId:h},stack:g});if(S||T)return M({context:{invalidEntry:E,invalidLuckyLoser:S,invalidVoluntaryConsolation:T},result:{error:zd},stack:g});let A=et({entryStageSequence:o,participantId:h,entryPosition:c,entryStatus:n,entryStage:i,extensions:d});return m&&Qt({element:A,extension:m}),p&&At({element:A,attribute:"roundTarget",name:Xr,value:p}),a.entries??=[],a.entries.push(A),Lt({drawDefinition:a}),{...P}}function S0(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=Nr,autoEntryPositions:o=!0,ignoreStageSpace:i,participantIds:s,drawDefinition:a,stageSequence:c,stage:u=j,roundTarget:p,extension:d,event:m}=t,l=En(a.drawType);if(!u)return{error:UI};if(!a)return{error:K};if(!Array.isArray(s))return{error:vr};if(!l&&!KC({stage:u,drawDefinition:a}))return{error:hc};if(d&&!Zn({extension:d}))return M({result:{error:O},info:"Invalid extension",context:{extension:d},stack:e});let f=QC({drawDefinition:a,stageSequence:c,entryStatus:n,stage:u});if(!i&&!f.success&&!l)return{error:f.error};let g=f.positionsAvailable??0;if(!i&&!l&&u!==Qe&&g<s.length)return{error:xI};let I=[],h=a.drawId,S=m?.eventId,T=s.reduce((y,E)=>{let A=n===Js&&Mu({participantId:E,drawDefinition:a,entryStatus:n}),N=u===Qe&&Mu({entryStage:u,drawDefinition:a,participantId:E}),D=Mu({participantId:E,drawDefinition:a});return n!==Js&&u!==Qe&&D&&(I.push(E),r&&it({payload:{error:Ll,participantId:E,eventId:S,drawId:h},topic:VE})),A||N?y.concat(E):y},[]);return I.length&&!r?M({context:{eventId:S,drawId:h,duplicateEntries:I},result:{error:Ll},stack:e}):(s.filter(y=>y&&!T.includes(y)).forEach(y=>{let E={entryStageSequence:c,entryStage:u,participantId:y,entryStatus:n};d&&Qt({element:E,extension:d}),p&&At({element:E,attribute:"roundTarget",name:Xr,value:p}),a.entries??=[],a.entries.push(E)}),o&&(a.entries=Io({entries:a.entries})),Lt({drawDefinition:a}),T?.length||I?.length?{info:"some participantIds could not be added",participantIdsNotAdded:T,duplicateEntries:I,...P}:{...P})}function Xh({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:d}){if(!o?.length)return{error:jo};if(!d)return{error:Br};if(!p)return{error:Un};let m=(d.entries??[]).map(lt);if(o.filter(I=>!m.includes(I)).length)return{error:jU};if(i){let I=S0({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}=Gt({event:d}),g=f?.flights.find(I=>I.drawId===p);return g?.drawEntries&&(o.forEach(I=>{let h=s===Js&&JC({participantId:I,entryStatus:s,flight:g}),S=c===Qe&&JC({participantId:I,entryStage:c,flight:g});!(s!==Js&&c!==Qe&&JC({flight:g,participantId:I}))&&!h&&!S&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=Io({entries:g.drawEntries}))),{...P}}function JC({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 vu({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:Se};if(!Array.isArray(e)||e.some(d=>!wt(d)))return M({result:{error:Hr},stack:i});let s=(o.drawDefinitions??[]).flatMap(d=>ss({drawDefinition:d}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(d=>d.entryStatus&&r.includes(d.entryStatus))||[]).map(lt).filter(d=>!s.includes(d)),c=(n&&o.entries?.filter(d=>d.entryStage&&d.entryStage===n)||[]).map(lt).filter(d=>!s.includes(d));if(e.length?e=e.filter(d=>(!r?.length||a.includes(d))&&(!n||c.includes(d))):a.length&&c.length?e=Ht(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(d=>e.includes(d)))return M({result:{error:Oa},stack:i});if(!e?.length)return{...P,participantIdsRemoved:[]};let u=[];o.entries=(o.entries??[]).filter(d=>{let m=!e.includes(d?.participantId);return m||u.push(d.participantId),m}),t&&(o.entries=Io({entries:o.entries}));let{flightProfile:p}=Gt({event:o});return p?.flights?.forEach(d=>{d.drawEntries=(d.drawEntries??[]).filter(m=>!e.includes(m.participantId))}),o.drawDefinitions?.forEach(d=>{d.entries=(d.entries??[]).filter(m=>!e.includes(m.participantId))}),{...P,participantIdsRemoved:u}}var XC={[Ke]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},Cs=XC;function NK(t,e,r,n){return e.gender&&r&&!(jr(e.gender)||To(e.gender))&&lr(e.gender)!==lr(t.person?.sex)?(n.push({participantId:t.participantId,sex:t.person?.sex}),!1):!0}function DK({participantIds:t,typedParticipantIds:e,checkTypedParticipants:r}){return t.filter(n=>!r||e.includes(n))}function UK({tournamentRecord:t,participantIds:e,event:r,entryStatus:n,genderEnforced:o,mismatchedGender:i}){function s(d,m,l){return oe(Ct)(m.eventType)&&d.participantType===ft&&!ua(l)}function a(d,m,l){return m.eventType===Ut&&d.participantType===dt&&!ua(l)}function c(d,m,l,f,g){return m.eventType===Ut&&d.participantType===ft&&ua(l)?m.gender&&f&&!(jr(m.gender)||To(m.gender))&&lr(m.gender)!==lr(d.person?.sex)?(g.push({participantId:d.participantId,sex:d.person?.sex}),!1):!0:!1}function u(d,m,l){return m.eventType===ah&&[ft,dt].includes(d.participantType)&&!ua(l)}function p(d,m,l){return m.eventType===bt&&(d.participantType===bt||ua(l)&&d.participantType===ft)}return t?.participants?.filter(d=>e.includes(d.participantId)?s(d,r,n)?NK(d,r,o,i):a(d,r,n)||c(d,r,n,o,i)||u(d,r,n)?!0:p(d,r,n):!1).map(d=>d.participantId)??[]}function RK(t,e,r,n,o){let i=[];for(let s of t.individualParticipantIds??[]){let a=e.participants?.find(u=>u.participantId===s);if(!a)continue;let c=$C(a,r.category,r,n,o,e);c&&i.push(c)}return i.length?{participantId:t.participantId,participantName:qC(t),rejectionReasons:i.flatMap(s=>s.rejectionReasons.map(a=>({...a,reason:`${s.participantName}: ${a.reason}`})))}:null}function bK(t){return(t.participantType===dt||t.participantType===bt)&&!!t.individualParticipantIds?.length}function CK({typedParticipantIds:t,categoryRejections:e,tournamentRecord:r,startDate:n,endDate:o,event:i}){let s=[];for(let a of t){let c=r.participants?.find(u=>u.participantId===a);if(c)if(i.category){let u=bK(c)?RK(c,r,i,n,o):$C(c,i.category,i,n,o,r);u?e.push(u):s.push(a)}else s.push(a)}return s}function MK({enforceCategory:t,event:e,tournamentRecord:r,typedParticipantIds:n,categoryRejections:o}){if(t&&e.category&&r){let i=I0(e,r);if(!("error"in i)){let{startDate:s,endDate:a}=i;return CK({typedParticipantIds:n,tournamentRecord:r,event:e,startDate:s,endDate:a,categoryRejections:o})}}return n}function vK({validParticipantIds:t,existingIds:e,entryStatus:r,entryStage:n,extensions:o,extension:i,roundTarget:s,entryStageSequence:a,addedParticipantIdEntries:c,event:u}){t.forEach(p=>{if(!e.has(p)){let d=et({participantId:p,entryStatus:r,entryStage:n,extensions:o});i&&Qt({element:d,extension:i}),s&&At({element:d,attribute:"roundTarget",name:Xr,value:s}),a&&(d.entryStageSequence=a),c.push(d.participantId),u.entries?.push(d)}})}function OK({tournamentRecord:t,removedEntries:e,event:r}){if(r.eventType&&[pi,Tr].includes(r.eventType)){let n=new Set((r.entries??[]).map(c=>c.participantId)),o=(r.entries??[]).filter(c=>ua(c.entryStatus)).map(c=>c.participantId),i=t?.participants??[],s=new Set(i.filter(c=>n.has(c.participantId)&&c.participantType&&[dt,bt].includes(c.participantType)).map(c=>c.individualParticipantIds).flat(1/0)),a=o.filter(c=>s.has(c));a.length&&(e.push(...a),vu({participantIds:a,autoEntryPositions:!1,event:r}))}}function _K(t,e){if(!Array.isArray(t.participantIds))return M({result:{error:vr},stack:e});let r=ct(t.participantIds??[]);return t.event?r?.length?t.event?.eventId?{participantIds:r}:{error:Br}:M({result:{error:jo},stack:e}):{error:Se}}function xK({policyDefinitions:t,tournamentRecord:e,event:r,enforceGender:n}){let o=gt({tournamentRecord:e,event:r}).appliedPolicies??{},i=t?.[Ke]??o?.[Ke]??Cs[Ke],s=(n??i?.participants?.enforceGender)!==!1;return{matchUpActionsPolicy:i,genderEnforced:s}}function wK(t,e,r){return t&&(!Array.isArray(t)||!t.every(n=>Zn({extension:n})))||e&&!Zn({extension:e})?M({context:et({extension:e,extensions:t}),result:{error:O},info:"Invalid extension(s)",stack:r}):null}function eo(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=Nr,autoEntryPositions:n=!0,enforceCategory:o=!1,enforceGender:i=!0,entryStageSequence:s,policyDefinitions:a,entryStage:c=j,tournamentRecord:u,ignoreStageSpace:p,drawDefinition:d,roundTarget:m,extensions:l,extension:f,drawId:g,event:I}=t,h="addEventEntries",S=_K(t,h);if("error"in S)return S;let T="participantIds"in S?S.participantIds:[],y=wK(l,f,h);if(y)return y;let{genderEnforced:E}=xK({policyDefinitions:a,tournamentRecord:u,event:I,enforceGender:i}),A=[],N=[],D=!!u,R=[],U,b=UK({tournamentRecord:u,participantIds:T,event:I,entryStatus:r,genderEnforced:E,mismatchedGender:R}),C=[];b=MK({enforceCategory:o,event:I,tournamentRecord:u,typedParticipantIds:b,categoryRejections:C});let _=DK({participantIds:T,typedParticipantIds:b,checkTypedParticipants:D});I.entries??=[];let v=new Set(I.entries.map(L=>L.participantId||L.participant?.participantId));if(vK({validParticipantIds:_,existingIds:v,entryStatus:r,entryStage:c,extensions:l,extension:f,roundTarget:m,entryStageSequence:s,addedParticipantIdEntries:A,event:I}),g&&!ua(c)){let L=Xh({participantIds:_,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:s,ignoreStageSpace:p,drawDefinition:d,entryStatus:r,roundTarget:m,entryStage:c,extension:f,drawId:g,event:I});L.error&&(U=L.error)}if(OK({event:I,tournamentRecord:u,removedEntries:N}),_.length!==T.length)return M({context:et({categoryRejections:C.length?C:void 0,mismatchedGender:R.length?R:void 0,gender:I.gender}),result:{error:vr},stack:h});n&&(I.entries=Io({entries:I.entries??[]}));let w=A.length,F=N.length;return M({result:{...P,addedEntriesCount:w,removedEntriesCount:F,...C.length&&{context:et({categoryRejections:C})}},stack:h,info:U})}var ZC="ADMINISTRATION",LK="CAPTAIN",FK="COACH",xe="COMPETITOR",kK="DIRECTOR",GK="HOSPITALITY",tM="MEDIA",eM="MEDICAL",Zh="OFFICIAL",rM="OTHER",VK="PHYSIO",nM="SECURITY",BK="STRINGER",HK="SUPERVISOR",WK="TRAINER",jK="TRANSPORT",YK="VOLUNTEER",kf={ADMINISTRATION:ZC,CAPTAIN:LK,COACH:FK,COMPETITOR:xe,DIRECTOR:kK,HOSPITALITY:GK,MEDIA:tM,MEDICAL:eM,OFFICIAL:Zh,OTHER:rM,PHYSIO:VK,SECURITY:nM,STRINGER:BK,SUPERVISOR:HK,TRAINER:WK,TRANSPORT:jK,VOLUNTEER:YK};function tS({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return M({result:{error:Y},stack:i});if(!r||!e)return M({result:{error:nt},stack:i});let a=(n.participants??[]).find(d=>d.participantId===r);if(!a)return M({result:{error:Wt},stack:i});if(![bt,zr].includes(a.participantType))return M({result:{participantType:a.participantType,error:Rn},stack:i});let c=T0({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:n,suppressErrors:o}),{removed:u,error:p}=c;if(p)return M({result:c,stack:i});if(t)for(let d of n.events??[]){let m=new Set((d.entries??[]).map(({participantId:l})=>l).filter(Boolean));if(m.has(r)){let l=u?.filter(f=>!m.has(f));eo({participantIds:l,entryStatus:kr,tournamentRecord:n,event:d})}}return u&&it({topic:Oe,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...P,...c}}function T0({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}=Nt({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));let p=i?.find(({participantId:f})=>f===e.participantId)?.events?.map(({eventId:f})=>f),d=new Set(t),m=(e.individualParticipantIds??[]).filter(f=>d.has(f)?qK({groupingParticipantEventIds:p,mappedMatchUps:o,participantId:f,participants:i})?(c.push(f),!0):(s.push(f),$K({groupingParticipantId:e.participantId,tournamentRecord:r,participantId:f}),!1):(a.push(f),!0));e.individualParticipantIds=m;let l={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:a,removed:s};return c.length&&!n&&{...l,cannotRemove:c,error:Kd}||l}function qK({groupingParticipantEventIds:t,mappedMatchUps:e,participantId:r,participants:n}){return n?.find(i=>i.participantId===r)?.matchUps.filter(({eventId:i})=>t.includes(i)).map(({matchUpId:i})=>e?.[i]).filter(({winningSide:i,score:s})=>i||le({score:s}))?.length>0}function $K({groupingParticipantId:t,tournamentRecord:e,participantId:r}){for(let n of e.events??[])for(let o of n.drawDefinitions??[])KK({drawDefinition:o,groupingParticipantId:t,participantId:r}),zK({drawDefinition:o,tournamentRecord:e,participantId:r})}function KK({drawDefinition:t,groupingParticipantId:e,participantId:r}){let n=$t({element:t,attribute:"lineUps",name:po}),o=n?.[e];n&&o&&(n[e]=o.filter(i=>i.participantId!==r),At({element:t,attribute:"lineUps",name:po,value:n}),Mc({drawDefinition:t}))}function zK({drawDefinition:t,tournamentRecord:e,participantId:r}){let n=sr({drawDefinition:t,inContext:!1}).matchUps??[];for(let o of n)for(let i of o.sides??[]){let s=i.lineUp??[];s.find(c=>c.participantId===r)&&(i.lineUp=s.filter(c=>c.participantId!==r),mt({tournamentId:e?.tournamentId,drawDefinition:t,matchUp:o}))}}function bm({participantRole:t=xe,individualParticipantIds:e=[],groupingTypes:r=[fr,zr],tournamentRecord:n}){if(!n)return{error:Y};let o=n.participants??[],{participants:i,mappedMatchUps:s}=Nt({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}=T0({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?P:{error:mR}}function Ms(t){let e=X(t,[{[Z]:!0},{participantIds:!0,[qe]:Ye,[qr]:jo}]);if(e.error)return e;let{addIndividualParticipantsToEvents:r,tournamentRecord:n,participantIds:o}=t,i=n.participants?.length||0;if(!i)return{...P};let s=(n.events??[])?.filter(({eventType:f})=>f===Ce).map(f=>f?.drawDefinitions?.map(({drawId:g})=>g)).flat(1/0),a=Nt({participantFilters:{participantIds:o},tournamentRecord:n,withDraws:!0}).participants??[],c=f=>{let I=(jt({matchUpFilters:{drawIds:f,matchUpTypes:[Ut]},tournamentRecord:n}).matchUps??[]).flatMap(({sides:h})=>h?.map(({participantId:S})=>S??[])).filter(Boolean);return Ht(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:Oa};let d={},m={};for(let f of n.events??[]){let g=vu({participantIds:o,event:f});if(g.error)return g;d[f.eventId]=g.participantIdsRemoved}n.participants=(n.participants??[]).filter(f=>{let g=o.includes(f.participantId)||f.participantType===dt&&f.individualParticipantIds?.some(I=>o.includes(I));if(!g&&f.participantType===Ce&&f.individualParticipantIds?.some(I=>o.includes(I))&&(f.individualParticipantIds=f.individualParticipantIds.filter(I=>!o.includes(I))),g&&r&&f.participantType&&[dt,bt].includes(f.participantType))for(let I of f.individualParticipantIds??[])o.includes(I)||(m[f.participantId]||(m[f.participantId]=[]),m[f.participantId].push(I));return!g});let l=i-n.participants.length;if(bm({individualParticipantIds:o,tournamentRecord:n}),r)for(let f of n.events??[]){let I=d[f.eventId].map(h=>m[h]??[]).flat();eo({participantIds:I,entryStatus:kr,tournamentRecord:n,event:f})}return l&&it({payload:{participantIds:o,tournamentId:n.tournamentId},topic:Uh}),l?{...P,participantsRemovedCount:l}:{error:Kd}}function EA({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Gt({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&&yr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function oM({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry",c=at({tournamentRecord:e,participantId:n,event:s},[Z,Ge,me]);if(c.error)return c;if(!s.eventType||![pi,Tr].includes(s.eventType))return M({result:{error:so},stack:a});let u=e.participants??[],p=u.find(T=>T.participantId===n);if(!p)return M({result:{error:Wt},stack:a});if(!p.participantType||![dt,fr].includes(p.participantType)||p.participantType===fr&&s.eventType!==Tr||p.participantType===dt&&s.eventType!==pi)return{error:Rn};let m=(s.entries??[]).find(T=>T.participantId===n);if(!m)return{error:Ly};let{stageEntries:l}=EA({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),f=l.map(lt),g=u.filter(({participantId:T})=>f.includes(T)).map(({individualParticipantIds:T})=>T).flat().filter(Boolean),I=p.individualParticipantIds?.filter(T=>Is(T,g).length===1),h=vu({participantIds:[n],event:s});if(h.error||I?.length&&(h=eo({participantIds:I,entryStatus:kr,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),h.error))return h;let S;return t&&Ms({participantIds:[n],tournamentRecord:e}).success&&(S=!0),{...P,participantRemoved:S}}function eS({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return oM({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function iM(t){if(!t.tournamentRecord)return{error:Y};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=oM({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...P}:{error:o}}function od(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=bu(t);if(u.error)return M({result:u,stack:c});let{participantId:p}=u,{drawPosition:d,event:m,structureId:l}=t,f=gt({tournamentRecord:e,drawDefinition:n,event:m}).appliedPolicies??{};if([tn,On].includes(i)&&p){let{tournamentRecord:h}=t,{participant:S}=Bn({tournamentRecord:h,participantId:p}),{participantType:T,individualParticipantIds:y}=S??{};if(o&&T===dt){let E=eS({tournamentRecord:h,drawDefinition:n,participantId:p,event:m});if(E.error)return M({result:E,stack:c});y&&xf({participantIds:y,tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:m})}else xf({participantIds:[p],tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:m})}if(r){let h=Mr({tournamentRecord:e,drawDefinition:n,drawPosition:d,structureId:l,matchUpsMap:s,event:m});if(h.error)return M({result:h,stack:c})}let{structure:g}=tt({drawDefinition:n,structureId:l});return gf({structure:g,drawPositions:[d]}),vc({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:d,entryStatus:i,structureId:l}}),u}function sM(t){return Object.assign(t,{entryStatus:On}),od(t)}var ti=({finishingPosition:t=As,hasExistingDrawDefinition:e,qualifyingRoundNumber:r,structureAbbreviation:n,seedAssignments:o=[],stageSequence:i=1,qualifyingOnly:s,structureOrder:a,seedingProfile:c,matchUpFormat:u,structureType:p,structureName:d,matchUps:m=[],matchUpType:l,structureId:f,roundOffset:g,roundLimit:I,stageOrder:h,structures:S,tieFormat:T,stage:y})=>{let E={structureId:f??ot(),structureAbbreviation:n,finishingPosition:t,seedAssignments:o,matchUpFormat:u,stageSequence:i,structureName:d};(s||e&&T)&&(E.tieFormat=T),a&&(E.structureOrder=a),p&&(E.structureType=p),c&&(typeof c=="string"?E.seedingProfile=c:typeof c=="object"&&typeof c.positioning=="string"&&(E.seedingProfile=c.positioning)),l&&(E.matchUpType=l),g&&(E.roundOffset=g),h&&(E.stageOrder=h),I&&(E.roundLimit=I),y&&(E.stage=y),r&&(E.qualifyingRoundNumber=r);let A=m.flatMap(({drawPositions:N})=>N).filter(Boolean);return S?E.structures=S:(E.matchUps=m,E.positionAssignments=ct(A).sort((N,D)=>N-D).map(N=>({drawPosition:N}))),E},gr=ti;function AA(t){return wt(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function Be(t){return wt(t)?AA(t.replace(/_/g," ")):""}function rS({structureName:t=Be(Qe),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:K};let i=gr({stage:Qe,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures??=[],r.structures.push(i),Lt({drawDefinition:r,structureIds:[i.structureId]}),{...P}}function QK({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(ee),e.reverse(),e}function y0({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 E0({positioning:t,size:e}){let r=QK({size:e}),n=[],o=[],i=m=>m[0],s=m=>m[m.length-1],a=(m,l)=>(t&&[fu,pm,qi].includes(t)&&l%2?s(m):i(m))||i(m),c=(m,l)=>{if(m.every(f=>!o.includes(f))){let f=a(m,l);return o.push(f),f}},u=m=>{let l=m.filter(f=>!o.includes(f));if(l.length)return o.push(...l),l},p=(m,l)=>{let f=a(m,l);if(!o.includes(f))return o.push(f),f},d=J(1,e+1);for(let m of r)if(m===1){let l=Ae(d,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=Ae(d,m).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function nS({drawPositions:t}){if(!t?.length)return{error:tu};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=ct(r.map(oS)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function oS(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(ee).join("|")}function aM({groupSize:t,drawPositionOffset:e}){if(!t)return[];let r=d=>[...Array(d)].map((m,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((d,m)=>{i.forEach((I,h)=>{o[m].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=d=>d[0].reduce((m,l)=>m+l);return[...o].reverse().sort((d,m)=>p(d)-p(m)).map(d=>d.filter(m=>m.every(l=>l<=t)).map(m=>{let l=m.map(f=>f+e);return oS(l)}))}function JK({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:nt}}var A0={getRoundRobinGroupMatchUps:nS,determineRoundNumber:JK,drawPositionsHash:oS,groupRounds:aM};function Fc(t){let{hasExistingDrawDefinition:e,groupNameBase:r="Group",playoffAttributes:n,stageSequence:o=1,structureOptions:i,appliedPolicies:s,qualifyingOnly:a,seedingProfile:c,stage:u=j,matchUpType:p,roundTarget:d,structureId:m,groupNames:l,tieFormat:f,drawSize:g,idPrefix:I,isMock:h,uuids:S}=t,T=t.structureName??n?.["0"]?.name??Be(j),{groupCount:y,groupSize:E}=XK({structureOptions:i,appliedPolicies:s,drawSize:g}),A=Ao,N,D=J(1,y+1).map(U=>{let b=ZK({groupSize:E,structureOrder:U,matchUpType:p,drawSize:g,idPrefix:I,isMock:h});N=Array.isArray(b)?Math.max(...b.map(({roundNumber:_})=>_??0)):0;let C=l?.[U-1]??`${r} ${U}`;return ti({structureId:S?.pop(),hasExistingDrawDefinition:e,structureType:gu,finishingPosition:A,qualifyingOnly:a,structureOrder:U,structureName:C,tieFormat:f,matchUps:b,stage:u})}),R=ti({structureId:m??S?.pop(),hasExistingDrawDefinition:e,structureType:Ie,finishingPosition:A,seedingProfile:c,structureName:T,stageSequence:o,structures:D,tieFormat:f,stage:u});return d&&At({element:R,attribute:"roundTarget",name:Xr,value:d}),{structures:[R],maxRoundNumber:N,groupCount:y,links:[],groupSize:E,...P}}function XK({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=Cm({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 Cm(t){let{groupSizeLimit:e=10,drawSize:r=0}=t??{},n=J(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{...P,validGroupSizes:n}}function ZK({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=J(1+a,r+1+a),u=nS({drawPositions:c}).uniqueMatchUpGroupings??[],p=aM({groupSize:r,drawPositionOffset:a});return u.map(l).sort((f,g)=>(f.roundNumber??1/0)-(g.roundNumber??1/0));function m(f){return p.reduce((g,I,h)=>I.includes(f)?h+1:g,void 0)}function l(f){let g=oS(f),I=m(g),h=[1,n],S=tz({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?Jt:"BYE",matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function tz({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||ot()}function iS(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!It(r))return{seedBlocks:void 0,...M({result:{error:O},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=Ci(r);if(e){let l=Math.min(e,o),f=[],g=1;for(J(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=J(g,g+l);g+=l,f.push(I)}return{...P,seedBlocks:f}}let i=J(1,o+1),s=[],a=o/2;for(;a>1;){let l=Ae(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,y=g[0],E=g[g.length-1];n&&f>4?f===8?h=S?E:y:h=T?y:E:h=S?y:E,we(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=J(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),d=0,m=[];return J(0,p).forEach(l=>{m.push(s.slice(d,d+u[l])),d+=u[l]}),{...P,seedBlocks:m}}function sS({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!It(e))return{seedGroups:void 0,...M({result:{error:O},context:{drawSize:e},stack:r})};if(t){if(!It(t))return{seedGroups:void 0,...M({context:{roundRobinGroupsCount:t},result:{error:O},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:J(0,o).map(()=>{let s=J(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=iS({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n??[]).map(s=>(s??[]).map(()=>(o+=1,o)))}}}function PA({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=Cm({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return M({context:{roundRobinGroupsCount:t},result:{error:O}})}let{seedGroups:r}=sS({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))??[];return{...P,seedingThresholds:n}}function Ou(t){if(!t)return 1/0;if(It(t))return st(t);let e=t.split("-")[0];return It(e)?st(e):1/0}function Ai({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s,random:a}){let c=[];if(!s)return{error:Hi};let{matchUps:u,roundMatchUps:p}=ht({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:d}=Dr({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:m}=pe({structure:s}),l=m?.length,f=d?.length??0,g=[],h=Object.keys(p).map(k=>Number.parseInt(k)).sort((k,G)=>k-G).map(k=>{let G=p[k].map(B=>B.drawPositions).flat(1/0).filter(Boolean),V=G.filter(B=>!g.includes(B));return g=g.concat(...G),V}).filter(k=>k.length).reverse(),S=h.pop()??[],T=S&&Math.min(...S)-1||0;n=n??r?.seeding?.seedingProfile;let y=S?.length||0,E=h.filter(k=>k.filter(G=>G<=f).length),{stage:A,structureType:N,roundLimit:D}=s,R=N===Ie,U=!R&&h?.length,b=!R&&A===rt&&D,C=E.flat(1/0),_=U?C?.length:0,v=i?l:f,x=_c({drawDefinition:o,structure:s,matchUps:u}),w=x?0:!U&&v||v&&C.length<v&&v-C.length||0;if(b){let k=s?.matchUps?s.matchUps.filter(({roundNumber:V})=>V===s.roundLimit).length:0,G=S.length/k;if(!U){let V=vm(n),B=Ae(S,G),$=1,H=J(0,B[0].length).map(()=>{let z=J($,$+B.length);return $+=B.length,z});({validSeedBlocks:c}=P0({drawPositionBlocks:B,nonRandom:n?.nonRandom,positioning:V,seedGroups:H,random:a}))}}else R?{validSeedBlocks:c}=ez({nonRandom:n?.nonRandom,seedingProfile:n,structure:s,random:a}):U?c=E.map(k=>({seedNumbers:k,drawPositions:k})):x&&Ae(S,2).map((G,V)=>({drawPositions:[G[0]],seedNumbers:[V+1]})).forEach(G=>c.push(G));if(!R&&!x&&!b){let{blocks:k}=rz({drawPositionOffset:T,seedNumberOffset:_,seedCountGoal:w,seedingProfile:n,baseDrawSize:y});k.forEach(G=>c.push(G))}let L=c.flatMap(k=>k.drawPositions).reduce((k,G)=>S?.includes(G)&&k,!0);return!x&&!U&&!R&&!L?{error:VU,validSeedBlocks:[],isContainer:R,isFeedIn:U}:{isLuckyStructure:x,validSeedBlocks:c,isContainer:R,isFeedIn:U}}function ez({seedingProfile:t,structure:e,nonRandom:r,random:n}){let o=e.structures??[],i=o.length,s=yt({structure:e})?.positionAssignments,a=vm(t),c=s?.length??0,{seedGroups:u}=sS({roundRobinGroupsCount:i,drawSize:c}),p=o.map(d=>yt({structure:d}).positionAssignments?.map(m=>m.drawPosition));return P0({drawPositionBlocks:p,positioning:a,seedGroups:u,nonRandom:r,random:n})}function P0({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n,random:o}){let i=[],{divisionGroupings:s}=E0({size:r.length,positioning:e}),a=[];return r.forEach((c,u)=>{let p=y0({blockPattern:s,index:u});c.forEach((d,m)=>{let l=u%2?t.length-m-1:m,g=t[l].slice().filter((h,S)=>p.includes(S+1)&&h);e!==qi?g=n?g:dr(g,o):u%2&&g.reverse();let I=g.find(h=>!a.includes(h));I&&(a.push(I),i.push({drawPositions:[I],seedNumbers:[d]}))})}),{validSeedBlocks:i}}function rz(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a,c=[],{seedBlocks:u}=iS({cluster:[fu,pm].includes(vm(o)),participantsCount:s,roundRobinGroupsCount:r});a=0;for(let p of u){if(a+1>i)break;let d=p.map(l=>l+e),m=nz(a+1,p.length).map(l=>+l+n);a+=p.length,c.push({drawPositions:d,seedNumbers:m})}return{blocks:c}}function nz(t,e){return Array.from(new Array(e),(r,n)=>n+t)}function Mm({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=tt({drawDefinition:e,structureId:o});t??=gt({drawDefinition:e}).appliedPolicies;let a=r?.validSeedBlocks;return!a&&s&&(a=Ai({appliedPolicies:t,drawDefinition:e,structure:s})?.validSeedBlocks),t?.seeding?.validSeedPositions?.ignore?!0:t?.seeding?.validSeedPositions?.strict?(a.find(d=>d.seedNumbers.includes(i))?.drawPositions??[]).includes(n):a.flatMap(u=>u.drawPositions).includes(n)}function NA(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s,random:a}=t,{structure:c}=tt({drawDefinition:r,structureId:i}),{seedAssignments:u}=Dr({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:c}),{positionAssignments:p}=pe({structure:c}),m=p?.filter(k=>k.participantId??k.bye??k.qualifier)?.map(k=>k.drawPosition).filter(Boolean),{appliedPolicies:l}=gt({drawDefinition:r}),g=((o?.validSeedBlocks||c&&Ai({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:l,drawDefinition:r,seedingProfile:n,structure:c})?.validSeedBlocks)??[]).find(k=>k.drawPositions.filter(V=>!m?.includes(V)).length),I=u?.map(k=>k.participantId).filter(Boolean),h=p?.map(k=>k.participantId).filter(Boolean),S=I?.filter(k=>h?.includes(k)),T=I?.filter(k=>!h?.includes(k)),y=u?.filter(k=>T?.includes(k.participantId)),E=u?.filter(k=>!k.participantId),N=(y?.length&&y.length>0?y.length:E?.length??0)&&g?.drawPositions.filter(k=>!m?.includes(k))||[],D=s?dr(N,a):N,R=[],U=D.map(()=>{let G=L(y,R)?.participantId;return G&&R.push(G),G}).filter(Boolean),b=u?.filter(k=>S?.includes(k.participantId)).map(k=>k.seedNumber),_=(g?.seedNumbers??[]).filter(k=>!b?.includes(k)),v=u?.filter(k=>_.includes(k.seedNumber)).map(k=>k.participantId),x=l?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(typeof x=="boolean"?x:!0)?U:v,unplacedSeedNumbers:_,unfilledPositions:D,unplacedSeedAssignments:y};function L(k,G){let V=k.filter(z=>!G.includes(z.participantId)),B=Math.min(...V.map(z=>Ou(z.seedValue))),$=V.filter(z=>Ou(z.seedValue)===B);return dr($,a).pop()}}function vm(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function Qa({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,seedBlockInfo:i,structureId:s,seedNumber:a,seedValue:c,eventId:u,event:p}){let d="assignSeed",{structure:m}=tt({drawDefinition:r,structureId:s}),{positionAssignments:l}=pe({structure:m}),f=Dr({provisionalPositioning:t,drawDefinition:r,structure:m}).seedAssignments,g=f.map(A=>A.seedNumber),I=Mu({drawDefinition:r,participantId:o});if(o&&!I)return M({result:{error:Hr},context:{participantId:o},stack:d});let h=p?Gt({event:p}).flightProfile?.flights?.length:0,S=h&&h>1,y=l?.find(A=>A.participantId===o)?.drawPosition;if(y&&!Mm({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return M({result:{error:EI},context:{assignedDrawPosition:y},info:"invalid seed position",stack:d});g.includes(a)||f.push({seedNumber:a,seedValue:c});let E;return f.forEach(A=>{A.participantId===o&&A.seedNumber!==a&&(A.participantId=void 0),A.seedNumber===a&&(A.participantId=o,!n?.groupSeedingThreshold&&!S&&(A.seedValue=c??a),E=!0)}),E?(ff({tournamentId:e?.tournamentId,drawDefinition:r,structure:m,eventId:u}),{...P}):M({result:{error:GU},stack:d})}function Gf({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),u=$t({element:o,attribute:"lineUps",name:po})??{},p=q(u[r],!1,!0);if(c)i?.sides?.forEach(d=>{d.sideNumber===a&&(d.lineUp=p)});else{i.sides=[1,2].map(m=>({...i.sides?.find(f=>f.sideNumber===m)??{},sideNumber:m}));let d=i.sides.find(m=>m.sideNumber===a);d&&(d.lineUp=p)}mt({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function DA(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=Jo({structureId:n.structureId,matchUpsMap:o});Ue({method:"getPairedPreviousMatchUpIsDoubleExit",color:"brightcyan",keyColors:{structureId:"brightyellow",sourceMatchUpId:"brightmagenta"},structureId:n.structureId?.slice(0,8),targetMatchUpId:r.matchUpId,targetRound:[r.roundNumber,r.roundPosition],previousRoundNumber:s,sourceMatchUpId:e?.matchUpId,sourceStructureId:e?.structureId?.slice(0,8),sourceRound:e?[e.roundNumber,e.roundPosition]:void 0,drawPosition:i,structureMatchUpCount:a?.length}),e&&e.structureId!==n.structureId&&i?(Ue({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"cross_structure_sourceMatchUp_resolving_in_target",originalSourceId:e?.matchUpId,originalSourceStructure:e?.structureId?.slice(0,8),targetStructure:n.structureId?.slice(0,8)}),e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)),Ue({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"resolved_cross_structure_sourceMatchUp",resolvedMatchUpId:e?.matchUpId,resolvedRound:e?[e.roundNumber,e.roundPosition]:void 0,resolvedStatus:e?.matchUpStatus})):!e&&i&&(e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)),Ue({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"resolved_sourceMatchUp_from_drawPosition",resolvedMatchUpId:e?.matchUpId,resolvedRound:e?[e.roundNumber,e.roundPosition]:void 0,resolvedStatus:e?.matchUpStatus}));let c=e?.roundPosition,u=c%2?1:-1,p=c+u,d=s&&a.find(({roundNumber:f,roundPosition:g})=>f===s&&g===p),m=d?.matchUpStatus,l=[Zt,Te].includes(m);return Ue({method:"getPairedPreviousMatchUpIsDoubleExit",color:l?"brightred":"brightgreen",keyColors:{pairedMatchUpId:"brightcyan",isDoubleExit:l?"brightred":"brightgreen"},sourceRoundPosition:c,offset:u,pairedRoundPosition:p,pairedMatchUpId:d?.matchUpId,pairedRound:d?[d.roundNumber,d.roundPosition]:void 0,pairedStatus:m,isDoubleExit:l}),{pairedPreviousMatchUp:d,pairedPreviousMatchUpIsDoubleExit:l}}function N0({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(ee).filter(Boolean),positionAdded:r,positionAssigned:n}}function UA({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:Jo({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function RA({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=UA({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 d=wt(p)||!isNaN(p)?{code:p}:p;return d.sideNumber===u?{...d,previousMatchUpStatus:e}:d})}}function Vf({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 kc({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:r,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,event:u}){let p="assignMatchUpDrawPosition";a??=ye({drawDefinition:o});let d=t??re({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[],m=d.find(F=>F.matchUpId===c),l=m?.structureId,f=o?.structures?.find(F=>F.structureId===l);if(!f)return{error:Pt};let g=a?.drawMatchUps?.find(F=>F.matchUpId===c),I=g?.drawPositions??[],{positionAdded:h,positionAssigned:S,updatedDrawPositions:T}=N0({drawPositions:I,drawPosition:s}),{positionAssignments:y}=yt({drawDefinition:o,structure:f}),A=y?.filter(F=>T.includes(F.drawPosition))?.find(({bye:F})=>F),N=g?.matchUpStatus&&ze(g.matchUpStatus)&&T.filter(Boolean).length<2;i=oz({isByeMatchUp:A,matchUpStatus:i,isDoubleExitExit:N,matchUp:g});let D=!!(ze(g?.matchUpStatus)&&g?.winningSide);g&&h&&iz({updatedDrawPositions:T,sourceMatchUpStatus:e,isPropagatedExit:D,isDoubleExitExit:N,tournamentRecord:r,inContextMatchUp:m,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,matchUp:g,stack:p});let R=ir({inContextDrawMatchUps:d,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:U,loserMatchUp:b,loserTargetDrawPosition:C},targetLinks:{loserTargetLink:_}}=R,v=cn(o?.drawType),x=sz({inContextDrawMatchUps:d,positionAssigned:S,isPropagatedExit:D,tournamentRecord:r,inContextMatchUp:m,drawDefinition:o,matchUpStatus:i,winnerMatchUp:U,drawPosition:s,isByeMatchUp:A,isLuckyDraw:v,matchUpsMap:a,matchUp:g,structure:f});if(x?.error)return x;g?.matchUpType===xt&&az({inContextDrawMatchUps:d,positionAssignments:y,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUp:g});let w=cz({updatedDrawPositions:T,loserTargetDrawPosition:C,tournamentRecord:r,loserTargetLink:_,drawDefinition:o,structureId:f.structureId,isByeMatchUp:A,loserMatchUp:b,matchUpsMap:a,event:u});return w?.error?w:S?{...P}:M({result:{error:Zc},context:{drawPosition:s},stack:p})}function oz({isByeMatchUp:t,matchUpStatus:e,isDoubleExitExit:r,matchUp:n}){return t&&"BYE"||e||r&&n.matchUpStatus||n?.matchUpStatus&&[Zt,Te].includes(n.matchUpStatus)&&n.matchUpStatus||Jt}function iz({updatedDrawPositions:t,sourceMatchUpStatus:e,isPropagatedExit:r,isDoubleExitExit:n,tournamentRecord:o,inContextMatchUp:i,sourceMatchUpId:s,drawDefinition:a,matchUpStatus:c,drawPosition:u,matchUpsMap:p,matchUpId:d,matchUp:m,stack:l}){let f=re({inContext:!0,drawDefinition:a,matchUpsMap:p}).matchUps??[],g=n&&Vf({inContextDrawMatchUps:f,drawPosition:u,matchUpId:d})||r&&m.winningSide||void 0;m?.matchUpStatusCodes&&RA({inContextDrawMatchUps:f,sourceMatchUpStatus:e,sourceMatchUpId:s,matchUpsMap:p,matchUp:m}),Object.assign(m,{drawPositions:t,winningSide:g,matchUpStatus:r?m?.matchUpStatus:c}),mt({tournamentId:o?.tournamentId,eventId:i?.eventId,context:l,drawDefinition:a,matchUp:m})}function sz({inContextDrawMatchUps:t,positionAssigned:e,isPropagatedExit:r,tournamentRecord:n,inContextMatchUp:o,drawDefinition:i,matchUpStatus:s,winnerMatchUp:a,drawPosition:c,isByeMatchUp:u,isLuckyDraw:p,matchUpsMap:d,matchUp:m,structure:l}){if(e&&u&&!p){if(a)if(["BYE",Zt,Te].includes(s)){let f=kc({matchUpId:a.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:c,matchUpsMap:d});if(f.error)return f}else{let{structureId:f}=a;f!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(e&&r){if(a){let f=kc({matchUpId:a.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:c,matchUpsMap:d});if(f.error)return f}}else if(a&&o&&!o.feedRound){let{pairedPreviousMatchUpIsDoubleExit:f}=DA({targetMatchUp:m,drawPosition:c,matchUpsMap:d,structure:l});if(f){let g=kc({matchUpId:a.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:c,matchUpsMap:d});if(g.error)return g}}}function az({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUp:i}){let s=t?.find(({matchUpId:p})=>p===i.matchUpId),c=(s?.sides??[]).reduce((p,d,m)=>d.drawPosition===o?m:p,void 0),u=e?.find(p=>p.drawPosition===o)?.participantId;u&&c!==void 0&&Gf({inContextTargetMatchUp:s,drawPositionSideIndex:c,teamParticipantId:u,tournamentRecord:r,drawDefinition:n,matchUp:i})}function cz({updatedDrawPositions:t,loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,structureId:i,isByeMatchUp:s,loserMatchUp:a,matchUpsMap:c,event:u}){if(n?.linkCondition!==Jn||t.filter(Boolean).length!==2||s)return;if(Jo({structureId:i,matchUpsMap:c}).filter(({drawPositions:l,roundNumber:f})=>f===1&&we(l,t)).every(({matchUpStatus:l})=>[ae,ve].includes(l))&&a){let{structureId:l}=a,f=Mr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:l,matchUpsMap:c,event:u});if(f.error)return f}}function bA({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=ts({drawDefinition:e})?.containedStructures?.[o.structureId]?.map(({structureId:d})=>d)??[];s.push(o?.structureId);let a=r?.map(({drawPosition:d})=>d)??[],c=t?.filter(d=>s.includes(d.structureId)&&Ht(d.drawPositions??[],a).length)??[],u=c.map(({matchUpId:d})=>d),p=n?.drawMatchUps?.filter(d=>u.includes(d.matchUpId))??[];return{drawPositions:a,matchUps:p,targetMatchUps:c}}function Bf({lineUp:t}){if(!Array.isArray(t))return;let e={};return ct(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}=Rm({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 xi(t){return`${t} must be an array`}function Hf({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(xi("lineUp")),{valid:!1,errors:r,error:O};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(xi("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=ct(t.map(lt)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?O:void 0}}function vs({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:K};if(typeof e!="string")return{error:$e};let o=Hf({lineUp:n,tieFormat:r});if(!o.valid)return o;let s=$t({element:t,attribute:"lineUps",name:po})??{};return s[e]=Bf({lineUp:n}),At({element:t,attribute:"lineUps",name:po,value:s}),Mc({drawDefinition:t}),{...P}}function aS({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,assignments:i,structure:s,event:a}){if(!n)return{error:K};let{drawPositions:c,matchUps:u,targetMatchUps:p}=bA({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let d of p)d.matchUpType===hr&&(d.sides??[]).forEach((m,l)=>{if(m?.drawPosition&&c?.includes(m.drawPosition)){let f=u.find(({matchUpId:g})=>g===d.matchUpId);if(f?.sides?.[l]){if(delete f.sides[l].lineUp,e===!1){let g=d.tieFormat,I=m.participantId;g&&I&&vs({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}mt({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...P}}function xn({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:r,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,seedBlockInfo:c,drawPosition:u,matchUpsMap:p,structureId:d,event:m}){let l="assignDrawPosition";if(!a&&!r)return M({result:{error:$e},stack:l});p=p??ye({drawDefinition:i}),e||({matchUps:e}=re({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=tt({drawDefinition:i,structureId:d});if(f.error)return M({result:f,stack:l});let{structure:g}=f;if(!g)return{error:Pt};if(De({structure:g}))return M({result:{error:mr},stack:l});let{seedAssignments:I}=Dr({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(C=>C.participantId===a)?.seedNumber,{appliedPolicies:T}=gt({tournamentRecord:o,drawDefinition:i,structure:g,event:m});if(S&&!Mm({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:d}))return M({result:{error:EI},context:{drawPosition:u},stack:l});let E=pe({structure:g}).positionAssignments??[],A=E?.find(C=>C.drawPosition===u);if(!A)return M({result:{error:hs},context:{drawPosition:u},stack:l});if(E?.map(lt).includes(a))return M({result:{error:Oa},context:{drawPosition:u},stack:l});let{containsParticipant:D,containsBye:R}=_f(A);if(R){let C=bu({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:d,matchUpsMap:p,event:m});if(C.error)return M({result:C,stack:l})}if(D&&A.participantId!==a){let{activeDrawPositions:C}=is({drawDefinition:i,structureId:d});if(C.includes(u))return M({result:{error:eu},stack:l});aS({assignments:[A],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}A.participantId=a,r&&(A.qualifier=!0),uz({provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,structureId:d,structure:g,event:m}),g.structureType===Ie?pz({inContextDrawMatchUps:e,positionAssignments:E,positionAssignment:A,tournamentRecord:o,drawDefinition:i,participantId:a,matchUpsMap:p,structure:g}):dz({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:m});let U=i.entries?.find(C=>C.participantId===a),b=m?.entries?.find(C=>C.participantId===a);return!U&&b&&Ff({entryStatus:b.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:i,participantId:a,event:m}),Tn({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:m}),{positionAssignments:E,...P}}function uz({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,structureId:i,structure:s,event:a}){if(!(s.stage===j&&(!s.stageSequence||s.stageSequence>1))&&!(s.stage&&[je,Vt].includes(s.stage)))return;let u=s.stage===rt?rt:j,m=(r.structures?.find(l=>l?.stage===u&&l?.stageSequence===1)?.seedAssignments??[]).find(l=>l.participantId===o);m?.participantId&&Qa({eventId:a?.eventId,participantId:m.participantId,seedNumber:m.seedNumber,seedValue:m.seedValue,provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,structureId:i,event:a})}function pz({inContextDrawMatchUps:t,positionAssignments:e,positionAssignment:r,tournamentRecord:n,drawDefinition:o,participantId:i,matchUpsMap:s,structure:a}){hA({positionAssignments:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s,structure:a});let{drawPositions:c,matchUps:u,targetMatchUps:p}=bA({assignments:[r],inContextDrawMatchUps:t,drawDefinition:o,matchUpsMap:s,structure:a});if(c&&u?.length===1&&u[0].matchUpType===xt){let m=(p?.[0].sides??[]).reduce((l,f,g)=>c?.includes(f.drawPosition)?g:l,void 0);Gf({inContextTargetMatchUp:p[0],teamParticipantId:i,matchUp:u[0],drawPositionSideIndex:m,tournamentRecord:n,drawDefinition:o})}}function dz({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=ht({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:d}=_e({matchUps:p}),{initialRoundNumber:m}=ca({drawPosition:i,matchUps:p}),l=m&&d?.[m].find(f=>f.drawPositions?.includes(i));if(l){let f=kc({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return M({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...P}}function Wf(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:K};let d=gt({tournamentRecord:o,drawDefinition:i,event:u}).appliedPolicies??{},{inContextDrawMatchUps:m,matchUpsMap:l}=t;l||(l=ye({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),m||({matchUps:m}=re({inContext:!0,drawDefinition:i,matchUpsMap:l}),Object.assign(t,{inContextDrawMatchUps:m}));let{positionAssignments:f}=yt({drawDefinition:i,structureId:c}),g=f?.find(y=>y.drawPosition===a);if(g?.participantId){let y=g.participantId,E=xn({inContextDrawMatchUps:m,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return E.success?T({appliedPolicies:d,removedParticipantId:y}):M({result:E,stack:p})}let I=bu({inContextDrawMatchUps:m,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(I.error)return M({result:I,stack:p});let h=I.participantId,S=xn({inContextDrawMatchUps:m,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(!S.success)return M({result:S,stack:p});return T({appliedPolicies:d,removedParticipantId:h});function T({appliedPolicies:y,removedParticipantId:E}){let{structure:A}=tt({drawDefinition:i,structureId:c});gf({drawPositions:[a],structure:A});let N={[e]:s,name:n,drawPosition:a,structureId:c};return vc({appliedPolicies:y,drawDefinition:i,positionAction:N}),M({context:{removedParticipantId:E},result:{...P},stack:p})}}function D0({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return Wf({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function cM(t){return D0(t)}function CA({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],mt({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:o,matchUp:s}))}function MA(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=X(t,r);if(n.error)return n;let o=tt(t);if(o.error)return o;let i=o.structure;if(!De({structure:i}))return M({result:{error:Wo,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=_e({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:zn}}function uM(t){let e=MA(t,[{targetRoundNumber:!0,roundNumber:!0,[qe]:wF}]);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 M({result:{error:O},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?J(s+1,i+1):J(i,s),u={};return c.forEach(p=>(n?.[p]??[]).forEach(({matchUpId:d})=>{u[d]=p-(a?1:-1)})),n?.[s]?.forEach(({matchUpId:p})=>u[p]=i),CA({params:t,modMap:u,structure:r}),{...P}}function pM({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:K};if(!Array.isArray(t))return{error:O};let i="setPositionAssignments";for(let a of t){let{structureId:c,positionAssignments:u}=a;if(!u)continue;let p=tt({drawDefinition:n,structureId:c});if(p.error)return p;let d=p.structure;if(!d)return{error:Pt};let m=yt({structure:d}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(Ht(m,l).length!==m?.length)return M({result:{error:O},info:"drawPositions do not match",stack:i});let f=ye({drawDefinition:n}),{matchUps:g}=re({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u??[]){let{drawPosition:h,participantId:S,bye:T,qualifier:y}=I;if(T){let E=Mr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:d,event:o});if(E?.error)return E}else if(y)u.forEach(E=>{E.drawPosition===h&&(E.qualifier=!0,delete E.participantId,delete E.bye)});else if(S){let E=xn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(E?.error)return E}}Tn({tournamentId:r?.tournamentId,drawDefinition:n,structure:d,event:o})}let s=t.map(({structureId:a})=>a);return Lt({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...P}}function dM(t){let e=MA(t,[{roundNumbers:!0,[qe]:Ye,[Xe]:s=>s.length===2&&s.every(He)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return M({result:{error:O,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]})),CA({params:t,modMap:i,structure:r}),{...P}}function id({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||ot()}function U0({includeMatchUpType:t,drawPosition:e,roundNumber:r,matchUpType:n,idPrefix:o,matchUps:i,isMock:s,uuids:a,nodes:c,fed:u}){let p=c.length,d=e?e-p:void 0,m=J(0,p).map(g=>d?d+g:void 0),l=[];for(let g=0;g<p;g++){let I=m.shift(),h={drawPosition:I,fed:u+1,feed:!0},S=c[g];S.roundNumber=r-1;let T=id({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 E={children:[S,h]};l.push(E)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function _u({includeMatchUpType:t,matchUpType:e,roundNumber:r,matchUps:n,idPrefix:o,isMock:i,uuids:s,nodes:a}){let c=0,u=[],p=1,d=r-1,m=a?.length;for(;c<(m||0);){let l=a?.[c],f=a?.[c+1];d&&(l.roundNumber=d),f&&d&&(f.roundNumber=d);let g=id({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 wi(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:d,idPrefix:m,isMock:l,uuids:f,fmlc:g}=t;i=i??F(e);let I=mz({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((L,k)=>L+k,0);else if(e){let L=e-i;r=I.filter(k=>k<=L?(L-=k,!0):!1),S=r.reduce((k,G)=>k+G,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((L,k)=>u&&!n||n&&k>=o+n||k<o?0:L),S=r.reduce((L,k)=>L+k,0),n=r.length;let T=[...I,...r].sort((L,k)=>k-L),y=T.length,A=[...(c??[]).map(L=>L-1),...(s??[]).map(L=>y-L)].map(L=>T[L]).reduce((L,k)=>L+k,0);S=S-A;let N=0,D=[],R,U=1,C=J(0,i).map((L,k)=>({drawPosition:k+1+S})),_=S+1;for(let L of I){if({roundNodes:R,matchUps:D}=_u({matchUpType:d,roundNumber:U,idPrefix:m,matchUps:D,isMock:l,nodes:C,uuids:f}),U++,r.includes(L)){let k=dn(r)[L],G=J(0,k),V=y+1-U,B=s?.includes(V)??c?.includes(U);G.forEach(()=>{({roundNodes:R,matchUps:D,drawPosition:_}=U0({drawPosition:!B&&_||void 0,nodes:R,matchUpType:d,roundNumber:U,idPrefix:m,matchUps:D,isMock:l,uuids:f,fed:N})),U++,N+=1})}C=R}y!==U-1&&console.log("ERROR");let v=i-S;D=aa({finishingPositionOffset:p?v:a,positionsFed:S,roundsCount:y,matchUps:D,fmlc:g});let w=R?.length?R[0]:R;return w&&(w.roundNumber=U-1,w.matchUps=D),{draw:w,matchUps:D,roundsCount:y};function F(L){let k=wl(L);return k>L?k/2:k}}function mz({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return J(0,e).reverse().map(n=>Math.pow(2,n))}function Er({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&&(!rn(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(!rn(a)&&!p)return{matchUps:[],roundsCount:0};let d=J(1,a+1).map(I=>({drawPosition:I})),m,l=[],f=1;for({roundNodes:m,matchUps:l}=_u({matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,nodes:d,uuids:u}),f++,i=i??r;m.length>1;)n&&m.length===n&&(i=f-1),{roundNodes:m,matchUps:l}=_u({nodes:m,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=aa({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 xu(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:d=0,drawDefinition:m,staggeredEntry:l,sequenceLimit:f,childStage:g,stage:I=j,drawSize:h,idPrefix:S,isMock:T,uuids:y}=t;if(!(!s||!u||s?.[c])||h<2||f&&a>f)return{};let A=[],N=[],D=[],R=t.matchUpType??m?.matchUpType,U=e+1,b=e+h,C=`${U}-${b}`,_=s?.[c],v=n&&`${n} `||"",x=s?.[C]??o?.[C],w=t.structureName||x?.name||_?.name&&(r?`${v}${_?.name}`:_.name)||`${v}${C}`,F=x?.abbreviation??_?.abbreviation,L=t.structureId??_?.structureId??y?.pop(),k={idPrefix:S&&`${S}-${w}-RP`,finishingPositionOffset:e,matchUpType:R,drawSize:h,isMock:T,uuids:y},{matchUps:G}=l?wi(k):Er(k),V=gr({structureAbbreviation:F,stageSequence:a,structureName:w,matchUpType:R,roundOffset:d,structureId:L,matchUps:G,stage:I});A.push(...G),N.push(V);let B=Math.ceil(Math.log(h)/Math.log(2)),$=p?Math.min(p-d,B):(!i||U<i)&&B||0;return h>2&&J(1,$+1).forEach(z=>H(z)),{structureId:V.structureId,matchUps:A,structureName:w,structures:N,links:D,...P};function H(z){let W=h/Math.pow(2,z);if(W<2)return;let Q=h/Math.pow(2,z)+e;if(i&&Q+1>i)return;let{structures:pt,structureId:Tt,matchUps:Ot,links:Et}=xu({finishingPositionOffset:Q,exitProfile:`${c}-${z}`,roundOffset:d+z,stageSequence:a+1,stage:g??I,drawSize:W,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:m,sequenceLimit:f,childStage:g,matchUpType:R,idPrefix:S,uuids:y});if(V.structureId&&Tt){let Bt={linkType:pr,source:{roundNumber:z,structureId:V.structureId},target:{roundNumber:1,feedProfile:Je,structureId:Tt}};Et&&V&&Et.push(Bt),Et?.length&&D.push(...Et)}return pt?.length&&N.push(...pt),Ot?.length&&A.push(...Ot),{structureId:Tt,childLinks:Et,structures:N}}}function R0({q1Structure:t,eliminatorStructure:e,q2Structure:r,finalStructure:n}){return[{linkType:Ar,source:{roundNumber:1,structureId:t.structureId},target:{feedProfile:Je,roundNumber:1,structureId:n.structureId}},{linkType:pr,source:{roundNumber:1,structureId:t.structureId},target:{feedProfile:Je,roundNumber:1,structureId:r.structureId}},{linkType:Ar,source:{roundNumber:1,structureId:e.structureId},target:{feedProfile:Je,roundNumber:1,structureId:r.structureId}},{linkType:Ar,source:{roundNumber:1,structureId:r.structureId},target:{feedProfile:Je,roundNumber:1,structureId:n.structureId}}]}function vA({finishingPositionOffset:t=0,stage:e=j,structureName:r,matchUpType:n,idPrefix:o,drawSize:i,isMock:s,uuids:a}){if(i!==4)return{error:ci,info:"PAGE_PLAYOFF requires exactly 4 participants"};let c=[],{matchUps:u}=Er({idPrefix:o&&`${o}-q1`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),p=ti({structureName:r?`${r} Qualifier 1`:"Qualifier 1",structureAbbreviation:"Q1",structureId:a?.pop(),matchUps:u,stageSequence:1,matchUpType:n,stage:e});c.push(p);let{matchUps:d}=Er({finishingPositionOffset:t+2,idPrefix:o&&`${o}-el`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),m=ti({structureName:r?`${r} Eliminator`:"Eliminator",structureAbbreviation:"EL",structureId:a?.pop(),matchUps:d,stageSequence:2,matchUpType:n,stage:e});c.push(m);let{matchUps:l}=Er({finishingPositionOffset:t+1,idPrefix:o&&`${o}-q2`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),f=ti({structureName:r?`${r} Qualifier 2`:"Qualifier 2",structureAbbreviation:"Q2",structureId:a?.pop(),stage:Vt,matchUps:l,stageSequence:3,matchUpType:n});c.push(f);let{matchUps:g}=Er({finishingPositionOffset:t,idPrefix:o&&`${o}-fi`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),I=ti({structureName:r?`${r} Final`:"Final",structureAbbreviation:"F",structureId:a?.pop(),matchUps:g,stage:Vt,stageSequence:4,matchUpType:n});c.push(I);let h=R0({eliminatorStructure:m,q1Structure:p,q2Structure:f,finalStructure:I});return{structures:c,links:h,...P}}function jf({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=tt({drawDefinition:t,structureId:r});if(n.error)return M({result:n});let{matchUps:o}=ht({structure:n.structure,matchUpsMap:e});return{..._e({matchUps:o}),matchUps:o,matchUpsMap:e}}function mM({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=jf({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(b0(n?.[s]).forEach(c=>{t.forEach(u=>{lz({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function lz({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return J(r,(n||r)+1).includes(t)}function b0(t){return[ct(t?.finishingPositionRange?.loser??[]),ct(t?.finishingPositionRange?.winner??[])]}function C0(t){return b0(t).map(e=>J(e[0],e[1]&&e[1]+1||e[0]+1))}function wu({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:O,context:{structureIds:e}};if(!t)return{error:K};e=e??(t.structures??[]).filter(a=>a.stage!==rt).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=jf({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(C0).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(ee).flat();return{positionsNotPlayedOff:ct(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function OA({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){let o=at({drawDefinition:r,structureId:n},[zt,Po]);if(o.error)return o;if(!e)return{error:nt,info:"missing playoffPositions"};let i=wu({drawDefinition:r});if(i.error)return i;let s=i.positionsPlayedOff,a=e.filter(T=>!s.includes(T)),c=mM({finishingPositions:a,drawDefinition:r,structureId:n}),p=Object.values(c).reduce((T,y)=>T.includes(y.roundNumber)?T:T.concat(y.roundNumber),[]).map(T=>st(T)).filter(T=>!t.includes(T)),d=mM({finishingPositions:s,drawDefinition:r,structureId:n}),m=d?Object.values(d):[],l=d?m.reduce((T,y)=>T.includes(y.roundNumber)?T:T.concat(y.roundNumber),[]).map(T=>st(T)):[],f=p.filter(T=>!l.includes(T)).sort(ee),{roundProfile:g}=jf({drawDefinition:r,structureId:n}),I=f.map(T=>{let y=g?.[T].finishingPositionRange.loser,[E,A]=y??[0,0];return J(E,(A||E)+1)}).flat().sort(ee),{playoffRoundsRanges:h}=fz({playoffSourceRounds:f,roundProfile:g}),S=[...f,...l];return{playoffPositionsReturned:I,playedOffSourceRounds:l,playoffRoundsRanges:h,playoffSourceRounds:f,sourceRounds:S,roundProfile:g}}function fz({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=J(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function sd({drawDefinition:t,structureId:e}){if(!t)return{error:K};let{matchUps:r,matchUpsMap:n}=sr({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=wu({drawDefinition:t,matchUpsMap:n}),{structures:s}=hn({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==Qe||u.structureId===e),c={};for(let u of a){let p=u?.structureId,d=gz({playoffPositions:o,drawDefinition:t,structure:u,matchUps:r}),{error:m,...l}=d;if(m)return d;c[p]={structureId:p,...l}}return e?{positionsPlayedOff:i,...c[e]}:{availablePlayoffProfiles:Object.values(c),availablePlayoffRounds:Object.values(c),positionsPlayedOff:i}}function gz({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=qa({drawDefinition:e,structureId:o});if(r.structureType===Ie||r.structures){let l=yt({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:U})=>U?.finishingPositions??[])??[],h=J(1,g+1).filter(U=>!I.includes(U)),S=n.find(U=>U.containerStructureId===o&&U.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:U})=>U.structureId),{positionsPlayedOff:y=[],positionsNotPlayedOff:E=[]}=wu({structureIds:T,drawDefinition:e}),A=new Set([...y,...E]),N=J(S[0],S[1]+1).filter(U=>!A.has(U)),D=Ae(N,N.length/h.length),R=h.map((U,b)=>{let C=D[b],_=[Math.min(...C??[]),Math.max(...C??[])].join("-");return{finishingPosition:U,finishingPositions:C,finishingPositionRange:_}});return{positionsNotPlayedOff:N,playoffFinishingPositionRanges:R,finishingPositionsAvailable:h,finishingPositionsPlayedOff:I,positionsPlayedOff:y,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==Jn).map(l=>l.source?.roundNumber)??[],a=i?.source?.filter(l=>l.linkCondition===Jn).map(l=>l.source?.roundNumber)??[],c=OA({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:e,structureId:o}),u=c?.playoffSourceRounds?[...c?.playoffSourceRounds??[]]:void 0,p=[...c?.playoffRoundsRanges??[]],{roundProfile:d,error:m}=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=d?.[l]?.finishingPositionRange?.loser;if(T){let y=Math.min(...T),E=y+S,A=J(y,E),N={finishingPositionRange:[y,E-1].join("-"),finishingPositions:A,roundNumber:l};p.push(N)}}}return u&&u.sort(ee),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:m}}function M0({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:K};if(!wt(r)||!Array.isArray(t))return{error:O};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:sd({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function Yf({playoffGroups:t,groupCount:e,groupSize:r}){if(!Array.isArray(t)||!t.length)return{error:O,valid:!1,info:"playoffGroups must be a non-empty array"};if(!e||e<1)return{error:O,valid:!1,info:"groupCount must be >= 1"};if(!r||r<1)return{error:O,valid:!1,info:"groupSize must be >= 1"};let n={};for(let a=1;a<=r;a++)n[a]=0;let o=e*r,i=0,s=!1;for(let a of t){let{finishingPositions:c,bestOf:u,rankBy:p,remainder:d}=a;if(d){let l=Iz({hasBestOf:s,totalAvailable:o,totalClaimed:i});if(l.error)return l;i+=o-i;continue}if(!Array.isArray(c)||!c.length)return{error:O,valid:!1,info:"Each playoffGroup must have non-empty finishingPositions"};for(let l of c)if(l<1||l>r)return{error:O,valid:!1,info:`finishingPosition ${l} out of range [1, ${r}]`};let m=e*c.length;if(u===void 0){let l=hz({finishingPositions:c,groupCount:e,consumptionMap:n});if(l?.error)return l;i+=m}else{let l=Sz({finishingPositions:c,guaranteedCount:m,consumptionMap:n,totalAvailable:o,groupCount:e,groupSize:r,bestOf:u,rankBy:p});if(l?.error)return l;s=!0,i+=u}}return i>o?{info:`Total claimed participants (${i}) exceeds available (${o})`,error:ci,valid:!1}:{valid:!0,consumptionMap:n}}function Iz({hasBestOf:t,totalAvailable:e,totalClaimed:r}){if(!t)return{error:ci,valid:!1,info:"A remainder group must appear after at least one bestOf group"};let n=e-r;return n<2?{error:ci,valid:!1,info:`Remainder group would have insufficient participants (${n}), minimum 2 required`}:{}}function hz({finishingPositions:t,groupCount:e,consumptionMap:r}){for(let n of t){let o=e-r[n];if(o<2)return{error:ci,valid:!1,info:`finishingPosition ${n} has insufficient remaining participants (${o}) for a standard playoff group (minimum 2 required)`};r[n]+=o}return{}}function Sz({finishingPositions:t,guaranteedCount:e,consumptionMap:r,totalAvailable:n,groupCount:o,groupSize:i,bestOf:s,rankBy:a}){if(typeof s!="number"||s<1)return{error:O,valid:!1,info:"bestOf must be a positive number"};if(s<e)return{info:`bestOf (${s}) cannot be less than guaranteed count (${e}) for finishingPositions [${t}] with ${o} groups`,error:ci,valid:!1};if(s>n)return{info:`bestOf (${s}) exceeds total available participants (${n})`,error:ci,valid:!1};if(a!==void 0&&a!==Nu)return{info:`Unsupported rankBy value: '${a}'. Currently only '${Nu}' is supported.`,error:O,valid:!1};for(let u of t)r[u]+=o;let c=s-e;if(c>0){let u=Tz({remainder:c,finishingPositions:t,groupCount:o,groupSize:i,consumptionMap:r,bestOf:s});if(u?.error)return u}return{}}function Tz({remainder:t,finishingPositions:e,groupCount:r,groupSize:n,consumptionMap:o,bestOf:i}){let s=t,a=[...e].sort(ee),c=Math.max(...a)+1;for(;s>0&&c<=n;){let u=r-o[c],p=Math.min(s,u);o[c]+=p,s-=p,c++}return s>0?{info:`bestOf (${i}) requires more participants than available from remaining finishing positions`,error:ci,valid:!1}:{}}function _A(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=j,matchUpType:a,structureId:c,idPrefix:u,drawSize:p,isMock:d,uuids:m}=t,l={finishingPositionOffset:e,matchUpType:a,drawSize:p,idPrefix:u,isMock:d,uuids:m},{matchUps:f}=o?wi(l):Er(l),g=gr({structureName:i||r?.["0"]?.name||Be(j),structureId:c||m?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],h=[];if(p>2){let S=p/2,{matchUps:T}=Er({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:d}),y=Be(je),E=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),A=gr({structureName:E,matchUps:T,structureId:m?.pop(),stage:je,stageSequence:1,matchUpType:a});I.push(A);let N={linkType:pr,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:Je,structureId:A.structureId}};h.push(N)}return{...P,structures:I,links:h}}function xA({consolationStructure:t,roundOffset:e=0,mainStructure:r,roundsCount:n,feedPolicy:o,fmlc:i}){let a=t.matchUps.reduce((p,d)=>(d.drawPositions??[]).filter(Boolean).length&&!p.includes(d.roundNumber)?p.concat(d.roundNumber):p,[]),c=o?.roundGroupedOrder??[],u=o?.roundFeedProfiles;return J(1+e,n+1+e).map(p=>{let d=u?.[p-1]?u[p-1]:p%2&&Je||$i,m=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:pr,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:d,roundNumber:m,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),We()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=Jn,l.target.feedProfile=Je),a.includes(m)?l:void 0}).filter(Boolean)}function wA(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=j,matchUpType:c,structureId:u,drawSize:p,idPrefix:d,isMock:m,uuids:l}=t,f={finishingPositionOffset:r,matchUpType:c,drawSize:p,idPrefix:d,isMock:m,uuids:l},{matchUps:g,roundsCount:I}=s?wi(f):Er(f),h=t.structureName??o?.["0"]?.name??Be(j),S=ti({structureId:u||l?.pop(),structureName:h,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[S],y=[];if(p>2){let N=[0,2].slice(0,p/16).map((D,R)=>{let U=R+1,{consolationStructure:b}=yz({idPrefix:d&&`${d}-c${R}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:U,roundOffset:D,matchUpType:c,drawSize:p,isMock:m,index:R,uuids:l});T.push(b);let C=xA({consolationStructure:b,roundsCount:2,mainStructure:S,roundOffset:D});return{consolationStructure:b,links:C}}).map(D=>D.links).flat();if(y.push(...N),p>=4&&p<=16||p>32){let{matchUps:D}=Er({idPrefix:d&&`${d}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:m}),R=o?.["3-4"]?.name??Be(Vt),U=i?.[R]||R,b=e?`${e} ${U}`:U,C=ti({structureId:l?.pop(),matchUps:D,stageSequence:2,stage:Vt,structureName:b,matchUpType:c}),_={linkType:pr,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:C.structureId,feedProfile:Je,roundNumber:1}};T.push(C),y.push(_)}}return{structures:T,links:y,...P}}function yz({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:d}){let m=c/(2*Math.pow(2,o)),{matchUps:l,roundsCount:f}=wi({finishingPositionOffset:m,baseDrawSize:m,isConsolation:!0,feedRounds:1,matchUpType:i,idPrefix:a,isMock:u,uuids:d}),I=p===0&&r?.["0-1"]?.name||p===1&&r?.["0-3"]?.name||`${Be(je)} ${p+1}`,h=n?.[I]||I,S=t?`${t} ${h}`:h;return{consolationStructure:ti({matchUps:l,stage:je,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function Lu(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=j,structureId:c,matchUpType:u,skipRounds:p,feedRounds:d,idPrefix:m,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,h=t.feedPolicy||t.policyDefinitions?.[hu]||t.appliedPolicies?.[hu],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:m,isMock:f,uuids:g},{matchUps:T}=i?wi(S):Er(S),y=gr({structureName:s||n?.["0"]?.name||Be(j),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),E=[y],A=[],N=l/2,{matchUps:D,roundsCount:R}=wi({finishingPositionOffset:N,idPrefix:m&&`${m}-c`,isConsolation:!0,feedsFromFinal:o,baseDrawSize:N,matchUpType:u,feedRounds:d,skipRounds:p,isMock:f,uuids:g,fmlc:I});if(l>2){let U=n?.["0-1"]?.name??Be(je),b=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${U}`:U,C=gr({matchUps:D,structureId:g?.pop(),stage:je,stageSequence:1,structureName:b,matchUpType:u});E.push(C);let _=xA({consolationStructure:C,mainStructure:y,roundsCount:R,feedPolicy:h,fmlc:I});A.push(..._)}return{...P,structures:E,links:A}}var Ez=new Set([qs,mm,Xl,Cp,bp,Zl]),Az=new Set([js,Rp,fm]);function qf({requireSequential:t=!0,playoffMatchUpFormat:e,playoffAttributes:r,sourceStructureId:n,policyDefinitions:o,stageSequence:i,drawDefinition:s,playoffGroups:a,matchUpType:c,feedPolicy:u,groupCount:p,groupSize:d,idPrefix:m,isMock:l,uuids:f}={}){let g=u||o?.[hu],I="processPlayoffGroups",h=0,S=[],T=[],y=[];if(a?.some(b=>b.bestOf!==void 0||b.remainder)&&d){let b=Yf({playoffGroups:a,groupCount:p,groupSize:d});if(!b.valid)return M({result:{error:b.error||ci},context:{info:b.info},stack:I})}let A=a?.filter(b=>!b.remainder),{error:N,positionRangeMap:D}=M0({structureId:n,playoffGroups:A,drawDefinition:s});if(N)return M({result:{error:N},stack:I});if(!(!D||A?.every(b=>{let{finishingPositions:C=[]}=b;if(!C.length)return!1;let _=[...C].sort(ee).map((v,x)=>(C[x+1]||v)-v).every(v=>v<2);return(!t||_)&&C.every(v=>D[v])})))return M({context:{validFinishingPositions:Object.values(D)},result:{error:O},stack:I});let U=0;for(let b of a){let{bestOf:C,rankBy:_,remainder:v}=b;if(v){let H=Pz({finishingPositionOffset:h,playoffMatchUpFormat:e,sourceStructureId:n,stageSequence:i,totalClaimed:U,playoffGroup:b,matchUpType:c,groupCount:p,groupSize:d,idPrefix:m,isMock:l,uuids:f});T.push(H.structure),y.push(H.link),S.push(H.target),h+=H.remainderCount,U+=H.remainderCount;continue}let x=b.finishingPositions??[],w=D&&x.flatMap(H=>D[H]?.finishingPositions??[]),F=C??p*x.length;U+=F;let L=Ci(F),k=L===2&&on||b.drawType||on;w&&(h=Math.min(...w)-1);let G=vz({positionsPlayedOff:w,playoffGroup:b}),B={...{addNameBaseToAttributeName:b.addNameBaseToAttributeName,playoffStructureNameBase:b.playoffStructureNameBase,finishingPositionNaming:b.finishingPositionNaming,finishingPositionLimit:b.finishingPositionLimit,structureId:b.structureId??f?.pop(),playoffAttributes:b.playoffAttributes,structureNameMap:b.structureNameMap,sequenceLimit:b.sequenceLimit,structureName:G},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:h,stage:Vt,stageSequence:i,matchUpType:c,drawSize:L,isMock:l,uuids:f},$=({playoffStructures:H,playoffLinks:z})=>{let[W]=H,Q=Fu({playoffStructureId:W.structureId,finishingPositions:x,sourceStructureId:n,bestOf:C,rankBy:_});y.push(Q,...z),T.push(...H),S.push({structureId:W.structureId,finishingPositions:x}),h+=F};if(k===on)Nz({finishingPositionOffset:h,playoffMatchUpFormat:e,finishingPositions:x,sourceStructureId:n,participantsInDraw:F,stageSequence:i,playoffGroup:b,structureName:G,matchUpType:c,drawSize:L,idPrefix:m,bestOf:C,rankBy:_,isMock:l,uuids:f,finishingPositionTargets:S,structures:T,links:y}),h+=F;else if(Az.has(k)){let H=Dz({finishingPositionOffset:h,finishingPositions:x,sourceStructureId:n,playoffAttributes:r,playoffDrawType:k,stageSequence:i,playoffGroup:b,drawSize:L,idPrefix:m,bestOf:C,rankBy:_,isMock:l,uuids:f,finishingPositionTargets:S,structures:T,links:y});if(H)return H;h+=F}else if(Ez.has(k))Uz({finishingPositionOffset:h,finishingPositions:x,sourceStructureId:n,playoffDrawType:k,playoffGroup:b,structureName:G,matchUpType:c,drawSize:L,idPrefix:m,bestOf:C,rankBy:_,isMock:l,uuids:f,feedPolicy:g,finishingPositionTargets:S,structures:T,links:y}),h+=F;else if(k===_r){let{structures:H,links:z}=Fc({...B,structureOptions:b.structureOptions||{groupSize:4}});$({playoffStructures:H,playoffLinks:z})}else if(k===Ga){let{structures:H,links:z}=_A(B);$({playoffStructures:H,playoffLinks:z})}else if(k===NF){let{structures:H,links:z}=wA(B);$({playoffStructures:H,playoffLinks:z})}else if(k===lm){let H=Rz({finishingPositionTargets:S,participantsInDraw:F,sourceStructureId:n,finishingPositions:x,drawDefinition:s,playoffGroup:b,structures:T,params:B,links:y,stack:I});if(H)return H}else k===vi&&Mz({finishingPositions:x,stageSequence:i,structureName:G,playoffGroup:b,groupSize:d,uuids:f,updateStructureAndLinks:$})}return{finishingPositionTargets:S,positionRangeMap:D,structures:T,links:y}}function Pz({finishingPositionOffset:t,playoffMatchUpFormat:e,sourceStructureId:r,stageSequence:n,totalClaimed:o,playoffGroup:i,matchUpType:s,groupCount:a,groupSize:c,idPrefix:u,isMock:p,uuids:d}){let l=a*c-o,f=Ci(l),g=Array.from({length:c},(y,E)=>E+1),I=i.structureName||"Remainder Playoff",{matchUps:h}=Er({finishingPositionLimit:t+l,idPrefix:u&&`${u}-po`,finishingPositionOffset:t,matchUpType:s,drawSize:f,isMock:p,uuids:d}),S=gr({structureId:i.structureId??d?.pop(),matchUpFormat:e,stage:Vt,structureName:I,stageSequence:n,matchUps:h}),T=Fu({playoffStructureId:S.structureId,finishingPositions:g,sourceStructureId:r,remainder:!0});return{structure:S,target:{structureId:S.structureId,finishingPositions:g},remainderCount:l,link:T}}function Nz({finishingPositionOffset:t,playoffMatchUpFormat:e,finishingPositions:r,sourceStructureId:n,participantsInDraw:o,stageSequence:i,playoffGroup:s,structureName:a,matchUpType:c,drawSize:u,idPrefix:p,bestOf:d,rankBy:m,isMock:l,uuids:f,finishingPositionTargets:g,structures:I,links:h}){let{matchUps:S}=Er({finishingPositionLimit:t+o,idPrefix:p&&`${p}-po`,finishingPositionOffset:t,matchUpType:c,drawSize:u,isMock:l,uuids:f}),T=gr({structureId:s.structureId??f?.pop(),matchUpFormat:e,stage:Vt,structureName:a,stageSequence:i,matchUps:S});I.push(T);let y=Fu({playoffStructureId:T.structureId,finishingPositions:r,sourceStructureId:n,bestOf:d,rankBy:m});h.push(y),g.push({structureId:T.structureId,finishingPositions:r})}function Dz({finishingPositionOffset:t,finishingPositions:e,sourceStructureId:r,playoffAttributes:n,playoffDrawType:o,stageSequence:i,playoffGroup:s,drawSize:a,idPrefix:c,bestOf:u,rankBy:p,isMock:d,uuids:m,finishingPositionTargets:l,structures:f,links:g}){let I={playoffAttributes:s.playoffAttributes??n,playoffStructureNameBase:s.playoffStructureNameBase,structureId:s.structureId??m?.pop(),structureName:s.structureName,idPrefix:c&&`${c}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:t,stage:Vt,roundOffset:0,stageSequence:i,drawSize:a,isMock:d,uuids:m};o===js?Object.assign(I,{playoffAttributes:s?.playoffAttributes??n??uh,roundOffsetLimit:3}):o===Rp&&Object.assign(I,{playoffAttributes:s?.playoffAttributes??n??ph,roundOffsetLimit:2});let h=xu(I);if(h.error)return h;if(h.links?.length&&g.push(...h.links),h.structures?.length&&f.push(...h.structures),f.sort(Xi),h.structureId){let S=Fu({playoffStructureId:h.structureId,finishingPositions:e,sourceStructureId:r,bestOf:u,rankBy:p});g.push(S),l.push({structureId:h.structureId,finishingPositions:e})}}function Uz({finishingPositionOffset:t,finishingPositions:e,sourceStructureId:r,playoffDrawType:n,playoffGroup:o,structureName:i,matchUpType:s,feedPolicy:a,drawSize:c,idPrefix:u,bestOf:p,rankBy:d,isMock:m,uuids:l,finishingPositionTargets:f,structures:g,links:I}){let h=[l?.pop(),l?.pop()],S={playoffStructureNameBase:o.playoffStructureNameBase,structureId:o.structureId??l?.pop(),playoffAttributes:o.playoffAttributes,idPrefix:u&&`${u}-po`,finishingPositionOffset:t,uuids:h,stage:Vt,structureName:i,matchUpType:s,feedPolicy:a,drawSize:c,isMock:m},T={[qs]:{fmlc:!0,feedRounds:1},[Zl]:{feedRounds:1},[Xl]:{feedsFromFinal:3},[Cp]:{feedsFromFinal:2},[bp]:{feedsFromFinal:1}};Object.assign(S,T[n]??{});let{structures:y,links:E}=Lu(S),[A]=y,N=Fu({playoffStructureId:A.structureId,finishingPositions:e,sourceStructureId:r,bestOf:p,rankBy:d});I.push(N,...E),g.push(...y),f.push({structureId:A.structureId,finishingPositions:e})}function Rz({finishingPositionTargets:t,participantsInDraw:e,sourceStructureId:r,finishingPositions:n,drawDefinition:o,playoffGroup:i,structures:s,params:a,links:c,stack:u}){if(e!==4)return M({result:{error:ci},context:{info:"PAGE_PLAYOFF requires exactly 4 participants"},stack:u});let p=o?.structures?.find(m=>m.structureId===r);return p&&!p.structures&&!p.structureType?bz({finishingPositionTargets:t,sourceStructureId:r,drawDefinition:o,playoffGroup:i,structures:s,params:a,links:c}):Cz({finishingPositionTargets:t,sourceStructureId:r,finishingPositions:n,playoffGroup:i,structures:s,params:a,links:c,stack:u})}function bz({finishingPositionTargets:t,sourceStructureId:e,drawDefinition:r,playoffGroup:n,structures:o,params:i,links:s}){let a=n.structureName,{matchUpType:c,isMock:u,uuids:p,idPrefix:d,finishingPositionOffset:m=0}=i,l=Vt,{matchUps:f}=Er({finishingPositionOffset:m+2,idPrefix:d&&`${d}-el`,drawSize:2,matchUpType:c,isMock:u,uuids:p}),g=gr({structureName:a?`${a} 3-4 Playoff`:"3-4 Playoff",structureAbbreviation:"EL",structureId:p?.pop(),matchUps:f,stageSequence:1,matchUpType:c,stage:l}),{matchUps:I}=Er({finishingPositionOffset:m+1,idPrefix:d&&`${d}-q2`,drawSize:2,matchUpType:c,isMock:u,uuids:p}),h=gr({structureName:a?`${a} Playoff Qualifier`:"Playoff Qualifier",structureAbbreviation:"Q2",structureId:p?.pop(),matchUps:I,stageSequence:2,matchUpType:c,stage:l}),{matchUps:S}=Er({finishingPositionOffset:m,idPrefix:d&&`${d}-fi`,drawSize:2,matchUpType:c,isMock:u,uuids:p}),T=gr({structureName:a?`${a} Final`:"Playoff Final",structureAbbreviation:"F",structureId:p?.pop(),matchUps:S,stageSequence:3,matchUpType:c,stage:l});o.push(g,h,T);let E=r?.structures?.find(D=>D.structureId===e)?.matchUps||[],A=E.length?Math.max(...E.map(D=>D.roundNumber)):1,N=A-1;s.push({linkType:pr,source:{structureId:e,roundNumber:N},target:{feedProfile:Je,roundNumber:1,structureId:g.structureId}},{linkType:Ar,source:{structureId:e,roundNumber:A},target:{feedProfile:Je,roundNumber:1,structureId:T.structureId}},{linkType:pr,source:{structureId:e,roundNumber:A},target:{feedProfile:Je,roundNumber:1,structureId:h.structureId}},{linkType:Ar,source:{structureId:g.structureId,roundNumber:1},target:{feedProfile:Je,roundNumber:1,structureId:h.structureId}},{linkType:Ar,source:{structureId:h.structureId,roundNumber:1},target:{feedProfile:Je,roundNumber:1,structureId:T.structureId}}),t.push({structureId:g.structureId,finishingPositions:[3,4]})}function Cz({finishingPositionTargets:t,sourceStructureId:e,finishingPositions:r,playoffGroup:n,structures:o,params:i,links:s,stack:a}){let c=vA({...i,structureName:n.structureName});if(c.error)return M({result:c,stack:a});o.push(...c.structures),s.push(...c.links);let u=c.structures.find(d=>d.structureAbbreviation==="Q1"),p=c.structures.find(d=>d.structureAbbreviation==="EL");if(r.length>=2&&u&&p){let d=Math.ceil(r.length/2),m=r.slice(0,d),l=r.slice(d);s.push(Fu({playoffStructureId:u.structureId,finishingPositions:m,sourceStructureId:e}),Fu({playoffStructureId:p.structureId,finishingPositions:l,sourceStructureId:e})),t.push({structureId:u.structureId,finishingPositions:m},{structureId:p.structureId,finishingPositions:l})}else u&&p&&(s.push(Fu({playoffStructureId:u.structureId,finishingPositions:r,sourceStructureId:e}),Fu({playoffStructureId:p.structureId,finishingPositions:r,sourceStructureId:e})),t.push({structureId:u.structureId,finishingPositions:r},{structureId:p.structureId,finishingPositions:r}))}function Mz({finishingPositions:t,stageSequence:e,structureName:r,playoffGroup:n,groupSize:o,uuids:i,updateStructureAndLinks:s}){!t.length&&o&&t.push(...Array.from({length:o},(c,u)=>u+1));let a=gr({structureId:n.structureId??i?.pop(),structureName:n.structureName||r||"Playoff",finishingPosition:Sf,stage:Vt,stageSequence:e,matchUps:[]});s({playoffStructures:[a],playoffLinks:[]})}function vz({positionsPlayedOff:t,playoffGroup:e}){let r=t&&`${Math.min(...t)}-${Math.max(...t)}`;return e.structureName||r&&e.playoffAttributes?.[r]?.name||e.playoffAttributes?.["0"]?.name}function Fu({playoffStructureId:t,finishingPositions:e,sourceStructureId:r,remainder:n,bestOf:o,rankBy:i}){let s={structureId:r,finishingPositions:e};return o!==void 0&&(s.bestOf=o,s.rankBy=i||Nu),n&&(s.remainder=!0),{linkType:fn,source:s,target:{structureId:t,feedProfile:ln,roundNumber:1}}}function v0(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Be(j),...t,stage:j},{structures:i,groupCount:s,groupSize:a}=Fc(o);if(s<1)return{error:ci};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Be(Vt)}],[u]=i,{structures:p,links:d}=qf({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...P,structures:i,links:d}}function O0({mainStructure:t,consolationStructure:e,deciderStructure:r}){let o=e.matchUps.reduce((p,d)=>(d.drawPositions??[]).filter(Boolean).length&&!p.includes(d.roundNumber)?p.concat(d.roundNumber):p,[]),i=t.matchUps.reduce((p,d)=>!p||d.roundNumber>p?d.roundNumber:p,void 0),s=e.matchUps.reduce((p,d)=>!p||d.roundNumber>p?d.roundNumber:p,void 0),a=o.map((p,d)=>{let l=o.indexOf(p)%2?Je:$i,f=1+d;return{linkType:pr,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:Ar,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:Je,roundNumber:i,structureId:t.structureId}},u=[{linkType:Ar,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Je,roundNumber:1,structureId:r.structureId}},{linkType:pr,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Je,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function _0({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=wi({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=ti({structureName:t||Be(j),structureId:i?.pop(),stageSequence:1,stage:j,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=wi({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),d=ti({structureName:Be(Cb),matchUps:p,structureId:i?.pop(),stage:je,stageSequence:2,matchUpType:e});s.push(d);let{matchUps:m}=Er({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=ti({structureName:Be(bb),matchUps:m,structureId:i?.pop(),stageSequence:3,stage:Vt,matchUpType:e});s.push(l);let f=O0({mainStructure:c,consolationStructure:d,deciderStructure:l});return{structures:s,links:f,...P}}function LA(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(rn(s))return Er(t);let u=FA(s),p=u.shift(),d=J(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),m=[],l=1;({matchUps:m}=_u({roundNumber:l,matchUpType:o,idPrefix:i,matchUps:m,isMock:a,nodes:d,uuids:c})),l++;let f=t.roundLimit||e;for(let I of u){let h=I.participantsCount/2,S=J(1,h+1);n&&h===n&&(f=l-1);let T=S.map(y=>{let E=id({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:E}});m.push(...T),l++}let g=l-1;return m=aa({finishingPositionOffset:r,lucky:!0,roundsCount:g,roundLimit:f,matchUps:m}),f&&(m=m.filter(I=>I.roundNumber<=f)),{matchUps:m,roundsCount:g,roundLimit:f}}function FA(t){let e=st(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 lM(t){let{finishingPositionOffset:e=0,playoffAttributes:r=dh,stageSequence:n=1,exitProfile:o="0",roundOffsetLimit:i=3,roundOffset:s=0,childStage:a=Vt,stage:c=j,matchUpType:u,structureId:p,drawSize:d,idPrefix:m,isMock:l,uuids:f}=t;if(!(!r||r[o])||d<2)return{};let I=[],h=[],S=r[o],T=t.structureName||S?.name||`${e+1}-${e+d}`,y=S?.abbreviation,E=p??S?.structureId??f?.pop(),{matchUps:A}=LA({finishingPositionOffset:e,matchUpType:u,drawSize:d,idPrefix:m&&`${m}-${T}-RP`,isMock:l,uuids:f}),N=gr({structureAbbreviation:y,structureName:T,stageSequence:n,matchUpType:u,roundOffset:s,structureId:E,matchUps:A,stage:c});I.push(N);let D=Oz(d),R=D.length,U=Math.min(i-s,R);for(let b=0;b<U;b++){let{roundNumber:C,childSize:_}=D[b];if(_<2)continue;let v=e+_z(d,C),x=`${o}-${C}`,w=lM({finishingPositionOffset:v,exitProfile:x,roundOffset:s+C,stageSequence:n+1,drawSize:_,stage:a,playoffAttributes:r,roundOffsetLimit:i,childStage:a,matchUpType:u,idPrefix:m,isMock:l,uuids:f});if(w.structureId&&N.structureId){let F={linkType:pr,source:{roundNumber:C,structureId:N.structureId},target:{roundNumber:1,feedProfile:Je,structureId:w.structureId}};h.push(F)}w.structures?.length&&I.push(...w.structures),w.links?.length&&h.push(...w.links)}return{structureId:N.structureId,structures:I,links:h,...P}}function Oz(t){if(rn(t)){let n=Math.ceil(Math.log(t)/Math.log(2)),o=[];for(let i=1;i<=n;i++){let s=t/Math.pow(2,i);s>=2&&o.push({roundNumber:i,childSize:s})}return o}let e=FA(t),r=[];for(let n=0;n<e.length-1;n++){let o=e[n],i=o.participantsCount/2,s=o.preFeedRound?i-1:i;s>=2&&r.push({roundNumber:n+1,childSize:s})}return r}function _z(t,e){if(rn(t))return t/Math.pow(2,e);let r=FA(t);return e<r.length?Math.ceil(r[e].participantsCount/2):1}function x0(t){let{finishingPositionOffset:e,qualifyingRoundNumber:r,qualifyingPositions:n,matchUpType:o,idPrefix:i,drawSize:s,isMock:a,uuids:c}=t;if(!It(s)||s<2)return{matchUps:[],roundsCount:0};let u=xz(t.roundProfile,s);if(u.error||!u.profile)return{matchUps:[],roundsCount:0,error:u.error,info:u.info};let p=u.profile,d=p[0]*2,m=J(1,d+1).map(h=>({drawPosition:h})),l=[],f=1;({matchUps:l}=_u({roundNumber:f,matchUpType:o,idPrefix:i,matchUps:l,isMock:a,nodes:m,uuids:c})),f++;let g=t.roundLimit||r;for(let h=1;h<p.length;h++){let S=p[h];n&&S===n&&(g=f-1);let T=J(1,S+1).map(y=>({roundPosition:y,roundNumber:f,matchUpId:id({roundPosition:y,roundNumber:f,idPrefix:i,uuids:c})}));l.push(...T),f++}let I=f-1;return l=aa({finishingPositionOffset:e,lucky:!0,roundsCount:I,roundLimit:g,matchUps:l}),g&&(l=l.filter(h=>h.roundNumber<=g)),{matchUps:l,roundsCount:I,roundLimit:g,roundProfile:p}}function xz(t,e){if(!Array.isArray(t)||!t.length)return{error:O,info:"roundProfile must be a non-empty array"};let r=t.map(o=>st(o));if(r.some(o=>!Number.isInteger(o)||o<1))return{error:O,info:"roundProfile entries must be positive integers"};if(r[r.length-1]!==1)return{error:O,info:"roundProfile must end with 1 (final matchUp)"};let n=r[0]*2;if(st(e)!==n)return{error:O,info:`roundProfile[0] * 2 (${n}) must equal drawSize (${e})`};for(let o=0;o<r.length-1;o++){let i=r[o],s=r[o+1]*2;if(s<i)return{error:O,info:`round ${o+2} has ${s} slots but round ${o+1} produces ${i} winners (would drop winners)`}}return{profile:r}}function $f(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=j,tieFormat:o,matchUpType:i,drawSize:s,uuids:a}=t,c=()=>!t.isMock&&!t.idPrefix?void 0:`${t.drawDefinition.drawId}-s-0`,u=t.structureId||c()||a?.pop(),p=t.appliedPolicies??gt(t),d=t.policyDefinitions?.[hu]||p?.[hu];t.skipRounds=t.skipRounds||s<=4&&(d?.feedFromMainFinal?0:1)||0;let m=t.structureName??e?.["0"]?.name??Be(j),l=()=>{let{matchUps:g}=Er(t);return{structures:[gr({stageSequence:r,structureName:m,matchUpType:i,structureId:u,tieFormat:o,matchUps:g,stage:n})],links:[],...P}};return{generators:{[vi]:()=>({structures:[gr({finishingPosition:Ao,stageSequence:r,structureName:m,matchUps:[],matchUpType:i,structureId:u,stage:n})],links:[],...P}),[$s]:()=>{let g=gr({finishingPosition:Ao,stageSequence:r,structureName:m,matchUps:[],matchUpType:i,structureId:u,stage:n});return s&&(g.positionAssignments=Array.from({length:s},(I,h)=>({drawPosition:h+1}))),{structures:[g],links:[],...P}},[di]:()=>{if(t.roundProfile){let{matchUps:h,roundProfile:S,error:T,info:y}=x0(t);if(T)return{error:T,info:y};let E=gr({stageSequence:r,structureName:m,matchUpType:i,structureId:u,matchUps:h,stage:n});return S&&(E.extensions=[{name:"customRoundProfile",value:S}]),{structures:[E],links:[],...P}}let{matchUps:g}=LA(t);return{structures:[gr({stageSequence:r,structureName:m,matchUpType:i,structureId:u,matchUps:g,stage:n})],links:[],...P}},[on]:()=>l(),[Ys]:()=>_0(t),[js]:()=>xu({...t,childStage:Vt,roundOffsetLimit:3,playoffAttributes:e??uh}),[Rp]:()=>xu({...t,childStage:Vt,roundOffsetLimit:2,playoffAttributes:e??ph}),[Ki]:()=>lM({...t,childStage:Vt,roundOffsetLimit:t.roundOffsetLimit??3,playoffAttributes:e??dh}),[lm]:()=>vA(t),[fm]:()=>xu({...t,childStage:Vt}),[yc]:()=>{let{matchUps:g}=wi({drawSize:s,uuids:a,matchUpType:i});return{structures:[gr({stageSequence:r,structureName:m,matchUpType:i,structureId:u,stage:j,tieFormat:o,matchUps:g})],links:[],...P}},[Ga]:()=>_A(t),[qs]:()=>Lu({...t,feedRounds:1,fmlc:!0}),[Rb]:()=>Lu({...t,feedRounds:1}),[fE]:()=>Lu({...t,feedsFromFinal:1}),[gE]:()=>Lu({...t,feedsFromFinal:2}),[IE]:()=>Lu({...t,feedsFromFinal:3}),[mm]:()=>Lu(t),[ch]:()=>wA(t),[_r]:()=>Fc(t),[sn]:()=>v0(t)}}}function kA({element:t}){if(!t)return{error:O};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:O};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function jn(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:VI};let i=YE(t);if(i.error)return i;if(!(St(o)&&wt(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:GI};if(o.itemDate&&typeof o.itemDate=="string"&&!Fe(o.itemDate))return{error:de};if(!i.timeItems)i.timeItems=[];else if(wz({element:i,duplicateValues:e,timeItem:o}))return{...P};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),{...P}}function wz({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&Fr({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function Om({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:Y};if(!o)return{error:$e};let s=Bn({tournamentRecord:r,participantId:o});return s.error?s:jn({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function ku(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:Y};let s=jn({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=kA({element:r});return it({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:ko}),s}function Os(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?jn({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:Br}}function cS(t){return pS({...t,itemType:"attachConsolationStructures"})}function uS(t){return pS({...t,itemType:"attachPlayoffStructures"})}function pS({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:K};if(!Array.isArray(o)||!Array.isArray(i))return M({result:{error:O},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 M({result:{error:qI},info:"playoff structure exists",stack:a});if(i.length){let h=new Set([...n.structures?.map(({structureId:T})=>T)??[],...o.map(({structureId:T})=>T)]),S=i.filter(T=>!h.has(T.source.structureId)||!h.has(T.target.structureId));if(S.length)return M({result:{error:Wo},info:"links reference non-existent structures",context:{invalidLinks:S.map(T=>({source:T.source.structureId,target:T.target.structureId}))},stack:a})}i.length&&n.links?.push(...i);let d=new Set(o.map(({structureId:h})=>h)),m=n.structures?.map(({structureId:h})=>h);n.structures=(n.structures??[]).map(h=>d.has(h.structureId)?o.find(({structureId:S})=>S===h.structureId):h);let l=o?.filter(({structureId:h})=>!m?.includes(h));l.length&&n.structures.push(...l),bs({drawDefinition:n});let f=o.map(h=>ht({structure:h})?.matchUps??[]).flat();zo({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(Lt({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:E,...A}=h[y.matchUpId].matchUp;if(Object.assign(y,A),E?.length){let N={};E.forEach(D=>h[D.matchUpId]=D),y.tieMatchUps.forEach(D=>Object.assign(D,N[D.matchUpId]))}h[y.matchUpId].matchUp=y,mt(h[y.matchUpId])}})};n.structures.forEach(T=>{if(m?.includes(T.structureId))if(T.structures)for(let y of T.structures)S(y);else S(T)})}let I=l.map(Gr("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};jn({element:r,timeItem:S})}return{...P,addedStructureIds:I}}function fM({structureName:t,structureType:e=vi,drawSize:r=2,matchUpFormat:n,matchUpType:o}){let i={stage:je,stageSequence:1,structureName:t||Be(je),drawSize:r,matchUpFormat:n,matchUpType:o},{generators:s,error:a}=$f(i);if(a)return{error:a};let c=s[e];if(!c)return{error:mp};let u=c();return u.error?u:{...P,structures:u.structures}}function gM({drawDefinition:t,structureId:e,structureName:r,structureType:n=vi,drawSize:o=2,matchUpFormat:i,matchUpType:s,links:a=[]}){if(!t)return{error:K};if(e||(e=t.structures?.find(m=>m.stage===j)?.structureId),!e)return{error:Hi};let{structure:c}=tt({drawDefinition:t,structureId:e});if(!c)return{error:Hi};let u=fM({structureName:r,structureType:n,drawSize:o,matchUpFormat:i,matchUpType:s||t.matchUpType});if(u.error)return u;let p=u.structures?.[0];if(!p)return{error:mp};let d=a.map(m=>({linkType:pr,source:{roundNumber:m.sourceRoundNumber,structureId:e},target:{roundNumber:m.targetRoundNumber,feedProfile:Je,structureId:p.structureId}}));return cS({drawDefinition:t,structures:[p],links:d})}function IM({drawDefinition:t,participantId:e,preferences:r}){if(!t)return{error:K};if(!e)return{error:Hr};if(!Array.isArray(r))return{error:O};let n=$t({element:t,attribute:"draftState",name:fi});if(!n)return{error:fe,info:"No active draft found"};if(n.status==="COMPLETE")return{error:O,info:"Draft is already complete"};if(!n.tiers?.find(c=>c.participantIds?.includes(e)))return{error:Hr,info:"Participant not in any draft tier"};let i=new Set(n.unassignedDrawPositions);for(let c of r)if(!i.has(c))return{error:hs,info:`Draw position ${c} is not available`};let s=n.preferencesCount??3,a=r.slice(0,s);return n.preferences[e]=a,n.status==="SEEDS_PLACED"&&(n.status="COLLECTING_PREFERENCES"),At({element:t,attribute:"draftState",name:fi,value:n}),{...P}}function hM({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i}){return Wf({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i})}function dS({targetMatchUpIds:t,drawDefinition:e}){if(!e)return{error:K};if(!Array.isArray(t)||!t.length)return{error:O};let{exitProfiles:r}=Pf({drawDefinition:e}),n=e.structures??[],o={},i=0;for(let s of n){let a=r?.[s.structureId]??[];if(s.structures?.length)for(let c of s.structures)i+=w0({exitProfiles:a,structure:c,parentStructure:s,targetMatchUpIds:t,idMap:o});i+=w0({exitProfiles:a,targetMatchUpIds:t,structure:s,idMap:o})}if(Object.keys(o).length)for(let s of n){F0(s,o);for(let a of s.structures??[])F0(a,o)}return{...P,remappedCount:i}}function w0({parentStructure:t,targetMatchUpIds:e,exitProfiles:r,structure:n,idMap:o}){let i=0,s=t?.stage??n.stage,a=t?.stageSequence??n.stageSequence;for(let c of n.matchUps??[]){let u=L0({stageSequence:a,roundPosition:c.roundPosition,roundNumber:c.roundNumber,structureId:n.structureId,parentStructureId:t?.structureId,stage:s,targetMatchUpIds:e,exitProfiles:r});u&&u.matchUpId!==c.matchUpId&&(o[c.matchUpId]=u.matchUpId,c.matchUpId=u.matchUpId,i++);for(let p of c.tieMatchUps??[]){let d=L0({stageSequence:a,roundPosition:p.roundPosition,roundNumber:p.roundNumber,structureId:n.structureId,parentStructureId:t?.structureId,stage:s,targetMatchUpIds:e,exitProfiles:r});d&&d.matchUpId!==p.matchUpId&&(o[p.matchUpId]=d.matchUpId,p.matchUpId=d.matchUpId,i++)}}return i}function L0({parentStructureId:t,targetMatchUpIds:e,stageSequence:r,roundPosition:n,exitProfiles:o,structureId:i,roundNumber:s,stage:a}){return e.find(c=>c.roundNumber!==s||c.roundPosition!==n?!1:c.structureId?c.structureId===i||c.structureId===t:c.exitProfile?o.includes(c.exitProfile):!(c.stage&&c.stage!==a||c.stageSequence&&c.stageSequence!==r))}function F0(t,e){let r=n=>{n.winnerMatchUpId&&e[n.winnerMatchUpId]&&(n.winnerMatchUpId=e[n.winnerMatchUpId]),n.loserMatchUpId&&e[n.loserMatchUpId]&&(n.loserMatchUpId=e[n.loserMatchUpId]);for(let o of n.tieMatchUps??[])r(o)};for(let n of t.matchUps??[])r(n)}function ad({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=qa({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:d}=tt({structureId:p,drawDefinition:r});if(!(e&&d?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}function mS({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return Wf({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function GA({drawDefinition:t,structureId:e}){if(!t)return{error:K};let{structure:r}=tt({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 lS({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:Se};let a={},c=[];for(let u of i.drawDefinitions??[]){let{structures:p,stageStructures:d}=hn({withStageGrouping:t,stageSequences:e,drawDefinition:u,stageSequence:r,roundTarget:n,stages:o,stage:s});if(c.push(...p),d)for(let m of Object.keys(d))a[m]||(a[m]=[]),a[m].push(...d[m])}return{structures:c,stageStructures:a}}function VA({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:Y};let a={},c=[];for(let u of e.events??[]){let{structures:p,stageStructures:d}=lS({withStageGrouping:t,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,event:u,stage:s});if(p&&c.push(...p),d)for(let m of Object.keys(d))a[m]||(a[m]=[]),a[m].push(...d[m])}return{structures:c,stageStructures:a}}function Bo(t){if(!t?.drawDefinition)return!1;let e=Xp(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e??{};return r&&(n=n?.filter(({matchUpType:a})=>a===xt),o=o?.filter(({matchUpType:a})=>a===xt),i=i?.filter(({matchUpType:a})=>a===xt)),!!(n?.length&&!o?.length&&!i?.length)}function BA(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:K};let{playoffStructures:n}=GA({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&yr.includes(c.entryStatus))?.length??0,i=0;return(n??[]).reduce((c,u)=>!!((yt({structure:u}).positionAssignments??[])?.filter(m=>(m.participantId&&i++,m?.bye??m?.participantId)).length&&c),!!n.length)||i===o}var k0=(t,e)=>{let r=[...new Set(e.slice(0,t.length))],n=[...r].sort((a,c)=>a-c),o=new Set,i=[];r.forEach(a=>{let c=t.indexOf(a);if(c!==-1&&!o.has(c))i.push(c),o.add(c);else{let u=n.indexOf(a),p=t.findIndex((d,m)=>!o.has(m));for(;o.has(p)&&p===-1&&o.size<t.length;)p=t.findIndex((d,m)=>!o.has(m)&&m>p);i.push(u),o.add(u)}});let s=t.filter((a,c)=>!o.has(c));return[...i,...s]};function SM({targetRoundNumber:t=1,tournamentRecord:e,drawDefinition:r,event:n,randomList:o}){let i=X({drawDefinition:r,event:n,tournamentRecord:e},[{[zt]:!0,[me]:!0,[Z]:!0}]);if(i.error)return i;let s=[],a=[],c=r.structures?.find(S=>S.stage===j&&S.stageSequence===1);if(!c)return M({result:{error:NI}});let d=(gt({tournamentRecord:e,drawDefinition:r,structure:c,event:n}).appliedPolicies??{})[uo]?.requireCompletedStructures,{qualifierPositions:m,positionAssignments:l}=pe({structure:c});if(!m.length)return M({result:{error:FI}});let f=J(0,m.length);o&&(f=k0(f,o));let g=l.map(S=>S.participantId).filter(Boolean),{relevantLinks:I}=ad({structureId:c.structureId,targetRoundNumber:t,linkType:Ar,drawDefinition:r})??{},{relevantLinks:h}=ad({structureId:c.structureId,targetRoundNumber:t,linkType:fn,drawDefinition:r})??{};return Lz({eliminationSourceLinks:I,requireCompletedStructures:d,assignedParticipantIds:g,qualifyingParticipantIds:a,drawDefinition:r}),Fz({roundRobinSourceLinks:h,assignedParticipantIds:g,qualifyingParticipantIds:a,drawDefinition:r}),a.length?(f.forEach((S,T)=>{let y=a[T],E=m[S].drawPosition;y&&mS({qualifyingParticipantId:y,structureId:c.structureId,drawPosition:E,tournamentRecord:e,drawDefinition:r})?.success&&s.push({participantId:y,drawPosition:E})}),M({result:et({...P,assignedParticipants:s})})):M({result:{error:pR}})}function Lz({eliminationSourceLinks:t,requireCompletedStructures:e,assignedParticipantIds:r,qualifyingParticipantIds:n,drawDefinition:o}){for(let i of t){let s=o.structures?.find(p=>p.structureId===i.source.structureId);if(s?.stage!==rt)continue;let a=Bo({structureId:i.source.structureId,drawDefinition:o});if(e&&!a)continue;let c=s.qualifyingRoundNumber,{matchUps:u}=ht({matchUpFilters:{...c&&{roundNumbers:[c]},isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,inContext:!0,structure:s});for(let p of u){let d=p.matchUpStatus==="BYE"&&p.sides?.find(({participantId:l})=>l),m=p.sides.find(l=>l?.sideNumber===p.winningSide);if(m||d){let{participantId:l}=m||(d??{});l&&!r.includes(l)&&n.push(l)}}}}function Fz({roundRobinSourceLinks:t,assignedParticipantIds:e,qualifyingParticipantIds:r,drawDefinition:n}){for(let o of t){let i=n?.structures?.find(u=>u.structureId===o.source.structureId);if(i?.stage!==rt||!Bo({structureId:o.source.structureId,drawDefinition:n}))continue;let{positionAssignments:a}=yt({structure:i}),c=a?.map(u=>{let p=u.participantId,d=$t({element:u,attribute:"tally",name:to});return d?{participantId:p,groupOrder:d?.groupOrder}:{}}).filter(({groupOrder:u,participantId:p})=>u===1&&!e.includes(p)).map(({participantId:u})=>u)??[];c&&r.push(...c)}}function HA({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=HA({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=HA({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 WA({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:_y};if(!Array.isArray(n))return{error:va};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=TM({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 TM({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:_y};if(!n)return{error:Ma};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s??{};if(u){let d=u.split(".");o.push(...HA({significantCharacters:p,value:n,accessors:d}))}else if(a){let d=s?.includeIds,m=(e?.[a]??[]).filter(l=>!d||d.includes(l));m?.length&&r?.length&&m.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(d=>{c[d].includes(n.participantId)&&o.push(d)})}),{values:ct(o)}}function yM({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}=TM({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function V0({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 B0(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=V0(t);return r.map(s=>{let a=e.filter(d=>s.includes(d)),c=i(a),p=a.filter(d=>!c.includes(d)).filter(d=>{let m=G0(d);return!n[m]?.includesGroupsToAvoid});return{unassigned:a,unpaired:c,pairedNoConflict:p}});function i(s){return s.filter(c=>!a(c));function a(c){let u=G0(c);return!s.includes(u)}}}function H0(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=V0(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 G0(t){return Number(t%2?t+1:t-1)}function W0({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function j0({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?H0({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):B0({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}));if(i){let a=s.map(p=>p.map(d=>d.unassigned).filter(d=>d?.length)).filter(p=>p?.length).sort((p,d)=>(d.length||0)-(p.length||0)),c=s.map(p=>p.map(d=>d.unpaired).filter(d=>d?.length)).filter(p=>p?.length),u=s.map(p=>p.map(d=>d.pairedNoConflict).filter(d=>d?.length)).filter(p=>p?.length).sort((p,d)=>(d.length||0)-(p.length||0));return{unassigned:a,unpaired:c,pairedNoConflict:u}}else{let a=s.map(p=>p.map(d=>d.unassigned).filter(d=>d?.length)).filter(p=>p?.length),c=s.map(p=>p.map(d=>d.unpaired).filter(d=>d?.length)).filter(p=>p?.length),u=s.map(p=>p.map(d=>d.pairedNoConflict).filter(d=>d?.length)).filter(p=>p?.length);return{unassigned:a,unpaired:c,pairedNoConflict:u}}}function jA({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function Y0({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:r=!0,allGroups:n,groupKey:o,random:i}){let s=Object.assign({},...Object.keys(n).map(d=>[d,n[d].filter(m=>e.includes(m))]).filter(d=>d[1].length).map(([d,m])=>({[d]:m}))),a=Object.keys(s).reduce((d,m)=>s[m].length>d?s[m].length:d,0),c=Object.keys(s).filter(d=>s[d].length===a),u=r?Dn(c,i):Dn(Object.keys(s),i);return o=t&&s[o]?.length?o:u,{participantId:o&&s[o]?Dn(s[o],i):Dn(e,i),groupKey:o}}function q0({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 $0({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a,random:c}){let p=o.reduce((U,b)=>b.length>U?b.length:U,0)<=2,d=jA({positionAssignments:t,participantIds:e}),m=q0({positionAssignments:t,drawPositionGroups:o}),{participantId:l,groupKey:f}=Y0({targetParticipantIds:d,useSpecifiedGroupKey:p,allGroups:s,groupKey:a,random:c}),g=W0({participantId:l,allGroups:s}),I=j0({positionAssignments:t,isRoundRobin:p,selectedParticipantGroups:g,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:m}),{unassigned:h,unpaired:S,pairedNoConflict:T}=I,y=T?.length&&T[0],E=S?.length&&S[0],A=i&&y?y:E,N=i?E:y,D=A?.length&&A||N?.length&&N,R;if(D?.length){let U=Sr(D,c);R=Sr(U,c)}else{let U=Sr(h[0],c);R=Sr(U,c)}return{newGroupKey:f,selectedParticipantId:l,targetDrawPosition:R}}function fS({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=nS({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{we(s[a[0]].values??[],s[a[1]].values??[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{we(n[0]?.values??[],n[1]?.values??[])&&(r.push(n),n.conflict=!0)}),r}function kz(t,e){let r=t.find(n=>n.includes(e));if(r)return r.find(n=>n!==e)}function K0(t,e){return t.find(r=>r.drawPosition===e)}function Gz({moveableParticipant:t,possibleDrawPosition:e,positionedParticipants:r,drawPositionGroups:n,isRoundRobin:o,getAvoidanceConflicts:i}){let s=kz(n,e),a=K0(r,s),u=i({isRoundRobin:o,groupedParticipants:[[t,a]]}),d=[K0(r,e),a],m=i({isRoundRobin:o,groupedParticipants:[d]});return!u.length&&!m.length}function z0({positionedParticipants:t,potentialDrawPositions:e,drawPositionGroups:r,avoidanceConflicts:n,isRoundRobin:o}){return n.flatMap(i=>{let s=i.map(c=>c.drawPosition);return i.filter(c=>e.includes(c.drawPosition)).map(c=>{let p=e.filter(d=>!s?.includes(d)).filter(d=>Gz({moveableParticipant:c,possibleDrawPosition:d,positionedParticipants:t,drawPositionGroups:r,isRoundRobin:o,getAvoidanceConflicts:fS}));if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)})}function EM(t){let{initialPositionAssignments:e,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:o,drawPositionGroups:i,policyAttributes:s,idCollections:a,allGroups:c,random:u}=t,p=[],d,m=Math.min(...(i??[]).map(y=>y?.length).filter(Boolean)),l=m>2,f=q(e,!1,!0).filter(y=>!y.qualifier),g=e.filter(y=>!y.participantId&&!y.qualifier&&(!y.bye||o?.includes(y.drawPosition))).map(y=>y.drawPosition);J(0,n).forEach(()=>{let{newGroupKey:y,selectedParticipantId:E,targetDrawPosition:A}=$0({...t,candidatePositionAssignments:f,allGroups:c,groupKey:d});d=y,f.forEach(N=>{N.drawPosition===A&&(N.participantId=E)})});let I=yM({candidatePositionAssignments:f,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),h=Ae(I,m),S=fS({groupedParticipants:h,isRoundRobin:l}),T=0;for(;T<20&&S.length;){let y=z0({positionedParticipants:I,potentialDrawPositions:g,avoidanceConflicts:S,drawPositionGroups:i,isRoundRobin:l});if(y.length){let E=Vz({candidatePositionAssignments:f,swapOptions:y,random:u});E.error&&console.log({result:E}),I=yM({candidatePositionAssignments:f,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),h=Ae(I,m),S=fS({groupedParticipants:h,isRoundRobin:l}),T++}else T=20}return f.forEach(y=>{if(y.bye&&y.participantId){let E=My;p.push(E)}if(y.qualifier&&y.participantId){let E=My;p.push(E)}}),{positionAssignments:f,conflicts:S.length,groupedParticipants:h,errors:p}}function Vz({candidatePositionAssignments:t,swapOptions:e,random:r}){let n=Sr(e,r);if(!n)return{error:{message:"No swap options"}};let o=n.drawPosition,i=Sr(n.possibleDrawPositions,r),s=t.find(p=>p.drawPosition===o),a=t.find(p=>p.drawPosition===i)??{},c={participantId:a?.participantId,qualifier:a?.qualifier,bye:a?.bye},u={participantId:s.participantId,qualifier:s.qualifier,bye:s.bye};return Object.assign(s,c),Object.assign(a,u),{...P}}function Q0({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unseededByePositions:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:p,drawSize:d,event:m,random:l}){if(!p)return{error:XU};let{candidatesCount:f=1,policyAttributes:g,targetDivisions:I}=p,{roundsToSeparate:h}=p,S="randomUnseededSeparation",{structure:T}=tt({drawDefinition:i,structureId:u}),{matchUps:y}=ht({provisionalPositioning:t,matchUpsMap:c,structure:T,event:m});if(I&&rn(I)&&!h){let B=OL(I)||0,$=y.reduce((H,z)=>Math.max(Number(z.roundNumber),H),0);h=$<B?1:$-B+1}let{positionAssignments:E}=pe({structure:T}),A=qp({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,N=E?.filter(B=>!B.participantId),D=E?.map(B=>B.drawPosition),R=T?.structureType===Ie,U=R?{structure:T,matchUps:y,allDrawPositions:D,roundsToSeparate:h}:{matchUps:y,allDrawPositions:D,roundsToSeparate:h},{drawPositionGroups:b,drawPositionChunks:C}=R?Bz(U):Hz(U),_={groupParticipants:a.filter(B=>B.participantType===zr).map(B=>B.participantId),teamParticipants:a.filter(B=>B.participantType===bt).map(B=>B.participantId),pairParticipants:a.filter(B=>B.participantType===dt).map(B=>B.participantId)},v=WA({targetParticipantIds:e,policyAttributes:g,idCollections:_,participants:a});if(v.error)return M({result:v,stack:S});let x=Object.assign({},...e.map(B=>{let $=Object.keys(v).filter(H=>(v[H]??[]).includes(B));return{[B]:$}})),w=jA({participantIds:e,positionAssignments:E});if(w.length>(N?.length||0))return{error:kI};let F,L=w.length,k=J(0,f).map(()=>EM({initialPositionAssignments:E,participantsWithGroupings:A,unseededParticipantIds:e,opponentsToPlaceCount:L,pairedPriority:!1,unseededByePositions:n,participantIdGroups:x,drawPositionChunks:C,drawPositionGroups:b,policyAttributes:g,idCollections:_,allGroups:v,drawSize:d,random:l}));if(F=k.reduce((B,$)=>!B||($.conflicts||0)<(B.conflicts||0)?$:B,void 0),!F||F.conflicts){let B=J(0,f).map(()=>EM({initialPositionAssignments:E,participantsWithGroupings:A,unseededParticipantIds:e,opponentsToPlaceCount:L,pairedPriority:!0,unseededByePositions:n,participantIdGroups:x,drawPositionChunks:C,drawPositionGroups:b,policyAttributes:g,idCollections:_,allGroups:v,drawSize:d,random:l}));F=k.concat(...B).filter(H=>!H.errors?.length).reduce((H,z)=>!H||(z.conflicts||0)<(H.conflicts||0)?z:H,void 0)}if(!F)return{error:Jd};let G=new Set((yt({structure:T})?.positionAssignments??[]).filter(B=>B.participantId).map(B=>B.participantId)),V=F.positionAssignments.filter(B=>!G.has(B.participantId));for(let B of V)if(B.bye){let $=Mr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:m,...B});if($.error)return M({result:$,stack:S})}else if(B.participantId){let $=xn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:m,...B});if($.error)return M({result:$,stack:S,context:{assignment:B}})}return{...P}}function Bz(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function Hz({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(m=>m.roundNumber===1).map(m=>m.drawPositions),o=n.flat().sort(ee),i=Math.max(...o),s=t.filter(m=>m>i),a=o.length,u=J(a===2?1:2,a).filter(m=>m===wl(m)),d=u.slice(0,e||u.length).reverse().map(m=>Ae(o,m));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:d}}function J0({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:r,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,structure:p,drawSize:d,event:m,random:l}){let f="positionUnseededParticipants";p||({structure:p}=tt({drawDefinition:i,structureId:u})),u||({structureId:u}=p);let{positionAssignments:g}=pe({structure:p}),{seedAssignments:I}=Dr({provisionalPositioning:t,drawDefinition:i,structure:p}),h=I?.map(C=>C.participantId).filter(Boolean),{stage:S,stageSequence:T}=p,y=S===rt?$t({element:p,attribute:"roundTarget",name:Xr}):void 0,A=ns({provisionalPositioning:t,drawDefinition:i,stageSequence:T,entryStatuses:rs,structureId:u,roundTarget:y,stage:S}),D=A.filter(C=>!h?.includes(C.participantId)).map(C=>C.participantId),R=g?.filter(C=>!C.participantId&&!C.bye&&!C.qualifier).map(C=>C.drawPosition);if(!n&&D.length>(R?.length||0))return M({result:{error:kI},context:{unseededParticipantsCount:D.length,unfilledDrawPositionsCount:R?.length},stack:f});let{appliedPolicies:U}=gt({tournamentRecord:o,drawDefinition:i,event:m}),b=U?.[Nc];if(p.stage===Vt){let C=A.reduce((_,v)=>(_[v.groupingValue]||(_[v.groupingValue]=[]),_[v.groupingValue].push(v.participantId),_),{});Object.keys(C).length&&(b??={policyName:"Playoff Avoidance"},b.policyAttributes??=[],b.policyAttributes.push({groupings:C}))}return b&&a?Q0({provisionalPositioning:t,unseededParticipantIds:D,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:b,drawSize:d,entries:A,random:l}):Wz({provisionalPositioning:t,unseededParticipantIds:D,inContextDrawMatchUps:e,unfilledDrawPositions:R,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:d,event:m,random:l})}function Wz({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unfilledDrawPositions:n,multipleStructures:o,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,matchUpsMap:c,structureId:u,drawSize:p,event:d,random:m}){let l=p>2?dr(n,m):n.reverse();for(let f of e){let g=l.pop();if(!o||g){let I=xn({provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,participantId:f,drawPosition:g,matchUpsMap:c,structureId:u,event:d});if(I?.error&&console.log("!!!!!",{result:I}),I?.error)return M({result:I,stack:"randomUnseededDistribution"})}}return{...P}}function X0(t){let{random:e}=t,r=t.structure??tt(t).structure,n="positionQualifiers",o=[];if(r.stage===je)return M({result:{error:hc},stack:n});let{unplacedRoundQualifierCounts:i,positionAssignments:s,roundDrawPositions:a}=jz(t);for(let c of Object.keys(i)){let u=s?.filter(p=>a[c].includes(p.drawPosition)&&!p.participantId&&!p.qualifier&&!p.bye).map(p=>p.drawPosition);if(i[c]>(u||0))return M({result:{error:FI},context:{unfilledDrawPositions:u},stack:n});J(0,i[c]).forEach(()=>{let p=Sr(u,e);o.push(p),s?.forEach(d=>{d.drawPosition===p&&(d.qualifier=!0,delete d.participantId,delete d.bye)})})}return{...P,qualifierDrawPositions:o}}function jz({drawDefinition:t,structure:e,structureId:r,qualifiersCount:n}){e||({structure:e}=tt({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:o}=pe({structure:e}),{stage:i,stageSequence:s}=e,{qualifiersCount:a,roundQualifiersCounts:c}=nd({drawDefinition:t,stageSequence:s,structureId:r,stage:i}),u=a||n||0,p=Object.keys(c??{}).length?c:u?{1:u}:{},m=(p?Object.keys(p):[]).map(y=>st(y)),{matchUps:l}=ht({structure:e}),{roundProfile:f}=_e({matchUps:l}),g=Object.assign({},...m.filter(y=>f?.[y]).map(y=>({[y]:f?.[y]?.drawPositions?.filter(Boolean)??[]}))),I=o?.filter(y=>y.qualifier).map(y=>y.drawPosition),h=(u??0)-(I?.length??0),S=I?.length;return{unplacedRoundQualifierCounts:Object.assign({},...m.map(y=>{let E=o?.filter(A=>A.qualifier&&g[y]?.drawPositions?.includes(A.drawPosition)).map(A=>A.drawPosition);return{[y]:(p?.[y]??0)-(E?.length??0)}})),unplacedQualifiersCount:h,placedQualifiersCount:S,roundQualifiersCounts:p,positionAssignments:o,roundDrawPositions:g,qualifiersCount:u}}function AM({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,groupsCount:u,structureId:p,matchUpsMap:d,structure:m,random:l,event:f}){let g=[],I=[],h=0;if(m||({structure:m}=tt({drawDefinition:i,structureId:p})),p||(p=m?.structureId),n??=gt({drawDefinition:i}).appliedPolicies,!o){let S=m&&Ai({provisionalPositioning:t,appliedPolicies:n,drawDefinition:i,seedingProfile:s,structure:m,random:l});S?.error&&I.push(S.error),o=S?.validSeedBlocks}return u=u??o?.length??0,J(0,u).forEach(()=>{if(h<(u||0)){let S=Yz({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,structureId:p,matchUpsMap:d,random:l,event:f});S?.success&&(h++,g.push(...S.seedPositions??[])),S.error&&I.push({seedPositionError:S.error})}}),I.length?{error:I}:{...P,seedPositions:g}}function Yz({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,participants:s,structureId:a,matchUpsMap:c,random:u,event:p}){let{unplacedSeedParticipantIds:d,unfilledPositions:m}=NA({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,random:u,event:p}),{appliedPolicies:l}=gt({drawDefinition:n}),f=l?.[Nc];f?.policyAttributes&&s&&d?.length>2&&qz({unplacedSeedParticipantIds:d,unfilledPositions:m,policyAttributes:f.policyAttributes,participants:s});let g=[];for(let I of d){let h=m.pop();if(!h)return{error:Ra};g.push(h);let S=xn({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,participantId:I,seedBlockInfo:i,drawPosition:h,matchUpsMap:c,structureId:a,event:p});if(!S.success)return S}return{...P,seedPositions:g}}function qz({unplacedSeedParticipantIds:t,unfilledPositions:e,policyAttributes:r,participants:n}){let o=WA({targetParticipantIds:t,policyAttributes:r,participants:n});if("error"in o)return;let s=Object.values(o).filter(l=>l.length>1);if(!s.length)return;let a=e.length;if(a<2)return;let c=Math.max(...e),u=Math.min(a,Math.max(2,s.length)),p=Math.ceil(c/u),d=l=>Math.floor((l-1)/p),m=t.map((l,f)=>{let g=e[a-1-f];return g===void 0?f:d(g)});for(let l of s){let f=l.map(y=>t.indexOf(y)),g=f.map(y=>m[y]);if(!(g.length!==new Set(g).size))continue;let h=new Set(l),S=t.map((y,E)=>h.has(y)?-1:E).filter(y=>y>=0),T=new Set;for(let y of f){let E=m[y];if(!T.has(E)){T.add(E);continue}let A=S.find(N=>!T.has(m[N]));if(A!==void 0){let N=t[y];t[y]=t[A],t[A]=N;let D=m[y];m[y]=m[A],m[A]=D,T.add(m[y]);let R=S.indexOf(A);R>=0&&S.splice(R,1)}}}}function Z0({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=pe({structure:r}),{seedAssignments:o}=Dr({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 t1({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:r,random:n}){let o=n??Math.random,i=[];e.forEach(a=>$z(a,r,i,t,o));let s=i.map(a=>Array.isArray(a)?dr(a,n):a).flat(1/0);return Py(r)&&e.map(c=>c.seedNumbers[0]).includes(r)?t:s}function $z(t,e,r,n,o){if(e-r.length>t.drawPositions.length)r.push(...t.drawPositions);else{let s=PM(Ae(t.drawPositions,2));Kz(s,r,n,o)}}function Kz(t,e,r,n){let o,i=r[e.length];for(;o=gS(t,i,n);)e.push(o),i=r[e.length]}function gS(t,e,r){return Array.isArray(t)&&t.length!==2?t.pop():Array.isArray(t[0])?Qz(t,e,r):zz(t,e,r)}function zz(t,e,r){return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(r())?t.pop():t.shift()}function Qz(t,e,r){let n=t[0].flat(1/0).length,o=t[1].flat(1/0).length;if(n===o){let i=t[0].flat(1/0).includes(e)?t[0]:t[1];return gS(e?i:t[Math.round(r())],e,r)}return n<o?gS(t[1],e,r):gS(t[0],e,r)}function PM(t){let e=Math.floor(t.length/2);return t.length>2?[PM(t.slice(0,e)),PM(t.slice(e))]:t}function r1({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=Ai({provisionalPositioning:t,appliedPolicies:r,drawDefinition:n,seedingProfile:o,structure:a}));let{isFeedIn:c,isLuckyStructure:u,isContainer:p}=i,{validSeedBlocks:d}=i;r?.seeding?.containerByesIgnoreSeeding&&(d=[]);let m=Z0({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=ct([].concat(...e.map(E=>E.drawPositions))),f=m.filter(E=>l.includes(E.drawPosition)),g=(E,A)=>Ou(E.seedValue)-Ou(A.seedValue),h=d.reduce((E,A)=>{let N=f.filter(D=>A.drawPositions?.includes(D.drawPosition)).sort(g);return E.concat(...N)},[]).map(E=>E.drawPosition),S=t1({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:d,byesToPlace:s}),T=e1({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),y=e1({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:m,isContainer:p,isFeedIn:c}}function e1({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 n1({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:r,appliedPolicies:n,drawDefinition:o,seedLimit:i,structure:s,isFeedIn:a,random:c}){let u=n?.seeding?.seedingProfile,p=s.stage===rt,{positionAssignments:d}=pe({structure:s}),m=d?.filter(w=>w.participantId).map(w=>w.drawPosition),l={isCollectionMatchUp:!1},{matchUps:f,roundMatchUps:g}=ht({provisionalPositioning:t,matchUpFilters:l,structure:s}),I=g?.[1]??[],h=s.structureType===Ie?f:I,S=ct(h.flatMap(w=>w.drawPositions)),T=Math.min(...S)-1,y=m?.filter(w=>S.includes(w)),E=w=>{let F=Math.ceil(w.length/2),L=[w.slice(0,F),w.slice(F)],k=L.map(Q=>Q.flat(1/0).flat().length),G=Math.min(...k.flat(1/0)),V=Math.max(...k.flat(1/0)),B=k.indexOf(V),$=G!==V,H=dr(L,c),[z,W]=!G||$?[L[B],L[1-B]]:[H[0],H[1]];return{greaterHalf:z,lesserHalf:W}},A=w=>{let{greaterHalf:F,lesserHalf:L}=E(w),{greaterHalf:k,lesserHalf:G}=E(F),B=dr(k.flat(1/0),c).pop(),$=k.flat().filter(z=>z!==B);return{newlyFilteredChunks:[...L,...G,$],drawPosition:B}},N=w=>!e.includes(w),D=w=>!y?.includes(w),R=w=>{let L=Ae(w.sort(ee),Math.ceil(w.length/4)).map(V=>V.filter(D)),k=L.flat(1/0).flat().length,G=[];for(let V=0;V<k;V++){let{newlyFilteredChunks:B,drawPosition:$}=A(L);G.push($),L=B}return G},{validSeedBlocks:U}=Ai({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),b=U?.map(w=>w.drawPositions?.map(F=>F+T)),C;if(a){let w=S.length,{seedBlocks:F}=iS({cluster:[fu,pm].includes(vm(u)),participantsCount:w});C=F.map(k=>k.map(G=>G+T)).map(R).filter(k=>k.length)}else p?C=b?.map(w=>w.filter(D)):C=b?.map(R).filter(w=>w.length);let _=h.map(w=>w.drawPositions).map(w=>w?.sort((F,L)=>F-L)).filter(w=>w?.[0]+1===w?.[1]),v=w=>_.reduce((F,L)=>L.includes(w)?L.reduce((k,G)=>G===w?k:G,void 0):F,void 0),x=C.map(w=>w.map(v)).flat(1/0).filter(D).filter(N).filter(Boolean);if(p&&!s.structures){let w=i%4,F=x.slice(0,w),L=g[s.roundLimit]?.length,k=Ae(x.slice(w),L).flatMap(G=>dr(G,c));x=F.concat(k)}return{unseededByePositions:x}}function o1({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=ht({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]??[],u=n?.structureType===Ie,p=u?s:c,d=u?n?.structures?.length||0:s.length,{structureId:m,stage:l,stageSequence:f}=n,g=ns({entryStatuses:yr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:m,stage:l}),{qualifiersCount:I}=nd({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:m,stage:l}),h=g.length+(I??0),{positionAssignments:S,unassignedPositions:T}=pe({structure:n}),y=T?.map(U=>U.drawPosition),E=S?.filter(U=>U.bye).length,A=S?.filter(U=>U.bye).map(U=>U.drawPosition),N=p.map(U=>U.drawPositions).filter(U=>U?.reduce((b,C)=>!A?.includes(C)&&b,!0)).flat(1/0).filter(U=>y?.includes(U)),D=S?.length,R=D?D-h:0;return R>d&&n.stageSequence===1&&n.stage!==je&&(R=d),{placedByes:E,byesCount:R,relevantMatchUps:p,placedByePositions:A,roundMatchUps:a,positionsToAvoidDoubleBye:N}}function NM({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,seedBlockInfo:o,seedingProfile:i,matchUpsMap:s,structureId:a,structure:c,seedLimit:u,seedsOnly:p,event:d,random:m}){c||({structure:c}=tt({drawDefinition:n,structureId:a})),a||(a=c?.structureId);let l=!(c?.structures??c?.stage===rt),{byesCount:f,placedByes:g,relevantMatchUps:I}=o1({provisionalPositioning:t,drawDefinition:n,matchUpsMap:s,structure:c,event:d}),h=f-(g||0);if(h<=0)return{...P};if(cn(n.drawType)){let _=(I??[]).flatMap(w=>w.drawPositions??[]).filter(Boolean),v=new Set(c?.positionAssignments?.filter(w=>w.participantId).map(w=>w.drawPosition)??[]),x=_.filter(w=>!v.has(w)).slice(0,h);for(let w of x){let F=Mr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:w,matchUpsMap:s,structureId:a,structure:c,event:d});if(F?.error)return F}return{...P,byeDrawPositions:x}}let{strictSeedOrderByePositions:S,blockSeedOrderByePositions:T,isLuckyStructure:y,isFeedIn:E}=r1({provisionalPositioning:t,relevantMatchUps:I,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:h,structure:c}),A=c?.structureType&&[Ie,gu].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,N=l&&T?.length?T:S,{unseededByePositions:D}=n1({provisionalPositioning:t,seedOrderByePositions:N,isLuckyStructure:y,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:E,random:m}),R=_=>_%2,U=(_,v)=>(_??[]).every(x=>R(x)?v!==x+1:v!==x-1),b=N.flat();if(!p)for(;D.length;){let _=D.find(v=>U(b,v));_?(b.push(_),D=D.filter(v=>v!==_)):(b.push(...D),D=[])}A&&(b=dr(b,m),We({ignoreSeededByes:A})&&console.log({byePositions:b}));let C=b.slice(0,h);for(let _ of C){let v=Mr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:_,matchUpsMap:s,structureId:a,structure:c,event:d});if(v?.error)return v}return{...P,unseededByePositions:D,byeDrawPositions:C}}function IS(t,e){return e||QI(),M({result:t,stack:"automatedPositioning"})}function Jz(t,e){return e||QI(),t}function Xz(t,e,r,n){let o=tt({drawDefinition:e,structureId:r});if(o.error)return{error:o.error};let i=o.structure;if(!i)return{error:Pt};let s=t.appliedPolicies||gt({drawDefinition:e,structure:i,event:n})?.appliedPolicies,{qualifiersCount:a}=nd({stageSequence:i.stageSequence,provisionalPositioning:t.provisionalPositioning,stage:i.stage,drawDefinition:e,structureId:r}),c=a||t.qualifiersCount||0,u=rs,p=ns({stageSequence:i.stageSequence,provisionalPositioning:t.provisionalPositioning,stage:i.stage,placementGroup:t.placementGroup,drawDefinition:e,entryStatuses:u,structureId:r});return{structure:i,appliedPolicies:s,qualifiersCount:c,entries:p}}function Zz({placeByes:t,provisionalPositioning:e,tournamentRecord:r,appliedPolicies:n,drawDefinition:o,seedBlockInfo:i,matchUpsMap:s,structure:a,seedLimit:c,seedsOnly:u,event:p,structureSeedingProfile:d,seedingProfile:m,inContextDrawMatchUps:l,participants:f,positioningReport:g,random:I}){let h=t?NM({provisionalPositioning:e,tournamentRecord:r,appliedPolicies:n,drawDefinition:o,seedBlockInfo:i,matchUpsMap:s,structure:a,seedLimit:c,seedsOnly:u,random:I,event:p}):void 0;if(h?.error)return{error:h.error};let S=h?.unseededByePositions;return g.push({action:"positionByes",unseededByePositions:S}),h=AM({seedingProfile:d?{positioning:d}:m,provisionalPositioning:e,inContextDrawMatchUps:l,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:i.validSeedBlocks,drawDefinition:o,seedBlockInfo:i,participants:f,matchUpsMap:s,structure:a,random:I,event:p}),h.error?{error:h.error}:(g.push({seedPositions:h.seedPositions,action:"positionSeedBlocks"}),{unseededByePositions:S})}function t6({drawType:t,structureSeedingProfile:e,seedingProfile:r,provisionalPositioning:n,inContextDrawMatchUps:o,tournamentRecord:i,appliedPolicies:s,validSeedBlocks:a,drawDefinition:c,seedBlockInfo:u,participants:p,matchUpsMap:d,structure:m,event:l,placeByes:f,seedLimit:g,seedsOnly:I,positioningReport:h,random:S}){let T;if(!cn(t)){let A=AM({seedingProfile:e?{positioning:e}:r,provisionalPositioning:n,inContextDrawMatchUps:o,tournamentRecord:i,appliedPolicies:s,validSeedBlocks:a,drawDefinition:c,seedBlockInfo:u,participants:p,matchUpsMap:d,structure:m,random:S,event:l});if(A.error)return{error:A.error};h.push({action:"positionSeedBlocks",seedPositions:A.seedPositions})}let y=f?NM({provisionalPositioning:n,tournamentRecord:i,appliedPolicies:s,drawDefinition:c,seedBlockInfo:u,matchUpsMap:d,structure:m,seedLimit:g,seedsOnly:I,random:S,event:l}):void 0;return y?.error?{error:y.error}:(T=y?.unseededByePositions,h.push({action:"positionByes",byeDrawPositions:y?.byeDrawPositions,unseededByePositions:T}),{unseededByePositions:T})}function e6({seedsOnly:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structure:u,positionQualifiers:p,positionUnseededParticipants:d,provisionalPositioning:m,unseededByePositions:l,multipleStructures:f,qualifiersCount:g,structureId:I,drawSize:h,event:S,positioningReport:T,conflicts:y,random:E}){if(t)return{};let A=p({inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,qualifiersCount:g,seedBlockInfo:s,participants:a,matchUpsMap:c,structure:u,random:E});return A.error?{error:A.error}:(A.conflicts&&(y.qualifierConflicts=A.conflicts),T.push({action:"positionQualifiers",qualifierDrawPositions:A.qualifierDrawPositions}),A=d({provisionalPositioning:m,inContextDrawMatchUps:e,unseededByePositions:l,multipleStructures:f,tournamentRecord:r,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:I,structure:u,drawSize:h,random:E,event:S}),A.error?{error:A.error}:(A.conflicts&&(y.unseededConflicts=A.conflicts),T.push({action:"positionUnseededParticipants"}),{}))}function Gu(t){let{drawDefinition:e}=t,{applyPositioning:r=!0,provisionalPositioning:n,multipleStructures:o,placeByes:i=!0,tournamentRecord:s,seedingProfile:a,structureId:c,seedLimit:u,seedsOnly:p,drawType:d,drawSize:m,random:l,event:f}=t,g=[];r||(JR(),e=q(e,!1,!0));let{structure:I,appliedPolicies:h,qualifiersCount:S,entries:T,error:y}=Xz(t,e,c,f);if(y)return IS(y,r);if(!T?.length&&!S)return Jz({...P},r);let E=t.matchUpsMap??ye({drawDefinition:e}),A=t.inContextDrawMatchUps??re({inContext:!0,drawDefinition:e,matchUpsMap:E})?.matchUps,N=Ai({provisionalPositioning:n,appliedPolicies:h,drawDefinition:e,seedingProfile:a,structure:I,random:l});if(N.error)return IS(N,r);let{validSeedBlocks:D}=N;g.push({validSeedBlocks:D});let R=t.participants||(s?Nt({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]),U;if(vm(I.seedingProfile||a)===qi){let v=Zz({placeByes:i,provisionalPositioning:n,tournamentRecord:s,appliedPolicies:h,drawDefinition:e,seedBlockInfo:N,matchUpsMap:E,structure:I,seedLimit:u,seedsOnly:p,event:f,structureSeedingProfile:I.seedingProfile,seedingProfile:a,inContextDrawMatchUps:A,participants:R,positioningReport:g,random:l});if(v?.error)return IS(v.error,r);U=v.unseededByePositions}else{let v=t6({drawType:d,structureSeedingProfile:I.seedingProfile,seedingProfile:a,provisionalPositioning:n,inContextDrawMatchUps:A,tournamentRecord:s,appliedPolicies:h,validSeedBlocks:D,drawDefinition:e,seedBlockInfo:N,participants:R,matchUpsMap:E,structure:I,event:f,placeByes:i,seedLimit:u,seedsOnly:p,positioningReport:g,random:l});if(v?.error)return IS(v.error,r);U=v.unseededByePositions}let b={},C=e6({seedsOnly:p,inContextDrawMatchUps:A,tournamentRecord:s,appliedPolicies:h,validSeedBlocks:D,drawDefinition:e,seedBlockInfo:N,participants:R,matchUpsMap:E,structure:I,positionQualifiers:X0,positionUnseededParticipants:J0,provisionalPositioning:n,unseededByePositions:U,multipleStructures:o,qualifiersCount:S,structureId:c,drawSize:m,event:f,positioningReport:g,conflicts:b,random:l});if(C?.error)return IS(C.error,r);let{positionAssignments:_}=yt({drawDefinition:e,structure:I});return Lt({drawDefinition:e,structureIds:[c]}),r||QI(),{positionAssignments:_,conflicts:b,...P,positioningReport:g}}function Ja(t){let{applyPositioning:e=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,placeByes:a,seedsOnly:c,random:u}=t;if(!o)return{error:Cr};if(!Bo({drawDefinition:o,structureId:s})&&!r)return{error:yI};let d=GA({drawDefinition:o,structureId:s}).playoffStructures?.sort((f,g)=>Ph(f)-Ph(g)),m=[],l=[];if(d)for(let f of d){let{structureId:g}=f,I=Gu({structureId:g,provisionalPositioning:r,applyPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,placeByes:a,seedsOnly:c,random:u});if(I.error)return I;I.positionAssignments&&m.push({positionAssignments:I.positionAssignments,structureId:g}),I.positioningReport&&l.push(I.positioningReport)}return{...P,structurePositionAssignments:m,positioningReports:l}}function DM({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:K};if(!o)return{error:mn};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:Hr};let{structure:c}=tt({drawDefinition:r,structureId:o});if(!c)return{error:Pt};if(!(!t||He(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>He(l)&&st(l)>0)))return{error:O};let{seedAssignments:p}=Dr({drawDefinition:r,structure:c}),d=p?.map(l=>l.seedNumber),m=p?.find(l=>l.participantId===n);if(m){let l=typeof i=="string"?i.includes("-")&&i.split("-").map(f=>parseInt(f)).join("-")||parseInt(i)>0&&parseInt(i)||"":i&&i>0&&i||"";m.seedValue=l}else{let f={seedNumber:Math.max(0,...d??[])+1,participantId:n};i&&(f.seedValue=i),c.seedAssignments??=[],c.seedAssignments.push(f)}return ff({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...P}}function UM({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>It(r)))&&M({result:{error:O},context:{orderMap:e}}),t.structures??=[],t.structures.forEach(r=>{let n=e[r.structureId];n&&(r.structureOrder=n)}),t.structures.sort((r,n)=>Jc(r.structureOrder)-Jc(n.structureOrder)),{...P}):{error:K}}function cd({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=r6({links:r,initStructureProfile:o,sourceStructureIds:i,hasDrawFeedProfile:s});n6(n);let c=s6(n),u=a.length;J(0,Math.ceil(u/2)).forEach(()=>{a=J(0,u).map(I=>{let h=a[I],S=a.reduce((T,y)=>we(h,y)?T.concat(...y):T,[])??[];return ct(h.concat(...S))})});let p=a[0],d=(I,h)=>Ht(I,h).length===I.length,m=a.slice(1).reduce((I,h)=>I&&d(h,p),!0),l=[p].filter(Boolean),f=[p].filter(Boolean);a6({structures:e,structureGroups:l,linkCheck:f});let g=m&&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 r6({links:t,initStructureProfile:e,sourceStructureIds:r,hasDrawFeedProfile:n}){return t.map(o=>{let i=o.source.structureId,s=o.target.structureId,a=e(i),c=e(s);return[$i,Je,dm,qi].includes(o.target.feedProfile)?(a?.targets.push(s),c?.sources.push(i)):o.target.feedProfile===ln&&(c?.drawSources.push(i),a?.drawTargets.push(s)),n[s]=n[s]||o.target.feedProfile===ln,r[s]=ct([...r[s]??[],i]).filter(Boolean),[o.source.structureId,o.target.structureId]})}function n6(t){for(let e of t.keys()){let r=t.get(e);r&&(o6(r,t),i6(r,t))}}function o6(t,e){let r=t.targets??[];for(;r.length;){let n=r.pop(),o=n&&e[n];o?.targets?.length?r.push(...o.targets):o&&(t.rootStage=o.stage)}t.rootStage??=t.stage}function i6(t,e){if(t.targets?.length)return;let r=t.sources??[];for(;r.length;){let n=r.pop(),o=n&&e[n];if(o?.sources?.length){for(let i of o.sources)t.progeny?.includes(i)||t.progeny?.push(i);r.push(...o.sources)}}}function s6(t){let e=0;for(let r of t.keys()){let n=t.get(r);if(n?.rootStage!==rt)continue;let o=[n.drawTargets?.[0]],i=0;for(;o.length;){i+=1;let s=o.pop(),a=s?t.get(s):void 0;a?.drawTargets?.length&&o.push(a.drawTargets[0])}n.distanceFromMain=i,i>e&&(e=i)}return e}function a6({structures:t,structureGroups:e,linkCheck:r}){t.forEach(n=>{let{structureId:o,stage:i}=n;e.find(a=>a.includes(o))||(e.push([o]),i!==Qe&&r.push([o]))})}function YA({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=cd({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...P}}function hS(t){let e=X(t,[{[Z]:!0,[zt]:!0}]);if(e.error)return e;let{tournamentRecord:r,drawDefinition:n,structure:o,link:i}=t;return c6({tournamentId:r.tournamentId,drawDefinition:n,structure:o,link:i})}function c6(t){let e=X(t,[{[zt]:!0,[Ec]:!0},{link:!0,[qe]:$r,[UU]:AI}]);if(e.error)return e;let{drawDefinition:r,tournamentId:n,structure:o,eventId:i,link:s}=t,a=s.target.structureId,c=tt({drawDefinition:r,structureId:a});if(c.error)return M({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:c});r.structures??=[],r.links??=[],r.structures.push(o),r.links.push(s),YA({drawDefinition:r});let u=ht({structure:o})?.matchUps??[];return zo({drawDefinition:r,tournamentId:n,matchUps:u,eventId:i}),Lt({drawDefinition:r,structureIds:[o.structureId]}),{...P}}function RM({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:O};if(!t)return{error:K};let r=Object.assign({},...e.map(n=>{if(!St(n))return;let{structureId:o,structureName:i}=n??{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:nt};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{...P}}function SS({drawDefinition:t,timeItem:e}){if(!t)return{error:Cr};if(!e)return{error:VI};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:GI};t.timeItems??=[];let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Mc({drawDefinition:t}),{...P}}function i1({positionAssignments:t,participantFactors:e,random:r}){if(!e||!t)return{error:nt};let n=q(e,!1,!0),o=t.map(({drawPosition:g})=>g),i=t.filter(g=>!g.participantId&&!g.bye&&!g.qualifier).map(zF),s,a=!0;for(;a;)({drawPositionResolutions:s,remainingPreferences:a,participantPreferences:n}=u6({participantPreferences:n,drawPositionResolutions:s,random:r}));let c=new Set(Object.keys(s).map(g=>st(g))),u=i.filter(g=>!c.has(g)),p=Object.keys(n),m=J(1,((g,I)=>Math.log(I)/Math.log(g))(2,o?.length||0)+1).map(g=>Math.pow(2,g)),l={};for(let g of m){let I=Ae(o,g).filter(T=>we(T,u)),h={};if(p.forEach(T=>{I.forEach(y=>{let E=y.join("|");we(y,e[T].preferences)&&(h[E]||(h[E]=[]),h[E].push(T))})}),dr(Object.keys(h),r).forEach(T=>{let y=h[T].filter(E=>p.includes(E));for(;y.length;){let E=Sr(y,r),A=T.split("|").map(N=>st(N)).filter(N=>u.includes(st(N)));if(A.length){let N=Sr(A,r);u=u.filter(R=>R!==N),p=p.filter(R=>R!==E),s[N]=E;let D=T.split("|").length;l[D]||(l[D]=0),l[D]+=1}}}),!u.length)break}let f={chunkResolution:l};return p.length&&(p.forEach(g=>{let I=Sr(u,r);I&&(s[I]=g)}),f.randomAssignment=p.length),{drawPositionResolutions:s,report:f}}function u6({participantPreferences:t,drawPositionResolutions:e={},random:r}){let n=Object.keys(t).reduce((a,c)=>{let p=t[c].preferences[0];return p&&(a[p]||(a[p]=[]),a[p].push(c)),a},{}),o=Math.min(...Object.values(n).filter(a=>a.length).map(a=>a.length)),i=Object.keys(n).filter(a=>n[a].length&&o&&n[a].length===o);i.forEach(a=>{let c=n[a],u=Sr(c,r);e[a]=u,delete t[u]});let s;return Object.values(t).forEach(a=>{a.preferences=a.preferences.filter(c=>{let u=!i.includes(c.toString());return u&&(s=!0),u})}),{drawPositionResolutions:e,remainingPreferences:s,participantPreferences:t}}function bM({tournamentRecord:t,drawDefinition:e,applyResults:r=!0,tierIndex:n,random:o,event:i}){if(!e)return{error:K};let s=$t({element:e,attribute:"draftState",name:fi});if(!s)return{error:fe,info:"No active draft found"};if(s.status==="COMPLETE")return{error:O,info:"Draft is already complete"};let a=s.structureId,{structure:c}=tt({drawDefinition:e,structureId:a});if(!c)return{error:fe,info:"Structure not found"};let{positionAssignments:u}=yt({drawDefinition:e,structureId:a});if(!u)return{error:fe,info:"No position assignments"};let p=p6({draftState:s,targetTierIndex:n});if(p?.error)return p;let d=u.map(g=>({...g})),m={},l=[];for(let g=0;g<s.tiers.length;g++){let I=s.tiers[g];I.resolved||n!==void 0&&g!==n||(d6({draftState:s,tier:I,tierIndex:g,workingAssignments:d,allResolutions:m,tierReports:l,random:o}),I.resolved=!0)}let f=f6(s,m);if(r){let g=m6({allResolutions:m,tournamentRecord:t,drawDefinition:e,structureId:a,draftState:s,transparencyReport:f,tierReports:l,event:i});if(g)return g}return{...P,drawPositionResolutions:m,tierReports:l,transparencyReport:f}}function p6({draftState:t,targetTierIndex:e}){if(e!==void 0){if(e<0||e>=t.tiers.length)return{error:O,info:"Invalid tier index"};if(t.tiers[e].resolved)return{error:O,info:"Tier already resolved"};for(let r=0;r<e;r++)if(!t.tiers[r].resolved)return{error:O,info:`Tier ${r+1} must be resolved first`}}}function d6({draftState:t,tier:e,tierIndex:r,workingAssignments:n,allResolutions:o,tierReports:i,random:s}){let a=new Set(n.filter(p=>!p.participantId&&!p.bye&&!p.qualifier).map(p=>p.drawPosition)),c={},u=[];for(let p of e.participantIds){let m=t.preferences[p]?.filter(l=>a.has(l));m?.length?c[p]={preferences:m}:u.push(p)}if(Object.keys(c).length){let{drawPositionResolutions:p,report:d}=i1({positionAssignments:n,participantFactors:c});if(p)for(let[m,l]of Object.entries(p)){o[Number(m)]=l;let f=n.find(g=>g.drawPosition===Number(m));f&&(f.participantId=l)}i.push({tierIndex:r,preferenceReport:d,participantsWithoutPreferences:u})}if(u.length){let p=n.filter(l=>!l.participantId&&!l.bye&&!l.qualifier).map(l=>l.drawPosition),d=s??Math.random,m=[...p].sort(()=>d()-.5);for(let l=0;l<u.length&&l<m.length;l++){let f=m[l],g=u[l];o[f]=g;let I=n.find(h=>h.drawPosition===f);I&&(I.participantId=g)}i.push({tierIndex:r,randomAssignment:u.length})}}function m6({allResolutions:t,tournamentRecord:e,drawDefinition:r,structureId:n,draftState:o,transparencyReport:i,tierReports:s,event:a}){let c=[];for(let[d,m]of Object.entries(t)){let l=xn({drawPosition:Number(d),participantId:m,tournamentRecord:e,drawDefinition:r,structureId:n,event:a});l.error&&c.push({drawPosition:Number(d),participantId:m,error:l.error})}let u=new Set(Object.keys(t).map(Number));if(o.unassignedDrawPositions=(o.unassignedDrawPositions??[]).filter(d=>!u.has(d)),l6({draftState:o,allResolutions:t}),o.tiers.every(d=>d.resolved)&&(o.status="COMPLETE",o.resolvedAt=new Date().toISOString(),o.transparencyReport=i),At({element:r,attribute:"draftState",name:fi,value:o}),c.length)return{...P,errors:c,drawPositionResolutions:t,tierReports:s,transparencyReport:i}}function l6({draftState:t,allResolutions:e}){let r={};for(let[n,o]of Object.entries(e))r[o]=Number(n);for(let n of t.tiers){if(!n.resolved||n.resolutions)continue;let o={};for(let i of n.participantIds){let s=r[i];if(s===void 0)continue;let c=(t.preferences[i]??[]).indexOf(s);o[i]={assignedPosition:s,preferenceMatch:c>=0?c+1:null}}n.resolutions=o}}function f6(t,e){let r=[],n={};for(let[o,i]of Object.entries(e))n[i]=Number(o);for(let o of t.tiers)for(let i of o.participantIds){let s=t.preferences[i]??[],a=n[i],c=s.indexOf(a);r.push({participantId:i,preferences:s,assignedPosition:a,preferenceMatch:c>=0?c+1:null})}return r}function CM({tournamentRecord:t,drawDefinition:e,event:r,structureId:n}){if(!e)return{error:K};let o=e.structures?.find(a=>a.stage===rt&&a.structureId===n);if(!o)return{error:Pt};if(o.matchUps?.some(({matchUpStatus:a,score:c})=>le({score:c})??Rt.includes(a)))return{error:au};let s=o.matchUps?.map(({matchUpId:a})=>a)??[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Vn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:s,drawDefinition:e}),Lt({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...P}}function MM(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=X(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:Pt};let c=s.find(({stage:h,stageSequence:S})=>h===j&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===rt).map(Gr("structureId"));if(u&&!p.length)return{error:RU};let d=p.includes(n),m=g6({isQualifyingStructure:d,structure:a,...t});if(m?.error)return m;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=h6({qualifyingStructureIds:p,isQualifyingStructure:d,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=S6({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(I6({removedMatchUpIds:g,drawDefinition:r}),u){let h=(c.matchUps??[])?.map(Gr("matchUpId"));g.push(...h),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return d&&YA({drawDefinition:r}),Vn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),Lt({drawDefinition:r,eventId:o?.eventId}),{...P,removedMatchUpIds:g,removedStructureIds:I}}function g6({isQualifyingStructure:t,tournamentRecord:e,drawDefinition:r,structureId:n,structure:o,event:i,force:s}){let a=[n];if(t){let p=m=>r.links?.find(l=>l.target.structureId===m),d=p(n)?.source.structureId;for(;d;)a.push(d),d=p(d)?.source.structureId}if(re({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>le({score:p}))){let p=gt({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[Jr]?.allowDeletionWithScoresPresent?.structures))return{error:au}}return{...P}}function I6({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=re({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function h6({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Gr("structureId")),c=m=>o.links?.map(l=>l.source.structureId===m&&l.target.structureId!==n?.structureId&&l.target.structureId).filter(Boolean)??[],u=m=>o.links?.map(l=>t.includes(l.source.structureId)&&l.target.structureId===m&&l.source.structureId).filter(Boolean)??[],p=new Map;return a.forEach(m=>p.set(m,e?u(m):c(m))),{structureIdsToRemove:r?p.get(i):[i],relatedStructureIdsMap:p}}function S6({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(...E6({idBeingRemoved:u,drawDefinition:o}));let p=y6({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let d=T6({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});d?.length&&i.push(...d)}return{removedMatchUpIds:c,removedStructureIds:a}}function T6({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function y6({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 E6({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=tt({structureId:t,drawDefinition:e}),n=ht({structure:r}).matchUps;return df(n)}var s1="qualifierDrawPositionAssignment",a1="withdrawParticipantAtDrawPosition",c1="alternateDrawPositionAssignment",u1="luckyLoserDrawPositionAssignment",vM="removeDrawPositionAssignment",qA="swapDrawPositionAssignments",p1="modifyPairAssignment",d1="adHocPositionSwap",m1="modifyParticipantOtherName",OM="assignDrawPosition",l1="removeSeededParticipant",f1="assignDrawPositionBye",g1="modifySeedAssignment",I1="seedWithdrawalCascade",$A="addPenalty",TS="MODIFY_PAIR",_m="QUALIFIER",yS="ALTERNATE",ES="WITHDRAW",ma="ASSIGN",KA="REMOVE",AS="LUCKY",xm="REMOVE_SEED",wm="SWAP",ud="NICKNAME",Xa="SEED_VALUE",Za="PENALTY",_M="SEED_CASCADE";var h1={MODIFY_PAIR_ASSIGNMENT:TS,QUALIFYING_PARTICIPANT:_m,ALTERNATE_PARTICIPANT:yS,WITHDRAW_PARTICIPANT:ES,ASSIGN_PARTICIPANT:ma,LUCKY_PARTICIPANT:AS,REMOVE_ASSIGNMENT:KA,SWAP_PARTICIPANTS:wm,ADD_NICKNAME:ud,REMOVE_SEED:xm,ADD_PENALTY:Za,ASSIGN_BYE:"BYE",SEED_CASCADE:_M,SEED_VALUE:Xa};function xM({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:K};if(!n)return{error:mn};if(r?.length!==2)return{error:O,drawPositions:r};let i=ye({drawDefinition:e}),{matchUps:s}=re({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=tt({drawDefinition:e,structureId:n});if(!a)return{error:Pt};let c=gt({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===Ie?u=N6({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=A6({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(gf({structure:a,drawPositions:r}),vc({appliedPolicies:c,drawDefinition:e,positionAction:{name:qA,drawPositions:r,structureId:n}}),Tn({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===Tr){let d=ht({matchUpFilters:{matchUpTypes:[hr]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),m=ht({matchUpFilters:{matchUpTypes:[hr]},structure:a}).matchUps;d.forEach(l=>{(l.sides??[]).forEach(f=>{let g=f?.drawPosition;if(r.includes(g)){let I=f.participantId,h=m.find(({matchUpId:T})=>T===l.matchUpId),S=l?.sides?.reduce((T,y,E)=>y.drawPosition===g?E:T,void 0);Gf({inContextTargetMatchUp:l,drawPositionSideIndex:S,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:h,event:o})}})})}return Lt({drawDefinition:e,structureIds:[n]}),{...P}}function A6({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:O,structure:i,info:"Missing positionAssignments"};if(a.filter(({bye:p})=>p).length===2)return{...P};if(a.filter(({qualifier:p})=>p).length===2)return{...P};let c=a.some(({qualifier:p})=>p);return a.some(({bye:p})=>p)&&!c?S1({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):P6({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function S1({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:d}=c,{structureId:m}=i,l=od({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:m,matchUpsMap:o});return l.error||(l=od({drawPosition:d,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:m,matchUpsMap:o}),l.error)||(Mr({drawPosition:d,tournamentRecord:e,drawDefinition:r,structureId:m,matchUpsMap:o,event:s}),l=xn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:m,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...P}}function P6({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,d={...n[1-u],drawPosition:p};return{[p]:d}}));return i.positionAssignments=i.positionAssignments.map(c=>a[c.drawPosition]||c),aS({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...P}}function N6({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i.structures?.reduce((p,d)=>{let m=d?.positionAssignments.filter(l=>n?.includes(l.drawPosition));return m&&p.push(...m),p},[]);if(a.filter(({bye:p})=>p).length===2)return{...P};if(a.filter(({qualifier:p})=>p).length===2)return{...P};aS({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)S1({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s});else{let p=q(a,!1,!0);a.forEach((d,m)=>{let l=p[1-m].participantId;d.qualifier=p[1-m].qualifier,d.participantId=l})}return{...P}}function wM({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:Y};if(!e)return{error:K};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![j,rt].includes(i.stage)||i.stage===j&&i.stageSequence!==1?M({result:{error:Wo},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...P}:M({info:"participant not seeded",result:{error:fe},context:{participantId:r}}):M({result:{error:Pt},stack:o})}function la({qualifyingPositions:t,targetEntryRound:e=1,finishingPositions:r,sourceRoundNumber:n,sourceStructureId:o,targetStructureId:i,linkType:s=Ar}){return!o||!i?{error:mn}:{link:et({linkType:s,source:{roundNumber:n,structureId:o,qualifyingPositions:t,finishingPositions:r},target:{feedProfile:ln,roundNumber:e,structureId:i}})}}function cs({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>pd({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function pd({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,d=m=>{if(!o&&!n?.isMock)return i?.pop()??ot();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${m+1}`};return J(0,p).map(m=>{let l=t+m+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:d(m),matchUpStatus:Jt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function D6(t,e){return t.drawDefinition?t.drawSize&&!It(t.drawSize)||t.participantsCount&&!It(t.participantsCount)||t.qualifyingPositions&&!It(t.qualifyingPositions)?M({result:{error:O},stack:e}):t.drawSize?t.qualifyingPositions&&t.qualifyingPositions>=t.drawSize?M({result:{error:O},context:{drawSize:t.drawSize,qualifyingPositions:t.qualifyingPositions},stack:e}):null:M({result:{error:ru},context:{drawSize:t.drawSize},stack:e}):M({result:{error:K},stack:e})}function U6(t,e,r){let{structureProfiles:n}=cd({drawDefinition:t}),o=n[e];return o||M({result:{error:Pt},context:{targetStructureId:e},stack:r})}function R6(t){let{maxRoundNumber:e,structures:r,groupCount:n}=Fc(t);return{qualifiersCount:n,roundLimit:e,structure:r[0],finishingPositions:[1]}}function b6(t){let{drawSize:e,matchUps:r,roundLimit:n,roundsCount:o}=Er(t);n||(n=o);let i=gr({structureName:t.structureName,structureId:t.structureId,qualifyingRoundNumber:n,stage:rt,matchUpFormat:t.matchUpFormat,stageSequence:t.stageSequence,matchUpType:t.matchUpType,roundLimit:n,matchUps:r});t.roundTarget&&At({element:i,attribute:"roundTarget",name:Xr,value:t.roundTarget});let s=r?.filter(a=>a.roundNumber===n)?.length??0;return{drawSize:e,structure:i,matchUps:r,roundLimit:n,qualifiersCount:s}}function Kf(t){let e="generateQualifyingStructure",r=D6(t,e);if(r)return r;let n=t.drawSize??xl(t.participantsCount),{hasExistingDrawDefinition:o,qualifyingRoundNumber:i,qualifyingPositions:s,targetStructureId:a,structureOptions:c,appliedPolicies:u,qualifyingOnly:p,drawDefinition:d,matchUpFormat:m,structureName:l,structureId:f,roundTarget:g,tieFormat:I,drawType:h,idPrefix:S,isMock:T,uuids:y}=t,E=U6(d,a,e);if(E?.error)return E;let A=d.matchUpType,N=1,D=g?`${g}-`:"",R=typeof E=="object"&&"stage"in E&&E.stage===rt,U=u?.[$o]?.namingConventions?.pre??gk[$o]?.namingConventions?.pre,b=R&&U?`${U}-`:"",C=l??(D?`${b}${Be(rt)} ${D}`:`${b}${Be(rt)}`),_,v,x,w,F;if(h===_r){let G=R6({structureName:l??C,structureId:f??y?.pop(),hasExistingDrawDefinition:o,stage:rt,structureOptions:c,appliedPolicies:u,qualifyingOnly:p,stageSequence:N,matchUpType:A,roundTarget:g,tieFormat:I,idPrefix:S,drawSize:n,isMock:T,uuids:y});w=G.qualifiersCount,x=G.roundLimit,_=G.structure,F=G.finishingPositions}else{let G=b6({qualifyingRoundNumber:i,qualifyingPositions:s,matchUpType:A,idPrefix:S,drawSize:n,isMock:T,uuids:y,structureName:l??C,structureId:f??y?.pop(),matchUpFormat:m,stageSequence:N,roundTarget:g});n=G.drawSize,_=G.structure,x=G.roundLimit,w=G.qualifiersCount}let L=h===_r?fn:Ar,k=_&&x&&la({sourceStructureId:_.structureId,sourceRoundNumber:x,targetStructureId:a,finishingPositions:F,linkType:L})?.link;return I&&(v=ht({structure:_})?.matchUps??[],v?.forEach(G=>{let{tieMatchUps:V}=cs({tieFormat:I,matchUp:G,isMock:T});Object.assign(G,{tieMatchUps:V,matchUpType:A})})),{qualifyingDrawPositionsCount:n,qualifiersCount:w,...P,structure:_,link:k}}function LM(t){if(!t.tournamentRecord)return{error:Y};let r=C6(t);return r.error,r}function C6(t){if(!t.drawDefinition)return{error:K};if(!t.targetStructureId)return{error:mn};let e=Kf(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:O}:hS({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function FM({tournamentRecord:t,drawDefinition:e,structureId:r,drawPosition:n,event:o}){if(!e)return{error:K};if(r=r||e.structures?.[0]?.structureId,!r)return{error:O};let{structure:i}=tt({drawDefinition:e,structureId:r});if(!i)return{error:O};if(i.stage!==j||i.stageSequence!==1)return{error:O};if(i.structureType===Ie)return{error:O};if(is({drawDefinition:e,structureId:r}).activeDrawPositions?.length)return{error:O};let{positionAssignments:a}=pe({structure:i});if(!a)return{error:O};let{seedAssignments:c}=Dr({drawDefinition:e,structure:i});if(!c?.length)return{error:O};let p=a.find(A=>A.drawPosition===n)?.participantId;if(!p)return{error:O};let d=c.find(A=>A.participantId===p);if(!d)return{error:O};let{validSeedBlocks:m}=Ai({drawDefinition:e,structure:i});if(!m?.length)return{error:O};let l=d.seedNumber,f=m.findIndex(A=>A.seedNumbers.includes(l));if(f<0)return{error:O};let g=[],I=n,h=l;for(let A=f+1;A<m.length;A++){let N=m[A],D=c.filter(C=>N.seedNumbers.includes(C.seedNumber)&&C.participantId).sort((C,_)=>C.seedNumber-_.seedNumber);if(!D.length)break;let R=D[0],U=R.participantId,b=a.find(C=>C.participantId===U);if(!b)break;g.push({replacementParticipantId:U,replacementSeedNumber:R.seedNumber,targetSeedNumber:h,sourceDrawPosition:b.drawPosition,targetDrawPosition:I}),I=b.drawPosition,h=R.seedNumber}for(let A of g){let N=a.find(R=>R.drawPosition===A.targetDrawPosition);N&&(N.participantId=A.replacementParticipantId);let D=c.find(R=>R.seedNumber===A.targetSeedNumber);D&&(D.participantId=A.replacementParticipantId)}let S=g.length?g.at(-1)?.sourceDrawPosition:n,T=a.find(A=>A.drawPosition===S);if(T&&(T.participantId=void 0),g.length===0)d.participantId=void 0;else{let A=g.at(-1),N=c.find(D=>D.seedNumber===A?.replacementSeedNumber);N&&(N.participantId=void 0)}let y=e.entries?.find(A=>A.participantId===p);y&&(y.entryStatus=On);let E=t?.tournamentId;return Tn({drawDefinition:e,tournamentId:E,structure:i,event:o}),ff({eventId:o?.eventId,drawDefinition:e,tournamentId:E,structure:i}),{...P,vacatedDrawPosition:S}}function kM(t){let e=X(t,[{[zt]:!0,[Po]:!0,[xr]:!0},{[bF]:!0,[Xe]:d=>Number.isInteger(d)&&d>0},{[Xe]:d=>Array.isArray(d)&&d.length===2&&d.every(wt),[wr]:vr,participantIds:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n,tournamentRecord:o,event:i}=t,{structure:s}=tt({drawDefinition:r,structureId:n});if(!s)return{error:Pt};if(!De({structure:s}))return{error:Wo};let a=d=>d.sides?.map(m=>m.participantId).some(m=>t.participantIds.includes(m)),c=d=>d.roundNumber===t.roundNumber,u=d=>!le(d),p=(s?.matchUps??[]).filter(c).filter(u).filter(a);if(p.length!==2)return{error:vr};for(let d of p){let m=d?.sides?.find(l=>t.participantIds.includes(l?.participantId));if(m){let l=t.participantIds.find(f=>f!==m?.participantId);m.participantId=l,mt({tournamentId:o?.tournamentId,eventId:i?.eventId,drawDefinition:r,matchUp:d})}}return Lt({drawDefinition:r,structureIds:[n]}),{...P}}var M6=new Set([vt,Mt,Zt,Te]);function Lm({matchUp:t}){if(!t)return{error:nr};let{winningSide:e,score:r,matchUpStatus:n}=t;if(!e||!r)return{error:O};if(n&&M6.has(n))return{...P,margin:Number.NaN,setRatio:Number.NaN,gameRatio:Number.NaN,pointRatio:Number.NaN,setsWonByLoser:0,setsWonByWinner:0,gameDifferential:0};let o=r.sets??[],i=e===1?2:1,s=o.filter(A=>A.winningSide===e).length,a=o.filter(A=>A.winningSide===i).length,c=s+a,u=c>0?a/c:Number.NaN,p=!1,d=0,m=0;for(let A of o){let N=e===1?A.side1PointScore:A.side2PointScore,D=e===1?A.side2PointScore:A.side1PointScore;N!=null&&(d+=Number(N),p=!0),D!=null&&(m+=Number(D),p=!0)}let l=d+m,f=p&&l>0?m/l:Number.NaN,{games:g}=Ef({score:r}),I=g[e-1],h=g[i-1],S=I+h,T=S>0?h/S:Number.NaN,y=I-h,E;return Number.isFinite(f)?E=f:Number.isFinite(T)?E=T:E=u,{...P,margin:E,setRatio:u,gameRatio:T,pointRatio:f,setsWonByLoser:a,setsWonByWinner:s,gameDifferential:y}}function zf({tournamentRecord:t,drawDefinition:e,structureId:r,cumulativeMargin:n}){if(!e)return{error:K};let o=cn(e.drawType);if(r=r||e.structures?.[0]?.structureId,!r)return o?{error:O}:{...P,isLuckyDraw:!1,rounds:[]};let{structure:i}=tt({drawDefinition:e,structureId:r});if(!i)return{error:O};if(!(o||_c({drawDefinition:e,structure:i})))return{...P,isLuckyDraw:!1,rounds:[]};let a=i.matchUps??[],{roundProfile:c,roundNumbers:u}=_e({matchUps:a});if(!c||!u?.length)return{...P,isLuckyDraw:!0,rounds:[]};let p=qt({element:i,name:"customRoundProfile"}).extension?.value,d=i.positionAssignments??[],m={};for(let g of d)g.drawPosition&&g.participantId&&(m[g.drawPosition]=g.participantId);let l={};if(t?.participants)for(let g of t.participants)g.participantId&&g.participantName&&(l[g.participantId]=g.participantName);let f=u.map(g=>{let I=c[g],h=a.filter(G=>G.roundNumber===g),S=h.filter(G=>Rt.includes(G.matchUpStatus)||G.winningSide||G.matchUpStatus==="BYE").length,T=S===I.matchUpsCount,y=I.matchUpsCount===1,E=0;if(!y)if(p){let G=p[g-1],V=p[g];G&&V&&(E=Math.max(0,2*V-G))}else I.matchUpsCount%2!==0&&(E=1);let A=E>0,N=g+1,R=a.filter(G=>G.roundNumber===N).some(G=>!G.drawPositions||G.drawPositions.filter(Boolean).length<2?!0:G.drawPositions.some(V=>{if(!V)return!0;let B=d.find($=>$.drawPosition===V);return!B?.participantId&&!B?.bye})),U=A&&T&&R,C=(e.links??[]).filter(G=>G.linkType===pr&&G.source.structureId===r&&(G.source.roundNumber||1)===g).map(G=>{let V=G.target.structureId,B=G.target.roundNumber,{structure:$}=tt({drawDefinition:e,structureId:V}),H=$?.positionAssignments??[],z=($?.matchUps??[]).filter(pt=>pt.roundNumber===B),W=new Set(z.flatMap(pt=>(pt.drawPositions??[]).filter(Boolean))),Q=W.size>0&&[...W].some(pt=>H.some(Tt=>Tt.drawPosition===pt&&Tt.participantId));return{targetStructureId:V,targetRoundNumber:B,feedProfile:G.target.feedProfile,losersPlaced:Q}}),_={roundNumber:g,matchUpsCount:I.matchUpsCount,completedCount:S,isComplete:T,isPreFeedRound:A,needsLuckySelection:U,nextRoundHasOpenPosition:R,requiredLuckyLoserCount:E,...C.length&&{consolidationLinks:C}},v=(G,V)=>{let B=G.sides?.find(H=>H.sideNumber===V);if(B)return B.participantId||B.participant?.participantId;let $=G.drawPositions?.[V-1];return $?m[$]:void 0},x=(G,V,B)=>G.sides?.find(H=>H.sideNumber===V)?.participant?.participantName||l[B],w=(G,V)=>{let B=v(G,V);if(!B)return;let $=x(G,V,B),H=Lm({matchUp:G});return{participantId:B,participantName:$,matchUpId:G.matchUpId,scoreString:G.score?.scoreStringSide1,margin:H.margin??0,gameRatio:Number.isFinite(H.gameRatio)?H.gameRatio:void 0,pointRatio:Number.isFinite(H.pointRatio)?H.pointRatio:void 0,setRatio:Number.isFinite(H.setRatio)?H.setRatio:void 0,gameDifferential:H.gameDifferential??0,setsWonByLoser:H.setsWonByLoser??0}},F=h.filter(G=>G.winningSide),L=[...h].sort((G,V)=>(G.roundPosition||0)-(V.roundPosition||0)),k=[];for(let G of L)if(G.winningSide){let V=w(G,G.winningSide);V&&k.push(V)}else if(G.matchUpStatus==="BYE"){let V=G.drawPositions??[];for(let B of V){if(!B)continue;let $=d.find(H=>H.drawPosition===B);if($?.participantId&&!$.bye){k.push({participantId:$.participantId,participantName:l[$.participantId],matchUpId:G.matchUpId,margin:0,gameDifferential:0,setsWonByLoser:0});break}}}if(_.advancingWinners=k,A){let G=F.map(V=>{let B=V.winningSide===1?2:1,$=w(V,B);if(!$||!n)return $;let H=a.filter(Q=>{if(!Q.roundNumber||Q.roundNumber>g||!Q.winningSide)return!1;let pt=v(Q,1),Tt=v(Q,2);return pt===$.participantId||Tt===$.participantId}),z=0,W=0;for(let Q of H){let pt=Lm({matchUp:Q});if(Number.isFinite(pt.margin)){let Tt=v(Q,1),Ot=Tt===$.participantId&&Q.winningSide!==1||Tt!==$.participantId&&Q.winningSide!==2;z+=Ot?pt.margin??0:1-(pt.margin??0),W++}}return W>0&&($.margin=z/W),$}).filter(V=>!!V).sort((V,B)=>(B.margin??0)!==(V.margin??0)?(B.margin??0)-(V.margin??0):(B.setsWonByLoser??0)-(V.setsWonByLoser??0));_.eligibleLosers=G}return _});return{...P,isLuckyDraw:!0,rounds:f}}var T1="luckyDrawAdvancement";function GM({tournamentRecord:t,drawDefinition:e,participantId:r,participantIds:n,structureId:o,roundNumber:i,random:s,event:a}){if(!e)return{error:K};if(o=o||e.structures?.[0]?.structureId,!o)return{error:O};let{structure:c}=tt({drawDefinition:e,structureId:o});if(!c)return{error:O};if(!cn(e.drawType)&&!_c({drawDefinition:e,structure:c}))return M({result:{error:O},info:"Not a lucky draw"});let u=zf({tournamentRecord:t,drawDefinition:e,structureId:o});if(u.error)return u;let p=u.rounds?.find(y=>y.roundNumber===i);if(!p?.isComplete)return M({result:{error:O},info:"Round is not complete"});let d=n??(r?[r]:[]);if(p.needsLuckySelection){if(!d.length)return{error:$e};if(d.length!==p.requiredLuckyLoserCount)return M({result:{error:O},info:`Expected ${p.requiredLuckyLoserCount} lucky loser(s), got ${d.length}`});if(new Set(d).size!==d.length)return M({result:{error:O},info:"Duplicate lucky loser participantIds"});let y=new Set((p.eligibleLosers??[]).map(A=>A.participantId)),E=d.find(A=>!y.has(A));if(E)return M({result:{error:O},info:`Participant ${E} is not an eligible loser from this round`})}let m=i+1,l=(c.matchUps??[]).filter(y=>y.roundNumber===m).sort((y,E)=>(y.roundPosition||0)-(E.roundPosition||0)),f=p.advancingWinners??[],g=f.map(y=>y.participantId);if(p.isPreFeedRound&&d.length&&x6({advancingParticipantIds:g,nextRoundMatchUps:l,roundStatus:p,luckyLoserIds:d,winners:f,random:s}),!l.length)return M({result:{error:O},info:"No matchUps found in next round"});let I=l.length*2;if(g.length!==I)return M({result:{error:O},info:`Expected ${I} advancing participants, got ${g.length}`});let h=c.positionAssignments??[];h=k6({positionAssignments:h,nextRoundMatchUps:l,structure:c,roundNumber:i}),c.positionAssignments=h;let S=_6({nextRoundMatchUps:l,positionAssignments:h});if(S)return S;let T=t?.tournamentId;return G6({advancingParticipantIds:g,positionAssignments:h,nextRoundMatchUps:l,drawDefinition:e,roundNumber:i,roundStatus:p,luckyLoserIds:d,tournamentId:T,structureId:o,structure:c}),Tn({drawDefinition:e,tournamentId:T,structure:c,event:a}),p.isPreFeedRound&&d.length&&O6({drawDefinition:e,tournamentRecord:t,roundStatus:p,luckyLoserIds:d,structureId:o,roundNumber:i,event:a}),{...P}}function v6({drawDefinition:t,tournamentRecord:e,targetStructureId:r,targetRoundNumber:n,feedProfile:o,participantIds:i,event:s}){let{structure:a}=tt({drawDefinition:t,structureId:r});if(!a)return{error:O};if(De({structure:a})&&a.finishingPosition===Ao)return{...P};let c=(a.matchUps??[]).filter(m=>m.roundNumber===n).sort((m,l)=>(m.roundPosition||0)-(l.roundPosition||0)),u=a.positionAssignments??[],p=[];a.matchUps??=[],c.length===0?(V6({targetStructure:a,targetStructureId:r,targetRoundNumber:n,participantIds:i,unfilledPositions:p}),c=a.matchUps.filter(m=>m.roundNumber===n).sort((m,l)=>(m.roundPosition||0)-(l.roundPosition||0))):B6({targetMatchUps:c,targetPositionAssignments:u,targetStructure:a,unfilledPositions:p}),o==="BOTTOM_UP"?p.sort((m,l)=>l-m):p.sort((m,l)=>m-l);let d=e?.tournamentId;for(let m=0;m<i.length&&m<p.length;m++){let l=p[m],f=i[m],g=u.find(h=>h.drawPosition===l&&!h.participantId);g?g.participantId=f:u.push({drawPosition:l,participantId:f});let I=c.find(h=>h.drawPositions?.includes(l));I&&mt({context:T1,drawDefinition:t,tournamentId:d,structureId:r,matchUp:I})}return a.positionAssignments=u,Tn({drawDefinition:t,tournamentId:d,structure:a,event:s}),{...P}}function O6({drawDefinition:t,tournamentRecord:e,roundStatus:r,luckyLoserIds:n,structureId:o,roundNumber:i,event:s}){let a=new Set(n),c=(r.eligibleLosers??[]).filter(p=>!a.has(p.participantId)).map(p=>p.participantId);if(!c.length)return;let u=(t.links??[]).filter(p=>p.linkType===pr&&p.source.structureId===o&&(p.source.roundNumber||1)===i);for(let p of u){let d=v6({drawDefinition:t,tournamentRecord:e,targetStructureId:p.target.structureId,targetRoundNumber:p.target.roundNumber,feedProfile:p.target.feedProfile,participantIds:c,event:s});d?.error&&We()&&console.warn("Failed to place discarded losers in consolidation structure:",d.error)}}function _6({nextRoundMatchUps:t,positionAssignments:e}){for(let r of t){let n=r.drawPositions;if(!n?.length)continue;if(n.filter(i=>i?e.some(s=>s.drawPosition===i&&s.participantId):!1).length)return M({result:{error:O},info:"Next round already has participants assigned"});n.some(Boolean)&&(r.drawPositions=[]),r.matchUpStatus&&r.matchUpStatus!=="TO_BE_PLAYED"&&(r.matchUpStatus=void 0,r.winningSide=void 0,r.score=void 0)}}function x6({advancingParticipantIds:t,nextRoundMatchUps:e,roundStatus:r,luckyLoserIds:n,winners:o,random:i}){let s=i??Math.random,a=e.length,c=new Set(o.map(u=>u.participantId));for(let u of n)w6({advancingParticipantIds:t,numMatchUps:a,roundStatus:r,winnerIds:c,winners:o,llId:u,rng:s})}function w6({advancingParticipantIds:t,numMatchUps:e,roundStatus:r,winnerIds:n,winners:o,llId:i,rng:s}){let a=r.eligibleLosers?.find(h=>h.participantId===i);if(!a||e<=1){t.push(i);return}let c=o.find(h=>h.matchUpId===a.matchUpId);if(!c){t.push(i);return}let u=t.indexOf(c.participantId);if(u<0){t.push(i);return}let p=(t.length+1)/2,d=Math.ceil(p/2),m=Math.max(1,Math.ceil(p/4)),l=L6({advancingParticipantIds:t,defeatingWinnerIdx:u,winnerIds:n,halfSplit:d,quarterSplit:m}),f=1/0;for(let h of l)h.score<f&&(f=h.score);let g=l.filter(h=>h.score===f).map(h=>h.p),I=g[Math.floor(s()*g.length)];t.splice(I,0,i)}function L6({advancingParticipantIds:t,defeatingWinnerIdx:e,winnerIds:r,halfSplit:n,quarterSplit:o}){let i=[];for(let s=0;s<=t.length;s++){let a=Math.floor(s/2),c=e+(s<=e?1:0),u=Math.floor(c/2),p=a<n?0:1,d=u<n?0:1,m=Math.floor(a/o),l=Math.floor(u/o),f=0;p===d&&(f+=100),m===l&&(f+=10),f+=F6({advancingParticipantIds:t,winnerIds:r,insertAtP:s,halfSplit:n,targetHalf:p})*2,i.push({p:s,score:f})}return i}function F6({advancingParticipantIds:t,winnerIds:e,insertAtP:r,halfSplit:n,targetHalf:o}){let i=0;for(let s=0;s<t.length;s++){if(e.has(t[s]))continue;let a=s<r?s:s+1;(Math.floor(a/2)<n?0:1)===o&&i++}return i}function k6({positionAssignments:t,nextRoundMatchUps:e,structure:r,roundNumber:n}){let o=new Set(e.flatMap(s=>(s.drawPositions??[]).filter(Boolean)));if(o.size){let s=[];for(let a of o){let c=t.filter(p=>p.drawPosition===a),u=c.some(p=>!p.participantId&&!p.bye);(c.length>1||u)&&s.push(a)}if(s.length){let a=new Set(s);t=t.filter(c=>!a.has(c.drawPosition))}}let i=new Set((r.matchUps??[]).filter(s=>s.roundNumber&&s.roundNumber<=n).flatMap(s=>s.drawPositions??[]).filter(Boolean));return t=t.filter(s=>s.participantId||s.bye?!0:i.has(s.drawPosition)),t}function G6({advancingParticipantIds:t,positionAssignments:e,nextRoundMatchUps:r,drawDefinition:n,roundNumber:o,roundStatus:i,luckyLoserIds:s,tournamentId:a,structureId:c,structure:u}){let p=new Set(e.map(S=>S.drawPosition)),d=(u.matchUps??[]).flatMap(S=>S.drawPositions??[]).filter(Boolean),m=[...p,...d],f=(m.length?Math.max(...m):0)+1,g=new Set(s??[]),I=i.isPreFeedRound&&g.size>0,h=()=>({name:"luckyAdvancement",value:{fromRoundNumber:o}});for(let S=0;S<r.length;S++){let T=r[S],y=f++,E=f++,A=t[S*2],N=t[S*2+1];T.drawPositions=[y,E];let D={drawPosition:y,participantId:A},R={drawPosition:E,participantId:N};I&&(g.has(A)&&(D.extensions=[h()]),g.has(N)&&(R.extensions=[h()])),e.push(D,R),mt({context:T1,drawDefinition:n,tournamentId:a,structureId:c,matchUp:T})}u.positionAssignments=e}function V6({targetStructure:t,targetStructureId:e,targetRoundNumber:r,participantIds:n,unfilledPositions:o}){let i=Math.ceil(n.length/2),s=1;for(let a=0;a<i;a++){let c=s++,u=s++,p={matchUpId:`${e}-mu-${a+1}`,roundNumber:r,roundPosition:a+1,drawPositions:[c,u],matchUpStatus:"TO_BE_PLAYED"};t.matchUps.push(p),o.push(c,u)}}function B6({targetMatchUps:t,targetPositionAssignments:e,targetStructure:r,unfilledPositions:n}){for(let o of t)for(let i of o.drawPositions??[]){if(!i)continue;let s=e.find(a=>a.drawPosition===i);!s?.participantId&&!s?.bye&&n.push(i)}if(!n.length){let o=new Set(e.filter(c=>c.participantId).map(c=>c.drawPosition)),i=(r.matchUps??[]).flatMap(c=>c.drawPositions??[]).filter(c=>c&&o.has(c)),s=[...o,...i],a=s.length?Math.max(...s)+1:1;for(let c of t)if(!c.drawPositions?.length||!c.drawPositions.some(Boolean)){let u=a++,p=a++;c.drawPositions=[u,p],n.push(u,p)}}}function y1(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return M({result:{error:nt},info:"playoffGroups required",stack:e});let{sourceStructureId:r,requireSequential:n,tournamentRecord:o,drawDefinition:i,playoffGroups:s,groupCount:a,groupSize:c,event:u}=t,p=qf({requireSequential:n,sourceStructureId:r,playoffGroups:s,groupCount:a,groupSize:c,...t});if(p.error)return M({result:p,stack:e});let{structures:d=[],links:m=[],finishingPositionTargets:l,positionRangeMap:f}=p,g=l?.flatMap(({finishingPositions:D})=>D).flatMap(D=>f[D].finishingPositions);i.structures.push(...d),i.links.push(...m);let{matchUps:I,matchUpsMap:h}=re({inContext:!0,drawDefinition:i}),S=new Set(d.map(({structureId:D})=>D)),T=I?.filter(({structureId:D})=>S.has(D)).map(Pe),y=h?.drawMatchUps?.filter(({matchUpId:D})=>T?.includes(D));if(y?.length){let D=tr({drawDefinition:i,event:u})?.tieFormat;D&&y.forEach(R=>{let{tieMatchUps:U}=cs({isMock:t.isMock,tieFormat:D,matchUp:R});Object.assign(R,{tieMatchUps:U,matchUpType:hr})})}let{positionAssignments:E}=yt({structureId:r,drawDefinition:i}),A={};E?.forEach(D=>{let U=$t({element:D,attribute:"tally",name:to})?.groupOrder;U&&(A[U]||(A[U]=[]),A[U].push(D.participantId))});let N=Ja({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return N.error&&N.error?.code!==yI.code?M({result:N,stack:e}):{structures:d,links:m,positionsPlayedOff:g,drawDefinition:i,...P}}function Qf({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Ur(o))return{error:O};if(!t)return{error:O};let{policyDefinitions:s}=Do({policyTypes:[Ih],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=Lf({positionAssignments:t}),c=o.length?pa({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;if(c?.error)return c;let{participantResults:u={},bracketComplete:p,report:d}=c??{},m=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;m.includes(f)?(At({value:u[f],element:l,attribute:"tally",name:to}),u[f].ties||At({element:l,attribute:"subOrder",name:Wa,value:void 0})):(At({element:l,attribute:"tally",name:to,value:void 0}),At({element:l,attribute:"subOrder",name:Wa,value:void 0}))}),Lt({drawDefinition:r}),{...P,participantResults:u,bracketComplete:p,report:d}}function zA({matchUps:t,matchUpId:e}){return{matchUp:(t??[]).find(n=>n.matchUpId===e)}}function Ft(t){let e=X(t,[{[zt]:!0,[xr]:!0}]);if(e.error)return e;let{tournamentParticipants:r,participantsProfile:n,afterRecoveryTimes:o,contextProfile:i,drawDefinition:s,matchUpsMap:a,matchUpId:c,inContext:u,context:p,event:d}=t,{structures:m=[]}=hn({drawDefinition:s}),l=t.contextContent||i&&lo({contextProfile:i,drawDefinition:s});for(let f of m){let{matchUps:g}=ht({tournamentParticipants:r,participantsProfile:n,afterRecoveryTimes:o,contextContent:l,drawDefinition:s,contextProfile:i,matchUpsMap:a,inContext:u,structure:f,context:p,event:d}),{matchUp:I}=zA({matchUps:g,matchUpId:c});if(I)return{matchUp:I,structure:f}}return{error:be}}function Fm(t){return!St(t)||!t.notes?{error:nt}:St(t.element)?!wt(t.notes)&&!t.notes?.testing?{error:O}:(Object.assign(t.element,{notes:t.notes}),{...P}):{error:O}}function PS(t){return St(t)?St(t.element)?(t.element.notes&&delete t.element.notes,{...P}):{error:O}:{error:nt}}var tc={matchUpStatus:Jt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Yn(t){let e="modifyMatchUpScore",r=t.matchUpFormat,n=t.matchUp,o,{matchUpStatusCodes:i,tournamentRecord:s,drawDefinition:a,matchUpStatus:c,removeScore:u,winningSide:p,matchUpId:d,event:m,notes:l,score:f}=t,g=H6({appliedPolicies:t.appliedPolicies,tournamentRecord:s,drawDefinition:a,structure:o,event:m}),I=n.matchUpType===xt,h=W6({isDualMatchUp:I,drawDefinition:a,matchUpId:d,matchUp:n,event:m});if(h?.error)return h;h&&({matchUp:n,structure:o}=h);let S=c&&n?.matchUpStatus===Mt&&c!==Mt;j6({matchUpStatusCodes:i,removeWinningSide:t.removeWinningSide,matchUpStatus:c,matchUpFormat:r,removeScore:u,winningSide:p,matchUp:n,score:f}),!o&&a&&({structure:o}=Ft({drawDefinition:a,matchUpId:d,event:m})),Y6({matchUpStatus:c,matchUp:n});let T;(S&&n?.processCodes?.length||c===Mt)&&(T=g?.[Jr]?.processCodes?.incompleteAssignmentsOnDefault);let y=q6({isDualMatchUp:I,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUpId:d,structure:o,matchUp:n,event:m});if(y?.error)return M({result:y,stack:e});if(a&&n.winningSide){let{competitionPolicy:N}=wo({tournamentRecord:s,drawDefinition:a,event:m});N?.processingGranularity==="PER_MATCHUP"&&Tm({tournamentRecord:s,drawDefinition:a,matchUp:n,event:m})}if(l){let N=Fm({element:n,notes:l});if(N.error)return M({result:N,stack:e})}let E=s?.tournamentId,A=$6({defaultedProcessCodes:T,tournamentRecord:s,drawDefinition:a,matchUpId:d});return A&&rr().topics.includes(Hp)&&XF({tournamentId:E,inContextMatchUp:A}),K6({defaultedProcessCodes:T,inContextMatchUp:A,matchUpStatus:c,matchUp:n}),mt({eventId:m?.eventId,context:e,drawDefinition:a,tournamentId:E,matchUp:n}),{...P}}function H6({appliedPolicies:t,tournamentRecord:e,drawDefinition:r,structure:n,event:o}){return t&&Object.keys(t).length?t:gt({policyTypes:[Jr],tournamentRecord:e,drawDefinition:r,structure:n,event:o})?.appliedPolicies}function W6({isDualMatchUp:t,drawDefinition:e,matchUpId:r,matchUp:n,event:o}){if(t&&e){if(r&&n.matchUpId!==r){let i=Ft({drawDefinition:e,matchUpId:r,event:o});return i.matchUp?{matchUp:i.matchUp,structure:i.structure}:{error:be}}return}n.matchUpId!==r&&console.log("!!!!!")}function j6({matchUpStatusCodes:t,removeWinningSide:e,matchUpStatus:r,matchUpFormat:n,removeScore:o,winningSide:i,matchUp:s,score:a}){r&&new Set([vt,Zt]).has(r)||o?Object.assign(s,{...tc}):a&&(s.score=a),r&&(s.matchUpStatus=r),n&&(s.matchUpFormat=n),t&&(s.matchUpStatusCodes=t),i&&(s.winningSide=i),e&&(s.winningSide=void 0)}function Y6({matchUpStatus:t,matchUp:e}){let r=new Set([yu,Ji,Zr]);t&&!e.winningSide&&le(e)&&!Rt.includes(t)&&!r.has(t)&&(e.matchUpStatus=vn)}function q6({isDualMatchUp:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUpId:o,structure:i,matchUp:s,event:a}){if(s.collectionId)return;let c=i?.structureType===Ie,u=De({structure:i});if(!_c({drawDefinition:r,structure:i})&&!u&&!c)return;let p=t?"SET1-S:T100":n??s.matchUpFormat??i?.matchUpFormat??r?.matchUpFormat??a?.matchUpFormat,d=t?{matchUpTypes:[xt]}:void 0,m=c&&i.structures.find(g=>g?.matchUps.find(I=>I.matchUpId===o))||i,{matchUps:l}=ht({structure:m,afterRecoveryTimes:!1,tournamentRecord:e,inContext:!0,matchUpFilters:d,drawDefinition:r,event:a});u&&(m.positionAssignments=ct(l.flatMap(g=>(g.sides??[]).map(I=>I.participantId)).filter(Boolean)).map(g=>({participantId:g})));let f=Qf({positionAssignments:m.positionAssignments,matchUpFormat:p,tournamentRecord:e,drawDefinition:r,matchUps:l,event:a});return f.error?f:{matchUpFormat:p}}function $6({defaultedProcessCodes:t,tournamentRecord:e,drawDefinition:r,matchUpId:n}){if(!rr().topics.includes(Hp)&&!t)return;let i=ye({drawDefinition:r});if(i)return re({matchUpFilters:{matchUpIds:[n]},nextMatchUps:!0,tournamentRecord:e,inContext:!0,drawDefinition:r,matchUpsMap:i}).matchUps?.[0]}function K6({defaultedProcessCodes:t,inContextMatchUp:e,matchUpStatus:r,matchUp:n}){if(!(!Array.isArray(t)||!e)&&!e.sides?.every(({participantId:o})=>o))if(r===Mt)n.processCodes=ct([...n.processCodes??[],...t]);else for(let o of t??[]){let i=o&&n?.processCodes?.lastIndexOf(o);n?.processCodes?.splice(i,1)}}function Jf(t){let{propagateExitStatus:e,matchUpStatusCodes:r,autoCalcDisabled:n,inContextMatchUp:o,matchUpStatus:i,dualMatchUp:s,structure:a,matchUp:c}=t,u=Ka({matchUpStatus:i})||[mo,Lr].includes(i)&&s||n,p=c?.sides?.map(h=>h.participantId).filter(Boolean).length||o?.sides?.map(h=>h.participantId).filter(Boolean).length,d="attemptToModifyScore";if(!(De({structure:a})&&p===1||i===Mt&&p||z6({structure:a,matchUp:c,inContextMatchUp:o})||t.appliedPolicies?.[Jr]?.requireParticipantsForScoring===!1||ze(i)&&p===1&&e))return M({result:{error:DI},stack:d});let f=[vt].includes(i),g=u?i:t.winningSide&&ae||Zr,I=Yn({...t,winningSide:t.winningSide,matchUpStatusCodes:(u&&r)??[],matchUpStatus:g,context:d,removeScore:f});return M({result:I,stack:d})}function z6({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=pe({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 QA({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=>st(n));return{groupValueGroups:e,groupValueNumbers:r}}function E1({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=>Rt.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:d,matchUpValue:m,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),Q6({collectionDefinition:t,collectionMatchUps:i,sideMatchUpValues:s,collectionValueProfiles:u,matchUpValue:m,scoreValue:f,setValue:g}),a=Z6({allCollectionMatchUpsCompleted:c,collectionDefinition:t,sideCollectionValues:a,belongsToValueGroup:I,sideMatchUpValues:s,groupValueGroups:r,collectionGroupNumber:p,collectionValue:d,matchUpValue:m,winCriteria:l,scoreValue:f,setValue:g,sideWins:h}),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 Q6({collectionDefinition:t,collectionMatchUps:e,sideMatchUpValues:r,collectionValueProfiles:n,matchUpValue:o,scoreValue:i,setValue:s}){It(o)?e.forEach(a=>{a.winningSide&&(r[a.winningSide-1]+=o)}):It(s)?e.forEach(a=>{a.score?.sets?.forEach(c=>{c.winningSide&&(r[c.winningSide-1]+=s)})}):It(i)?J6({collectionMatchUps:e,sideMatchUpValues:r}):Array.isArray(n)&&X6({collectionMatchUps:e,collectionDefinition:t,sideMatchUpValues:r})}function J6({collectionMatchUps:t,sideMatchUpValues:e}){t.forEach(r=>{r.score?.sets?.forEach(n=>{let{side1TiebreakScore:o=0,side2TiebreakScore:i=0,side1Score:s=0,side2Score:a=0}=n;(r.matchUpStatus===ae||r.winningSide||n.winningSide)&&(s||a?(e[0]+=s,e[1]+=a):(o||i)&&n.winningSide&&(e[n.winningSide-1]+=1))})})}function X6({collectionMatchUps:t,collectionDefinition:e,sideMatchUpValues:r}){t.forEach(n=>{if(n.winningSide){let o=n.collectionPosition,i=e5({collectionDefinition:e,collectionPosition:o});It(i)&&(r[n.winningSide-1]+=i)}})}function Z6({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideCollectionValues:r,belongsToValueGroup:n,sideMatchUpValues:o,groupValueGroups:i,collectionGroupNumber:s,collectionValue:a,matchUpValue:c,winCriteria:u,scoreValue:p,setValue:d,sideWins:m}){if(It(a)){let l=t5({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideMatchUpValues:o,matchUpValue:c,winCriteria:u,scoreValue:p,setValue:d,sideWins:m});l&&(n?i[s].values[l-1]+=a:r[l-1]+=a)}else n?(i[s].values[0]+=o[0]||0,i[s].values[1]+=o[1]||0):r=o;return r}function t5({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideMatchUpValues:r,matchUpValue:n,winCriteria:o,scoreValue:i,setValue:s,sideWins:a}){if(o?.aggregateValue){if(t){if(It(n||s||i)&&r[0]!==r[1])return r[0]>r[1]?1:2;if(a[0]!==a[1])return a[0]>a[1]?1:2}return}if(o?.valueGoal)return r.reduce((u,p,d)=>p>=o.valueGoal?d+1:u,0);let c=Math.floor(e.matchUpCount/2)+1;return a.reduce((u,p,d)=>p>=c?d+1:u,0)}function e5({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles??[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function Vu(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||Number.isNaN(e.reduce((I,h)=>I+h)))return{error:O};if(!s)return{error:nr};let c=tr({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:ba};let u=ur({tieFormat:c});if(u.error)return u;let d=r5(c,s).map((I,h)=>(I||0)+e[h]),m={side1Score:d[0],side2Score:d[1],winningSide:void 0},l=d.join(r),f=d.slice().reverse().join(r),g=o5({drawDefinition:n,matchUpsMap:o,sideScores:d,tieFormat:c,matchUp:s});return g&&(m.winningSide=g),{scoreStringSide1:l,scoreStringSide2:f,winningSide:g,set:m}}function r5(t,e){let r=t?.collectionDefinitions??[],n=e?.tieMatchUps??[],o=[0,0],{groupValueGroups:i,groupValueNumbers:s}=QA(t);for(let a of r)E1({collectionDefinition:a,groupValueNumbers:s,groupValueGroups:i,sideTieValues:o,tieMatchUps:n});for(let a of s){let c=n5(i[a]);c&&(o[c-1]+=i[a].groupValue||0)}return o}function n5(t){let{allGroupMatchUpsCompleted:e,matchUpCount:r,winCriteria:n,sideWins:o,values:i}=t;if(n?.aggregateValue)return e&&i[0]!==i[1]?i[0]>i[1]?1:2:void 0;if(n?.valueGoal)return i.reduce((a,c,u)=>c>=n.valueGoal?u+1:a,void 0);let s=Math.floor(r/2)+1;return o.reduce((a,c,u)=>c>=s?u+1:a,void 0)}function o5({drawDefinition:t,matchUpsMap:e,sideScores:r,tieFormat:n,matchUp:o}){if(!n?.winCriteria)return;let{valueGoal:i,aggregateValue:s,tallyDirectives:a}=n.winCriteria,c=o?.tieMatchUps??[],u;return i?u=i5(r,i):s&&(u=s5(c,r)),!u&&a&&(u=a5({drawDefinition:t,matchUpsMap:e,matchUp:o})),u}function i5(t,e){return t.map((n,o)=>({sideNumber:o+1,points:n})).find(({points:n})=>n>=e)?.sideNumber}function s5(t,e){if(t.every(n=>n.matchUpStatus&&Rt.includes(n.matchUpStatus)||n.winningSide)&&e[0]!==e[1])return e[0]>e[1]?1:2}function a5({drawDefinition:t,matchUpsMap:e,matchUp:r}){let n=r.matchUpId,o=r.hasContext?r:e?.drawMatchUps?.[n]||t&&Ft({inContext:!0,drawDefinition:t,matchUpId:n})?.matchUp;if(!o)return;let{completedTieMatchUps:i,order:s}=pa({matchUps:[o]});if(!i||!s?.length)return;let a=s[0].participantId;return o.sides.find(({participantId:c})=>c===a)?.sideNumber}function Gc({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Ft({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let i=$t({element:e,attribute:"lineUps",name:po}),s=q(i??{},!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:d,...m}=n.sides?.find(({sideNumber:f})=>f===c.sideNumber)??{},l=d?.length?d:p;return{...a(c),...m,lineUp:l}}),mt({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function ar(t){if(t)return q(t,!1,!0)}function NS(t){let e=X(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 JA({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=NS({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function bo(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&&JA({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:Y};let d=Ft({drawDefinition:r,event:a,matchUpId:s});if(d.error)return d;if(!d.matchUp)return{error:be};let{matchUp:m,structure:l}=d;if(!m.tieMatchUps)return{error:mr};if(Gc({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:m,drawDefinition:r}),$t({element:m,attribute:"disableAutoCalc",name:Ks}))if(o)At({element:m,attribute:"disableAutoCalc",name:Ks,value:void 0});else return{...P,score:m.score};let g=tr({drawDefinition:r,structure:l,matchUp:m,event:a})?.tieFormat;m.tieFormat=ar(g);let I=Vu({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:m,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:y}=I,E=S?.side1Score||S?.side2Score;if(e&&!m.score&&!E)return{...P};let A={scoreStringSide1:T,scoreStringSide2:y,sets:S?[S]:[]},N=h&&[1,2].includes(h),D=N&&ae||Qh({matchUpStatus:n??m.matchUpStatus,tieMatchUps:m.tieMatchUps,winningSide:m.winningSide,score:A})&&vn||Jt,R=!!(m.winningSide&&!N),U=m.tieMatchUps.find(({score:C,winningSide:_,matchUpStatus:v})=>C?.sets?.length&&(C.sets[0].side1Score||C.sets[0].side2Score)||v&&Rt.includes(v)||_),b;if(m.tieFormat&&!N&&!U){let C=tr({drawDefinition:r,structure:l,event:a})?.tieFormat;C&&JSON.stringify(g)===JSON.stringify(C)&&(m.tieFormatId=void 0,m.tieFormat=void 0,b=!0)}return Yn({appliedPolicies:t.appliedPolicies,matchUpStatus:D,score:A,removeWinningSide:R,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:m,event:a}),{...P,score:A,removeWinningSide:R,tieFormatRemoved:b,winningSide:h}}function A1({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:r,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:d,event:m}){let l="directWinner";if(s){let f=c5({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,matchUpsMap:d,event:m,stack:l});if(f?.error)return f}else{let f=kc({matchUpId:u.matchUpId,drawPosition:o,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:d});if(f.error)return f}return p&&r&&u5({projectedWinningSide:r,tournamentRecord:i,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:d,stack:l}),{...P}}function c5({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,winningDrawPosition:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,event:p,stack:d}){let m=c.drawPositions??[],l=m[t],f=i.source.structureId,g=tt({structureId:f,drawDefinition:a});if(g.error)return g;let{structure:I}=g,{positionAssignments:h}=pe({structureId:f,drawDefinition:a}),T=h?.find(U=>U.drawPosition===n)?.participantId,y=i.target.structureId,{positionAssignments:E}=pe({structureId:y,drawDefinition:a}),N=E?.find(U=>U.participantId===T)?.drawPosition,D=E?.filter(U=>{let b=m.includes(U.drawPosition),C=!U.participantId&&!U.bye&&!U.qualifier;return b&&C}).map(U=>U.drawPosition),R=D?.includes(l);if(T&&i.target.roundNumber===1&&R)xn({drawPosition:l,participantId:T,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:o,drawDefinition:a,matchUpsMap:u,event:p});else if(T&&D?.length){let U=D.pop();U&&xn({participantId:T,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:o,drawDefinition:a,drawPosition:U,matchUpsMap:u,event:p})}else if(N){let U=kc({drawPosition:N,matchUpId:c.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,matchUpsMap:u});if(U.error)return M({result:U,stack:d})}else if(I?.stage!==rt){let U="winner target position unavaiallble";console.log(U),M({stack:d,result:{error:U}})}if(I?.seedAssignments&&I.structureId!==y){let U=I.seedAssignments.find(({participantId:C})=>C===T),b=U?.participantId;U&&b&&Qa({eventId:c?.eventId,structureId:y,...U,tournamentRecord:o,drawDefinition:a,participantId:b})}}function u5({projectedWinningSide:t,tournamentRecord:e,drawDefinition:r,winnerMatchUp:n,dualMatchUp:o,matchUpsMap:i,stack:s}){let a=o.sides?.find(f=>f.sideNumber===t);if(!a?.lineUp)return;let c=o.roundPosition,u=n.roundPosition,p=c===u&&c!==1||Math.floor(c/2)===u?2:1,d=i?.drawMatchUps?.find(({matchUpId:f})=>f===n.matchUpId),m=[1,2].map(f=>({...d.sides?.find(I=>I.sideNumber===f)??{},sideNumber:f}));d.sides=m;let l=d.sides.find(f=>f.sideNumber===p);if(l){let f=a.lineUp?.filter(g=>g?.participantId);l.lineUp=Bf({lineUp:f}),mt({tournamentId:e?.tournamentId,eventId:n?.eventId,matchUp:d,context:s,drawDefinition:r})}}function P1(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,propagateExitStatus:o,sourceMatchUpStatus:i,loserDrawPosition:s,tournamentRecord:a,loserTargetLink:c,drawDefinition:u,loserMatchUp:p,dualMatchUp:d,matchUpsMap:m,event:l}=t,f="directLoser",g=c.linkCondition,I=p.drawPositions??[],h=g===Jn&&p.roundNumber===2&&Math.min(...I.filter(Boolean)),S=h||I[e],T=h||I[1-e],y=c.source.structureId,{structure:E}=tt({structureId:y,drawDefinition:u}),{matchUps:A}=ht({afterRecoveryTimes:!1,inContext:!0,drawDefinition:u,structure:E,event:l}),D=A.filter(H=>H.drawPositions?.includes(s)).filter(H=>{let z=H.sides.find(Q=>Q.drawPosition===s),W=H.matchUpStatus===vt||H.matchUpStatus===Mt&&!le(H);return z?.sideNumber===H.winningSide&&!W}),R=g===Jn&&D.length===0,{positionAssignments:U}=pe({structureId:y,drawDefinition:u}),C=U?.find(H=>H.drawPosition===s)?.participantId,_={loserParticipantId:C},v=c.target.structureId,{positionAssignments:x}=pe({structureId:v,drawDefinition:u}),w=x?.filter(({drawPosition:H})=>I.includes(H)),F=w?.some(H=>H.participantId&&C&&H.participantId===C),L=o&&[ve,vt,Mt].includes(i||"");if(F)return{...P,stack:f};let k=w?.filter(H=>{let z=I.includes(H.drawPosition),W=!H.participantId&&!H.bye&&!H.qualifier;return z&&W}).map(H=>H.drawPosition),G=k?.includes(S),V=c.target.roundNumber>1&&k?.length,B=c.target.roundNumber===1&&G,$=p5({fedDrawPositionFMLC:h,isFirstRoundValidDrawPosition:B,loserParticipantId:C,isFeedRound:V,unfilledTargetMatchUpDrawPositions:k,targetDrawPositionIsUnfilled:G,validForConsolation:R,targetMatchUpDrawPosition:S,loserBackdrawPosition:T,targetStructureId:v,inContextDrawMatchUps:r,sourceMatchUpStatus:i,validExitToPropagate:L,propagateExitStatus:o,loserDrawPosition:s,loserTargetLink:c,tournamentRecord:a,drawDefinition:u,matchUpsMap:m,event:l});return $.context&&Object.assign(_,$.context),$.error?M({result:$,stack:f}):$.earlyReturn?$.earlyReturn:(d5({loserParticipantId:C,targetStructureId:v,tournamentRecord:a,drawDefinition:u,loserMatchUp:p,structure:E}),m5({projectedWinningSide:n,tournamentRecord:a,drawDefinition:u,loserMatchUp:p,dualMatchUp:d,matchUpsMap:m,stack:f}),M({result:{...P},stack:f,context:_}))}function p5({fedDrawPositionFMLC:t,isFirstRoundValidDrawPosition:e,loserParticipantId:r,isFeedRound:n,unfilledTargetMatchUpDrawPositions:o,targetDrawPositionIsUnfilled:i,validForConsolation:s,targetMatchUpDrawPosition:a,loserBackdrawPosition:c,targetStructureId:u,inContextDrawMatchUps:p,sourceMatchUpStatus:d,validExitToPropagate:m,propagateExitStatus:l,loserDrawPosition:f,loserTargetLink:g,tournamentRecord:I,drawDefinition:h,matchUpsMap:S,event:T}){let y=()=>{let A=r?xn({drawPosition:a,participantId:r,structureId:u,inContextDrawMatchUps:p,sourceMatchUpStatus:d,tournamentRecord:I,drawDefinition:h,matchUpsMap:S,event:T}):{error:$e};return!A.error&&m&&l?{context:{progressExitStatus:!0}}:M({result:A,stack:"assignLoserDrawPosition"})};if(t){let A="loserLinkFedFMLC";if(s)return M({result:y(),stack:A});let N=Mr({drawPosition:c,structureId:u,tournamentRecord:I,drawDefinition:h,event:T});return M({result:M({result:N,stack:"assignLoserPositionBye"}),stack:A})}if(e)return y();if(r&&(n||o?.length)){o.sort(ee);let A=o[0],N=xn({participantId:r,structureId:u,drawPosition:A,inContextDrawMatchUps:p,sourceMatchUpStatus:d,tournamentRecord:I,drawDefinition:h,matchUpsMap:S,event:T});return N.error?N:m&&l?{earlyReturn:{stack:"directLoser",context:{progressExitStatus:!0,loserParticipantId:r}}}:{...P}}return{context:{loserDrawPosition:f,loserTargetLink:g,targetDrawPositionIsUnfilled:i},error:i?hs:BL}}function d5({loserParticipantId:t,targetStructureId:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,structure:i}){if(!i?.seedAssignments||i.structureId===e)return;let s=i.seedAssignments.find(({participantId:c})=>c===t),a=s?.participantId;s&&a&&Qa({eventId:o?.eventId,structureId:e,...s,tournamentRecord:r,drawDefinition:n,participantId:a})}function m5({projectedWinningSide:t,tournamentRecord:e,drawDefinition:r,loserMatchUp:n,dualMatchUp:o,matchUpsMap:i,stack:s}){if(!o||!t)return;let a=o.sides?.find(g=>g.sideNumber===3-t);if(!a?.lineUp)return;let{roundNumber:c,eventId:u}=n,{roundPosition:p}=o,d=c===1?2-p%2:1,m=i?.drawMatchUps?.find(({matchUpId:g})=>g===n.matchUpId),l=[1,2].map(g=>({...m.sides?.find(h=>h.sideNumber===g)??{},sideNumber:g}));m.sides=l;let f=m.sides.find(g=>g.sideNumber===d);f&&(f.lineUp=Bf({lineUp:a.lineUp}),mt({tournamentId:e?.tournamentId,matchUp:m,context:s,drawDefinition:r,eventId:u}))}function XA(t){let e="directParticipants",r=Jf(t);if(r.error)return M({result:r,stack:e});let n=Ka({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:p,matchUpStatus:d,dualMatchUp:m,matchUpsMap:l,winningSide:f,targetData:g,matchUpId:I,structure:h,matchUp:S,event:T}=t,y=!!S.collectionId,E=De({structure:h}),A=S.drawPositions,N;if(y){let{matchUpTieId:D,matchUpsMap:R}=t,U=bo({appliedPolicies:t.appliedPolicies,matchUpId:D,tournamentRecord:u,drawDefinition:p,matchUpsMap:R,event:T});if(N=U&&{tieMatchUpResult:U},A=i.find(({matchUpId:C})=>C===D)?.drawPositions,!o)return M({result:{...P,...N},stack:e})}return E?M({result:{...P,...N},stack:e}):A?l5({matchUpStatusIsValid:n,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:p,drawPositions:A,matchUpStatus:d,dualMatchUp:m,matchUpsMap:l,winningSide:f,targetData:g,matchUpId:I,structure:h,annotate:N,matchUp:S,stack:e,event:T}):M({result:{error:tu},stack:e})}function l5({matchUpStatusIsValid:t,inContextDrawMatchUps:e,projectedWinningSide:r,propagateExitStatus:n,matchUpStatusCodes:o,tournamentRecord:i,drawDefinition:s,drawPositions:a,matchUpStatus:c,dualMatchUp:u,matchUpsMap:p,winningSide:d,targetData:m,matchUpId:l,structure:f,annotate:g,matchUp:I,stack:h,event:S}){let T=r?r-1:d-1,y=1-T,E=a[T],A=a[y],N={},{targetLinks:{loserTargetLink:D,winnerTargetLink:R,byeTargetLink:U},targetMatchUps:{winnerMatchUpDrawPositionIndex:b,loserMatchUpDrawPositionIndex:C,winnerMatchUp:_,loserMatchUp:v,byeMatchUp:x}}=m,w=cn(s?.drawType),F=f5(w,I,f),L=!w||!F,k=t&&c||ae;if(_&&L){let G=A1({sourceMatchUpStatus:k,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:l,inContextDrawMatchUps:e,projectedWinningSide:r,winningDrawPosition:E,tournamentRecord:i,winnerTargetLink:R,drawDefinition:s,winnerMatchUp:_,dualMatchUp:u,matchUpsMap:p,event:S});if(G.error)return M({result:G,stack:h})}if(v&&L){let G=P1({sourceMatchUpStatus:k,sourceMatchUpStatusCodes:o??[],sourceWinningSide:d,loserMatchUpDrawPositionIndex:C,sourceMatchUpId:l,inContextDrawMatchUps:e,projectedWinningSide:r,propagateExitStatus:n,loserDrawPosition:A,tournamentRecord:i,loserTargetLink:D,drawDefinition:s,loserMatchUp:v,winningSide:d,matchUpsMap:p,dualMatchUp:u,event:S});if(G.context?.progressExitStatus&&Object.assign(N,G.context,{sourceMatchUpStatus:k,sourceMatchUpStatusCodes:o??[],loserMatchUp:v,matchUpsMap:p}),G.error)return M({result:G,stack:h})}if(x){let G=x.drawPositions??[],V=Math.min(...G.filter(Boolean)),B=U.target.structureId,$=Mr({drawPosition:V,structureId:B,tournamentRecord:i,drawDefinition:s,event:S});if($.error)return M({result:$,stack:h})}return M({result:{...P,...g},stack:h,context:N})}function f5(t,e,r){return!t||!e.roundNumber||!r?.matchUps?!1:r.matchUps.filter(o=>o.roundNumber===e.roundNumber).length%2!==0}function Xf(t){let e="genPlayoffStructure",r=g5(t,e);if(r.error||r.earlyReturn)return r.earlyReturn??r;let{addNameBaseToAttributeName:n,playoffStructureNameBase:o,finishingPositionNaming:i,finishingPositionLimit:s,availabilityResult:a,sourceStructureId:c,playoffAttributes:u,playoffPositions:p,roundOffsetLimit:d,tournamentRecord:m,exitProfileLimit:l,drawDefinition:f,roundProfiles:g,roundNumbers:I,structure:h,idPrefix:S,isMock:T,event:y,uuids:E}=r,{playoffRoundsRanges:A,playoffRounds:N}=a,{playoffPositionsReturned:D,error:R,playoffSourceRounds:U,playoffRoundsRanges:b}=OA(t);if(R)return M({result:{error:R},stack:e});let C=g?.length&&Object.assign({},...g),_=I||typeof g=="object"&&g.flatMap(W=>Object.keys(W)),v=Array.isArray(_)&&_.map(W=>!Number.isNaN(Number(W))&&st(W)).filter(Boolean);if(v){if(!Array.isArray(v))return M({result:{error:O},context:{validRoundNumbers:v},stack:e});v.forEach(W=>{if(!N?.includes(W))return M({result:{error:O},context:{roundNumber:W},stack:e})})}p&&p.forEach(W=>{if(!D?.includes(W))return M({result:{error:O},context:{playoffPosition:W},stack:e})});let x=v||U,w=v?A:b,F=[],L=[],k=cn(f.drawType);for(let W of x??[]){let Q=w?.find(he=>he.roundNumber===W);if(!Q)return M({result:{error:O},context:{roundNumber:W},stack:e});let pt=h5({finishingPositionsCount:Q.finishingPositions.length,isLuckyDraw:k,roundNumber:W,structure:h}),Tt=Math.min(...Q.finishingPositions)-1,Ot=2,Et=W&&C?.[W]&&Ot+C[W]-1,Bt=xu({exitProfile:`0-${W}`,addNameBaseToAttributeName:n,playoffStructureNameBase:o,finishingPositionOffset:Tt,playoffAttributes:u,exitProfileLimit:l,stage:Vt,roundOffset:0,drawDefinition:f,sequenceLimit:Et,stageSequence:Ot,drawSize:pt,idPrefix:S,isMock:T,uuids:E,finishingPositionNaming:i,finishingPositionLimit:s,roundOffsetLimit:d});if(Bt.error)return M({result:Bt,stack:e});let{structures:ce,links:ge}=Bt;if(ce?.length&&F.push(...ce),ge?.length&&L.push(...ge),Bt.structureId&&W){let he={linkType:pr,source:{structureId:c,roundNumber:W},target:{structureId:Bt.structureId,feedProfile:Je,roundNumber:1}};L.push(he)}}if(!F.length)return M({result:{error:O},info:"No structures generated",stack:e});f.structures.push(...F),f.links.push(...L);let{matchUps:G,matchUpsMap:V}=re({inContext:!0,drawDefinition:f}),B=new Set(F.map(({structureId:W})=>W)),$=G?.filter(({structureId:W})=>B.has(W)).map(Pe),H=V?.drawMatchUps?.filter(({matchUpId:W})=>$?.includes(W));if(H?.length){let W=tr({drawDefinition:f,event:y})?.tieFormat;W&&H.forEach(Q=>{let{tieMatchUps:pt}=cs({matchUp:Q,tieFormat:W,isMock:T});Object.assign(Q,{tieMatchUps:pt,matchUpType:xt})})}N1({inContextDrawMatchUps:G,sourceStructureId:c,tournamentRecord:m,drawDefinition:f,matchUpsMap:V,structure:h,event:y}),D1({inContextDrawMatchUps:G,sourceStructureId:c,tournamentRecord:m,drawDefinition:f,event:y});let z=S5({inContextDrawMatchUps:G,sourceStructureId:c,tournamentRecord:m,drawDefinition:f,matchUpsMap:V,params:t,stack:e});return{structures:F,matchUpModifications:z,links:L,drawDefinition:f,...P}}function g5(t,e){if(!t.drawDefinition)return{error:!0,earlyReturn:M({result:{error:K},stack:e})};let r=sd(t);if(r.error)return{error:!0,earlyReturn:M({result:r,stack:e})};let{structureId:n,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:d,exitProfileLimit:m,playoffGroups:l,roundProfiles:f,roundNumbers:g,idPrefix:I,isMock:h,event:S,uuids:T}=t,y=q(t.drawDefinition,!1,!0),{structure:E}=tt({structureId:n,drawDefinition:y});return E?E.structureType===Ie||E.structures?{error:!0,earlyReturn:y1({sourceStructureId:E.structureId,...t,...r,drawDefinition:y})}:l?.length?{error:!0,earlyReturn:I5({sourceStructureId:n,tournamentRecord:d,drawDefinition:y,playoffGroups:l,structure:E,idPrefix:I,isMock:h,event:S,uuids:T,stack:e})}:{addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,availabilityResult:r,sourceStructureId:n,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:d,exitProfileLimit:m,drawDefinition:y,roundProfiles:f,roundNumbers:g,structure:E,idPrefix:I,isMock:h,event:S,uuids:T}:{error:!0,earlyReturn:M({result:{error:Pt},stack:e})}}function I5({sourceStructureId:t,tournamentRecord:e,drawDefinition:r,playoffGroups:n,structure:o,idPrefix:i,isMock:s,event:a,uuids:c,stack:u}){let p=qf({requireSequential:!1,matchUpType:a?.eventType,sourceStructureId:t,drawDefinition:r,playoffGroups:n,groupCount:1,idPrefix:i,isMock:s,uuids:c});if(p.error)return M({result:p,stack:u});let{structures:d,links:m}=p;if(!d?.length)return M({result:{error:O},info:"No playoff structures generated",stack:u});r.structures.push(...d),m?.length&&r.links.push(...m);let{matchUps:l,matchUpsMap:f}=re({inContext:!0,drawDefinition:r});return N1({inContextDrawMatchUps:l,sourceStructureId:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:f,structure:o,event:a}),D1({inContextDrawMatchUps:l,sourceStructureId:t,tournamentRecord:e,drawDefinition:r,event:a}),{structures:d,links:m,matchUpModifications:[],drawDefinition:r,...P}}function h5({finishingPositionsCount:t,isLuckyDraw:e,roundNumber:r,structure:n}){let o=t;if(e&&n){let s=(n.matchUps??[]).filter(c=>c.roundNumber===r).length;if(!(s===1)&&s%2!==0){let c=s-1,u=c%2===0?c:c+1,p=1;for(;p<u;)p*=2;o=p}else o=Ci(o)}return o}function N1({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:i,event:s}){t?.filter(c=>ia({matchUp:c})&&c.structureId===e)?.forEach(c=>{let{matchUpId:u,score:p,winningSide:d}=c,m=ir({inContextDrawMatchUps:t,drawDefinition:n,matchUpId:u}),l=XA({inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,winningSide:d,targetData:m,matchUpId:u,structure:i,matchUp:c,score:p,event:s});l.error&&console.log(l.error)})}function D1({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:r,drawDefinition:n,event:o}){t?.filter(s=>s.matchUpStatus==="BYE"&&s.structureId===e)?.forEach(s=>{let{matchUpId:a}=s,c=ir({inContextDrawMatchUps:t,drawDefinition:n,matchUpId:a}),{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUpDrawPositionIndex:p,loserMatchUp:d}}=c;if(u&&d){let m=u.target.structureId,l=d.drawPositions[p],f=Mr({drawPosition:l,structureId:m,tournamentRecord:r,drawDefinition:n,event:o});f.error&&console.log(f.error)}})}function S5({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,params:i,stack:s}){let a=[],c=bs({inContextDrawMatchUps:t,drawDefinition:n,matchUpsMap:o}).goesToMap,{structure:u}=tt({drawDefinition:i.drawDefinition,structureId:e}),{matchUps:p}=ht({structure:u});return p.forEach(d=>{let m=c?.loserMatchUpIds[d.matchUpId];if(m&&d.loserMatchUpId!==m){d.loserMatchUpId=m;let f={tournamentId:r?.tournamentId,eventId:i.event?.eventId,context:s,matchUp:d};a.push(f)}let l=c?.winnerMatchUpIds[d.matchUpId];if(l&&d.winnerMatchUpId!==l){d.winnerMatchUpId=l;let f={tournamentId:r?.tournamentId,eventId:i.event?.eventId,context:s,matchUp:d};a.push(f)}}),a}function DS(t){let{structures:e,links:r,matchUpModifications:n,error:o}=Xf(t);if(o)return{error:o};let i=t.drawDefinition;return uS({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function _s(t){let e=X(t,[{_anyOf:{[Ne]:!1,[Z]:!1,[zt]:!1,[me]:!1},[mh]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=U1(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&Lt({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:Y};for(let i of o){let s=t.tournamentRecords[i],a=U1(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:Y};return r.length?{...P,applied:r}:{error:xy}}function U1(t,e){let r=gt(t).appliedPolicies??{};e.extensions??=[];let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:Ca};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!St(s))return{error:O};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!wt(a))return{error:O};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...Qt({element:e,extension:{name:wp,value:r}}),applied:n}:{applied:n,error:xy}}function US({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return M({result:{error:O},context:{drawName:n}});r||(r=Gt({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);return s&&(s.drawName=n,At({element:i,attribute:"flightProfile",name:Kr,value:{...r,flights:r.flights}})),e&&(e.drawName=n,Lt({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:K}:{...P,flight:s}}function VM({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!St(r))return{error:O};let i=Gt({event:o}).flightProfile,s=r.drawName&&US({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);return!a&&!e?{error:K}:(a&&At({element:o,attribute:"flightProfile",name:Kr,value:{...i,flights:i.flights}}),e&&(r.policyDefinitions&&_s({policyDefinitions:r.policyDefinitions,drawDefinition:e}),Lt({tournamentId:t?.tournamentId,drawDefinition:e})),{...P})}function BM({tournamentRecord:t,removeScheduling:e,removeAssignments:r,drawDefinition:n}){if(!n)return{error:K};let o=cn(n.drawType),i=ye({drawDefinition:n}),s=c=>i?.drawMatchUps?.find(u=>u.matchUpId===c);for(let c of n.structures??[]){let{stage:u}=c;if(u===Qe){T5(c);continue}y5({structure:c,isLuckyDraw:o,removeAssignments:r}),A5({removeScheduling:e,tournamentRecord:t,drawDefinition:n,getRawMatchUp:s,isLuckyDraw:o,matchUpsMap:i,structure:c,removeAssignments:r})}n.entries?.length&&(n.entries=n.entries.filter(c=>c.entryStage!==Qe)),n.extensions=n.extensions.filter(c=>c.name!==Tu&&c.name!==fi),delete n.draftState;let a=(n.structures??[]).map(({structureId:c})=>c);return Lt({drawDefinition:n,structureIds:a}),{...P}}function T5(t){t.matchUps=[],t.positionAssignments&&(t.positionAssignments=t.positionAssignments.map(e=>(delete e.participantId,e))),t.seedAssignments=[]}function y5({structure:t,isLuckyDraw:e,removeAssignments:r}){let{positionAssignments:n,stage:o,stageSequence:i}=t,s=i===1&&[rt,j].includes(o);e&&n?E5({structure:t,positionAssignments:n,isMainOrQualifyingFirst:s,removeAssignments:r}):n&&(!s||r)&&(t.positionAssignments=n.map(a=>(delete a.participantId,a)),t.seedAssignments=[])}function E5({structure:t,positionAssignments:e,isMainOrQualifyingFirst:r,removeAssignments:n}){let o=new Set((t.matchUps??[]).filter(i=>i.roundNumber===1).flatMap(i=>i.drawPositions??[]).filter(Boolean));r?(t.positionAssignments=e.filter(i=>o.has(i.drawPosition)).map(i=>(n&&(delete i.bye,delete i.participantId),i)),n&&(t.seedAssignments=[])):(t.positionAssignments=[],t.seedAssignments=[])}function A5({removeScheduling:t,tournamentRecord:e,removeAssignments:r,drawDefinition:n,getRawMatchUp:o,isLuckyDraw:i,matchUpsMap:s,structure:a}){let{matchUps:c,isRoundRobin:u}=ht({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:s,structure:a});for(let p of c){let{matchUpId:d,roundNumber:m}=p,l=p.sides??[],f=o(d);f&&(delete f.extensions,delete f.notes,P5({matchUp:f,isLuckyDraw:i,removeAssignments:r,roundNumber:m,sides:l,isRoundRobin:u}),N5({matchUp:f,removeScheduling:t}),mt({tournamentId:e?.tournamentId,context:"resetDrawDefinition",drawDefinition:n,matchUp:f}))}}function P5({matchUp:t,isLuckyDraw:e,removeAssignments:r,roundNumber:n,sides:o,isRoundRobin:i}){if(e)!r&&t.matchUpStatus==="BYE"||Object.assign(t,tc),n&&n>1&&(t.drawPositions=[]);else if(t.matchUpStatus!=="BYE"&&Object.assign(t,tc),n&&n>1&&t.drawPositions?.length&&!i){let s=o?.map(({drawPosition:c,participantFed:u})=>!u&&c).filter(Boolean),a=t.drawPositions.map(c=>s.includes(c)?void 0:c);t.drawPositions=a}}function N5({matchUp:t,removeScheduling:e}){e?delete t.timeItems:t.timeItems?.length&&(t.timeItems=t.timeItems.filter(r=>r.itemType&&![Hn,Ro,Ii,Du,Us,hi,Si,Ds].includes(r.itemType)))}function dd({tournamentRecord:t}){if(!t)return{error:Y};let e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={};return(t.events?.flatMap(o=>{let i=o.eventId;return r[i]=o,(o?.drawDefinitions??[]).map(s=>({drawDefinition:s,eventId:i}))}).filter(Boolean)).forEach(({drawDefinition:o,eventId:i})=>{let s=0,a=0,c=0,{allStructuresLinked:u}=cd({drawDefinition:o}),p=r[i],m=(o?.structures??[]).map(E=>{let{stage:A,stageSequence:N,structureId:D}=E,R=ka[A],{inContextStructureMatchUps:U}=is({drawDefinition:o,structureId:D,structure:E,event:p}),b=U?.filter(({winningSide:H})=>H),C=b.filter(Boolean).length||0;a+=C,c+=U.length-a;let _=Math.max(b.filter(({roundNumber:H})=>H===1).map(({roundPosition:H})=>H)),{positionAssignments:v}=yt({structure:E}),x=v?.filter(({participantId:H})=>H);s+=x?.length??0;let w=(v?.length??0)-(x?.length??0),{roundMatchUps:F,roundProfile:L,roundNumbers:k,maxMatchUpsCount:G}=_e({matchUps:U}),V=L&&Object.keys(L).filter(H=>!L[H].inactiveRound).map(H=>Number.parseInt(H)),B=L&&Object.keys(L).filter(H=>L[H].inactiveRound).map(H=>Number.parseInt(H)),$=L&&Object.values(L).every(H=>H.inactiveRound);return{positionsAssignedCount:x?.length??0,maxWinningSideFirstRoundPosition:_,unassignedPositionsCount:w,inactiveStructure:$,maxMatchUpsCount:G,inactiveRounds:B,roundMatchUps:F,activeRounds:V,roundNumbers:k,roundProfile:L,structureId:D,stageSequence:N,orderNumber:R,stage:A}}),l=m.find(E=>E.orderNumber===2&&E.stageSequence===1),f=m.filter(({inactiveStructure:E})=>!E).length,{links:g}=qa({structureId:l.structureId,drawDefinition:o}),I=st(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=m?.every(({inactiveStructure:E})=>E),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:m,inactiveDraw:h,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=y}),{...P,drawsAnalysis:e}}function HM({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:Y};if(!r)return{error:K};let o=[],{drawsAnalysis:i}=dd({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=hn({stageSequence:1,drawDefinition:r,stage:j}),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 d=o.map(Pe),m=p.map(Pe).filter(l=>!d.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Pe),g=d.filter(T=>!f.includes(T));m.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}Vn({tournamentId:e?.tournamentId,matchUpIds:m,drawDefinition:r}),Lt({drawDefinition:r})}return{...P,matchUps:o}}function R1({isPositionAction:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,loserMatchUp:o,matchUpsMap:i,structureId:s,structure:a,event:c}){if(!r)return{error:K};if(a||({structure:a}=tt({drawDefinition:r,structureId:s})),!a)return{error:Pt};s||({structureId:s}=a);let u="assignDrawPositionQualifier";Ue({method:u,color:"cyan",drawPosition:n}),i??=ye({drawDefinition:r});let{positionAssignments:p}=yt({structure:a}),{activeDrawPositions:d}=is({drawDefinition:r,structureId:s});if(p?.find(T=>T.drawPosition===n)?.qualifier)return{...P};let l=!!(o&&i.drawMatchUps.some(T=>T.loserMatchUpId===o?.matchUpId&&ze(T.matchUpStatus)));if(d?.includes(n)&&!l)return{error:eu};let g=p?.find(T=>T.drawPosition===n);if(!g)return{error:hs};let{containsQualifier:I,containsParticipant:h}=_f(g);if(I)return{...P};let S=gt({tournamentRecord:e,drawDefinition:r,event:c}).appliedPolicies??{};return p?.forEach(T=>{T.drawPosition===n&&(T.qualifier=!0,l&&(T.participantId=void 0,console.log("oddity: invalid participantId on qualifier position cleared")))}),Tn({tournamentId:e?.tournamentId,drawDefinition:r,structure:a,event:c}),D5({assignedParticipantId:h,isPositionAction:t,appliedPolicies:S,drawDefinition:r,drawPosition:n,structureId:s,stack:u})}function D5({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&vc({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),M({result:{...P},stack:s})}function WM({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,qualifier:i,event:s,bye:a}){if(!e)return{error:K};if(!n)return{error:Ra};if(!o)return{error:mn};if(a){let c=Mr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else if(i){let c=R1({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{let c=xn({participantId:r,tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}return{...P}}function jM({tournamentRecord:t,drawDefinition:e,scaleAttributes:r,preferencesCount:n=3,tierMethod:o,ascending:i,structureId:s,tierCount:a,event:c,force:u}){if(!e)return{error:K};if(a!==void 0&&a<1)return{error:O};if(n<1)return{error:O};if(!s){let b=e.structures?.filter(C=>C.stage===j);b?.length===1&&(s=b[0].structureId)}if(!s)return{error:mn};let{structure:p}=tt({drawDefinition:e,structureId:s});if(!p)return{error:mn};let d=$t({element:e,attribute:"draftState",name:fi});if(d?.status&&d.status!=="COMPLETE"&&!u)return{error:AR};let{positionAssignments:m}=yt({drawDefinition:e,structureId:s}),l=m?.filter(b=>!b.participantId&&!b.bye&&!b.qualifier).map(b=>b.drawPosition);if(!l?.length)return{error:iu};let f=p.seedAssignments??[],g=new Set(f.map(b=>b.participantId).filter(Boolean)),I=m?.filter(b=>b.participantId).map(b=>b.participantId)??[],S=e.entries?.filter(b=>!g.has(b.participantId)&&!I.includes(b.participantId))?.map(b=>b.participantId)??[],T=o??"ENTRY_ORDER",y=r??U5(T,c),E=i??T==="RANKING",A=R5({participantIds:S,tierMethod:T,scaleAttributes:y,ascending:E,tournamentRecord:t}),N=a??C5(A.length,g.size),D=Math.min(N,A.length),R=M5(A,D),U={status:"SEEDS_PLACED",structureId:s,preferencesCount:n,tierMethod:T,scaleAttributes:y,ascending:E,tiers:R,preferences:{},unassignedDrawPositions:l};return At({element:e,attribute:"draftState",name:fi,value:U}),{...P,draftState:U,unassignedDrawPositions:l,tiers:R}}function U5(t,e){if(t==="RANKING")return{scaleType:co};if(t==="RATING"){let r=e?.category?.ratingType;return r?{scaleType:qo,scaleName:r}:void 0}}function R5({participantIds:t,tierMethod:e,scaleAttributes:r,ascending:n,tournamentRecord:o}){if(e==="ENTRY_ORDER"||!r||!o)return t;let i=[],s=[];for(let a of t){let{scaleItem:c}=as({tournamentRecord:o,scaleAttributes:r,participantId:a}),u=c?.scaleValue,p=b5(u);p===void 0?s.push(a):i.push({participantId:a,scaleValue:p})}return i.sort((a,c)=>n?a.scaleValue-c.scaleValue:c.scaleValue-a.scaleValue),[...i.map(a=>a.participantId),...s]}function b5(t){if(t!=null){if(typeof t=="number")return t;if(typeof t=="string"){let e=Number.parseFloat(t);return Number.isNaN(e)?void 0:e}if(typeof t=="object")for(let e of Object.values(t)){if(typeof e=="number")return e;if(typeof e=="string"){let r=Number.parseFloat(e);if(!Number.isNaN(r))return r}}}}function C5(t,e){return t<4?1:e>0&&t>=24?3:2}function M5(t,e){let r=[],n=Math.floor(t.length/e),o=t.length%e,i=0;for(let s=0;s<e;s++){let a=n+(s<o?1:0);r.push({participantIds:t.slice(i,i+a),resolved:!1}),i+=a}return r}function ZA(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:Pt};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:Pt};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===As)return{error:Wo};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Pe);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function YM(t){let e=X(t,[{[zt]:!0},{[Va]:{[Iu]:!1,roundNumbers:!1},[wr]:O,[qe]:Ye}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=ZA(t);if(c.error)return c;let{structure:u,structureId:p,existingMatchUps:d,matchUpIds:m}=c,l=[],f=d?.filter(({matchUpId:h,score:S,winningSide:T})=>{if(T&&!o)return!1;if(T||le({score:S})){if(!T&&!r)return!1;l.push(h)}else if(!n)return!1;return m?.includes(h)})??[],g=f.map(Pe),I=f.map(({tieMatchUps:h})=>h?.map(Pe)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),Vn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=ct(u.matchUps.map(Gr("roundNumber"))),S=GL(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,mt({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=ct(u.matchUps.flatMap(R=>(R.sides??[]).map(U=>U.participantId)).filter(Boolean)).map(R=>({participantId:R}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,E=c.existingMatchUps.some(R=>R.matchUpType===hr)?{matchUpTypes:[hr]}:void 0,{matchUps:A}=ht({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:E,structure:u,event:a});De({structure:u})&&(u.positionAssignments=ct(A.flatMap(R=>(R.sides??[]).map(U=>U.participantId)).filter(Boolean)).map(R=>({participantId:R})));let D=Qf({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:A,event:a});D.error&&console.log(D)}Lt({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&m.length?{error:au}:{...P,deletedMatchUpsCount:[...g,...I].length}}function qM({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){let s=at({tournamentRecord:e,drawDefinition:r},[Z,zt]);if(s.error)return s;if(!o)return M({result:{error:nt},info:"roundNumber required"});let a=tt({drawDefinition:r,structureId:n});if(a.error)return a;let c=a.structure;return c?.structures?{error:Wo}:De({structure:c})?v5({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:c}):(console.log("not implemented"),{...P})}function v5({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:r,roundNumber:n,structure:o,eventId:i}){let s=o?.matchUps??[],a=[],c=[],u=!1;if(s.reduce((d,m)=>{let l=m?.roundNumber;return l?d.includes(l)?d:d.concat(l):d},[]).sort(ee).includes(n)){let d=s.filter(m=>{let l=m.roundNumber===n&&(!Rt.includes(m.matchUpStatus)||t);return l&&(c.push(m.matchUpId),m.tieMatchUps&&a.push(...m.tieMatchUps.map(Pe))),!l});c.length&&(Vn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),d.some(l=>l.roundNumber===n)||(d.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,mt({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=d)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...P}}function md(t){let{suppressNotifications:e,tournamentRecord:r,drawDefinition:n,matchUps:o,event:i}=t;if(typeof n!="object")return{error:K};let s=t?.structureId;if(!s&&n.structures?.length===1&&(s=n.structures?.[0]?.structureId),typeof s!="string")return{error:mn};if(!Ur(o))return{error:O,info:xi("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:Pt};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===As)return{error:Wo};let p=jt({tournamentRecord:r,inContext:!1})?.matchUps?.map(Pe)??[],d=o.map(Pe);if(we(p,d))return{error:kR,info:"One or more matchUpIds already present in tournamentRecord"};a.matchUps.push(...o);let m=o.map(({tieMatchUps:l})=>l).filter(Boolean).flat();return e||(zo({tournamentId:r?.tournamentId,matchUps:[...m,...o],eventId:i?.eventId,drawDefinition:n}),Lt({drawDefinition:n,structureIds:[s]})),{...P}}function $M({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:K};if(!n)return{error:mn};if(!r)return{error:Ra};let{structure:s}=tt({drawDefinition:e,structureId:n});if(!s)return{error:Pt};let a=s;s.structures&&s.structureType===Ie&&(a=s.structures?.find(f=>f.positionAssignments?.find(g=>g.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(f=>f.drawPosition===r);u&&At({element:u,attribute:"subOrder",name:Wa,value:o});let d=(i?.eventType===xt||e.matchUpType===xt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[xt]},{matchUps:m}=ht({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),l=s?.matchUpFormat??e.matchUpFormat;return Qf({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:l,matchUps:m,event:i}),Lt({drawDefinition:e,structureIds:[n]}),{...P}}var uv={};_t(uv,{addGoesTo:()=>bs,allPlayoffPositionsFilled:()=>BA,checkValidEntries:()=>ig,findDrawDefinition:()=>iP,getAssignedParticipantIds:()=>ss,getAvailableMatchUpsCount:()=>Zf,getAvailablePlayoffProfiles:()=>sd,getDraftState:()=>PP,getDrawDefinitionTimeItem:()=>qE,getDrawParticipantRepresentativeIds:()=>eP,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>gd,getEligibleVoluntaryConsolationParticipants:()=>tP,getLuckyDrawRoundStatus:()=>zf,getMatchUpsMap:()=>ye,getParticipantIdFinishingPositions:()=>rg,getPositionAssignments:()=>Bu,getPositionsPlayedOff:()=>wu,getRandomQualifierList:()=>SP,getSeedingThresholds:()=>PA,getSeedsCount:()=>Id,getStructureSeedAssignments:()=>Dr,getSwissChart:()=>AP,getSwissStandings:()=>TP,getTally:()=>EP,getTeamLineUp:()=>oa,getValidGroupSizes:()=>Cm,hasLuckyRounds:()=>Wh,isAdHoc:()=>De,isCompletedStructure:()=>Bo,isValidForQualifying:()=>yP,positionActions:()=>hP,predictDrawCompetitiveBands:()=>ld,validatePlayoffGroups:()=>Yf});function tP({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:r,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:d,winsLimit:m,event:l}){if(!a)return{error:K};let f=[j,Vt];r&&f.push(rt);let g=_5({includeEventParticipants:e,tournamentRecord:s,drawDefinition:a,stages:f,event:l}),I=ns({stage:Qe,drawDefinition:a}),h=new Set(I.map(({participantId:b})=>b)),S=x5({excludedMatchUpStatuses:t,includeEventParticipants:e,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:d,winsLimit:m,event:l}),{participantMatchUps:T,losingParticipants:y,matchUpParticipants:E,participantWins:A}=w5({excludedMatchUpStatuses:S.excludedMatchUpStatuses,finishingRoundLimit:S.finishingRoundLimit,roundNumberLimit:S.roundNumberLimit,requirePlay:S.requirePlay,matchUps:g}),N=Object.keys(y),D=k5({includeEventParticipants:S.includeEventParticipants,requireLoss:S.requireLoss,requirePlay:S.requirePlay,allEntries:S.allEntries,matchUpParticipants:E,losingParticipants:y,tournamentRecord:s,drawDefinition:a,event:l}),R=new Set(N);return{eligibleParticipants:D.filter(b=>O5({voluntaryConsolationEntryIds:h,losingParticipantIdSet:R,participantMatchUps:T,participantWins:A,resolvedPolicy:S,participant:b})).map(b=>({...b,individualParticipants:b.individualParticipantIds?.map(C=>s?.participants?.find(_=>_.participantId===C))})),losingParticipantIds:N,...P}}function O5({voluntaryConsolationEntryIds:t,losingParticipantIdSet:e,participantMatchUps:r,participantWins:n,resolvedPolicy:o,participant:i}){let s=i.participantId,a=o.requireLoss?e.has(s):!0,c=o.requirePlay?(r[s]||0)>=0:!0,u=o.winsLimit?(n[s]||0)<=o.winsLimit:!0,p=o.matchUpsLimit?r[s]<=o.matchUpsLimit:!0,d=!t.has(s);return a&&c&&u&&p&&d}function _5({includeEventParticipants:t,tournamentRecord:e,drawDefinition:r,stages:n,event:o}){let i=o?.eventType?{matchUpTypes:[o.eventType]}:void 0,s=r?.matchUpType?{matchUpTypes:[r.matchUpType]}:void 0;return t&&o?_n({contextFilters:{stages:n},matchUpFilters:i,tournamentRecord:e,inContext:!0,event:o})?.matchUps??[]:sr({contextFilters:{stages:n},matchUpFilters:s,tournamentRecord:e,inContext:!0,drawDefinition:r})?.matchUps??[]}function x5({excludedMatchUpStatuses:t,includeEventParticipants:e,finishingRoundLimit:r,policyDefinitions:n,roundNumberLimit:o,tournamentRecord:i,drawDefinition:s,matchUpsLimit:a,requirePlay:c,requireLoss:u,allEntries:p,winsLimit:d,event:m}){let f=(n??Do({policyTypes:[NE],tournamentRecord:i,drawDefinition:s,event:m}).policyDefinitions)?.[NE],g=t.length&&t||(f?.excludedMatchUpStatuses??[]);return{includeEventParticipants:e??f?.includeEventParticipants,finishingRoundLimit:r??f?.finishingRoundLimit,excludedMatchUpStatuses:g,roundNumberLimit:o??f?.roundNumberLimit,matchUpsLimit:a??f?.matchUpsLimit,requirePlay:c??f?.requirePlay??!0,requireLoss:u??f?.requireLoss??!0,allEntries:p??f?.allEntries,winsLimit:d??f?.winsLimit}}function w5({excludedMatchUpStatuses:t,finishingRoundLimit:e,roundNumberLimit:r,requirePlay:n,matchUps:o}){let i={},s={},a={},c={},u=new Set(t);for(let p of o)L5({matchUp:p,requirePlay:n,finishingRoundLimit:e,roundNumberLimit:r})&&F5({matchUp:p,requirePlay:n,excludedSet:u,participantMatchUps:i,losingParticipants:s,matchUpParticipants:a,participantWins:c});return{participantMatchUps:i,losingParticipants:s,matchUpParticipants:a,participantWins:c}}function L5({matchUp:t,requirePlay:e,finishingRoundLimit:r,roundNumberLimit:n}){return!(e&&t.winningSide&&![1,2].includes(t.winningSide)&&t.matchUpStatus!==Zt||t.finishingRound&&r&&t.finishingRound>=r||t.finishingRound&&n&&t.finishingRound<=n)}function F5({matchUp:t,requirePlay:e,excludedSet:r,participantMatchUps:n,losingParticipants:o,matchUpParticipants:i,participantWins:s}){let a=t.sides?.find(({sideNumber:u})=>t.winningSide&&u===3-t.winningSide),c=t.sides?.find(({sideNumber:u})=>t.winningSide&&u===t.winningSide);if(t.sides?.forEach(u=>{let p=u?.participant?.participantId;p&&(i[p]=u.participant,t.matchUpStatus===Zt&&!e&&(o[p]=u.participant,n[p]||(n[p]=0),(!t.matchUpStatus||!r.has(t.matchUpStatus))&&(n[p]+=1)))}),a?.participant){let u=a.participant.participantId;o[u]=a.participant,n[u]||(n[u]=0),t.matchUpStatus&&!r.has(t.matchUpStatus)&&(n[u]+=1)}if(c?.participant){let u=c.participant.participantId;s[u]||(s[u]=0),s[u]+=1,n[u]||(n[u]=0),t.matchUpStatus&&!r.has(t.matchUpStatus)&&(n[u]+=1)}}function k5({includeEventParticipants:t,matchUpParticipants:e,losingParticipants:r,tournamentRecord:n,drawDefinition:o,requireLoss:i,requirePlay:s,allEntries:a,event:c}){let u=n?.participants&&!s&&!i&&a,p;t&&c?p=c.entries:p=o.entries;let d=new Set([On,kr]),m=u?(p??[]).filter(l=>!d.has(l.entryStatus)).map(({participantId:l})=>l):[];if(u){let l=new Set(m);return(n?.participants??[]).filter(({participantId:f})=>l.has(f))}return Object.values(i?r:e)}function Zf(t){let e=X(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:mn};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:Pt};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===As)return{error:Wo};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return yr.includes(I)})??[],p=Math.floor(u?.length/2)||1,d=n??c??1,m=i.matchUps?.filter(g=>g.roundNumber===d)?.length??0,l=p-m,f=l>0?l:0;return{...P,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function eP({drawDefinition:t}){let e=qt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value??[]}}function zM(t){let e=Math.min(.999999999,Math.max(1e-9,t));return Math.log(e/(1-e))}function b1(t,e){let r=zM(t.probability)-zM(e.probability),n=e.delta-t.delta,o=n===0?0:r/n,i=o===0?t.delta:t.delta+zM(t.probability)/o;return{k:o,x0:i}}function C1({k:t,x0:e},r){return t===0?.5:1/(1+Math.exp(t*(r-e)))}function tg(t,e){let[r,n]=e.competitiveAnchors,[o,i]=e.decisiveAnchors;if(!r||!n||!o||!i)return{competitive:0,decisive:0,routine:1};let s=b1(r,n),a=C1(s,t),c=b1({delta:o.delta,probability:1-o.probability},{delta:i.delta,probability:1-i.probability}),u=1-C1(c,t),p=Math.min(1,Math.max(0,a)),d=Math.min(1,Math.max(0,u)),m=1-p-d,l=Math.max(0,m);if(m<0){let f=p+d;return{competitive:p/f,decisive:d/f,routine:0}}return{competitive:p,decisive:d,routine:l}}var G5=new Set([on,Ys,qs,Ga,Cp,bp,js,di,Ki]),V5=new Set([_r,hE,sn]),B5=new Set([$s]),H5=zs[gn].predictionModel;function W5(t,e){if(t)return t;if(e){let{policy:r}=Uo({policyType:gn,tournamentRecord:e});if(r?.predictionModel)return r.predictionModel}return H5}function j5(t){if(G5.has(t))return"BALANCED_BRACKET";if(V5.has(t))return"ROUND_ROBIN";if(B5.has(t))return"MIN_DELTA"}function Y5(t){let e=[],r=Math.floor(t.length/2);for(let n=0;n<r;n++)e.push([t[n],t[t.length-1-n]]);return e}function q5(t){let e=[],r=t.length-t.length%2;for(let n=0;n<r;n+=2)e.push([t[n],t[n+1]]);return e}function M1(t){let e=[];for(let r=0;r<t.length;r++)for(let n=r+1;n<t.length;n++)e.push([t[r],t[n]]);return e}function $5(t,e){if(!e||e<2)return M1(t);let r=[];for(let n=0;n<t.length;n+=e){let o=t.slice(n,n+e);o.length>=2&&r.push(...M1(o))}return r}function K5(t,e,r){return e==="BALANCED_BRACKET"?Y5(t):e==="ROUND_ROBIN"?$5(t,r):q5(t)}function z5(t){if(t.length===0)return{competitive:0,decisive:0,routine:0};let e=t.reduce((n,o)=>(n.competitive+=o.competitive,n.decisive+=o.decisive,n.routine+=o.routine,n),{competitive:0,decisive:0,routine:0}),r=t.length;return{competitive:e.competitive/r,decisive:e.decisive/r,routine:e.routine/r}}function ld({tournamentRecord:t,projectionMode:e,predictionModel:r,groupSize:n,ratings:o,drawType:i}){if(!Array.isArray(o)||o.length<2)return{competitive:0,decisive:0,routine:0,error:O};let s=e??(i?j5(i):void 0);if(!s)return{competitive:0,decisive:0,routine:0,error:O};let a=W5(r,t),c=[...o].sort((m,l)=>l-m),u=K5(c,s,n),p=u.map(([m,l])=>tg(Math.abs(m-l),a));return{...z5(p),perMatchUpPredictions:p,projectionMode:s,projectedPairs:u,expectedMatchCount:u.length}}function v1({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:K};let n=re({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=q(n.matchUps,!1,!0),i=ct(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(d=>d.participantId).filter(Boolean).includes(a));return{[a]:c}}));return{participantIds:i,participantIdMatchUps:s}}function Bu({tournamentRecord:t,drawDefinition:e,stage:r=j,structureId:n,structure:o}){if(!t)return{error:Y};if(!o&&!e)return{error:K};if(!o&&!n&&e?.structures?.filter(a=>a.stage===r).length===1&&(o=e.structures.find(a=>a.stage===r)),!o&&!n)return{error:mn};let{error:i,positionAssignments:s}=yt({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function QM({dates:t=[],disabledValue:e,extension:r}){let n=e!==void 0?e:r?.value;if(n===void 0)return!1;if(typeof n=="boolean"&&n)return!0;if(!t.length)return!1;let o=St(n)?n?.dates:void 0;if(Array.isArray(o))return o?.length?!!o.filter(s=>!t.length||t.includes(s)).length:!1}function O1({inContextCourt:t,venue:e}){let{defaultStartTime:r,defaultEndTime:n,dateAvailability:o}=e;if(!(r||n||o?.length))return;let s=t.dateAvailability;if(!s?.length){o?.length?t.dateAvailability=o.map(a=>({...a})):r&&n&&(t.dateAvailability=[{startTime:r,endTime:n}]);return}t.dateAvailability=s.map(a=>{let c=Q5({date:a.date,venueDateAvailability:o,defaultStartTime:r,defaultEndTime:n});if(!c)return a;let u=J5(a.startTime,c.startTime),p=X5(a.endTime,c.endTime),d=Z5(a.bookings,c.bookings);return{...a,startTime:u,endTime:p,...d.length?{bookings:d}:{}}})}function Q5({date:t,venueDateAvailability:e,defaultStartTime:r,defaultEndTime:n}){if(e?.length){if(t){let i=e.find(s=>s.date===t);if(i)return i}let o=e.find(i=>!i.date);if(o)return o}if(r||n)return{startTime:r,endTime:n}}function J5(t,e){return t?e?t>e?t:e:t:e}function X5(t,e){return t?e?t<e?t:e:t:e}function Z5(t,e){let r=[];return t?.length&&r.push(...t),e?.length&&r.push(...e),r}function JM({convertExtensions:t,ignoreDisabled:e,venue:r,court:n}){let o={...q(n,t,!0),venueId:r.venueId},i=$t({element:n,attribute:"disabled",name:Gn});if(e&&i!==void 0){let s=St(i)?i?.dates:void 0,a=i===!0?[]:o.dateAvailability.map(c=>{let u=c.date;if(!(!u||s.includes(u)))return c}).filter(Boolean);o.dateAvailability=a}return O1({inContextCourt:o,venue:r}),{inContextCourt:o}}function t4(t,e,r){return!(e.length&&!e.includes(t.venueId)||r&&$t({element:t,attribute:"disabled",name:Gn}))}function e4({venue:t,convertExtensions:e,ignoreDisabled:r,dates:n,uniqueVenueIds:o,venues:i,uniqueCourtIds:s,courts:a}){o.includes(t.venueId)||(i.push(q(t,e,!0)),o.push(t.venueId));for(let c of t.courts??[])if(!s.includes(c.courtId)){if(r){let p=$t({element:c,attribute:"disabled",name:Gn});if(QM({disabledValue:p,dates:n}))continue}let{inContextCourt:u}=JM({convertExtensions:e,ignoreDisabled:r,venue:t,court:c});a.push(u),s.push(c.courtId)}}function qn(t){let{convertExtensions:e,ignoreDisabled:r,venueIds:n=[],dates:o}=t,i=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},s=[],a=[],c=[],u=[];return Object.keys(i).filter(d=>!t.tournamentId||d===t.tournamentId).forEach(d=>{let m=i[d];for(let l of m.venues??[])t4(l,n,!!r)&&e4({venue:l,convertExtensions:e,ignoreDisabled:r,dates:o,uniqueVenueIds:s,venues:u,uniqueCourtIds:a,courts:c})}),{courts:c,venues:u,...P}}function r4({convertExtensions:t,tournamentRecord:e,ignoreDisabled:r,dates:n}){if(!e)return{error:kt};let o=q(e.venues??[],t).filter(s=>r?!$t({element:s,attribute:"disabled",name:Gn})&&s:s).filter(Boolean),i=o.reduce((s,a)=>{let c=(a?.courts??[]).filter(u=>{if(!r&&!n?.length)return u;let p=$t({element:u,attribute:"disabled",name:Gn});return QM({disabledValue:p,dates:n})}).filter(Boolean).map(u=>{let{inContextCourt:p}=JM({convertExtensions:t,ignoreDisabled:r,venue:a,court:u});return p});return c.length?s.concat(c):s},[]);return{venues:o,courts:i}}function km({tournamentRecords:t,requireCourts:e,dates:r}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:Object.keys(t).reduce((o,i)=>{let s=t[i],{venues:a}=r4({tournamentRecord:s,dates:r});return a?.forEach(c=>{let{venueId:u,courts:p}=c;(!e||p?.length)&&!o.venueIds.includes(u)&&(o.venues.push(c),o.venueIds.push(u))}),o},{venues:[],venueIds:[]})}function rP({event:t}){let{surfaceCategory:e,onlineResources:r,matchUpFormat:n,discipline:o,eventLevel:i,eventName:s,eventType:a,startDate:c,category:u,ballType:p,eventId:d,endDate:m,gender:l,notes:f}=t,g=t.entries?.length??0;return{eventInfo:{drawDefinitionCount:t.drawDefinitions?.length,entriesCount:g,surfaceCategory:e,onlineResources:r,matchUpFormat:n,discipline:o,eventLevel:i,eventName:s,eventType:a,ballType:p,startDate:c,category:u,endDate:m,eventId:d,gender:l,notes:f}}}var n4="IN_PROGRESS",o4="ABANDONED",i4="CANCELLED",s4="COMPLETED",a4="ACTIVE",XM="tournamentImage",nP={TOURNAMENT_IMAGE_RESOURCE_NAME:XM,IN_PROGRESS:n4,ABANDONED:o4,CANCELLED:i4,COMPLETED:s4,ACTIVE:a4};var c4={[Ba]:{policyName:"Staff Privacy Policy",participant:{contacts:!1,individualParticipants:!1,individualParticipantIds:!1,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantRoleResponsibilities:!0,participantStatus:!0,penalties:!1,representing:!0,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}},_1=c4;function fa(t){let{tournamentRecord:e,withMatchUpStats:r,withStructureDetails:n,withVenueData:o}=t??{};if(!e)return{error:Y};let s=(({tournamentId:I,tournamentRank:h,tournamentStatus:S,formalName:T,tournamentName:y,promotionalName:E,onlineResources:A,localTimeZone:N,activeDates:D,startDate:R,endDate:U,hostCountryCode:b,venues:C,notes:_,registrationProfile:v,updatedAt:x})=>({tournamentId:I,tournamentRank:h,tournamentStatus:S,formalName:T,tournamentName:y,promotionalName:E,onlineResources:A,localTimeZone:N,activeDates:D,startDate:R,endDate:U,hostCountryCode:b,venues:C,notes:_,registrationProfile:v,updatedAt:x}))(e),a=e.venues?.find(I=>I.isPrimary);a?.addresses?.length&&(s.tournamentAddress=a.addresses[0]);let u=Nt({participantFilters:{participantRoles:[ZC,Zh,tM,eM,nM]},policyDefinitions:_1,tournamentRecord:e})?.participants??[];u&&(s.tournamentContacts=u);let p=e?.onlineResources?.find(I=>I.name===XM&&I.resourceType==="URL")?.identifier;p&&(s.imageUrl=p);let d=da({tournamentRecord:e})?.publishState,m=d?.tournament?.status?.publishedEventIds??[],l=[];for(let I of e.events??[])if(!t?.usePublishState||m.includes(I.eventId)){let h=rP({event:I}).eventInfo;h&&l.push(h)}s.timeItemValues=kA({element:e}),s.publishState=d?.tournament,s.eventInfo=l;let f=[],g=[];if(r||n)for(let I of e.events??[])for(let h of I.drawDefinitions??[])for(let S of h.structures??[])g.push(...S.matchUps??[]),f.push(et({eventId:I.eventId,eventName:I.eventName,eventType:I.eventType,drawId:h.drawId,drawName:h.drawName,drawType:h.drawType,structureId:S.structureId,structureName:S.structureName,stage:S.stage,stageSequence:S.stageSequence,positionAssignments:S.positionAssignments,seedAssignments:S.seedAssignments,matchUpFormat:S.matchUpFormat}));if(n&&(s.structures=f),r){let I=e.participants?.filter(D=>D.participantType===ft).length??0,h=e.participants?.filter(D=>D.participantType===bt).length??0,S=e.events?.length??0,T=g?.filter(D=>D.matchUpStatus!=="BYE"),y=T?.length,E=T?.filter(D=>Rt.includes(D.matchUpStatus)||D.winningSide)?.length,A=T?.filter(D=>na({matchUp:D})?.scheduledDate||bf({matchUp:D})?.scheduledTime)?.length,N=y>0?Math.round(E/y*100):0;s.matchUpStats={total:y,completed:E,scheduled:A,percentComplete:N},s.individualParticipantCount=I,s.teamParticipantCount=h,s.eventCount=S}if(o){let{venues:I}=qn({tournamentRecord:e});s.venues=I??[]}return{tournamentInfo:q(et(s),!1,!0),...P}}function oP({publishStatus:t,drawId:e}){return t?.drawDetails?go(t.drawDetails?.[e]?.publishingDetail):t?.drawIds?t.drawIds.includes(e):!0}var ZM="PUBLIC",u4="ADMIN",x1={PUBLIC_DISPLAY:ZM,ADMIN_DISPLAY:u4};function eg(t){let{tournamentParticipants:e=[],includePositionAssignments:r,policyDefinitions:n,tournamentRecord:o,inContext:i=!0,usePublishState:s,status:a=Rr,pressureRating:c,refreshResults:u,contextProfile:p,drawDefinition:d,noDeepCopy:m,sortConfig:l,context:f,event:g}=t;if(!d)return{error:K};let{matchUpFormat:I,updatedAt:h,drawType:S,drawName:T,drawId:y}=d,E={matchUpFormat:I,updatedAt:h,drawName:T,drawType:S,drawId:y};E.display=qt({element:d,name:sf}).extension?.value;let A={},N,D,{allStructuresLinked:R,sourceStructureIds:U,hasDrawFeedProfile:b,structureGroups:C}=cd({drawDefinition:d});if(!R)return{error:HU};let _=t?.eventPublishState??da({event:g}).publishState,v=t?.publishStatus??br({event:g,status:a}),x=_?.status?.drawDetails?.[d.drawId],w=!!_?.status?.published,F=x?.structureDetails,L=!1,k=!1,V=C.map(B=>{let $={},H=B.map(z=>{let{structure:W}=tt({drawDefinition:d,structureId:z}),{seedAssignments:Q}=Dr({drawDefinition:d,structure:W});return W?.stage===j&&W.stageSequence===1&&(N=Q),W?.stage===rt&&(A[W.stageSequence??0]=Q),W}).sort((z,W)=>Xi(z,W,l)).map(z=>{if(!z)return;let W=z?.structureId,Q=[];z.stage&&[j,je,Vt].includes(z.stage)&&(Q=N),z?.stage===rt&&(Q=A[z.stageSequence??0]);let{matchUps:pt,roundMatchUps:Tt,roundProfile:Ot}=ht({seedAssignments:z?.seedAssignments?.length?void 0:Q,context:{drawId:E.drawId,...f},hydrateParticipants:t.hydrateParticipants,participantsProfile:t.participantsProfile,tournamentParticipants:e,policyDefinitions:n,tournamentRecord:o,usePublishState:s,publishStatus:v,contextProfile:p,drawDefinition:d,inContext:i,structure:z,event:g}),{positionAssignments:Et}=yt({structure:z}),Bt=Et?.filter(Gr(Ge)).map(oo=>{let Ln=$t({element:oo,attribute:"tally",name:to}),{drawPosition:Fn,participantId:Ui}=oo;return k=!0,{participantResult:Ln,participantId:Ui,drawPosition:Fn}});if(pt.length&&(!Bt?.length&&t.allParticipantResults||u&&!z.structures)){let{subOrderMap:oo}=Lf({positionAssignments:Et}),Fn=pt.some(ii=>ii.matchUpType===hr)?pt.filter(ii=>ii.matchUpType===hr):pt,Ui=pa({matchUpFormat:z.matchUpFormat,matchUps:Fn,policyDefinitions:n,pressureRating:c,subOrderMap:oo});D=Ui?.report,Bt=Et?.filter(Gr(Ge)).map(ii=>{let{drawPosition:Pa,participantId:Fs}=ii;return k=!0,{participantResult:Fs&&Ui?.participantResults?.[Fs],participantId:Fs,drawPosition:Pa}})}let ce=z?{stageSequence:z.stageSequence,structureName:z.structureName,structureType:z.structureType,finishingPosition:z.finishingPosition,matchUpFormat:z.matchUpFormat,stage:z.stage}:{},ge=qt({element:z,name:sf}).extension?.value;ce.display=ge?.[ZM]??ge,ce.sourceStructureIds=U[W],ce.hasDrawFeedProfile=b[W],ce.positionAssignments=Et,ce.structureActive=pt.reduce((oo,Ln)=>{let Fn=[Zt,Te,vn,ae,mo,Mt,ve,vt].includes(Ln.matchUpStatus);return oo||Fn||!!Ln.winningSide||!!Ln.score?.scoreStringSide1},!1);let he=pt.every(oo=>[...Rt,"BYE"].includes(oo.matchUpStatus));return ce.structureCompleted=he,$[W]=he,ce.structureActive&&(L=!0),{...ce,participantResults:Bt,seedAssignments:Q,roundMatchUps:Tt,roundProfile:Ot,structureId:W,report:D}});return H.forEach(z=>{r||delete z.positionAssignments,z.sourceStructuresComplete=z.sourceStructureIds?.every(W=>$[W])}),H}).flat().filter(B=>!s||go(F?.[B?.structureId])||!0);return E.drawActive=L,E.participantPlacements=k,E.drawGenerated=V?.reduce((B,$)=>B||!!$?.roundMatchUps,!1),E.drawCompleted=V?.reduce((B,$)=>B&&$.structureCompleted,!0),E.drawPublished=s?w&&oP({publishStatus:v,drawId:E.drawId}):void 0,{structures:!s||E.drawPublished?m&&V||q(V,!1,!0):void 0,drawInfo:m?E:q(E,!1,!0),...P}}function fd(t){let{includePositionAssignments:e,participantsProfile:r,policyDefinitions:n,usePublishState:o,status:i=Rr,contextProfile:s,sortConfig:a}=t,c=X(t,[{tournamentRecord:!0},{[Op]:{event:!1,eventId:!1}}]);if(c.error)return c;let u=q(t.tournamentRecord,!1,!0),p=t.event==null?Ve({tournamentRecord:u,eventId:t.eventId}).event:void 0,d=t.event?q(t.event,!1,!0):p&&q(p,!1,!0)||void 0;if(!d)return{error:Br};let{eventId:m}=d,{tournamentId:l,endDate:f}=u,g=br({event:d,status:i}),I=da({event:d}).publishState??{},h=!!I?.status?.published,{participants:S}=Nt({participantFilters:t.participantFilters,withGroupings:!0,withEvents:!1,withDraws:!1,policyDefinitions:n,...r,tournamentRecord:u}),T=({stage:v,drawId:x})=>{if(!o)return!0;let w=g?.drawDetails?.[x]?.stageDetails;return!w||!Object.keys(w).length?!0:go(w[v])},y=({structureId:v,drawId:x})=>{if(!o)return!0;let w=g?.drawDetails?.[x]?.structureDetails;return!w||!Object.keys(w).length?!0:go(w[v])},E=({drawId:v})=>o?oP({publishStatus:g,drawId:v}):!0,A=({drawId:v,drawType:x,structure:w})=>{if(!o||!En(x))return w;let F=g?.drawDetails?.[v]?.structureDetails?.[w.structureId]?.roundLimit;if(It(F)){let L=J(1,F+1),k={},G={};for(let V of L)w.roundMatchUps[V]&&(k[V]=w.roundMatchUps[V],G[V]=w.roundProfile[V]);w.roundMatchUps=k,w.roundProfile=G}return w},N=d.drawDefinitions??[],D=!o||h?N.filter(E).map(v=>(({drawInfo:x,structures:w})=>({...x,structures:w}))(eg({allParticipantResults:t.allParticipantResults,hydrateParticipants:t.hydrateParticipants,context:{eventId:m,tournamentId:l,endDate:f},pressureRating:t.pressureRating,refreshResults:t.refreshResults,includePositionAssignments:e,tournamentParticipants:S,eventPublishState:I,noDeepCopy:!0,policyDefinitions:n,tournamentRecord:u,usePublishState:o,contextProfile:s,drawDefinition:v,publishStatus:g,sortConfig:a,event:d}))).map(({structures:v,...x})=>{let w=v?.filter(({stage:F,structureId:L})=>y({structureId:L,drawId:x.drawId})&&T({stage:F,drawId:x.drawId})).map(F=>A({drawId:x.drawId,drawType:x.drawType,structure:F}));return{...x,structures:w}}).filter(v=>v.structures?.length):void 0,U=(Array.isArray(u.venues)?u.venues:[]).map(v=>{let{venueData:x}=Ru({venueId:v.venueId,tournamentRecord:u});return{...x}}),b=(({eventId:v,eventName:x,eventType:w,eventLevel:F,surfaceCategory:L,matchUpFormat:k,category:G,gender:V,startDate:B,endDate:$,ballType:H,discipline:z})=>({eventId:v,eventName:x,eventType:w,eventLevel:F,surfaceCategory:L,matchUpFormat:k,category:G,gender:V,startDate:B,endDate:$,ballType:H,discipline:z}))(d);b.display=qt({element:d,name:sf}).extension?.value;let{tournamentInfo:C}=fa({tournamentRecord:u}),_={tournamentInfo:C,venuesData:U,eventInfo:b,drawsData:D};return _.eventInfo.publishState=I,_.eventInfo.published=I?.status?.published,{...P,eventData:_,participants:S}}function rg({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r,event:n}){if(!r)return{error:K};let{participantIds:o,participantIdMatchUps:i}=v1({tournamentParticipants:e?.participants,drawDefinition:r}),s=Object.values(i).some(f=>f.some(g=>g.containerStructureId)),c=(s&&fd({tournamentRecord:e,event:n}))?.eventData?.drawsData?.find(f=>f.drawId===r.drawId)?.structures,u=r?.structures?.find(f=>f.stage===j&&f.stageSequence===1),p=u?.structureType===Ie&&u.structures,m=(s?Bu({tournamentRecord:e,drawDefinition:r,structureId:u?.structureId})?.positionAssignments:void 0)?.length||0,l=o?.map(f=>{let I=i[f].filter(y=>[ae,"BYE"].includes(y.matchUpStatus)||y.winningSide),h=I.map(y=>{let E=y.sides.find(R=>R.bye),A=y.sides.find(R=>R.participantId===f).sideNumber;if(y.containerStructureId){let R=p4({containedStructures:p,drawPositionsCount:m,drawDataStructures:c,drawDefinition:r,participantId:f,matchUp:y});if(R)return R}return(y.winningSide||t&&E&&A)===A?y.finishingPositionRange.winner:y.finishingPositionRange.loser}),S=y=>Math.abs(y[0]-y[1]),T=h.reduce((y,E)=>y&&S(y)<S(E)?y:E,void 0);return{[f]:{finishingPositionRanges:h,finishingPositionRange:T,relevantMatchUps:I}}})??[];return Object.assign({},...l)}function p4({containedStructures:t,drawPositionsCount:e,drawDataStructures:r,drawDefinition:n,participantId:o,matchUp:i}){let a=t?.find(f=>f.structureId===i.structureId)?.positionAssignments?.length,c=r.find(f=>f.structureId===i.containerStructureId)?.participantResults?.find(f=>f.participantId===o)?.participantResult,{ties:u,groupOrder:p,provisionalOrder:d}=c??{},m=t?.length,l=n.structure?.find(f=>f.stage===Vt);if(We()&&console.log({drawPositionsCount:e,provisionalOrder:d,bracketsCount:m,bracketSize:a,groupOrder:p,ties:u}),e===a&&p)return[p,p];if(m>1&&p&&!l)return[1,m];if(m>1&&p&&l){let f=n.links?.find(I=>I.source.structureId===i.containerStructureId)?.source?.finishingPositions,g=f.length*m;if(p in f)return[1,g];{let I=(a-p)*m;return[g+1,e-I]}}}function ei({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:Y};if(!n)return{error:Un};if(!e&&t){if(typeof r!="string"&&(r=JA({tournamentRecords:t,drawId:n}),!r))return{error:Ic};if(e=t[r],!e)return{error:Y}}let o=e&&Ve({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...P}:M({result:{error:Cr},stack:"findDrawDefinition"})}function iP(t){let{drawDefinition:e,error:r}=ei(t);return r?{error:r}:{drawDefinition:q(e)}}function w1({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[kr,es].includes(a)).map(({participantId:a})=>a)??[];if(s.length){let a=n.individualParticipantIds,c=e?t.filter(({participantId:d})=>s.includes(d)):void 0,u=e?t.filter(({participantId:d})=>a.includes(d)):void 0;return{validModifyAssignedPairAction:et({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:p1,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:TS},!1,!1,!0)}}return{}}function us(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===Jn&&r?.matchUp?.matchUpStatus==="BYE")return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&ir({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,d=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,m=p?.sides[d]?.participant,l=ze(s?.matchUpStatus),f=l&&!m,g=s?.sides?.filter(E=>E?.participant).length??0,I=s?.winningSide&&l&&g===1,h=a?.drawPositions?.filter(Boolean).length||0;if(!I&&(s?.winningSide&&!f||a?.winningSide&&h===2&&(!a.feedRound||!ze(a?.matchUpStatus))))return!0;let S=a&&ir({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),T=u&&us({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(S&&us({targetData:S,inContextDrawMatchUps:e,drawDefinition:n})||T)}var sP={[uo]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[rt,j],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[ud,Za,_m,Xa],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var RS="positionAction",aP="matchUpAction";function cP({actionType:t=RS,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===RS&&uo||t===aP&&Ke,i=t===RS&&sP||t===aP&&XC,s=o&&(e?.[o]||i?.[o]),c=r.links?.filter(m=>m?.target?.structureId===n?.structureId)?.map(({target:m})=>m.feedProfile)??[],{enabledStructures:u,disabledStructures:p}=s??{},d=p?.find(m=>{let{stages:l,stageSequences:f,structureTypes:g,feedProfiles:I}=m;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:d,actionsPolicy:s}}function L1({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function uP({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:d,structureTypes:m,feedProfiles:l}=u??{},f=!p?.length||Array.isArray(p)&&p.includes(n),g=!d?.length||Array.isArray(d)&&d.includes(o),I=!m?.length||Array.isArray(m)&&m.includes(i),h=!l?.length||Array.isArray(l)&&l.some(S=>a.includes(S));return g&&I&&h&&u&&f})}}function ro({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 tv="replaceTieMatchUpParticipantId",ev="assignTieMatchUpParticipantId",pP="removeTieMatchUpParticipantId",rv="assignMatchUpSideParticipant",F1="removeMatchUpSideParticipant",nv="substituteParticipant",dP="REMOVE_SUBSTITUTION",ov="REPLACE_PARTICIPANT",bS="REMOVE_PARTICIPANT",mP="setMatchUpStatus",lP="SUBSTITUTION",iv="SCHEDULE",d4="PENALTY",fP="REFEREE",sv="STATUS",gP="START",av="SCORE";var k1={REPLACE_TEAM_POSITION_METHOD:tv,ASSIGN_TEAM_POSITION_METHOD:ev,REMOVE_TEAM_POSITION_METHOD:pP,REPLACE_PARTICIPANT:ov,SUBSTITUTION_METHOD:nv,REMOVE_SUBSTITUTION:dP,REMOVE_PARTICIPANT:bS,SCHEDULE_METHOD:mP,SUBSTITUTION:lP,SCHEDULE:iv,PENALTY:d4,REFEREE:fP,STATUS:sv,SCORE:av,START:gP,END:"END"};function G1({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:d,side:m}){let l=[],f=o.sides?.find(F=>F.participant),g=jr(o.gender)&&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(lt),E=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),A=E?.map(lt),D=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:L,person:k})=>!A?.includes(L)&&(!S||To(S)||k.sex===S||jr(S)&&!g||g&&k.sex!==g))),R=c?D?.[c-1]:D?.map((F,L)=>({participants:F,sideNumber:L+1})),U=c?D?.[c-1]?.map(lt):D?.map((F,L)=>({participants:F?.map(lt),sideNumber:L+1})),b=c&&(oe(ks)(I)&&!A?.length||oe(si)(I)&&(A?.length??0)<2)||!c&&(oe(ks)(I)&&(A?.length??0)<2||oe(si)(I)&&(A?.length??0)<4),C=U?.filter(F=>!y?.includes(F)),_=R?.filter(({participantId:F})=>C.includes(F));if(b&&C?.length&&l.push({availableParticipantIds:C,method:ev,availableParticipants:_,type:ma,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:d}}),A?.length&&(!le(p)||m?.substitutions?.length)&&l.push({method:pP,type:bS,existingParticipantIds:A,payload:{participantId:void 0,tieMatchUpId:u,drawId:d}}),_?.length&&(!c&&A?.length||c&&m?.participant)&&l.push({availableParticipantIds:C,method:tv,availableParticipants:_,type:ov,existingParticipantIds:A,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:d}}),ro({policyActions:i,action:dP})&&m?.substitutions?.length){let F=m.participant?.participantType===ft&&[m.participantId]||m.participant?.participantType===dt&&m.participant.individualParticipantIds||[],L=m.substitutions.map(k=>k.participantId).filter(k=>F.includes(k));(!a||L.includes(a))&&l.push({method:pP,type:dP,substitutedParticipantIds:L,payload:{participantId:void 0,tieMatchUpId:u,drawId:d}})}let v=t?.[Ke],x=v?.substituteWithoutScore,w=v?.substituteAfterCompleted;if(ro({policyActions:i,action:lP})&&r.length===2&&(!c&&A?.length||c&&m?.participant)&&(x||le(p))&&(w||p.matchUpStatus&&!Rt.includes(p.matchUpStatus))&&E?.length&&R.length){let F=E.map(lt);l.push({info:"list of team players available for substitution",method:nv,availableParticipantIds:U,existingParticipantIds:F,availableParticipants:R,existingParticipants:E,type:lP,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:d}})}return l}function V1({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:r,positionAssignments:n,returnParticipants:o,appliedPolicies:i,drawDefinition:s,drawPosition:a,validActions:c,structureId:u,structure:p,drawId:d,event:m}){if(r.includes(a))return{};let l=c.find(D=>D.type===ma)?.availableParticipantIds,f=i?.[uo]?.otherFlightEntries,g=i?.[uo]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:D})=>!g||(p.stage===rt?D===rt:D!==rt)).sort((D,R)=>(D.entryPosition??1/0)-(R.entryPosition??1/0)).map(({participantId:D})=>D).filter(Boolean),{allPositionedParticipantIds:h}=kE({drawDefinition:s}),S=n.map(D=>D.participantId).filter(Boolean),T=I.filter(D=>p.stage&&[rt,j,Vt].includes(p.stage)?!h?.includes(D):!S.includes(D)),E=(m?.entries??[]).filter(D=>D.entryStatus===tn&&cv({restrictQualifyingAlternates:g,structure:p,entry:D})&&(p.stage&&[rt,j,Vt].includes(p.stage)?!h?.includes(D.participantId):!S.includes(D.participantId))).sort((D,R)=>(D.entryPosition??1/0)-(R.entryPosition??1/0)).map(D=>D.participantId),A=ct(T.concat(E));if(f){let R=(m?Gt({event:m}).flightProfile:void 0)?.flights?.filter(U=>U.drawId!==d).map(U=>U.drawEntries.filter(b=>b.participantId&&![On,kr,es].includes(b.entryStatus)&&!I.includes(b.participantId)).map(({participantId:b})=>b)).flat().filter(Boolean);R?.length&&A.push(...R)}l?.length&&(A=A.filter(D=>!l.includes(D)));let N=o?t?.filter(D=>A.includes(D.participantId)):void 0;return N?.forEach(D=>{let R=(s.entries??[]).find(U=>U.participantId===D.participantId);D.entryPosition=R?.entryPosition}),N?.sort((D,R)=>(D.entryPosition||1/0)-(R.entryPosition||1/0)),A.length?{validAlternatesAction:et({payload:{drawId:d,structureId:u,drawPosition:a},willDisableLinks:e,method:c1,availableAlternatesParticipantIds:A,type:yS,availableAlternates:N})}:{}}function cv({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===rt&&!t||r.entryStage===j&&n===je)return!0}function B1({eventEntries:t,structure:e}){let r=o=>o.entryStatus===tn&&cv({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(lt)}function H1({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:d}){let m=[],l=c?.matchUps??[],g=u.sides?.find(R=>R.sideNumber===s)?.participantId,I=l.filter(({roundNumber:R})=>R===u.roundNumber),h=o?.entries?.filter(({entryStatus:R})=>R&&rs.includes(R)).map(lt)??[],S=I.map(R=>(R.sides??[]).flatMap(lt)).flat().filter(Boolean),T=h.filter(R=>!r.includes(R)&&(!t||!S.includes(R))),y=e?.filter(R=>T?.includes(R.participantId)).map(R=>q(R,void 0,!0));y?.forEach(R=>{let U=(o.entries??[]).find(b=>b.participantId===R.participantId);R.entryPosition=U?.entryPosition}),T.length&&m.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:rv,type:ma,availableParticipantIds:T,participantsAvailable:y});let E=d?.entries??[],A=B1({eventEntries:E,structure:c}),N=ct(h.concat(A));if(n){let U=(d?Gt({event:d}):void 0)?.flights?.filter(b=>b.drawId!==p).flatMap(b=>b.drawEntries.filter(C=>C.participantId&&![On,kr,es].includes(C.entryStatus)).map(({participantId:C})=>C)).filter(Boolean);U?.length&&N.push(...U)}N=N.filter(R=>!r.includes(R)&&!T.includes(R)&&(!t||!S.includes(R)));let D=e?.filter(R=>N.includes(R.participantId)).map(R=>q(R,void 0,!0));if(D?.forEach(R=>{let U=(o.entries??[]).find(b=>b.participantId===R.participantId);R.entryPosition=U?.entryPosition}),D?.sort((R,U)=>(R.entryPosition||1/0)-(U.entryPosition||1/0)),N.length&&m.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:N,participantsAvailable:D,method:rv,type:tn}),!le(u)&&s&&g){m.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:F1,type:bS});let R=L=>L.sides.map(lt),U=({matchUpId:L})=>L!==u.matchUpId,b=L=>!le(L),C=u.sides?.find(L=>L.sideNumber!==s)?.participantId,v=l.filter(({roundNumber:L})=>L!==u.roundNumber).filter(U).map(R),x=[C,...v.filter(L=>L.includes(g)).flat()].filter(Boolean),w=L=>!x.flat().includes(L),F=I.filter(b).filter(U).map(R).flat().filter(w);if(F.length){let L=e?.filter(k=>F.includes(k.participantId)).map(k=>q(k,void 0,!0));m.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:d1,type:wm,swappableParticipants:L})}}return m}function ng(t){if(!t)return{error:O};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&&wt(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:Y};if(!c||!wt(c))return{error:cr};if(a&&![1,2].includes(a))return M({result:{error:O},context:{sideNumber:a}});if(!e){let x=m4({tournamentRecord:u,matchUpId:c});x.drawDefinition&&(e=x.drawDefinition),x.event&&(r=x.event)}if(!e)return{error:K};let p=Nt({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:d}=e,{matchUp:m,structure:l}=Ft({drawDefinition:e,matchUpId:c,event:r});if(!m)return{error:be};let{appliedPolicies:f,policyActions:g,matchUpActionsPolicy:I,otherFlightEntries:h}=l4({specifiedPolicyDefinitions:o,tournamentRecord:u,drawDefinition:e,structure:l,event:r}),S=t.matchUpsMap??ye({drawDefinition:e}),T=t.inContextDrawMatchUps??re({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:S,event:r}).matchUps,y=T?.find(x=>x.matchUpId===c),E=a&&y?.sides?.find(x=>x.sideNumber===a),A=y?.sides?.map(x=>x.participantId||x.participant?.participantid).filter(Boolean)??[],{assignedPositions:N,allPositionsAssigned:D}=pe({structure:l}),{structureId:R}=l??{},U=[];if(!R)return{validActions:U};let b=!!m.collectionId;De({structure:l})&&!b&&U.push(...H1({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:A,otherFlightEntries:h,drawDefinition:e,structureId:R,sideNumber:a,matchUpId:c,structure:l,matchUp:m,drawId:d,event:r}));let C=Bo({drawDefinition:e,structure:l}),_=f4({matchUp:m,isCollectionMatchUp:b,assignedPositions:N});if(_)return{validActions:U,isByeMatchUp:_};let v=m.matchUpStatus&&[Zt,Te].includes(m.matchUpStatus);return g4({validActions:U,policyActions:g,matchUpActionsPolicy:I,specifiedPolicyDefinitions:o,inContextDrawMatchUps:T,matchUpParticipantIds:A,allPositionsAssigned:D,inContextMatchUp:y,assignedPositions:N,appliedPolicies:f,isCollectionMatchUp:b,enforceGender:i,participantId:s,isDoubleExit:v,sideNumber:a,matchUpId:c,structure:l,matchUp:m,drawId:d,drawDefinition:e,side:E}),{structureIsComplete:C,validActions:U,isDoubleExit:v,...P}}function m4({tournamentRecord:t,matchUpId:e}){let n=(jt({tournamentRecord:t}).matchUps??[]).find(s=>s.matchUpId===e),o=(t?.events??[]).find(s=>s.eventId===n?.eventId);return{drawDefinition:(o?.drawDefinitions??[]).find(s=>s.drawId===n?.drawId),event:o}}function l4({specifiedPolicyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:o}){let i=gt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}).appliedPolicies??{};Object.assign(i,t??{});let s=i?.[uo]?.otherFlightEntries,a=i?.[Ke]??Cs[Ke],{enabledStructures:c}=cP({actionType:aP,appliedPolicies:i,drawDefinition:r,structure:n}),{policyActions:u}=uP({enabledStructures:c,drawDefinition:r,structure:n});return{appliedPolicies:i,policyActions:u,matchUpActionsPolicy:a,otherFlightEntries:s}}function f4({matchUp:t,isCollectionMatchUp:e,assignedPositions:r}){let n=r?.filter(o=>o.bye).map(o=>o.drawPosition);return t.matchUpStatus==="BYE"||!e&&t.drawPositions?.reduce((o,i)=>n?.includes(i)||o,!1)}function g4({validActions:t,policyActions:e,matchUpActionsPolicy:r,specifiedPolicyDefinitions:n,inContextDrawMatchUps:o,matchUpParticipantIds:i,allPositionsAssigned:s,inContextMatchUp:a,assignedPositions:c,appliedPolicies:u,isCollectionMatchUp:p,enforceGender:d,participantId:m,isDoubleExit:l,sideNumber:f,matchUpId:g,structure:I,matchUp:h,drawId:S,drawDefinition:T,side:y}){ro({policyActions:e,action:fP})&&t.push({type:fP,payload:{matchUpId:g}});let E=!Ka({matchUpStatus:h.matchUpStatus}),A=I4({appliedPolicies:u,allPositionsAssigned:s,structure:I}),N=h.sides?.filter(_=>_?.participantId).length===2,D=ir({inContextDrawMatchUps:o,drawDefinition:T,matchUpId:g}),R=us({inContextDrawMatchUps:o,drawDefinition:T,targetData:D}),U=c?.filter(_=>_.participantId).map(_=>_.drawPosition),C=(a?.drawPositions?.length===2&&a.drawPositions.every(_=>U?.includes(_))&&a?.sides?.length===2&&a.sides.every(({participantId:_})=>_)||N)&&!(l&&R);E&&t.push({payload:{drawId:S,matchUpId:g,schedule:{}},method:mP,type:iv}),ro({policyActions:e,action:Za})&&(y?.participant||!f&&i?.length)&&t.push({method:$A,type:Za,payload:{drawId:S,matchUpId:g,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}}),E&&C&&t.push({type:sv}),A&&C&&(t.push({info:"set outcome and winningSide",method:mP,type:av,payload:{drawId:S,matchUpId:g,matchUpFormat:h.matchUpFormat,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0}}),ro({policyActions:e,action:gP})&&t.push({type:gP}),ro({policyActions:e,action:"END"})&&t.push({type:"END"})),p&&a&&t.push(...G1({specifiedPolicyDefinitions:n,inContextDrawMatchUps:o,matchUpParticipantIds:i,matchUpActionsPolicy:r,inContextMatchUp:a,policyActions:e,enforceGender:d,participantId:m,sideNumber:f,matchUpId:g,matchUp:h,drawId:S,side:y}))}function I4({appliedPolicies:t,allPositionsAssigned:e,structure:r}){let n=t?.scoring?.structures,o=r?.stage&&n?.stage?.[r.stage],i=r?.stageSequence&&o?.stageSequence?.[r.stageSequence];return!(t?.scoring?.requireAllPositionsAssigned||o?.requireAllPositionsAssigned||i?.requireAllPositionsAssigned)||e}function j1({positionAssignments:t,activeDrawPositions:e,drawDefinition:r,isByePosition:n,structure:o,drawPosition:i,structureId:s,drawId:a}){if(o.stage!==j||o.stageSequence!==1)return{};if(o.structureType===Ie)return{};if(n)return{};if(e.length)return{};let c=t.find(f=>f.drawPosition===i);if(!c?.participantId)return{};let{seedAssignments:u}=Dr({drawDefinition:r,structure:o});if(!u?.length)return{};let p=u.find(f=>f.participantId===c.participantId);if(!p)return{};let{validSeedBlocks:d}=Ai({drawDefinition:r,structure:o});if(!d?.length)return{};let m=d.findIndex(f=>f.seedNumbers.includes(p.seedNumber));return m<0||m>=d.length-1?{}:d.slice(m+1).some(f=>u.some(g=>f.seedNumbers.includes(g.seedNumber)&&g.participantId))?{validSeedCascadeAction:{type:_M,method:I1,payload:{drawId:a,structureId:s,drawPosition:i}}}:{}}function Y1({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:o,positionAssignments:i,drawDefinition:s,drawPosition:a,structureId:c,structure:u,drawId:p,event:d}){if(o.includes(a)||n&&!e)return{};let{sourceStructureIds:m,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}=tt({structureId:S,drawDefinition:s}),y=T?.finishingPosition===As&&(m?.length!==1||l?.length!==1),E={};if(y){let{matchUps:R}=ht({drawDefinition:s,structure:u,event:d}),{initialRoundNumber:U}=ca({drawPosition:a,matchUps:R}),C=s.links?.find(_=>_.target?.structureId===u?.structureId&&_.target.roundNumber===U)?.source?.roundNumber;E.roundNumbers=[C]}let{completedMatchUps:A}=Xp({structureId:S,inContext:!0,matchUpFilters:E,drawDefinition:s}),N=i.map(R=>R.participantId).filter(Boolean);A?.filter(({matchUpType:R,winningSide:U})=>U&&(d?.eventType!==Ce||R===Ce)).map(({winningSide:R,sides:U})=>R&&U?.[1-(R-1)]).map(lt).filter(R=>R&&!N.includes(R))?.forEach(R=>{f.includes(R)||f.push(R)})}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:AS,method:u1,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function q1({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:o,isWinRatioFedStructure:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,seedingProfile:p,isByePosition:d,drawPosition:m,structureId:l,event:f}){let{drawId:g}=u,I=[],h,S,T=[],y=c?.[Xn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=NA({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:p,structureId:l,event:f})),T?.length||(T=s.filter(E=>!E.participantId&&!E.bye&&!E.qualifier).map(E=>E.drawPosition)),d||I.push({payload:{drawId:g,structureId:l,drawPosition:m,isPositionAction:!0},willDisableLinks:r,method:f1,type:"BYE"}),i&&y){let E=s.map(U=>U.participantId).filter(Boolean),A={structureIds:t},{completedMatchUps:N}=$a({inContext:!0,matchUpFilters:A,drawDefinition:u}),D=ct((N??[]).filter(({matchUpType:U})=>f?.eventType!==Ce||U===Ce)?.map(({sides:U})=>U?.map(lt)).flat().filter(U=>U&&!E.includes(U))),R=a?o?.filter(U=>D?.includes(U.participantId)).map(U=>q(U,void 0,!0)):void 0;return R?.forEach(U=>{let b=(u.entries??[]).find(C=>C.participantId===U.participantId);U.entryPosition=b?.entryPosition}),R?.length&&I.push(et({payload:{drawId:g,structureId:l,drawPosition:m},willDisableLinks:r,method:OM,type:ma,availableParticipantIds:D,participantsAvailable:R})),{validAssignmentActions:I}}if(T.includes(m)||d){let E;if(S?.length){let N=S.filter(D=>h?.includes(D.participantId));N.sort(h4),E=N.map(D=>D.participantId)}else E=e;let A=a?o?.filter(N=>E.includes(N.participantId)).map(N=>q(N,void 0,!0)):void 0;A?.length&&I.push(et({payload:{drawId:g,structureId:l,drawPosition:m},willDisableLinks:r,method:OM,type:ma,availableParticipantIds:E,participantsAvailable:A}))}return{validAssignmentActions:I}}function h4(t,e){return t.bye||Ou(t.seedValue)<Ou(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function $1({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:r,returnParticipants:n,appliedPolicies:o,drawDefinition:i,drawPosition:s,structureId:a,drawId:c}){let u=[],p=[],d=[],m=[],l=new Set(r.map(E=>E.participantId).filter(Boolean)),f=o?.[uo],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=ad({targetRoundNumber:g,linkType:Ar,drawDefinition:i,structureId:a})??{};h?.length&&m.push(...h);let{sourceStructureIds:T,relevantLinks:y}=ad({targetRoundNumber:g,linkType:fn,drawDefinition:i,structureId:a})??{};return T?.length&&m.push(...T),S4({requireCompletedStructures:I,tournamentParticipants:e,assignedParticipantIds:l,eliminationSourceLinks:S,qualifyingParticipantIds:p,qualifyingParticipants:u,returnParticipants:n,drawDefinition:i}),T4({requireCompletedStructures:I,tournamentParticipants:e,assignedParticipantIds:l,qualifyingParticipantIds:p,qualifyingParticipants:u,roundRobinSourceLinks:y,returnParticipants:n,drawDefinition:i}),p.length&&d.push(et({qualifyingParticipants:n?u:void 0,method:s1,type:_m,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:d,sourceStructureIds:m}}function S4({requireCompletedStructures:t,tournamentParticipants:e,assignedParticipantIds:r,eliminationSourceLinks:n,qualifyingParticipantIds:o,qualifyingParticipants:i,returnParticipants:s,drawDefinition:a}){for(let c of n){let u=a.structures?.find(l=>l.structureId===c.source.structureId);if(u?.stage!==rt)continue;let p=Bo({structureId:c.source.structureId,drawDefinition:a});if(t&&!p)continue;let d=u.qualifyingRoundNumber,{matchUps:m}=ht({matchUpFilters:{roundNumbers:[d],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:u});for(let l of m){let f=l.sides.find(I=>I?.sideNumber===l.winningSide),g=l.matchUpStatus==="BYE"&&l.sides?.find(({participantId:I})=>I);if(f||g){let{participantId:I,participant:h}=f||(g??{});I&&!r.has(I)&&(h&&s&&i.push(h),o.push(I))}}}}function T4({requireCompletedStructures:t,tournamentParticipants:e,assignedParticipantIds:r,qualifyingParticipantIds:n,qualifyingParticipants:o,roundRobinSourceLinks:i,returnParticipants:s,drawDefinition:a}){for(let c of i){let u=a.structures?.find(l=>l.structureId===c.source.structureId);if(u?.stage!==rt)continue;let p=Bo({structureId:c.source.structureId,drawDefinition:a});if(t&&!p)continue;let{positionAssignments:d}=yt({structure:u}),m=d?.map(l=>{let f=l.participantId,g=$t({element:l,attribute:"tally",name:to});return g?{participantId:f,groupOrder:g?.groupOrder}:{}}).filter(({groupOrder:l,participantId:f})=>l===1&&!r.has(f)).map(({participantId:l})=>l)??[];if(m&&n.push(...m),s){let l=new Set(m),f=e.filter(({participantId:g})=>l.has(g));o.push(...f)}}}function K1({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:r,inactiveDrawPositions:n,activeDrawPositions:o,positionAssignments:i,returnParticipants:s,byeDrawPositions:a,drawDefinition:c,isByePosition:u,drawPosition:p,structureId:d,structure:m,drawId:l,event:f}){if(o.includes(p))return{};let g=U=>!t||U.participantId||U.qualifier||U.bye,I=n?.filter(U=>U!==p&&!(u&&a.includes(U))),h=i?.filter(U=>g(U)&&I?.includes(U.drawPosition))??[],S=h.map(({drawPosition:U})=>U),{matchUps:T}=ht({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:m,event:f}),y=T.filter(({drawPositions:U})=>we(U,S)),E=Object.assign({},...y.map(U=>U.sides?.filter(({sourceDrawPositionRange:b})=>b).map(({drawPosition:b,sourceDrawPositionRange:C})=>({[b]:C}))).flat()),A=h.map(U=>U.participantId).filter(Boolean),N=(r??[]).filter(U=>A.includes(U.participantId)),D=Object.assign({},...N.map(U=>({[U.participantId]:U}))),R=h.map(U=>{let b=D?.[U.participantId],C=E[U.drawPosition];return et({...U,participant:s?q(b,!1,!0):void 0,sourceDrawPositionRange:C})});return R.length?{validSwapAction:{payload:{drawId:l,structureId:d,drawPositions:[p]},willDisableLinks:e,method:qA,type:wm,availableAssignments:R}}:{}}function y4(t,e){return t.filter(r=>!e.includes(r.participantId)).map(r=>r.participantId)}function E4({validActions:t,policyActions:e,isActiveDrawPosition:r,positionAssignments:n,disablePlacementActions:o,positionAssignment:i,isByePosition:s,getValidAssignmentActions:a,positionSourceStructureIds:c,unassignedParticipantIds:u,possiblyDisablingAction:p,isWinRatioFedStructure:d,tournamentParticipants:m,returnParticipants:l,appliedPolicies:f,drawDefinition:g,drawPosition:I,structureId:h,event:S}){if(ro({policyActions:e,action:ma})&&!r&&n&&!o&&(!i||s)){let{validAssignmentActions:T}=a({positionSourceStructureIds:c,unassignedParticipantIds:u,possiblyDisablingAction:p,isWinRatioFedStructure:d,tournamentParticipants:m,positionAssignments:n,returnParticipants:l,appliedPolicies:f,drawDefinition:g,isByePosition:s,drawPosition:I,structureId:h,event:S});T?.forEach(y=>t.push(y))}}function A4({validActions:t,policyActions:e,isActiveDrawPosition:r,getValidQualifiersAction:n,drawPositionInitialRounds:o,tournamentParticipants:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,structureId:d,drawId:m}){if(ro({policyActions:e,action:_m})&&!r){let{validAssignmentActions:l}=n({drawPositionInitialRounds:o,tournamentParticipants:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,structureId:d,drawId:m});l?.forEach(f=>t.push(f))}}function P4({isLuckyDrawAdvancedPosition:t,validActions:e,policyActions:r,isActiveDrawPosition:n,drawId:o,structureId:i,drawPosition:s,possiblyDisablingAction:a,isByePosition:c}){ro({policyActions:r,action:KA})&&!n&&(e.push({type:KA,method:vM,payload:{drawId:o,structureId:i,drawPosition:s},willDisableLinks:a}),!c&&!t&&e.push({type:ES,method:a1,payload:{drawId:o,structureId:i,drawPosition:s},willDisableLinks:a}),ro({policyActions:r,action:"BYE"})&&!c&&!t&&e.push({type:"BYE",method:vM,payload:{drawId:o,structureId:i,drawPosition:s,replaceWithBye:!0},willDisableLinks:a}))}function N4({validActions:t,policyActions:e,activePositionsCheck:r,activePositionOverrides:n,activeDrawPositions:o,drawDefinition:i,structureId:s,drawPosition:a,structure:c,isByePosition:u,participantId:p,participant:d,drawId:m}){let l=c.stage===rt||c.stage===j&&c.stageSequence===1;if(!u&&r({activePositionOverrides:n,activeDrawPositions:o,action:Xa})&&ro({policyActions:e,action:Xa})&&Mm({drawDefinition:i,structureId:s,drawPosition:a})&&l){let{seedAssignments:f}=Dr({returnAllProxies:!0,drawDefinition:i,structure:c}),{seedNumber:g,seedValue:I}=f?.find(h=>h.participantId===p)??{};t.push({type:Xa,method:g1,participant:d,seedNumber:g,payload:{drawId:m,structureId:s,participantId:p,seedValue:I}})}if(!u&&r({activePositionOverrides:n,activeDrawPositions:o,action:xm})&&ro({policyActions:e,action:xm})&&Mm({drawDefinition:i,structureId:s,drawPosition:a})&&l){let{seedAssignments:f}=Dr({returnAllProxies:!0,drawDefinition:i,structure:c}),{seedNumber:g}=f?.find(I=>I.participantId===p)??{};t.push({method:l1,type:xm,participant:d,seedNumber:g,payload:{participantId:p,structureId:s,drawId:m}})}}function D4({validActions:t,policyActions:e,isByePosition:r,participantId:n,participant:o,drawId:i}){if(!r&&n){if(ro({policyActions:e,action:Za})){let s={type:Za,method:$A,participant:o,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:i}};t.push(s)}if(ro({policyActions:e,action:ud})){let s={type:ud,method:m1,participant:o,payload:{participantId:n,otherName:void 0}};t.push(s)}}}function U4({validActions:t,policyActions:e,getValidSwapAction:r,possiblyDisablingAction:n,tournamentParticipants:o,inactiveDrawPositions:i,activeDrawPositions:s,positionAssignments:a,returnParticipants:c,byeDrawPositions:u,drawDefinition:p,isByePosition:d,drawPosition:m,structureId:l,structure:f,drawId:g}){if(ro({policyActions:e,action:wm})){let{validSwapAction:I}=r({possiblyDisablingAction:n,tournamentParticipants:o,inactiveDrawPositions:i,activeDrawPositions:s,positionAssignments:a,returnParticipants:c,byeDrawPositions:u,drawDefinition:p,isByePosition:d,drawPosition:m,structureId:l,structure:f,drawId:g});I&&t.push(I)}}function R4({validActions:t,policyActions:e,getValidAlternatesAction:r,possiblyDisablingAction:n,tournamentParticipants:o,positionAssignments:i,activeDrawPositions:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,structureId:d,structure:m,drawId:l,event:f,disablePlacementActions:g}){if(ro({policyActions:e,action:yS})&&!g){let{validAlternatesAction:I}=r({possiblyDisablingAction:n,tournamentParticipants:o,positionAssignments:i,activeDrawPositions:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,validActions:t,structureId:d,structure:m,drawId:l,event:f});I&&t.push(I)}}function b4({validActions:t,policyActions:e,getValidLuckyLosersAction:r,sourceStructuresComplete:n,possiblyDisablingAction:o,isWinRatioFedStructure:i,tournamentParticipants:s,activeDrawPositions:a,positionAssignments:c,drawDefinition:u,drawPosition:p,structureId:d,structure:m,drawId:l,disablePlacementActions:f,isActiveDrawPosition:g}){if(ro({policyActions:e,action:AS})&&!f&&!g&&c){let{validLuckyLosersAction:I}=r({sourceStructuresComplete:n,possiblyDisablingAction:o,isWinRatioFedStructure:i,tournamentParticipants:s,activeDrawPositions:a,positionAssignments:c,drawDefinition:u,drawPosition:p,structureId:d,structure:m,drawId:l});I&&t.push(I)}}function C4({validActions:t,policyActions:e,getValidModifyAssignedPairAction:r,participant:n,tournamentParticipants:o,returnParticipants:i,drawPosition:s,drawId:a,event:c}){if(n?.participantType===dt&&ro({policyActions:e,action:TS})){let{validModifyAssignedPairAction:u}=r({tournamentParticipants:o,returnParticipants:i,drawPosition:s,participant:n,drawId:a,event:c});u&&t.push(u)}}function hP(t){return v4(t)}function M4(t){let e=X(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return{earlyReturn:e};let{policyDefinitions:r,returnParticipants:n=!0,provisionalPositioning:o,tournamentRecord:i,drawDefinition:s,drawPosition:a,event:c}=t,u=t.tournamentParticipants??(i&&Nt({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=tt({structureId:t.structureId,drawDefinition:s});if(p.error)return{earlyReturn:p};let d=p.containingStructure||p.structure;if(!d)return{earlyReturn:{error:Pt}};let m=d.structureId;if(p=is({drawDefinition:s,structureId:m}),a===void 0&&!p.isAdHoc)return{earlyReturn:{error:Ra}};if(p.isAdHoc)return{earlyReturn:ng(t)};if(p.error)return{earlyReturn:p};let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=gt({tournamentRecord:i,drawDefinition:s,structure:d,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:y}=cP({actionType:RS,appliedPolicies:h,drawDefinition:s,structure:d}),E=S?.activePositionOverrides??[],{sourceStructureIds:A}=ad({finishingPosition:Ao,targetRoundNumber:1,linkType:fn,drawDefinition:s,structureId:m})??{},N;A?.length&&(N=A.every(Q=>Bo({structureId:Q,drawDefinition:s})));let D=A.length,R=A.length&&!N,{policyActions:U}=uP({enabledStructures:T,drawDefinition:s,structure:d}),b=![rt,j].includes(d.stage)||d.stageSequence!==1,{drawId:C}=s,{assignedPositions:_,positionAssignments:v}=pe({structure:d}),x=_?.find(Q=>Q.drawPosition===a),w=!!x;if(!v?.map(Q=>Q.drawPosition)?.includes(a)&&!(d.matchUps?.flatMap(pt=>pt.drawPositions??[])??[]).includes(a))return{earlyReturn:{error:hs}};let{stage:L,stageSequence:k}=d,G=[L];L===je&&G.push(j),L===j&&G.push(je);let V=ns({entryStatuses:rs,provisionalPositioning:o,drawDefinition:s,stageSequence:k,structureId:m,stages:G}),B=ss({drawDefinition:s,stages:G}).assignedParticipantIds??[],$=y4(V,B),H=I.includes(a),z=g.includes(a),W=cn(s.drawType)&&l?.[a]>1;return y?{earlyReturn:{info:"Actions Disabled for structure",isActiveDrawPosition:z,isDrawPosition:!0,hasPositionAssigned:w,validActions:[],isByePosition:H}}:{positionSourceStructureIds:A,isLuckyDrawAdvancedPosition:W,drawPositionInitialRounds:l,unassignedParticipantIds:$,sourceStructuresComplete:N,activePositionOverrides:E,tournamentParticipants:u,disablePlacementActions:R,possiblyDisablingAction:b,isWinRatioFedStructure:D,inactiveDrawPositions:f,isActiveDrawPosition:z,positionAssignments:v,hasPositionAssigned:w,positionAssignment:x,activeDrawPositions:g,returnParticipants:n,byeDrawPositions:I,appliedPolicies:h,drawDefinition:s,policyActions:U,isByePosition:H,drawPosition:a,structureId:m,structure:d,drawId:C,event:c}}function v4(t){let e=M4(t);if("earlyReturn"in e)return e.earlyReturn;let{positionSourceStructureIds:r,isLuckyDrawAdvancedPosition:n,drawPositionInitialRounds:o,unassignedParticipantIds:i,sourceStructuresComplete:s,activePositionOverrides:a,tournamentParticipants:c,disablePlacementActions:u,possiblyDisablingAction:p,isWinRatioFedStructure:d,inactiveDrawPositions:m,isActiveDrawPosition:l,positionAssignments:f,hasPositionAssigned:g,positionAssignment:I,activeDrawPositions:h,returnParticipants:S,byeDrawPositions:T,appliedPolicies:y,drawDefinition:E,policyActions:A,isByePosition:N,drawPosition:D,structureId:R,structure:U,drawId:b,event:C}=e,_=[];E4({validActions:_,policyActions:A,isActiveDrawPosition:l,positionAssignments:f,disablePlacementActions:u,positionAssignment:I,isByePosition:N,getValidAssignmentActions:q1,positionSourceStructureIds:r,unassignedParticipantIds:i,possiblyDisablingAction:p,isWinRatioFedStructure:d,tournamentParticipants:c,returnParticipants:S,appliedPolicies:y,drawDefinition:E,drawPosition:D,structureId:R,event:C}),A4({validActions:_,policyActions:A,isActiveDrawPosition:l,getValidQualifiersAction:$1,drawPositionInitialRounds:o,tournamentParticipants:c,positionAssignments:f,returnParticipants:S,appliedPolicies:y,drawDefinition:E,drawPosition:D,structureId:R,drawId:b});let{participantId:v}=I??{},x=v&&c.find(w=>w.participantId===v);if(I){if(P4({isLuckyDrawAdvancedPosition:n,validActions:_,policyActions:A,isActiveDrawPosition:l,drawId:b,structureId:R,drawPosition:D,possiblyDisablingAction:p,isByePosition:N}),n||N4({validActions:_,policyActions:A,activePositionsCheck:L1,activePositionOverrides:a,activeDrawPositions:h,drawDefinition:E,structureId:R,drawPosition:D,structure:U,isByePosition:N,participantId:v,participant:x,drawId:b}),!n&&!N){let{validSeedCascadeAction:w}=j1({positionAssignments:f,activeDrawPositions:h,drawDefinition:E,isByePosition:N,structure:U,drawPosition:D,structureId:R,drawId:b});w&&_.push(w)}D4({validActions:_,policyActions:A,isByePosition:N,participantId:v,participant:x,drawId:b}),U4({validActions:_,policyActions:A,getValidSwapAction:K1,possiblyDisablingAction:p,tournamentParticipants:c,inactiveDrawPositions:m,activeDrawPositions:h,positionAssignments:f,returnParticipants:S,byeDrawPositions:T,drawDefinition:E,isByePosition:N,drawPosition:D,structureId:R,structure:U,drawId:b})}return R4({validActions:_,policyActions:A,getValidAlternatesAction:V1,possiblyDisablingAction:p,tournamentParticipants:c,positionAssignments:f,activeDrawPositions:h,returnParticipants:S,appliedPolicies:y,drawDefinition:E,drawPosition:D,structureId:R,structure:U,drawId:b,event:C,disablePlacementActions:u}),b4({validActions:_,policyActions:A,getValidLuckyLosersAction:Y1,sourceStructuresComplete:s,possiblyDisablingAction:p,isWinRatioFedStructure:d,tournamentParticipants:c,activeDrawPositions:h,positionAssignments:f,drawDefinition:E,drawPosition:D,structureId:R,structure:U,drawId:b,disablePlacementActions:u,isActiveDrawPosition:l}),C4({validActions:_,policyActions:A,getValidModifyAssignedPairAction:w1,participant:x,tournamentParticipants:c,returnParticipants:S,drawPosition:D,drawId:b,event:C}),{isActiveDrawPosition:l,isDrawPosition:!0,hasPositionAssigned:g,isByePosition:N,validActions:_,...P}}function gd({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[of]?.drawTypeCoercion,o=e?.[of]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}var SP=({drawDefinition:t,random:e})=>{let r=X({drawDefinition:t},[{[zt]:!0}]);if(r.error)return r;let n=t.structures?.find(s=>s.stage===j&&s.stageSequence===1);if(!n)return M({result:{error:NI}});let{qualifierPositions:o}=pe({structure:n}),i=e??Math.random;return J(0,o.length).sort(()=>i()-.5)};function og({participantIds:t,matchUps:e,allowDraws:r=!1}){let n=new Map;for(let s of t)n.set(s,{participantId:s,wins:0,losses:0,draws:0,points:0,opponentIds:[],opponentOutcomes:new Map,roundPoints:[]});for(let s of e){if(s.matchUpStatus!==ae||!s.sides||s.sides.length<2)continue;let a=lt(s.sides[0]),c=lt(s.sides[1]);if(!a||!c)continue;let u=n.get(a),p=n.get(c);!u||!p||(u.opponentIds.includes(c)||u.opponentIds.push(c),p.opponentIds.includes(a)||p.opponentIds.push(a),s.winningSide===1?(u.wins+=1,u.points+=1,p.losses+=1,u.opponentOutcomes.set(c,"WIN"),p.opponentOutcomes.set(a,"LOSS"),u.roundPoints.push(1),p.roundPoints.push(0)):s.winningSide===2?(p.wins+=1,p.points+=1,u.losses+=1,p.opponentOutcomes.set(a,"WIN"),u.opponentOutcomes.set(c,"LOSS"),u.roundPoints.push(0),p.roundPoints.push(1)):r&&(u.draws+=1,p.draws+=1,u.points+=.5,p.points+=.5,u.opponentOutcomes.set(c,"DRAW"),p.opponentOutcomes.set(a,"DRAW"),u.roundPoints.push(.5),p.roundPoints.push(.5)))}let o=new Map;for(let[s,a]of n){let c=`${a.wins}-${a.losses}-${a.draws}`,u=o.get(c)??[];u.push(s),o.set(c,u)}let i=[];for(let[s,a]of o){let[c,u,p]=s.split("-").map(Number);i.push({wins:c,losses:u,draws:p,participantIds:a})}return i.sort((s,a)=>{let c=s.wins+s.draws*.5,u=a.wins+a.draws*.5;return u!==c?u-c:s.losses-a.losses}),{scoreGroups:i,records:n}}function Q1({records:t,tiebreakMethods:e=["BUCHHOLZ","SONNEBORN_BERGER"]}){let r=[];for(let[n,o]of t){let i={participantId:n,wins:o.wins,losses:o.losses,draws:o.draws,points:o.points,opponentIds:o.opponentIds,rank:0};e.includes("BUCHHOLZ")&&(i.buchholz=J1(n,t)),e.includes("MEDIAN_BUCHHOLZ")&&(i.medianBuchholz=O4(n,t)),e.includes("SONNEBORN_BERGER")&&(i.sonnebornBerger=_4(n,t)),e.includes("PROGRESSIVE_SCORE")&&(i.progressiveScore=x4(o)),r.push(i)}w4(r,e);for(let n=0;n<r.length;n++)r[n].rank=n+1;return r}function J1(t,e){let r=e.get(t);return r?r.opponentIds.reduce((n,o)=>{let i=e.get(o);return n+(i?.points??0)},0):0}function O4(t,e){let r=e.get(t);return!r||r.opponentIds.length<3?J1(t,e):r.opponentIds.map(i=>e.get(i)?.points??0).sort((i,s)=>i-s).slice(1,-1).reduce((i,s)=>i+s,0)}function _4(t,e){let r=e.get(t);if(!r)return 0;let n=0;for(let o of r.opponentIds){let i=e.get(o);if(!i)continue;let s=r.opponentOutcomes.get(o);s==="WIN"?n+=i.points:s==="DRAW"&&(n+=i.points*.5)}return n}function x4(t){let e=0,r=0;for(let n of t.roundPoints)e+=n,r+=e;return r}function w4(t,e){t.sort((r,n)=>{if(n.points!==r.points)return n.points-r.points;for(let o of e){let i=z1(r,o),s=z1(n,o);if(s!==i)return s-i}return 0})}function z1(t,e){switch(e){case"BUCHHOLZ":return t.buchholz??0;case"MEDIAN_BUCHHOLZ":return t.medianBuchholz??0;case"SONNEBORN_BERGER":return t.sonnebornBerger??0;case"PROGRESSIVE_SCORE":return t.progressiveScore??0;default:return 0}}function TP({tiebreakMethods:t=["BUCHHOLZ","SONNEBORN_BERGER"],drawDefinition:e,structureId:r}){if(!e)return{error:K};let n=r?tt({drawDefinition:e,structureId:r}).structure:e.structures?.find(m=>De({structure:m}));if(!n)return{error:Pt};let o=n.matchUps??[],i=(e.entries??[]).filter(m=>yr.includes(m.entryStatus??"")).map(lt).filter(Boolean);if(!i.length)return{standings:[],scoreGroups:[],roundsPlayed:0,...P};let{scoreGroups:s,records:a}=og({participantIds:i,matchUps:o}),c=Q1({records:a,tiebreakMethods:t}),u=o.filter(m=>m.winningSide),d=[...new Set(u.map(m=>m.roundNumber).filter(Boolean))].length;return{standings:c,scoreGroups:s,roundsPlayed:d,...P}}function yP({structureId:t,drawDefinition:e}){if(!e)return{error:K};if(!wt(t))return{error:O};let r=qa({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!Ht([$i,Je,dm,qi],n).length;return{...P,valid:o}}function EP({positionAssignment:t}){if(!t)return{error:RI};let e=$t({element:t,attribute:"tally",name:to});return e===void 0?{error:fe}:{tally:e}}function AP({drawDefinition:t,structureId:e}){if(!t)return{error:K};let r=e?tt({drawDefinition:t,structureId:e}).structure:t.structures?.find(a=>De({structure:a}));if(!r)return{error:Pt};let n=r.matchUps??[],o=(t.entries??[]).filter(a=>yr.includes(a.entryStatus??"")).map(lt).filter(Boolean);if(!o.length)return{rounds:[],totalRounds:0,...P};let i=[...new Set(n.map(a=>a.roundNumber).filter(Boolean))].sort((a,c)=>(a??0)-(c??0)),s=[];s.push({roundNumber:0,nodes:[{wins:0,losses:0,draws:0,participantIds:[...o]}]});for(let a of i){let c=n.filter(p=>p.matchUpStatus===ae&&(p.roundNumber??0)<=(a??0)),{scoreGroups:u}=og({matchUps:c,participantIds:o});s.push({roundNumber:a??0,nodes:u.map(p=>({wins:p.wins,losses:p.losses,draws:p.draws,participantIds:[...p.participantIds]}))})}return{rounds:s,totalRounds:i.length,...P}}function PP({drawDefinition:t}){if(!t)return{error:K};let e=$t({element:t,attribute:"draftState",name:fi});if(!e)return{error:fe,info:"No draft found"};let r=e.tiers?.reduce((i,s)=>i+(s.participantIds?.length??0),0),n=Object.keys(e.preferences??{}).length,o=e.tiers?.filter(i=>i.resolved).length??0;return{draftState:e,summary:{status:e.status,totalParticipants:r,preferencesSubmitted:n,preferencesOutstanding:r-n,tiersTotal:e.tiers?.length??0,tiersResolved:o,unassignedDrawPositions:e.unassignedDrawPositions,preferencesCount:e.preferencesCount}}}function NP({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:O};let r=Ci(t);return r?{drawSize:r}:M({result:{error:O},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function Id(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=Do({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return M({result:I,stack:c});r=I.policyDefinitions}let p=It(u);if(u&&!p)return M({result:{error:O},context:{participantsCount:u},stack:c});if(o&&!p)return M({result:{error:lR},stack:c});if(Number.isNaN(Number(n)))if(u)({drawSize:n}=NP({participantsCount:u}));else return M({result:{error:ru},stack:c});let d=o&&u||n;if(d&&d>n)return{error:xI};let m=r?.[Xn];if(!m)return{error:ZU};let l=m.seedsCountThresholds;return l?(m.drawSizeProgression!==void 0&&(e=m.drawSizeProgression),{seedsCount:l.filter(I=>e?I.drawSize<=n:n===I.drawSize).reduce((I,h)=>u&&u>=h.minimumParticipantCount?h.seedsCount:I,0)}):{error:LU}}function ig({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=Nt({tournamentRecord:r})),!s)return{error:va};if(!Array.isArray(s))return{error:O};if(!a)return{error:Se};let c=e?.[Ke]??n?.[Ke]??Cs[Ke],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:d}=a,m=p===pi,l=p===Tr&&bt||m&&dt||ft,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=L4({participant:S,participantType:l,eventType:p,entryStatusMap:f}),y=F4({genderEnforced:u,participantMap:o,eventGender:d,participant:S,isDoubles:m,mismatch:T});return T||!y});if(h.length){let S=h.map(T=>T.participantId);return{error:YU,invalidParticipantIds:S}}return{...P,valid:!0}}function L4({participant:t,participantType:e,eventType:r,entryStatusMap:n}){if(r===ah&&[ft,dt].includes(t.participantType))return!1;let o=n[t.participantId],i=r&&[pi,Tr].includes(r)&&t.participantType===ft&&(ua(o)||o===On);return t.participantType!==e&&!i}function F4(t){let{participant:e,participantMap:r,eventGender:n,mismatch:o,isDoubles:i,genderEnforced:s}=t,a=!o&&i&&ct(e?.individualParticipantIds?.map(d=>r?.[d]?.participant?.person?.sex).filter(Boolean)??[])||[],c=!n||!a?.length||To(n)||bn(n)&&lr(a[0])===lr(n)||jr(n)&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||jr(n)||To(n)||bn(n)&&lr(u)===lr(n);return!s||c&&p}function DP({hasExistingDrawDefinition:t,qualifyingProfiles:e,appliedPolicies:r,qualifyingOnly:n,tieFormat:o,idPrefix:i,isMock:s,uuids:a}){let c="generateQualifyingSTructures",u=[],p=[],d=[],m=(S,T)=>S.stageSequence-T.stageSequence,l=(S,T)=>S.roundTarget-T.roundTarget,f=0,g=0,I,h=1;for(let S of e.sort(l)){let T=S.structureProfiles??[];h=S.roundTarget||h;let y=1,E=0,A,N,D;for(let R of(T??[]).sort(m)){let U=k4({structureProfile:R,qualifyingProfiles:e,structureProfiles:T,hasExistingDrawDefinition:t,appliedPolicies:r,qualifyingOnly:n,stageSequence:y,roundTarget:h,tieFormat:o,idPrefix:i,isMock:s,uuids:a,stack:c,finalQualifyingStructureId:N,finalQualifyingRoundNumber:A,qualifyingDrawPositionsCount:f,targetRoundQualifiersCount:E,finishingPositions:I,linkType:D,links:d,structures:p});if(U.error)return U;({qualifyingDrawPositionsCount:f,targetRoundQualifiersCount:E,finalQualifyingStructureId:N,finalQualifyingRoundNumber:A,finishingPositions:I,linkType:D,stageSequence:y}=U)}g+=E,u.push({qualifiersCount:E,finalQualifyingRoundNumber:A,finalQualifyingStructureId:N,finishingPositions:I,roundTarget:h,linkType:D}),h+=1}return{qualifiersCount:g,qualifyingDrawPositionsCount:f,qualifyingDetails:u,structures:p,...P,links:d}}function k4({structureProfile:t,qualifyingProfiles:e,structureProfiles:r,hasExistingDrawDefinition:n,appliedPolicies:o,qualifyingOnly:i,stageSequence:s,roundTarget:a,tieFormat:c,idPrefix:u,isMock:p,uuids:d,stack:m,finalQualifyingStructureId:l,finalQualifyingRoundNumber:f,qualifyingDrawPositionsCount:g,targetRoundQualifiersCount:I,finishingPositions:h,linkType:S,links:T,structures:y}){let E=xl(t.drawSize||t.participantsCount),{qualifyingRoundNumber:A,structureOptions:N,matchUpFormat:D,structureName:R,structureId:U,drawType:b}=t,C=t.matchUpType,_=t.qualifyingPositions||G4({drawSize:E,qualifyingRoundNumber:A});if(!It(E))return M({result:{error:ru},stack:m});let v=e.length>1?`${a}-`:"",x=r.length>1||v?s:"",w=R||(v||x?`${Be(rt)} ${v}${x}`:Be(rt)),F,L,k;if(b===_r){let G=Fc({structureName:t.structureName||w,structureId:U||d?.pop(),hasExistingDrawDefinition:n,stage:rt,structureOptions:N,appliedPolicies:o,qualifyingOnly:i,stageSequence:s,matchUpType:C,roundTarget:a,tieFormat:c,drawSize:E,idPrefix:u,isMock:p,uuids:d});I=G.groupCount,F=G.maxRoundNumber,L=G.structures[0],h=[1]}else({drawSize:E,matchUps:k,roundLimit:F}=Er({qualifyingRoundNumber:A,qualifyingPositions:_,matchUpType:C,drawSize:E,idPrefix:u,isMock:p,uuids:d})),L=gr({structureName:t.structureName||w,structureId:U||d?.pop(),qualifyingRoundNumber:F,hasExistingDrawDefinition:n,stage:rt,qualifyingOnly:i,matchUpFormat:D,stageSequence:s,matchUpType:C,roundLimit:F,tieFormat:c,matchUps:k}),a&&At({element:L,attribute:"roundTarget",name:Xr,value:a}),I=k?.filter(G=>G.roundNumber===F)?.length||0;if(s>1){let{link:G}=la({sourceStructureId:l,sourceRoundNumber:f,targetStructureId:L.structureId,finishingPositions:S===fn?[1]:void 0,linkType:S});T.push(G),g+=(E||0)-I}else g+=E||0;return S=b===_r?fn:Ar,l=L.structureId,f=F,c&&(k=ht({structure:L})?.matchUps??[],k?.forEach(G=>{let{tieMatchUps:V}=cs({tieFormat:c,matchUp:G,isMock:p});Object.assign(G,{tieMatchUps:V,matchUpType:C})})),y.push(L),s+=1,{qualifyingDrawPositionsCount:g,targetRoundQualifiersCount:I,finalQualifyingStructureId:l,finalQualifyingRoundNumber:f,finishingPositions:h,stageSequence:s,linkType:S}}function G4({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function UP(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=st(t.drawSize),o=e&&!En(t.drawType)&&(typeof e=="boolean"||e<=2)&&n===2&&on||t.drawType||on,i=Mb.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=on;else if(n<4&&r)return{...M({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:$d},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function sg(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,qualifyingOnly:o,staggeredEntry:i,drawDefinition:s,tieFormat:a,isMock:c,uuids:u}=t??{},p=st(t.drawSize),d=t.drawTypeCoercion??gd({appliedPolicies:n,drawType:t.drawType}),m="generateDrawStructuresAndLinks",l=UP({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:d,drawSize:p});if(l.error)return l;let f=l.drawType,g=[],I=[],h=t?.matchUpType??Ct,{existingQualifyingDrawPositionsCount:S,mainStructureIsPlaceholder:T,existingQualifyingLinks:y,existingMainStructure:E,existingQualifiersCount:A}=V4({drawDefinition:s,structures:g});if(s?.structures?.filter(({stage:V})=>V===rt)?.length&&!T)return{error:Fy};let N=!s?.structures?.filter(({stage:V})=>V===rt)?.length&&t.qualifyingProfiles,D=N?.length&&DP({idPrefix:t.idPrefix,qualifyingProfiles:N,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,isMock:c,uuids:u});if(D?.error)return D;let{qualifyingDrawPositionsCount:R,qualifyingDetails:U,qualifiersCount:b}=D||{qualifyingDrawPositionsCount:S,qualifiersCount:A},C=b||t.qualifiersCount||0;R&&(D?.structures&&g.push(...D.structures),D?.links&&I.push(...D.links)),Object.assign(t,et({drawSize:p,matchUpType:h,tieFormat:a}));let _=B4({drawType:f,drawSize:p,staggeredEntry:i});if(_&&!R)return M({context:{drawSize:p,invalidDrawSize:_},result:{error:$d},stack:m});let{generators:v,error:x}=$f(t);if(x)return{error:x};let w=v[f];if(!w)return{error:mp};let F=w?.();if(F.error)return F;let{structures:L,links:k}=F;if(L?.length){let V=H4({mainStructureIsPlaceholder:T,existingMainStructure:E,generatedStructures:L,overwriteExisting:r,generatedLinks:k,structures:g});if(V?.error)return V}g.sort(Xi),k?.length&&I.push(...k);let G=F.structures.find(({stage:V,stageSequence:B})=>V===j&&B===1);for(let V of U??[]){let{finalQualifyingRoundNumber:B,finalQualifyingStructureId:$,roundTarget:H,finishingPositions:z,linkType:W}=V,Q=G&&la({targetStructureId:G.structureId,sourceStructureId:$,sourceRoundNumber:B,finishingPositions:z,targetEntryRound:H,linkType:W})?.link;if(Q?.error)return Q;Q&&I.push(Q)}return y&&I.push(...y),{...P,qualifyingResult:{qualifyingDrawPositionsCount:R,qualifiersCount:C},structures:g,links:I}}function X1(t,e){if(t.linkType===fn&&e?.structures){let r=t.source.finishingPositions??[];return e.structures.length*r.length}else if(t.linkType===Ar&&e?.matchUps?.length){let r=t.source.roundNumber;return e.matchUps.filter(({roundNumber:o})=>o===r).length}}function V4({drawDefinition:t,structures:e}){let r=t?.structures?.filter(({stage:u})=>u===rt);r&&e.push(...r);let n=r?.map(({structureId:u})=>u),o=t?.structures?.find(({stage:u,stageSequence:p})=>u===j&&p===1),i=t?.links?.filter(u=>u.target.structureId===o?.structureId&&n?.includes(u.source.structureId)),s=r?.map(u=>{let p=i?.find(g=>g.target.structureId===u.structureId),d=yt({structure:u})?.positionAssignments?.length??0;if(!p)return d;let m=p?.source.structureId,l=t.structures?.find(g=>g.structureId===m),f=X1(p,l)||0;return d-f}).filter(Boolean).reduce((u,p)=>u+p,0),a=i?.map(u=>{let p=u.source.structureId,d=r?.find(m=>m.structureId===p);return X1(u,d)}).filter(Boolean).reduce((u,p)=>u+p,0),c=!!(o&&!o?.matchUps?.length);return{existingQualifyingDrawPositionsCount:s,mainStructureIsPlaceholder:c,existingQualifyingLinks:i,existingMainStructure:o,existingQualifiersCount:a}}function B4({drawType:t,drawSize:e,staggeredEntry:r}){return!!(!En(t)&&(!e||e<2||[di,Ki].includes(t)&&!rn(e)&&e<5||!r&&![yc,di,Ki].includes(t)&&([sn,_r].includes(t)&&e<3||![_r,sn].includes(t)&&!rn(e))))}function H4({mainStructureIsPlaceholder:t,existingMainStructure:e,generatedStructures:r,overwriteExisting:n,generatedLinks:o,structures:i}){let s=r.find(({stage:a,stageSequence:c})=>a===j&&c===1);if(e&&s){if(t)W4(s,e.structureId,o);else if(!n)return{error:Fy}}i.push(...r)}function W4(t,e,r){let n=t.structureId;t.structureId=e;for(let o of r??[])o.source.structureId===n&&(o.source.structureId=e),o.target.structureId===n&&(o.target.structureId=e)}function ag(t){let{modifyOriginal:e=!0,isMock:r}=t??{},n="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return M({result:{error:K},stack:n});let o=e?t.drawDefinition:q(t.drawDefinition,!1,!0),{tieFormat:i,matchUpType:s}=t;if(i){let I=ur({tieFormat:i});if(I.error)return I}i=ar(i??tr({drawDefinition:o})?.tieFormat),s=s??(o.matchUpType||Ct),t.tieFormat=i,t.matchUpType=s;let a=zC({drawDefinition:o,stage:j});t.drawSize=t.drawSize??a;let c=new Set(ye({drawDefinition:o}).drawMatchUps.map(Pe)),u=sg(t);if(u.error)return M({result:u,stack:n});let{structures:p,links:d}=u;o.structures=p,o.links=d;let m=t.drawSize??a;Object.assign(t,et({drawSize:m,matchUpType:s,tieFormat:i}));let{matchUps:l,matchUpsMap:f}=re({drawDefinition:o});i&&l?.forEach(I=>{if(!c.has(I.matchUpId)){let{tieMatchUps:h}=cs({tieFormat:i,matchUp:I,isMock:r});Object.assign(I,{tieMatchUps:h,matchUpType:s})}});let{inContextDrawMatchUps:g}=bs({drawDefinition:o,matchUpsMap:f});return Lt({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:o}),{inContextDrawMatchUps:g,drawDefinition:o,matchUpsMap:f,...P,structures:p,matchUps:l,links:d}}function ec(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!Z1({scaleItem:o}))return{error:ou};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===fr&&o?.eventType!==Tr)return{error:ou};let a=tG({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=rr();c.includes(Oe)&&it({topic:Oe,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...P,info:WI,existingValue:o?.scaleValue}||s&&{...P,newValue:o?.scaleValue}||{error:Wt}}function pv(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t,s=at({tournamentRecord:n},[Z]);if(s.error)return s;if(!n.participants)return{error:va};let a=j4(e);if(a.error)return a;let{modificationsApplied:c,modifiedParticipants:u,error:p}=Y4({participants:n.participants,participantScaleItemsMap:a,removePriorValues:r});if(p)return p;let d=c?void 0:_a,{topics:m}=rr();return m.includes(Oe)&&c&&it({topic:Oe,payload:{tournamentId:n.tournamentId,participants:u}}),q4({context:i,tournamentRecord:n}),o&&m.includes(Zi)&&it({topic:Zi,payload:o}),et({...P,modificationsApplied:c,info:d})}function Z1({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function tG({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Ma};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:ou};let s=new Date().toISOString();e.timeItems??=[];let{scaleItem:a}=Lo({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){if(r.scaleDate&&typeof r.scaleDate=="string"&&!Fe(r.scaleDate))return{error:de};let{scaleType:p,eventType:d,scaleName:m}=r,l=[mi,p,d,m].join("."),f=et({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{...P,valueChanged:u,newValue:r.scaleValue}}function j4(t){let e={};for(let r of t){let n=r?.participantId;if(Array.isArray(r?.scaleItems))for(let o of r.scaleItems)if(Z1({scaleItem:o}))Array.isArray(e[n])||(e[n]=[]),e[n].push(o);else return{error:ou}}return e}function Y4({participants:t,participantScaleItemsMap:e,removePriorValues:r}){let n=0,o=[];for(let i of t){let{participantId:s}=i??{};if(Array.isArray(e[s]))for(let a of e[s]){if(i.participantType===fr&&a?.eventType!==Tr)return{error:M({context:{participantId:s,scaleItem:a,participantType:i.participantType},info:"Invalid participantType for eventType",result:{error:ou}}),modificationsApplied:n,modifiedParticipants:o};tG({participant:i,scaleItem:a,removePriorValues:r}),o.push(i),n++}}return{modificationsApplied:n,modifiedParticipants:o,error:void 0}}function q4({context:t,tournamentRecord:e}){if(!t)return;let{eventId:r,drawId:n,...o}=t,i=o.scaleAttributes?.scaleType&&[o.scaleAttributes.scaleType];if(!Object.keys(o).length)return;let s={itemType:Dh,itemValue:o};if(i&&(s.itemSubTypes=i),n||r){let{drawDefinition:a,event:c}=Ve({tournamentRecord:e,eventId:r,drawId:n});n&&SS({drawDefinition:a,timeItem:s}),r&&Os({event:c,timeItem:s})}else ku({tournamentRecord:e,timeItem:s})}function CS(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=X(t,[{[Z]:!0},{modifiedScaleValues:!0,[qe]:$r}]);if(o.error)return o;for(let i in r){let s=ec({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...P}}var $4=(t=0)=>250/Math.pow(t+5,.4),K4=()=>1;function z4(t=3,e=2){let r=t/e;return Number.isNaN(r)?cg.kDefault():r}var cg={nSpread:400,diffThreshold:.125,kCalc:$4,kMultiplier:z4,kDefault:K4};function RP(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=Ze,winnerCountables:o=1,loserCountables:i=0,ratingType:s="ELO",maxCountables:a,countables:c}=t??{},u=n?.[s];if(!u)return{error:nt};let p=u.range||t.ratingRange;e=e||u.defaultInitialization,r=r||u.defaultInitialization;let d=p[0]>p[1],m=u.decimalsCount||0,l=d?p.slice().reverse():p,f=(w,F)=>Number.parseFloat(F)>=Math.min(...w)&&Number.parseFloat(F)<=Math.max(...w);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=kp({targetRange:Ze["ELO"].range,sourceRange:l,value:d?p[0]-e:e}),I=kp({targetRange:Ze["ELO"].range,sourceRange:l,value:d?p[0]-r:r}),h=(w,F)=>1/(1+Math.pow(10,(F-w)/cg.nSpread)),S=h(g,I),T=h(I,g),y=cg.kCalc(o),E=cg.kCalc(i),A=cg.kMultiplier(a,c),N=g+A*y*(1-S),D=I+A*E*(0-T),R=kp({sourceRange:Ze["ELO"].range,value:N,targetRange:l}),U=kp({sourceRange:Ze["ELO"].range,value:D,targetRange:l}),b=d?p[0]-R:R,C=Number.parseFloat(b.toFixed(m)),_=d?p[0]-U:U,v=Number.parseFloat(_.toFixed(m)),x=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(R>U&&x>cg.diffThreshold||C<0||v<0)&&(C=e,v=r),{newWinnerRating:C,newLoserRating:v}}var eG=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function bP(t){let e=X(t,[{[Z]:!0},{matchUpIds:!0,[qe]:Ye,[qr]:Vs},{ratingType:!1,[Xe]:N=>Ze[N]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i="ELO",convertToELO:s,refreshDynamic:a,considerGames:c,drawDefinition:u,matchUpIds:p,asDynamic:d}=t,m=Ze[i],l=s&&i!=="ELO",f=l?"ELO":i,g=Ze[f],I=m.accessor,h=g.accessor,S={},T=(t.matchUps||a&&sr({drawDefinition:u,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:Rt}}).matchUps||jt({matchUpFilters:{matchUpIds:p,matchUpStatuses:Rt},tournamentRecord:o,inContext:!0}).matchUps)??[],y=`${f}.${_p}`,E=d?y:f;T.sort(sa);for(let N of T){let{endDate:D,matchUpFormat:R,score:U,sides:b,winningSide:C}=N,_=N.matchUpType,v={eventType:_,scaleName:i,scaleType:qo},x={scaleName:y,eventType:_,scaleType:qo},w=l?{scaleName:`${i}.${_p}`,eventType:_,scaleType:qo}:void 0,F=Object.assign({},...(b??[]).map(H=>{let{sideNumber:z,participant:W}=H;return z&&{[z]:[W?.participantId,...W?.individualParticipantIds??[]].filter(Boolean).flat()}})),L=Object.assign({},...Object.values(F).flat().map(H=>Q4({participantId:H,modifiedScaleValues:S,refreshDynamic:a,dynamicScaleAttributes:x,sourceDynamicScaleAttributes:w,scaleAttributes:v,tournamentRecord:o,sourceAccessor:I,outputScaleName:E,ratingType:i,isEloNative:l,accessor:h,matchUpType:_,endDate:D}))),k=R?ne(R):{},G=k?.bestOf||1,V=k?.setsTo||1,B=c?G&V:G,$=U?.sets&&eG(U.sets)||C===1&&[1,0]||[0,1];X4({sideParticipantIds:F,computeRatingType:f,outputScaleName:E,scaleItemMap:L,winningSide:C,countables:$,maxCountables:B,accessor:h}),Object.assign(S,L),r&&CS({tournamentRecord:o,modifiedScaleValues:S,removePriorValues:n})}let A=T.map(({matchUpId:N})=>N);return{...P,modifiedScaleValues:S,outputScaleName:E,processedMatchUpIds:A,...l&&{sourceRatingType:i}}}function Q4({participantId:t,modifiedScaleValues:e,refreshDynamic:r,dynamicScaleAttributes:n,sourceDynamicScaleAttributes:o,scaleAttributes:i,tournamentRecord:s,sourceAccessor:a,outputScaleName:c,ratingType:u,isEloNative:p,accessor:d,matchUpType:m,endDate:l}){let f=e[t],g=!r||f,I=g?as({scaleAttributes:n,tournamentRecord:s,participantId:t}).scaleItem:void 0;!I&&o&&g&&(I=J4({sourceDynamicScaleAttributes:o,tournamentRecord:s,participantId:t,sourceAccessor:a,outputScaleName:c,ratingType:u}));let h=as({tournamentRecord:s,scaleAttributes:i,participantId:t}).scaleItem,S=I??h;if(!I&&h&&p){let y=h.scaleValue,E=a&&typeof y=="object"?y[a]:y;E!=null&&(S={...h,scaleName:c,scaleValue:Gp({sourceRatingType:u,sourceRating:E})})}let T=d?{[d]:void 0}:void 0;return t&&{[t]:S??{scaleName:c,eventType:m,scaleDate:l,scaleType:qo,scaleValue:T}}}function J4({sourceDynamicScaleAttributes:t,tournamentRecord:e,participantId:r,sourceAccessor:n,outputScaleName:o,ratingType:i}){let s=as({scaleAttributes:t,tournamentRecord:e,participantId:r}).scaleItem;if(!s)return;let a=s.scaleValue,c=n&&typeof a=="object"?a[n]:a;if(c!=null)return{...s,scaleName:o,scaleValue:Gp({sourceRatingType:i,sourceRating:c})}}function X4({sideParticipantIds:t,computeRatingType:e,outputScaleName:r,scaleItemMap:n,winningSide:o,countables:i,maxCountables:s,accessor:a}){let c=o?t[o]:[],u=o?t[3-o]:[];for(let p of c){let d=n[p]?.scaleValue,m=typeof d=="object"?d[a]:d;for(let l of u){let f=n[l]?.scaleValue,g=typeof f=="object"?f[a]:f,I=o?i[o]:[0,0],h=o?i[3-o]:[0,0],{newWinnerRating:S,newLoserRating:T}=RP({ratingType:e,winnerCountables:I,loserCountables:h,maxCountables:s,winnerRating:m,loserRating:g}),y=a?{...d,[a]:S}:S,E=a?{...f,[a]:T}:T;n[p].scaleValue=y,n[l].scaleValue=E,n[p].scaleName=r,n[l].scaleName=r}}}function Vc(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:K};let{participantIdPairings:a,matchUpsCount:c}=t,u=Zf(t);if(u.error)return M({result:u});let{lastRoundNumber:p,availableMatchUpsCount:d=0,roundMatchUpsCount:m=0}=u;if(!c)o?c=m:d>0&&(c=d);else if(c>m&&t.restrictMatchUpsCount!==!1)return M({result:{error:O,info:"matchUpsCount error",context:{roundMatchUpsCount:m}}});if(a&&!Array.isArray(a)||c&&!It(c)||e&&!Array.isArray(e)||!a&&!c)return{error:O,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:O,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:O,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??J(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((A,N)=>et({sideNumber:N+1,participantId:A})),E=e[h]??f(h)??ot();return{roundNumber:l,matchUpStatus:Jt,matchUpId:E,sides:y}});if(g?.length){let I=tr({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=cs({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:xt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...P}}function nG({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:r,valueObjects:n,deltaObjects:o,random:i}){let s=i??Math.random,a=Object.assign({},...e.map(y=>({[y.pairing]:y.value}))),c=Object.keys(r),u=[],p=rG({actorsCount:c.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:o,valueObjects:n,random:i}),d=[dv(p)];u.push(p);let m=p.value,l=p,f=1,g=0,I=c.length,h;do I-=1,h=c.length*r[c[0]].length;while(h>t&&I>5);let S=[];c.forEach(y=>{r[y].slice(0,I).forEach(A=>{g+=1;let N=ga(y,A.opponent);if(!S.includes(N)){let D=rG({stipulated:[[y,A.opponent]],actorsCount:c.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:o,valueObjects:n,random:i});if(!d.includes(dv(D))){d.push(dv(D)),u.push(D);let{maxDelta:R,value:U}=D;R<l.maxDelta&&(l=D),(U<m||U===m&&Math.round(s()))&&(m=U),S.push(N),f+=1}}}),u=u.filter(A=>Math.abs(A.value-m)<5)}),u.sort((y,E)=>y.maxDiff-E.maxDiff);let T=Sr(u,i);return{candidatesCount:f,deltaCandidate:l,maxIterations:t,iterations:g,candidate:T}}function dv(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function rG({valueSortedPairings:t,stipulated:e=[],pairingValueMap:r,deltaObjects:n,valueObjects:o,actorsCount:i,random:s}){let a=s??Math.random,c=e.flat(),u=[],p=0;e.filter(Boolean).forEach(f=>{let[g,I]=f,h=ga(g,I),S=r[h];u.push({participantIds:f,value:S}),p+=r[h]}),Ae(t,i).flatMap(f=>dr(f,s).map(g=>({...g,value:g.value+a()*Math.round(a())}))).forEach(f=>{let g=f.pairing.split("|");if(!g.reduce((h,S)=>c.includes(S)||h,!1)){c.push(...g);let h=f.value;p+=h,u.push({participantIds:g,value:h})}}),u.sort((f,g)=>f.value-g.value);let m=u.reduce((f,g)=>{let[I,h]=g.participantIds,S=ga(I,h),T=n[S];return Math.max(T,f)},0),l=u.reduce((f,g)=>{let[I,h]=g.participantIds,S=ga(I,h),T=o[S];return Math.max(T,f)},0);return{value:p,participantIdPairings:u,maxDelta:m,maxDiff:l}}function ga(t,e){return[t,e].sort(ed).join("|")}function mv({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=ga(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 CP({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(lt);if(n.length===2){let[o,i]=n,s=ga(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function oG({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=ga(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var Z4=0;function iG({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=Ze[n]?.defaultInitialization??Z4;return o.split("|").map(s=>{if(r===Xt){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 sG(t){let{tournamentParticipants:e,adHocRatings:r={},possiblePairings:n,uniquePairings:o,maxIterations:i,minimizeDelta:s,deltaObjects:a,valueObjects:c,eventType:u,scaleName:p,salted:d}=t;o.forEach(T=>{let y=iG({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),E=typeof d=="number"&&d||.5,A=t.random??Math.random,N=d&&(Math.round(A())?E:E*-1)||0,D=Math.abs(y[0]-y[1])+N,R=Math.abs(y[0]-y[1]);a[T]=R,c[T]||(c[T]=0),c[T]+=D?Math.pow(D,2):0});let m=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=oG({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=nG({random:t.random,valueSortedPairings:m,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 tQ=100,eQ=100,rQ=4e3;function ug(t){let{encounterValue:e=tQ,sameTeamValue:r=eQ,maxIterations:n=rQ,updateParticipantRatings:o,generateMatchUps:i=!0,ignoreLastRoundNumber:s,iterationMatchUps:a,tournamentRecord:c,dynamicRatings:u,convertToELO:p,refreshDynamic:d,participantIds:m,drawDefinition:l,roundNumber:f,structureId:g,matchUpIds:I,eventType:h,scaleName:S,idPrefix:T,isMock:y,salted:E,event:A}=t;if(!l)return{error:K};if(!t.structure&&!g)return{error:Pt};let N=t.structure||tt({drawDefinition:l,structureId:g}).structure;if(!St(N))return{error:Hi};if(!m?.length)return{error:jo};let D=[...a??[],...N?.matchUps??[]],{encounters:R}=CP({matchUps:D}),U=c?.participants??[],b={},C,{competitionPolicy:_}=wo({tournamentRecord:c,drawDefinition:l,event:A}),{competitionState:v}=_?Ko({drawDefinition:l}):{competitionState:void 0};if(_&&v&&_.pairingPolicy.ratingSource==="DYNAMIC_FORM")for(let[Et,Bt]of Object.entries(v.participantStates))b[Et]=Bt.dynamicFormRating;else if(u){let Et=ct(N?.matchUps?N.matchUps.map(({roundNumber:ce})=>ce):[]),Bt=Math.max(...Et,0);if(Bt){let ce=N?.matchUps?.filter(({roundNumber:he})=>he===Bt).map(({matchUpId:he})=>he),ge=bP({ratingType:S??A?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,convertToELO:p,refreshDynamic:d,drawDefinition:l,matchUpIds:ce});if(ge.error)return ge;ge.modifiedScaleValues&&(b=ge.modifiedScaleValues),ge.sourceRatingType&&(C=ge.sourceRatingType)}}let{valueObjects:w}=nQ({tournamentParticipants:U,encounterValue:e,sameTeamValue:r,encounters:R}),{uniquePairings:F,possiblePairings:L,deltaObjects:k}=mv({participantIds:m}),G=Object.values(b).length?b:t.adHocRatings,V={tournamentParticipants:U,possiblePairings:L,participantIds:m,uniquePairings:F,drawDefinition:l,maxIterations:n,adHocRatings:G,deltaObjects:k,valueObjects:w,random:t.random,eventType:h,scaleName:S,structure:N,salted:E},{candidatesCount:B,participantIdPairings:$,deltaCandidate:H,iterations:z,candidate:W}=sG(V);if(!B)return{error:Jd};let Q,pt;if(i){let Et=Vc({structureId:N?.structureId,ignoreLastRoundNumber:s,participantIdPairings:$,newRound:!0,drawDefinition:l,roundNumber:f,matchUpIds:I,idPrefix:T,isMock:y,event:A});if(Et.error)return Et;Q=Et.roundNumber,pt=Et.matchUps}let{maxDelta:Tt,maxDiff:Ot}=W;return{roundNumber:Q,participantIdPairings:$,modifiedScaleValues:b,sourceRatingType:C,candidatesCount:B,deltaCandidate:H,...P,iterations:z,matchUps:pt,maxDelta:Tt,maxDiff:Ot}}function nQ({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===bt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=mv({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function MP(t){let{drawType:e=on,applyPositioning:r=!0,tournamentRecord:n,staggeredEntry:o,automated:i,placeByes:s,isMock:a,event:c}=t,u=t?.drawDefinition;if(!u)return{error:K};let p=Qe,d=ns({entryStatuses:Em,stageSequence:1,drawDefinition:u,stage:p}),l=[_r,Ys,sn,di].includes(e)?d.length:Ci(d.length);if(!o&&e===yc&&d.length<2||e===_r&&d.length<3)return{error:$d};let{tieFormat:f,matchUpType:g}=t;if(f){let v=ur({tieFormat:f});if(v.error)return v}f=ar(f??tr({drawDefinition:u})?.tieFormat),g=g??u.matchUpType;let{structures:I}=hn({stageSequence:1,drawDefinition:u,stage:p});if(I.length>1)return{error:qU};if(I?.[0]?.matchUps?.length)return{error:qI};let S=I?.[0]?.structureId;Object.assign(t,et({structureName:t.structureName??Be(Qe),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:p}));let T=$f(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:mp};let E=y?.();if(E.error)return E;let{structures:A,links:N}=E,D=A.flatMap(v=>ht({structure:v}).matchUps);f&&D.forEach(v=>{let{tieMatchUps:x}=cs({matchUp:v,tieFormat:f,isMock:a});Object.assign(v,{tieMatchUps:x,matchUpType:g})});let R=q(u,!1,!0);R.links??=[],N.length&&R.links.push(...N);let U=new Set(A.map(({structureId:v})=>v));R.structures??=[];let b=new Set(R.structures.map(({structureId:v})=>v));R.structures=R.structures.map(v=>U.has(v.structureId)?A.find(({structureId:x})=>x===v.structureId):v);let C=A.filter(({structureId:v})=>!b.has(v));if(C.length&&R.structures.push(...C),i&&r){let v=A[0],x=(v?.structures?.length||0)>1;Gu({structureId:S||v?.structureId,seedingProfile:t.seedingProfile,drawDefinition:R,random:t.random,multipleStructures:x,applyPositioning:r,tournamentRecord:n,placeByes:s,event:c})}let _=R.structures.filter(({structureId:v})=>U.has(v));return{links:N,structures:_,...P}}var WS={};_t(WS,{ScoringEngine:()=>kS,addPoint:()=>xs,analyzeScore:()=>VS,analyzeSequence:()=>Yv,analyzeSet:()=>Sd,calculateMatchStatistics:()=>pg,calculatePointsTo:()=>Vm,checkScoreHasValue:()=>le,checkSetIsComplete:()=>Wm,createMatchUp:()=>ds,deduceMatchUpFormat:()=>Km,enrichPointHistory:()=>gv,exportMatchUpJSON:()=>WG,generate:()=>Ev,generateScoreString:()=>Li,generateTieMatchUpScore:()=>Vu,getEpisodes:()=>vS,getQuickStats:()=>Iv,getScore:()=>ms,getScoreboard:()=>MS,getSetComplement:()=>HS,getSetScoreString:()=>wG,getTiebreakComplement:()=>qm,getWinner:()=>_S,groupByMatch:()=>KP,helpers:()=>kv,inferServeSide:()=>xS,isComplete:()=>OS,isValidMatchUpFormat:()=>Or,keyValueScore:()=>Fv,mcpValidator:()=>HG,mutate:()=>Av,parseCSV:()=>$P,parseMCPPoint:()=>qP,parseMatchUpFormat:()=>ne,parseScoreString:()=>$m,pbpValidator:()=>kG,pointParser:()=>qv,query:()=>Bv,resolvePointValue:()=>wS,reverseScore:()=>lv,shotParser:()=>YP,shotSplitter:()=>jv,stringifyMatchUpFormat:()=>sm,toStatObjects:()=>dg,validateMCPMatch:()=>$v,validateMatchUp:()=>Hv,validateMatchUpScore:()=>Gv,validateScore:()=>BS,validateSet:()=>LG,validateSetScore:()=>WP,validateTieFormat:()=>ur});var Ev={};_t(Ev,{ScoringEngine:()=>kS,generateScoreString:()=>Li,generateTieMatchUpScore:()=>Vu,reverseScore:()=>lv});function Li(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:nt,info:"missing sets"};let p=s&&ne(s),{bestOf:d,finalSetFormat:m,setFormat:l}=p??{},g=o||!(!e||!c||c===1),I=n?oQ({matchUpStatus:i}):"",h=u?.sort(iQ).map(S).filter(Boolean).join(" ")||"";if(!I)return h;if(c===2)return`${I} ${h}`;return`${h} ${I}`;function S(T){let E=d&&T.setNumber===d&&m?m:l,A=W=>He(W?.side1Score)||He(W?.side2Score),D=(W=>He(W?.side1TiebreakScore)||He(W?.side2TiebreakScore))(T),R=E?.tiebreakSet||!A(T)&&D,{side1Score:U,side2Score:b,side1TiebreakScore:C,side2TiebreakScore:_}=T,v=C||(He(C)||D&&a?0:""),x=_||(He(_)||D&&a?0:"");if(R){let W=A(T)&&!D,Q=W?U:v,pt=W?b:x;return`[${(g?[pt,Q]:[Q,pt]).join("-")}]`}let w=D?Math.min(v,x):"",F=w===v?1:2,L=He(w)?`(${w})`:"",k=U||(He(U)||a?0:""),G=b||(He(b)||a?0:""),V=W=>!r&&F===W?L:"",B=`${k}${V(1)}`,$=`${G}${V(2)}`,H=r&&D?`(${w})`:"",z=g?`${[$,B].join("-")}${H}`:`${[B,$].join("-")}${H}`;return["-"," "].includes(z)&&(z=""),z}}function oQ({matchUpStatus:t}){let e={[ve]:"RET",[vt]:"WO",[Te]:"DF/DF",[Zt]:"WO/WO",[Ji]:"SUS",[Lr]:"ABN",[Mt]:"DEF",[Vp]:"DR"};return t&&e[t]||""}function iQ(t,e){return t.setNumber-e.setNumber}function lv(t){if(!t?.score)return{error:nt};let{sets:e}=t.score,r=e.map(s=>{let{side1TiebreakScore:a,side2TiebreakScore:c,side1PointScore:u,side2PointScore:p,winningSide:d,side1Score:m,side2Score:l,setNumber:f}=s;return et({winningSide:d?3-d:void 0,side1TiebreakScore:c,side2TiebreakScore:a,side1PointScore:p,side2PointScore:u,side1Score:l,side2Score:m,setNumber:f})}),n=t?.setTBlast,o=Li({setTBlast:n,sets:r}),i=Li({sets:r,reversed:!0,setTBlast:n});return{reversedScore:{sets:r,scoreStringSide1:o,scoreStringSide2:i},...P}}var sQ={A:"Ace",D:"Double Fault",S:"Serve Winner",R:"Return Winner",W:"Winner",E:"Unforced Error",F:"Forced Error"},aQ=new Set(["A","S"]),cQ=new Set(["D","R","E","F"]);function aG(t,e){let r={...t};return r.server=e.server,r.index=e.index,r.set=e.set,r.game=e.game,r.code&&!r.winner&&(r.winner=uQ(r.code,e.server)),r.code&&!r.result&&(r.result=sQ[r.code]),r.first_serve?r.serve=2:r.serve||(r.serve=1),r}function uQ(t,e){return aQ.has(t)?e:cQ.has(t)?1-e:e}function cG(t){let e=[],r=[],n=t.result?.toLowerCase()||"";return n.includes("ace")&&e.push("aces"),(n.includes("winner")||n.includes("ace"))&&e.push("winners"),n.includes("double fault")&&r.push("doubleFaults"),n.includes("unforced error")&&r.push("unforcedErrors"),n.includes("forced error")&&r.push("forcedErrors"),t.winner===t.server?(e.push("servesWon"),t.serve===1?e.push("serves1stWon"):t.serve===2&&e.push("serves2ndWon")):(e.push("returns"),t.serve===1?e.push("received1stWon"):t.serve===2&&e.push("received2ndWon")),e.push("pointsWon"),{winner:e,loser:r}}function fv(t,e){let r={players:{},teams:{}};for(let i=0;i<2;i++)r.players[i]={},r.teams[i]={};let n=t;e?.setFilter!==void 0&&(n=t.filter(i=>i.set===e.setFilter));let o;return n.forEach((i,s)=>{if(i.winner===void 0){We()&&console.warn("Point missing winner:",i);return}let{winner:a,loser:c}=cG(i),u=i.winner,p=1-u;uG(r,u,a,i),uG(r,p,c,i),pQ(r,i),dQ(r,i,u,s),mQ(r,i,o),lQ(r,i,u),o=i}),r}function Bc(t,e,r,n){t[e][r]||(t[e][r]=[]),t[e][r].push(n)}function uG(t,e,r,n){r.forEach(o=>{Bc(t.teams,e,o,n),Bc(t.players,e,o,n)})}function pQ(t,e){if(e.server===void 0)return;let r=e.server;Bc(t.teams,r,"pointsServed",e),e.serve===1?Bc(t.teams,r,"serves1stIn",e):e.serve===2&&Bc(t.teams,r,"serves2ndIn",e)}function dQ(t,e,r,n){e.hand&&Bc(t.teams,r,e.hand,{point:e,index:n})}function mQ(t,e,r){if(!fQ(e,r)||r?.winner===void 0)return;let n=r.winner;Bc(t.teams,n,"gamesWon",r),Bc(t.players,n,"gamesWon",r)}function lQ(t,e,r){if(!e.breakpoint)return;let n=e.server;Bc(t.teams,n,"breakpointsFaced",e),r===n&&Bc(t.teams,n,"breakpointsSaved",e)}function fQ(t,e){return e&&t.game!==void 0&&e.game!==void 0?t.game!==e.game:!1}function pG(t){let e={totalPoints:0,byTeam:[0,0],byCategory:{}};for(let n=0;n<2;n++)if(t.teams[n].pointsWon){let o=t.teams[n].pointsWon.length;e.byTeam[n]=o,e.totalPoints+=o}let r=new Set;for(let n=0;n<2;n++)Object.keys(t.teams[n]).forEach(o=>r.add(o));return r.forEach(n=>{e.byCategory[n]=0;for(let o=0;o<2;o++)t.teams[o][n]&&(e.byCategory[n]+=t.teams[o][n].length)}),e}function mG(t){if(!t?.teams)return[];let e=[];return Object.values({Aces:{category:"Aces",numerators:["aces"],calc:"number"},"Double Faults":{category:"Double Faults",numerators:["doubleFaults"],calc:"number"},Winners:{category:"Winners",numerators:["winners"],calc:"number"},"Unforced Errors":{category:"Unforced Errors",numerators:["unforcedErrors"],calc:"number"},"Forced Errors":{category:"Forced Errors",numerators:["forcedErrors"],calc:"number"},"Total Points Won":{category:"Total Points Won",numerators:["pointsWon"],calc:"number"},"Max Pts/Row":{category:"Max Pts/Row",numerators:["pointsWon"],calc:"maxConsecutive",attribute:"index"},"Max Games/Row":{category:"Max Games/Row",numerators:["gamesWon"],calc:"maxConsecutive",attribute:"game"},"First Serve %":{category:"First Serve %",numerators:["serves1stIn"],denominators:["pointsServed"],calc:"percentage"},"Points Won 1st":{category:"Points Won 1st",numerators:["serves1stWon"],denominators:["serves1stIn"],calc:"percentage"},"Points Won 2nd":{category:"Points Won 2nd",numerators:["serves2ndWon"],denominators:["serves2ndIn"],calc:"percentage"},"Points Won Receiving":{category:"Points Won Receiving",numerators:["received1stWon","received2ndWon"],denominators:["-pointsServed"],calc:"percentage"},"Breakpoints Saved":{category:"Breakpoints Saved",numerators:["breakpointsSaved"],denominators:["breakpointsFaced"],calc:"percentage"},"Breakpoints Converted":{category:"Breakpoints Converted",numerators:["-breakpointsSaved"],denominators:["-breakpointsFaced"],calc:"difference"},"Games Won":{category:"Games Won",numerators:["gamesWon"],calc:"number"},"Service Points Won":{category:"Service Points Won",numerators:["servesWon"],denominators:["pointsServed"],calc:"percentage"},"Aggressive Margin":{category:"Aggressive Margin",numerators:["*doubleFaults","*unforcedErrors"],denominators:["*aces","*winners","-*forcedErrors"],calc:"aggressiveMargin"}}).forEach(n=>{let o=[dG(n,t.teams,0),dG(n,t.teams,1)];(o[0].value!==0||o[1].value!==0)&&e.push({category:n.category,teams:o})}),e}function dG(t,e,r){switch(t.calc){case"number":return gQ(t,e,r);case"percentage":return IQ(t,e,r);case"maxConsecutive":return hQ(t,e,r);case"difference":return SQ(t,e,r);case"aggressiveMargin":return TQ(t,e,r)}}function gQ(t,e,r){let n=Gm(t.numerators,e,r);return{value:n,display:String(n),numerators:t.numerators}}function IQ(t,e,r){let n=Gm(t.numerators,e,r),o=Gm(t.denominators??[],e,r);if(!o)return{value:0,display:"0",numerators:t.numerators};let i=Math.round(n/o*100);return{value:i,display:`${i}% (${n}/${o})`,numerators:t.numerators}}function hQ(t,e,r){let n=t.numerators[0],o=t.attribute||"index";if(!e[r][n])return{value:0,display:"0"};let i=e[r][n],s=0,a=i.length?1:0,c;return i.forEach(u=>{let p=u[o];c!==void 0&&p===c+1?a++:(a>s&&(s=a),a=1),c=p}),a>s&&(s=a),{value:s,display:String(s)}}function SQ(t,e,r){let n=Gm(t.numerators,e,r),o=Gm(t.denominators??[],e,r);if(!o)return{value:0,display:"0",numerators:t.numerators};let i=Math.abs(o-n),s=Math.round(i/o*100);return{value:s,display:`${s}% (${i}/${o})`,numerators:t.numerators}}function TQ(t,e,r){let n=Gm(t.denominators??[],e,r),o=Gm(t.numerators,e,r),i=n-o;return{value:i,display:String(i)}}function Gm(t,e,r){return t?t.reduce((n,o)=>{let i=o.startsWith("-"),s=o.includes("*"),a=o.replace("-","").replace("*",""),c=i?1-r:r,u=e[c]?.[a];return u?n+u.length:n},0):0}function pg(t,e,r){let n=fv(e??[],r),o=mG(n),i=pG(n);return{counters:n,calculated:o,summary:i}}function gv(t){if(!t)return[];let e=[],r=0,n=0,o=0;return t.forEach((i,s)=>{let a=aG(i,{server:r,index:s,set:n,game:o});e.push(a)}),e}function Iv(t,e){let r=fv(t??[],e);return{aces:[r.teams[0].aces?.length||0,r.teams[1].aces?.length||0],doubleFaults:[r.teams[0].doubleFaults?.length||0,r.teams[1].doubleFaults?.length||0],winners:[r.teams[0].winners?.length||0,r.teams[1].winners?.length||0],unforcedErrors:[r.teams[0].unforcedErrors?.length||0,r.teams[1].unforcedErrors?.length||0],totalPoints:[r.teams[0].pointsWon?.length||0,r.teams[1].pointsWon?.length||0]}}function Re(t,e,r){return t.teams[e]?.[r]?.length??0}function ps(t,e){return!e||!t?0:Number.parseFloat((t/e*100).toFixed(2))}function vP(t,e,r){return t.find(o=>o.category===e)?.teams[r]?.value??0}function dg(t){if(!t?.counters?.teams)return[];let{counters:e,calculated:r}=t,n=[];n.push({name:"Aces",numerator:[Re(e,0,"aces"),Re(e,1,"aces")],default:"numerator"},{name:"Double Faults",numerator:[Re(e,0,"doubleFaults"),Re(e,1,"doubleFaults")],default:"numerator"});let o=[Re(e,0,"serves1stWon"),Re(e,1,"serves1stWon")],i=[Re(e,0,"servesWon"),Re(e,1,"servesWon")];if(o[0]+o[1]>0&&(i[0]!==o[0]||i[1]!==o[1])){let E=[Re(e,0,"pointsServed"),Re(e,1,"pointsServed")],A=[Re(e,0,"serves1stIn"),Re(e,1,"serves1stIn")],N=[Re(e,0,"serves2ndWon"),Re(e,1,"serves2ndWon")],D=[Re(e,0,"serves2ndIn"),Re(e,1,"serves2ndIn")];n.push({name:"1st Serve In",numerator:A,denominator:E,pct:[ps(A[0],E[0]),ps(A[1],E[1])]},{name:"1st Serve Points Won",numerator:o,denominator:A,pct:[ps(o[0],A[0]),ps(o[1],A[1])]},{name:"2nd Serve Points Won",numerator:N,denominator:D,pct:[ps(N[0],D[0]),ps(N[1],D[1])]})}n.push({name:"Total Points Won",numerator:[Re(e,0,"pointsWon"),Re(e,1,"pointsWon")],default:"numerator"});let a=Re(e,0,"received1stWon")+Re(e,0,"received2ndWon"),c=Re(e,1,"received1stWon")+Re(e,1,"received2ndWon"),u=Re(e,1,"pointsServed"),p=Re(e,0,"pointsServed");n.push({name:"Receiving Points Won",numerator:[a,c],denominator:[u,p],pct:[ps(a,u),ps(c,p)]});let d=Re(e,1,"breakpointsFaced")-Re(e,1,"breakpointsSaved"),m=Re(e,0,"breakpointsFaced")-Re(e,0,"breakpointsSaved"),l=Re(e,1,"breakpointsFaced"),f=Re(e,0,"breakpointsFaced");n.push({name:"Break Points Won",numerator:[d,m],denominator:[l,f],pct:[ps(d,l),ps(m,f)]});let g=Re(e,0,"breakpointsSaved"),I=Re(e,1,"breakpointsSaved"),h=Re(e,0,"breakpointsFaced"),S=Re(e,1,"breakpointsFaced");n.push({name:"Break Points Saved",numerator:[g,I],denominator:[h,S],pct:[ps(g,h),ps(I,S)]},{name:"Winners",numerator:[Re(e,0,"winners"),Re(e,1,"winners")],default:"numerator"},{name:"Unforced Errors",numerator:[Re(e,0,"unforcedErrors"),Re(e,1,"unforcedErrors")],default:"numerator"},{name:"Forced Errors",numerator:[Re(e,0,"forcedErrors"),Re(e,1,"forcedErrors")],default:"numerator"});let T=i,y=[Re(e,0,"pointsServed"),Re(e,1,"pointsServed")];return n.push({name:"Service Points Won",numerator:T,denominator:y,pct:[ps(T[0],y[0]),ps(T[1],y[1])]},{name:"Games Won",numerator:[Re(e,0,"gamesWon"),Re(e,1,"gamesWon")]},{name:"Most Consecutive Points Won",numerator:[vP(r,"Max Pts/Row",0),vP(r,"Max Pts/Row",1)]},{name:"Most Consecutive Games Won",numerator:[vP(r,"Max Games/Row",0),vP(r,"Max Games/Row",1)]}),n}function OP(t){return t?!!t.aggregate:!1}function Hu(t,e){let r=t.bestOf||t.exactly||3,n=Math.ceil(r/2);if(e[0]===n-1&&e[1]===n-1&&t.finalSetFormat){let s=t.finalSetFormat;return s.tiebreakSet?"matchTiebreak":s.timed?"timed":"standard"}let i=t.setFormat;return i?i.tiebreakSet?"tiebreakOnly":i.timed?"timed":"standard":"standard"}function ds(t){let{matchUpId:e=ot(),matchUpFormat:r,participants:n=[],isDoubles:o=!1,matchUpType:i}=t,s=i||(o?"DOUBLES":"SINGLES"),a=n.map((p,d)=>({sideNumber:d+1,participantId:p.participantId,participant:p}));return a.length===0&&a.push({sideNumber:1},{sideNumber:2}),{matchUpId:e,matchUpFormat:r,matchUpStatus:"TO_BE_PLAYED",matchUpType:s,sides:a,score:{sets:[]},createdAt:new Date().toISOString()}}function MS(t,e){let r=t.score.sets;if(r.length===0)return"0-0";let n=e?.perspective,o=r.map(s=>{let a=s.side1Score||0,c=s.side2Score||0;if(n===1&&([a,c]=[c,a]),s.side1TiebreakScore!==void 0||s.side2TiebreakScore!==void 0){let u=s.side1TiebreakScore||0,p=s.side2TiebreakScore||0;return n===1&&([u,p]=[p,u]),a>c?`${a}-${c}(${p})`:`${a}(${u})-${c}`}return`${a}-${c}`}),i=r.at(-1);if(t.matchUpStatus==="IN_PROGRESS"&&i&&!i.winningSide){let s=i.side1GameScores??[],a=s.length-1;if(a>=0&&s.length>0){let c=s[a]||0,u=(i.side2GameScores??[])[a]||0;if(c===0&&u===0)return o.join(", ");n===1&&([c,u]=[u,c]);let p=i.side1Score||0,d=i.side2Score||0,m=t.matchUpFormat?ne(t.matchUpFormat):void 0,l=m?.setFormat?.setTo||6,f=(typeof m?.setFormat?.tiebreakAt=="number"?m.setFormat.tiebreakAt:void 0)??l,g=p===f&&d===f,I=m?.gameFormat?.type==="CONSECUTIVE",h=o.at(-1),S=`${o.slice(0,-1).join(", ")}${o.length>1?", ":""}${h}`;if(g||I)return`${S} (${c}-${u})`;{let T=yQ(c,u);return`${S} (${T})`}}}return o.join(", ")}function yQ(t,e){let r=["0","15","30","40"];if(t<=3&&e<=3)return`${r[t]}-${r[e]}`;if(t>=3&&e>=3){let n=t-e;return n===0?"40-40":n===1?"A-40":n===-1?"40-A":n>=2?"G-40":"40-G"}return t>=3?"G-40":e>=3?"40-G":`${r[t]}-${r[e]}`}function vS(t){if(!t)return[];let e=t.history?.points;if(!e||e.length===0)return[];let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=n<e.length-1?e[n+1]:void 0,s=n===e.length-1,a=t.matchUpStatus==="COMPLETED",c=o.set??0,u=o.game??0,p=o.number??0,{gameComplete:d,setComplete:m}=EQ({nextPoint:i,isLastPoint:s,isCompleted:a,pointSet:c,pointGame:u}),l=d?o.winner:void 0,f=AQ(m,t,c),g=PQ(o),I=i?.server??o.server??0,h=NQ(t,c,u);r.push({action:"addPoint",point:{index:n,number:p,winner:o.winner,server:o.server,score:o.score,result:o.result},game:{index:u,isTiebreak:h,complete:d,winner:l},set:{index:c,complete:m,winner:f},needed:g,nextService:I,result:o.result,complete:s&&a})}return r}function EQ({nextPoint:t,isLastPoint:e,isCompleted:r,pointSet:n,pointGame:o}){let i=t?t.set??0:void 0,s=t?t.game??0:void 0;return{gameComplete:e?r||i===void 0&&s===void 0:i!==n||s!==o,setComplete:e?r||!1:t!==void 0&&i!==n}}function AQ(t,e,r){if(!t)return;let n=e.score.sets[r];if(n?.winningSide!==void 0)return n.winningSide-1}function PQ(t){let e={};return t.pointsToGame&&(e.pointsToGame=t.pointsToGame),t.pointsToSet&&(e.pointsToSet=t.pointsToSet),t.pointsToMatch&&(e.pointsToMatch=t.pointsToMatch),t.gamesToSet&&(e.gamesToSet=t.gamesToSet),t.isBreakpoint!==void 0&&(e.isBreakpoint=t.isBreakpoint),e}function NQ(t,e,r){let n=t.score.sets[e];return!!(n?.isTiebreakOnly||r>0&&n?.side1Score!==void 0&&n?.side2Score!==void 0&&!n?.isTiebreakOnly)}function OS(t){return t.matchUpStatus==="COMPLETED"}function _S(t){if(t.matchUpStatus==="COMPLETED")return t.winningSide}function Vm(t,e,r,n,o){if(r==="timed"||!n)return;let i=DQ(t),s=UQ(t),a=e.exactly||e.bestOf||3,c=Math.ceil(a/2),{side1Points:u,side2Points:p}=RQ(i),d=bQ(u,p,n,r,e,i),m=MQ(i,n,r),l=vQ(d,m,n,r),f=OQ(l,s,c,e),g=xQ(d,o);return{pointsToGame:d,pointsToSet:l,pointsToMatch:f,gamesToSet:m,isBreakpoint:g}}function DQ(t){let e=t.score.sets;if(e.length===0)return;let r=e.at(-1);return r?.winningSide===void 0?r:void 0}function UQ(t){let e=[0,0];return t.score.sets.forEach(r=>{r.winningSide===1&&e[0]++,r.winningSide===2&&e[1]++}),e}function RQ(t){if(!t)return{side1Points:0,side2Points:0};let e=t.side1GameScores??[],r=t.side2GameScores??[];if(e.length===0&&r.length===0)return{side1Points:0,side2Points:0};let n=Math.max(e.length,r.length)-1;return{side1Points:e[n]??0,side2Points:r[n]??0}}function bQ(t,e,r,n,o,i){if(n==="tiebreakOnly"){let s=r.tiebreakSet?.tiebreakTo||11,a=r.tiebreakSet?.NoAD||!1;return hv(t,e,s,a)}if(n==="matchTiebreak"){let s=o.finalSetFormat?.tiebreakSet?.tiebreakTo||10,a=o.finalSetFormat?.tiebreakSet?.NoAD||!1;return hv(t,e,s,a)}if(i){let s=i.side1Score||0,a=i.side2Score||0,c=r.setTo||6,u=(typeof r.tiebreakAt=="number"?r.tiebreakAt:void 0)??c;if(!(r.noTiebreak||!1)&&s===u&&a===u){let d=r.tiebreakFormat?.tiebreakTo||7,m=r.tiebreakFormat?.NoAD||!1;return hv(t,e,d,m)}}if(o.gameFormat?.type==="CONSECUTIVE"){let s=o.gameFormat.count||3;return[s,s]}return CQ(t,e,r,o)}function CQ(t,e,r,n){let o=r.gameFormat?.NoAD||r.NoAD||!1,i=n?.gameFormat?.deuceAfter,s=4;return[lG(t,e,s,o,i),lG(e,t,s,o,i)]}function lG(t,e,r,n,o){if(t>=r-1&&e>=r-1){if(n||o&&t>=2+o&&e>=2+o)return t>e?0:t===e?1:2;let i=t-e;return i>=2?0:i===1?1:2}return t>=r?0:r-t}function hv(t,e,r,n){return[fG(t,e,r,n),fG(e,t,r,n)]}function fG(t,e,r,n){if(t>=r&&(t-e>=2||n&&t>e))return 0;if(t>=r-1&&e>=r-1){if(n)return t>e?0:t===e?1:2;let o=t-e;return o>=2?0:o===1?1:2}return t>=r?0:r-t}function MQ(t,e,r){if(r==="tiebreakOnly"||r==="matchTiebreak")return!t||t.winningSide!==void 0?[1,1]:[1,1];let n=t?.side1Score||0,o=t?.side2Score||0,i=e.setTo||6,s=(typeof e.tiebreakAt=="number"?e.tiebreakAt:void 0)??i,a=e.noTiebreak||!1,c=e.winBy||2;return[gG(n,o,i,s,a,c),gG(o,n,i,s,a,c)]}function gG(t,e,r,n,o,i){if(!o&&t===n&&e===n)return 1;if(t>=r){let a=t-e;return a>=i?0:i-a}let s=r-t;if(e>=r-1&&t>=r-1){if(!o)return Math.max(1,r-t);let a=t-e;return a>=i?0:i-a}return s}function vQ(t,e,r,n){if(n==="tiebreakOnly"||n==="matchTiebreak")return[...t];let o=4;return[IG(t[0],e[0],o),IG(t[1],e[1],o)]}function IG(t,e,r){if(e<=0)return 0;let n=Math.max(0,e-1);return t+n*r}function OQ(t,e,r,n){let o=n.setFormat,i=_Q(o,n);return[hG(t[0],e[0],r,i),hG(t[1],e[1],r,i)]}function _Q(t,e){if(!t)return 24;if(t.tiebreakSet)return t.tiebreakSet.tiebreakTo||11;if(t.timed)return 0;let r=t.setTo||6,o=e.gameFormat?.type==="CONSECUTIVE"?e.gameFormat?.count||3:4;return r*o}function hG(t,e,r,n){if(e>=r)return 0;let o=Math.max(0,r-e-1);return t+o*n}function xQ(t,e){if(e===void 0)return!1;let r=1-e;return t[r]===1}function xS(t,e,r){if(r==="timed")return;let n=wQ(t);return OP(e)?LQ(t,n):r==="tiebreakOnly"||r==="matchTiebreak"?FQ(n):kQ(t,e,n)}function wQ(t){let e=t.score.sets;if(e.length===0)return;let r=e[e.length-1];return r.winningSide===void 0?r:void 0}function LQ(t,e){let r=0;for(let n of t.score.sets)n.winningSide!==void 0&&(n.side1TiebreakScore!==void 0?r+=(n.side1TiebreakScore??0)+(n.side2TiebreakScore??0):r+=(n.side1Score??0)+(n.side2Score??0));if(e&&e.winningSide===void 0){let n=e.side1GameScores??[],o=e.side2GameScores??[];if(n.length>0||o.length>0){let i=Math.max(n.length,o.length)-1;r+=(n[i]??0)+(o[i]??0)}else r+=(e.side1Score??0)+(e.side2Score??0)}return r%2===0?"deuce":"ad"}function FQ(t){if(!t)return"deuce";let e=t.side1GameScores??[],r=t.side2GameScores??[];return e.length===0&&r.length===0||((e[0]??0)+(r[0]??0))%2===0?"deuce":"ad"}function kQ(t,e,r){if(!r)return"deuce";let n=r.side1GameScores??[],o=r.side2GameScores??[];if(n.length===0&&o.length===0)return"deuce";let i=Math.max(n.length,o.length)-1;return((n[i]??0)+(o[i]??0))%2===0?"deuce":"ad"}function wS(t,e){if(!e.length)return 1;for(let{condition:r,value:n}of e)if(r.results&&t.result&&r.results.includes(t.result)||r.strokes&&t.stroke&&r.strokes.includes(t.stroke))return n;return 1}function xs(t,e,r){if(!St(e))return t;let n=e.winner,o=e.server,{timestamp:i}=e;if(n===void 0&&e.winningSide!==void 0&&(n=e.winningSide-1),o===void 0&&e.serverSideNumber!==void 0&&(o=e.serverSideNumber-1),n==null)return t;let s=t;s.history??={points:[]};let a=ne(t.matchUpFormat);if(!a)throw new Error(`Invalid matchUpFormat: ${t.matchUpFormat}`);let c=a.exactly||a.bestOf||3,u=Math.ceil(c/2),p=s.history.points.length+1,d=s.history.points.length,m=[0,0];s.score.sets.forEach(N=>{N.winningSide===1&&m[0]++,N.winningSide===2&&m[1]++});let l=Hu(a,m),f=m[0]===u-1&&m[1]===u-1,g=f&&a.finalSetFormat?a.finalSetFormat:a.setFormat,I=g?.tiebreakSet?.modifier==="RALLY"||g?.modifier==="RALLY";o===void 0&&!I&&(o=FS(s,a,l));let h=e.code;!h&&n!==void 0&&o!==void 0&&(h=n===o?"S":"R");let S={...e,pointNumber:p,winner:n,winningSide:n+1,server:o,serverSideNumber:o===void 0?void 0:o+1,serverParticipantId:e.serverParticipantId,timestamp:i||new Date().toISOString()};h&&(S.code=h),S.index=d;let T=Vm(s,a,l,g,o);T&&(S.pointsToGame=T.pointsToGame,S.pointsToSet=T.pointsToSet,S.pointsToMatch=T.pointsToMatch,S.gamesToSet=T.gamesToSet,S.isBreakpoint=T.isBreakpoint);let y=xS(s,a,l);y!==void 0&&(S.serveSide=y);let E=r?.pointMultipliers??[],A=e.scoreValue??wS(S,E);switch(A!==1&&(S.scoreValue=A),s.history.points.push(S),s.matchUpStatus==="TO_BE_PLAYED"&&(s.matchUpStatus="IN_PROGRESS"),l){case"tiebreakOnly":BQ(s,S,n,a,g,u,A);break;case"matchTiebreak":HQ(s,S,n,a,u,A);break;case"timed":WQ(s,S,n,g,A);break;default:GQ(s,S,n,a,g,u,f);break}return s}function GQ(t,e,r,n,o,i,s){let a=_P(t,!1,!1),c=t.score.sets.indexOf(a),u=a.side1Score||0,p=a.side2Score||0,d=a.side1GameScores??[],m=a.side2GameScores??[];d.length===0&&m.length===0&&(d.push(0),m.push(0));let l=Math.max(d.length,m.length)-1,f=l>=0?d[l]??0:0,g=l>=0?m[l]??0:0,I=Math.max(d.length,m.length)-1,h=u+p-I;e.set=c,e.game=h+l,e.number=f+g;let S=o.setTo||6,T=(typeof o.tiebreakAt=="number"?o.tiebreakAt:void 0)??S,y=s&&n.finalSetFormat?.noTiebreak;r===0?(f++,d[d.length-1]=f):(g++,m[m.length-1]=g),a.side1GameScores=d,a.side2GameScores=m;let E=n.gameFormat?.type==="CONSECUTIVE",A=n.gameFormat?.count||3;if(E){let U=a.currentStreak;U?.side===r?a.currentStreak={side:r,count:U.count+1}:a.currentStreak={side:r,count:1}}let N=!y&&u===T&&p===T,D;E&&!N?D=a.currentStreak.count>=A?a.currentStreak.side:void 0:D=jQ(f,g,o,N,n);let R=D===void 0?yv(f,g,N,E&&!N):"0-0";e.score=R,D!==void 0&&VQ(a,D,u,p,f,g,N,E,t,n,o,s,i)}function VQ(t,e,r,n,o,i,s,a,c,u,p,d,m){a&&(t.currentStreak=void 0),e===0?t.side1Score=r+1:t.side2Score=n+1,s&&(t.side1TiebreakScore=o,t.side2TiebreakScore=i);let l=Tv(t.side1Score||0,t.side2Score||0,p,d,u.finalSetFormat);typeof l=="number"?(t.winningSide=l+1,LS(c,u,m)):(t.side1GameScores.push(0),t.side2GameScores.push(0))}function BQ(t,e,r,n,o,i,s=1){let a=_P(t,!0,!1),c=t.score.sets.indexOf(a),u=o.tiebreakSet.tiebreakTo||11,p=o.tiebreakSet.NoAD||!1,d=a.side1GameScores??[],m=a.side2GameScores??[];d.length===0&&m.length===0&&(d.push(0),m.push(0),a.side1GameScores=d,a.side2GameScores=m);let l=d[0]||0,f=m[0]||0;e.set=c,e.game=0,e.number=l+f,r===0?(l+=s,d[0]=l):(f+=s,m[0]=f),a.side1GameScores=d,a.side2GameScores=m;let g=Sv(l,f,u,p);e.score=g===void 0?`${l}-${f}`:"0-0",g!==void 0&&(a.winningSide=g+1,a.side1TiebreakScore=l,a.side2TiebreakScore=f,a.side1Score=g===0?1:0,a.side2Score=g===0?0:1,LS(t,n,i))}function HQ(t,e,r,n,o,i=1){let s=n.finalSetFormat?.tiebreakSet?.tiebreakTo||10,a=n.finalSetFormat?.tiebreakSet?.NoAD||!1,c=_P(t,!1,!1),u=t.score.sets.indexOf(c),p=c.side1GameScores??[],d=c.side2GameScores??[];p.length===0&&d.length===0&&(p.push(0),d.push(0),c.side1GameScores=p,c.side2GameScores=d);let m=p[0]||0,l=d[0]||0;e.set=u,e.game=0,e.number=m+l,r===0?(m+=i,p[0]=m):(l+=i,d[0]=l),c.side1GameScores=p,c.side2GameScores=d;let f=Sv(m,l,s,a);e.score=f===void 0?`${m}-${l}`:"0-0",f!==void 0&&(c.side1TiebreakScore=m,c.side2TiebreakScore=l,c.side1Score=f===0?1:0,c.side2Score=f===0?0:1,c.winningSide=f+1,LS(t,n,o))}function WQ(t,e,r,n,o=1){let i=_P(t,!1,!0),s=t.score.sets.indexOf(i);e.set=s,e.game=0,e.number=(i.side1Score||0)+(i.side2Score||0),r===0?i.side1Score=(i.side1Score||0)+o:i.side2Score=(i.side2Score||0)+o;let a=i.side1Score||0,c=i.side2Score||0;e.score=`${a}-${c}`}function _P(t,e,r){let n=t.score.sets.length-1,o=n>=0?t.score.sets[n]:void 0;if(o&&o.winningSide===void 0&&!o.segmentComplete)return o;let i={setNumber:t.score.sets.length+1,side1Score:0,side2Score:0,side1GameScores:[],side2GameScores:[]};return e&&(i.isTiebreakOnly=!0),r&&(i.isTimed=!0),t.score.sets.push(i),i}function LS(t,e,r){let n=[0,0];t.score.sets.forEach(c=>{c.winningSide===1&&n[0]++,c.winningSide===2&&n[1]++});let o=OP(e),i=e.exactly;if(o){let c=i||e.bestOf||3;if(t.score.sets.length<c)return;let p=t.score.sets.reduce((d,m)=>(m.side1TiebreakScore!==void 0&&m.side2TiebreakScore!==void 0?(d[0]+=m.side1TiebreakScore,d[1]+=m.side2TiebreakScore):(d[0]+=m.side1Score??0,d[1]+=m.side2Score??0),d),[0,0]);p[0]!==p[1]&&(t.matchUpStatus="COMPLETED",t.winningSide=p[0]>p[1]?1:2,t.endTime=new Date().toISOString());return}if(!(n[0]>=r||n[1]>=r)||i&&t.score.sets.filter(u=>u.winningSide!==void 0).length<i)return;let a=n[0]>=r?0:1;t.matchUpStatus="COMPLETED",t.winningSide=a+1,t.endTime=new Date().toISOString()}function Sv(t,e,r,n=!1){let o=Math.abs(t-e),i=n?1:2;if((t>=r||e>=r)&&o>=i)return t>e?0:1}function jQ(t,e,r,n,o){let i=r.gameFormat?.NoAD||r.NoAD||!1;if(n){let u=r.tiebreakFormat?.tiebreakTo||7,p=r.tiebreakFormat?.NoAD||!1;return Sv(t,e,u,p)}let s=4,a=Math.abs(t-e);if(i)return t>=s||e>=s?t>e?0:1:void 0;let c=o?.gameFormat?.deuceAfter;if(c&&t>=2+c&&e>=2+c)return t!==e?t>e?0:1:void 0;if((t>=s||e>=s)&&a>=2)return t>e?0:1}function Tv(t,e,r,n,o){let i=r.setTo||6,s=(typeof r.tiebreakAt=="number"?r.tiebreakAt:void 0)??i,a=n&&o?.noTiebreak;if(i===1)return t>=1||e>=1?t>e?0:1:void 0;let u=(n&&o?o:r).winBy||2;if(!a&&(t===s+1||e===s+1)||(t>=i||e>=i)&&Math.abs(t-e)>=u)return t>e?0:1}function FS(t,e,r){let n=xP(t,e,r);if(t.serverFlip!==void 0)return t.serverFlip?1-n:n;let o=t.history?.points?.[0];if(o?.server!==void 0){let i=o.set??0,s=o.game??0,a=0;for(let u=0;u<i;u++){let p=t.score.sets[u];a+=(p.side1Score||0)+(p.side2Score||0)}a+=s;let c=a%2;if(o.server!==c)return 1-n}return n}function xP(t,e,r){let n=t.score.sets.length-1,o=n>=0?t.score.sets[n]:void 0;if(r==="tiebreakOnly"||r==="matchTiebreak")return YQ(t,o);if(r==="timed")return qQ(o);let i=o?.side1Score||0,s=o?.side2Score||0,a=0;for(let l=0;l<t.score.sets.length-1;l++){let f=t.score.sets[l];a+=(f.side1Score||0)+(f.side2Score||0)}let c=e.setFormat?.setTo||6,u=(typeof e.setFormat?.tiebreakAt=="number"?e.setFormat.tiebreakAt:void 0)??c;if(!e.finalSetFormat?.noTiebreak&&i===u&&s===u){let l=o?.side1GameScores??[],f=o?.side2GameScores??[],g=(l.at(-1)||0)+(f.at(-1)||0),h=(a+i+s)%2,S=Math.floor(g/2)%2;return(h+S)%2}return(a+i+s)%2}function YQ(t,e){let r=e?.side1GameScores??[],n=e?.side2GameScores??[],o=(r[0]||0)+(n[0]||0),i=0;for(let c=0;c<t.score.sets.length-1;c++){let u=t.score.sets[c];i+=(u.side1Score||0)+(u.side2Score||0)}let s=i%2,a=Math.floor(o/2)%2;return(s+a)%2}function qQ(t){return((t?.side1Score||0)+(t?.side2Score||0))%2}function yv(t,e,r,n){if(r||n)return`${t}-${e}`;let o=["0","15","30","40"];if(t<4&&e<4)return`${o[t]}-${o[e]}`;if(t>=3&&e>=3&&t===e)return"40-40";if(t>=3&&e>=3){let i=t-e;if(i===1)return"A-40";if(i===-1)return"40-A";if(i>=2)return"G-40";if(i<=-2)return"40-G"}return t>=3?`40-${e<4?o[e]:"40"}`:e>=3?`${t<4?o[t]:"40"}-40`:`${t<4?o[t]:"0"}-${e<4?o[e]:"0"}`}function ms(t,e){let r=t.score.sets,n=zQ(t,e?.useBracketNotation),o=r.length>0?r.at(-1):null,i=o&&o.winningSide===void 0?[o.side1Score||0,o.side2Score||0]:[0,0],s=[0,0];if(o?.side1GameScores&&o.side2GameScores){let u=Math.max(o.side1GameScores.length,o.side2GameScores.length)-1;u>=0&&(s=[o.side1GameScores[u]||0,o.side2GameScores[u]||0])}let a=$Q(t,s),c=KQ(t);return{sets:r,scoreString:n,games:i,points:s,pointDisplay:a,situation:c}}function $Q(t,e){if(t.matchUpStatus==="COMPLETED"||t.matchUpStatus==="TO_BE_PLAYED")return;let r=ne(t.matchUpFormat);if(!r)return;let n=t.score.sets.at(-1);if(!n||n.winningSide!==void 0)return;let o=[0,0];t.score.sets.forEach(d=>{d.winningSide===1&&o[0]++,d.winningSide===2&&o[1]++});let i=Hu(r,o),s=i==="tiebreakOnly"||i==="matchTiebreak",a=r.gameFormat?.type==="CONSECUTIVE",c=s;if(!c&&i==="standard"){let d=r.exactly||r.bestOf||3,m=Math.ceil(d/2),l=o[0]===m-1&&o[1]===m-1,f=l&&r.finalSetFormat?r.finalSetFormat:r.setFormat;if(f){let g=n.side1Score||0,I=n.side2Score||0,h=f.setTo||6,S=(typeof f.tiebreakAt=="number"?f.tiebreakAt:void 0)??h,T=f.noTiebreak||!1,y=l&&r.finalSetFormat?.noTiebreak;c=!T&&!y&&g===S&&I===S}}let p=yv(e[0],e[1],c,a&&!c).split("-");return p.length===2?[p[0],p[1]]:[String(e[0]),String(e[1])]}function KQ(t){if(t.matchUpStatus==="COMPLETED"||t.matchUpStatus==="TO_BE_PLAYED")return;let e=ne(t.matchUpFormat);if(!e)return;let r=e.exactly||e.bestOf||3,n=Math.ceil(r/2),o=[0,0];t.score.sets.forEach(A=>{A.winningSide===1&&o[0]++,A.winningSide===2&&o[1]++});let i=Hu(e,o),s=o[0]===n-1&&o[1]===n-1,a=s&&e.finalSetFormat?e.finalSetFormat:e.setFormat,c=a?.tiebreakSet?.modifier==="RALLY"||a?.modifier==="RALLY",u;c||(u=FS(t,e,i));let p=Vm(t,e,i,a,u);if(!p)return{isBreakPoint:!1,isGamePoint:!1,isSetPoint:!1,isMatchPoint:!1,isGoldenPoint:!1,isTiebreak:!1,server:u};let{pointsToGame:d,pointsToSet:m,pointsToMatch:l,isBreakpoint:f}=p,g=i==="tiebreakOnly"||i==="matchTiebreak";if(!g&&i==="standard"&&a){let A=t.score.sets.at(-1);if(A){let N=A.side1Score||0,D=A.side2Score||0,R=a.setTo||6,U=(typeof a.tiebreakAt=="number"?a.tiebreakAt:void 0)??R,b=a.noTiebreak||!1,C=s&&e.finalSetFormat?.noTiebreak;g=!b&&!C&&N===U&&D===U}}let I=!!(a?.NoAD||a?.gameFormat?.NoAD||g&&(a?.tiebreakFormat?.NoAD||a?.tiebreakSet?.NoAD||e.finalSetFormat?.tiebreakSet?.NoAD)),h=e.gameFormat?.deuceAfter,S=d[0]===1&&d[1]===1&&(I||!!h&&!g),T=u===void 0?!1:d[u]===1,y=Math.min(m[0],m[1])===1,E=Math.min(l[0],l[1])===1;return{isBreakPoint:f,isGamePoint:T,isSetPoint:y,isMatchPoint:E,isGoldenPoint:S,isTiebreak:g,server:u}}function zQ(t,e=!1){let r=t.score.sets;return r.length===0?"0-0":r.map(o=>{let i=o.side1Score||0,s=o.side2Score||0;if(o.side1TiebreakScore!==void 0||o.side2TiebreakScore!==void 0){let a=o.side1TiebreakScore||0,c=o.side2TiebreakScore||0;return e&&(i===0&&s===1||i===1&&s===0)?`[${a}-${c}]`:i>s?`${i}-${s}(${c})`:`${i}(${a})-${s}`}return`${i}-${s}`}).join(", ")}var kS=class{constructor(e={}){this.pointMultipliers=[];this.redoStack=[];e.competitionFormat?(this.competitionFormat=e.competitionFormat,this.matchUpFormat=e.matchUpFormat||e.competitionFormat.matchUpFormat||"SET3-S:6/TB7",this.pointMultipliers=e.pointMultipliers||(e.competitionFormat.pointMultipliers??[])):(this.matchUpFormat=e.matchUpFormat||"SET3-S:6/TB7",this.pointMultipliers=e.pointMultipliers??[]),this.matchUpId=e.matchUpId,this.isDoubles=e.isDoubles||!1,this.eventHandlers=e.eventHandlers,this.state=ds({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles}),this.cacheFormatStructure()}setState(e){this.state=e,this.matchUpFormat=e.matchUpFormat,this.matchUpId=e.matchUpId,this.isDoubles=e.matchUpType==="DOUBLES",this.redoStack=[],this.initialScore=void 0,this.cacheFormatStructure()}getState(){return JSON.parse(JSON.stringify(this.state))}addPoint(e){let r=this.state.history?.points.length||0,n=this.state.score.sets.reduce((a,c)=>a+(c.side1Score||0)+(c.side2Score||0),0),o=this.state.score.sets.filter(a=>a.winningSide!==void 0).length,i=this.state.matchUpStatus==="COMPLETED",s=this.hasLineUp()?this.getActivePlayers():void 0;if(this.state=xs(this.state,e,{pointMultipliers:this.pointMultipliers}),s){let a=this.state.history.points[this.state.history.points.length-1];this.isDoubles?a.activePlayers=[s.side1,s.side2]:a.activePlayers=[s.side1[0]||"",s.side2[0]||""]}if(e.penaltyType){let a=this.state.history.points[this.state.history.points.length-1];a.penaltyType=e.penaltyType}if(this.ensureHistory(),this.state.history.entries.push({type:"point",data:{winner:e.winner,winningSide:e.winningSide,server:e.server,serverSideNumber:e.serverSideNumber,serverParticipantId:e.serverParticipantId,timestamp:e.timestamp,rallyLength:e.rallyLength,result:e.result,penaltyType:e.penaltyType},timestamp:e.timestamp||new Date().toISOString(),pointIndex:r}),this.redoStack=[],this.eventHandlers){let a=this.buildEventContext();if(this.eventHandlers.onPoint?.(a),this.state.score.sets.reduce((p,d)=>p+(d.side1Score||0)+(d.side2Score||0),0)>n&&this.eventHandlers.onGameComplete?.({...a,gameWinner:e.winner}),this.state.score.sets.filter(p=>p.winningSide!==void 0).length>o){let d=this.state.score.sets.findLast(m=>m.winningSide!==void 0)?.winningSide===1?0:1;this.eventHandlers.onSetComplete?.({...a,setWinner:d})}if(!i&&this.state.matchUpStatus==="COMPLETED"){let p=this.state.winningSide===1?0:1;this.eventHandlers.onMatchComplete?.({...a,matchWinner:p})}}}addSet(e){this.applyAddSet(e),this.ensureHistory();let r=this.state.score.sets.at(-1)?.winningSide;this.state.history.entries.push({type:"set",data:{...e,winningSide:r},timestamp:e.timestamp||new Date().toISOString()}),this.redoStack=[]}addGame(e){this.applyAddGame(e),this.ensureHistory(),this.state.history.entries.push({type:"game",data:e,timestamp:e.timestamp||new Date().toISOString()}),this.redoStack=[]}endSegment(e){this.applyEndSegment(e),this.ensureHistory();let r=(e?.setNumber??this.state.score.sets.length)-1;this.state.history.entries.push({type:"endSegment",data:{setNumber:r+1,...e},timestamp:e?.timestamp||new Date().toISOString()})}setInitialScore(e){this.initialScore=e,this.redoStack=[],this.applyInitialScore(this.state,e),this.ensureHistory(),this.state.history.entries.push({type:"setInitialScore",data:e,timestamp:new Date().toISOString()}),this.state.matchUpStatus==="TO_BE_PLAYED"&&(this.state.matchUpStatus="IN_PROGRESS")}undo(e=1){let r=this.state.history?.entries;if(r&&r.length>0){let i=Math.min(e,r.length);for(let s=0;s<i;s++){let a=r.pop();this.redoStack.push(a),a.type==="point"&&this.state.history.points.pop()}return this.rebuildFromEntries(),this.eventHandlers?.onUndo?.(this.buildEventContext()),!0}let n=this.state.history?.points??[];if(n.length===0)return!1;let o=Math.min(e,n.length);for(let i=0;i<o;i++){let s=n.pop();this.redoStack.push({type:"point",data:{winner:s.winner,server:s.server,timestamp:s.timestamp,rallyLength:s.rallyLength},timestamp:s.timestamp||""})}return this.rebuildState(),this.eventHandlers?.onUndo?.(this.buildEventContext()),!0}redo(e=1){if(this.redoStack.length===0)return!1;let r=Math.min(e,this.redoStack.length);for(let n=0;n<r;n++){let o=this.redoStack.pop();this.ensureHistory(),this.state.history.entries.push(o),o.type}return this.rebuildFromEntries(),this.eventHandlers?.onRedo?.(this.buildEventContext()),!0}canUndo(){let e=this.state.history?.entries;return e&&e.length>0?!0:(this.state.history?.points.length||0)>0}canRedo(){return this.redoStack.length>0}getUndoDepth(){let e=this.state.history?.entries;return e&&e.length>0?e.length:this.state.history?.points.length||0}getRedoDepth(){return this.redoStack.length}getScore(){return ms(this.state)}getScoreboard(e){return MS(this.state,e)}getWinner(){return _S(this.state)}isComplete(){return OS(this.state)}getPointCount(){return this.state.history?.points.length||0}getFormat(){return this.state.matchUpFormat}getStatistics(e){let r=this.state.history?.points??[];return pg(this.state,r,e)}getStatObjects(e){return dg(this.getStatistics(e))}getNextServer(){if(this.competitionFormat?.serverRule==="WINNER_SERVES"){let o=this.state.history?.points.at(-1);return o?o.winner:0}if(!this.cachedFormatStructure)return 0;let r=[0,0];this.state.score.sets.forEach(o=>{o.winningSide===1&&r[0]++,o.winningSide===2&&r[1]++});let n=Hu(this.cachedFormatStructure,r);return FS(this.state,this.cachedFormatStructure,n)}setServer(e,r){if(!this.cachedFormatStructure)return;let n=[0,0];this.state.score.sets.forEach(s=>{s.winningSide===1&&n[0]++,s.winningSide===2&&n[1]++});let o=Hu(this.cachedFormatStructure,n),i=xP(this.state,this.cachedFormatStructure,o);this.state.serverFlip=e!==i,r?.recordEntry!==!1&&(this.ensureHistory(),this.state.history.entries.push({type:"setServer",data:{side:e},timestamp:new Date().toISOString()}),this.redoStack=[])}getEpisodes(){return vS(this.state)}isNoAd(){return!!(this.cachedFormatStructure?.setFormat?.NoAD||this.cachedFormatStructure?.setFormat?.gameFormat?.NoAD)}getSetsToWin(){if(!this.cachedFormatStructure)return 2;let e=this.cachedFormatStructure.exactly||this.cachedFormatStructure.bestOf||3;return Math.ceil(e/2)}getTiebreakAt(){let e=this.cachedFormatStructure?.setFormat;if(!e||e.tiebreakSet||e.timed||e.noTiebreak)return null;let r=e.setTo||6;return(typeof e.tiebreakAt=="number"?e.tiebreakAt:void 0)??r}hasFinalSetTiebreak(){let e=this.cachedFormatStructure?.finalSetFormat;return e?e.tiebreakSet?!0:e.noTiebreak?!1:!!(e.tiebreakFormat||e.tiebreakAt!==void 0):this.getTiebreakAt()!==null}getFormatStructure(){return this.cachedFormatStructure}getInputMode(){let e=this.state.history?.entries??[];if(e.length===0)return(this.state.history?.points.length||0)>0?"points":"none";let r=new Set(e.filter(n=>n.type!=="setInitialScore"&&n.type!=="endSegment").map(n=>n.type));if(r.size===0)return"none";if(r.size===1){let n=r.values().next().value;if(n==="point")return"points";if(n==="game")return"games";if(n==="set")return"sets"}return"mixed"}setLineUp(e,r){let n=this.state.sides.find(o=>o.sideNumber===e);n&&(n.lineUp=r),this.initialLineUps??={},this.initialLineUps[e]=r.map(o=>({...o}))}substitute(e){let r=this.state.sides.find(i=>i.sideNumber===e.sideNumber);if(!r?.lineUp)return;let n=r.lineUp.findIndex(i=>i.participantId===e.outParticipantId);if(n===-1)return;this.ensureHistory(),this.state.history.substitutions??=[];let o={sideNumber:e.sideNumber,outParticipantId:e.outParticipantId,inParticipantId:e.inParticipantId,beforePointIndex:this.state.history.points.length,timestamp:e.timestamp};this.state.history.substitutions.push(o),r.lineUp[n]={...r.lineUp[n],participantId:e.inParticipantId},this.state.history.entries.push({type:"substitution",data:o,timestamp:e.timestamp||new Date().toISOString()}),this.redoStack=[]}getActivePlayers(){let e=this.state.sides.find(n=>n.sideNumber===1),r=this.state.sides.find(n=>n.sideNumber===2);return{side1:e?.lineUp?.map(n=>n.participantId)??[],side2:r?.lineUp?.map(n=>n.participantId)??[]}}hasLineUp(){return this.state.sides.some(e=>e.lineUp&&e.lineUp.length>0)}setPointMultipliers(e){this.pointMultipliers=e}getPointMultipliers(){return this.pointMultipliers}getSupplementaryState(){return{redoStack:[...this.redoStack],initialLineUps:this.initialLineUps?Object.fromEntries(Object.entries(this.initialLineUps).map(([e,r])=>[e,r.map(n=>({...n}))])):void 0}}loadSupplementaryState(e){e.redoStack&&(this.redoStack=[...e.redoStack]),e.initialLineUps&&(this.initialLineUps=Object.fromEntries(Object.entries(e.initialLineUps).map(([r,n])=>[r,n.map(o=>({...o}))])))}getPenaltyProfile(){return this.competitionFormat?.penaltyProfile}getPointProfile(){return this.competitionFormat?.pointProfile}getTimerProfile(){return this.competitionFormat?.timerProfile}getTimeoutRules(){return this.competitionFormat?.timeoutRules}getPenaltyBoxProfile(){return this.competitionFormat?.penaltyBoxProfile}getSubstitutionRules(){return this.competitionFormat?.substitutionRules}getPlayerRules(){return this.competitionFormat?.playerRules}setEventHandlers(e){this.eventHandlers=e}getEventHandlers(){return this.eventHandlers}decoratePoint(e,r){let n=this.state.history?.points[e];n&&Object.assign(n,r)}markHardBoundary(e){let r=this.state.score.sets[e.setIndex];r&&(r.hardBoundaries??=[],r.hardBoundaries.includes(e.gameIndex)||(r.hardBoundaries.push(e.gameIndex),r.hardBoundaries.sort((n,o)=>n-o)))}editPoint(e,r,n){let o=this.state.history?.points;if(!o||e<0||e>=o.length)return;let i=n?.recalculate!==!1,s=o[e];if(r.winner!==void 0&&(s.winner=r.winner),r.server!==void 0&&(s.server=r.server),r.timestamp!==void 0&&(s.timestamp=r.timestamp),r.rallyLength!==void 0&&(s.rallyLength=r.rallyLength),r.wrongSide!==void 0&&(s.wrongSide=r.wrongSide),r.wrongServer!==void 0&&(s.wrongServer=r.wrongServer),r.penaltyPoint!==void 0&&(s.penaltyPoint=r.penaltyPoint),!i)return;let a=this.state.history?.entries;if(a){let c=a.find(u=>u.type==="point"&&u.pointIndex===e);c&&(r.winner!==void 0&&(c.data.winner=r.winner),r.server!==void 0&&(c.data.server=r.server))}a&&a.length>0?this.rebuildFromEntries():this.rebuildState(),this.redoStack=[]}removePoint(e,r){let n=this.state.history?.points;if(!n||e<0||e>=n.length)return;let o=r?.recalculate!==!1;n.splice(e,1);let i=this.state.history?.entries;if(i){let s=i.findIndex(a=>a.type==="point"&&a.pointIndex===e);s!==-1&&i.splice(s,1);for(let a of i)a.type==="point"&&a.pointIndex>e&&(a.pointIndex-=1)}o&&(i&&i.length>0?this.rebuildFromEntries():this.rebuildState(),this.redoStack=[])}reset(){this.state=ds({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles}),this.redoStack=[],this.initialScore=void 0,this.initialLineUps=void 0,this.eventHandlers?.onReset?.(this.buildEventContext())}ensureHistory(){this.state.history??={points:[]},this.state.history.entries??=[]}buildEventContext(){return{state:this.state,score:ms(this.state)}}cacheFormatStructure(){this.cachedFormatStructure=ne(this.matchUpFormat)}getInitialLineUps(){return this.initialLineUps}applyAddSet(e){let{side1Score:r,side2Score:n,side1TiebreakScore:o,side2TiebreakScore:i}=e,s=e.winningSide;s===void 0&&(r>n?s=1:n>r&&(s=2));let a={setNumber:this.state.score.sets.length+1,side1Score:r,side2Score:n,winningSide:s};o!==void 0&&(a.side1TiebreakScore=o),i!==void 0&&(a.side2TiebreakScore=i),this.state.score.sets.push(a),this.state.matchUpStatus==="TO_BE_PLAYED"&&(this.state.matchUpStatus="IN_PROGRESS"),s!==void 0&&this.checkMatchCompletion()}applyAddGame(e){let{winner:r,tiebreakScore:n}=e,o=this.state.score.sets.length>0?this.state.score.sets.at(-1):void 0;(!o||o.winningSide!==void 0)&&(o={setNumber:this.state.score.sets.length+1,side1Score:0,side2Score:0},this.state.score.sets.push(o)),r===0?o.side1Score=(o.side1Score||0)+1:o.side2Score=(o.side2Score||0)+1,(o.side1GameScores?.length||o.side2GameScores?.length)&&(o.side1GameScores=o.side1GameScores??[],o.side2GameScores=o.side2GameScores??[],o.side1GameScores.push(0),o.side2GameScores.push(0)),n&&(o.side1TiebreakScore=n[0],o.side2TiebreakScore=n[1]),this.state.matchUpStatus==="TO_BE_PLAYED"&&(this.state.matchUpStatus="IN_PROGRESS"),this.checkSetCompletion(o),o.winningSide!==void 0&&this.checkMatchCompletion()}applySubstitution(e){let r=this.state.sides.find(o=>o.sideNumber===e.sideNumber);if(!r?.lineUp)return;let n=r.lineUp.findIndex(o=>o.participantId===e.outParticipantId);n!==-1&&(r.lineUp[n]={...r.lineUp[n],participantId:e.inParticipantId},this.state.history??={points:[]},this.state.history.substitutions??=[],this.state.history.substitutions.push(e))}applyEndSegment(e){let r=(e?.setNumber??this.state.score.sets.length)-1,n=this.state.score.sets[r];if(!n||n.winningSide!==void 0)return;let o=n.side1Score||0,i=n.side2Score||0;o>i?n.winningSide=1:i>o&&(n.winningSide=2),n.segmentComplete=!0,this.checkMatchCompletion()}checkSetCompletion(e){let r=ne(this.state.matchUpFormat);if(!r)return;let n=r.exactly||r.bestOf||3,o=Math.ceil(n/2),i=[0,0];this.state.score.sets.forEach(p=>{p.winningSide===1&&i[0]++,p.winningSide===2&&i[1]++});let s=i[0]===o-1&&i[1]===o-1,a=s&&r.finalSetFormat?r.finalSetFormat:r.setFormat;if(!a)return;let c=e.side1Score||0,u=e.side2Score||0;if(a.tiebreakSet){let p=a.tiebreakSet.tiebreakTo||11,m=a.tiebreakSet.NoAD||!1?1:2;(c>=p||u>=p)&&Math.abs(c-u)>=m&&(e.winningSide=c>u?1:2)}else if(!a.timed){let p=Tv(c,u,a,s,r.finalSetFormat);typeof p=="number"&&(e.winningSide=p+1)}}checkMatchCompletion(){let e=ne(this.state.matchUpFormat);if(!e)return;let r=e.exactly||e.bestOf||3,n=Math.ceil(r/2);LS(this.state,e,n)}rebuildFromEntries(){let e=this.state.history?.entries??[],r=this.prepareRebuildState(e);this.state=r;for(let n of e)switch(n.type){case"point":this.state=xs(this.state,n.data,{pointMultipliers:this.pointMultipliers}),this.state.history.entries=r.history.entries;break;case"set":this.applyAddSet(n.data);break;case"game":this.applyAddGame(n.data);break;case"endSegment":this.applyEndSegment(n.data);break;case"substitution":this.applySubstitution(n.data);break;case"setInitialScore":break;case"setServer":this.replaySetServerEntry(n.data);break}}prepareRebuildState(e){let r=this.getInitialLineUps(),n=ds({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles});if(r)for(let o of n.sides)r[o.sideNumber]&&(o.lineUp=r[o.sideNumber].map(i=>({...i})));return this.initialScore&&(this.applyInitialScore(n,this.initialScore),n.matchUpStatus==="TO_BE_PLAYED"&&(n.matchUpStatus="IN_PROGRESS")),n.history={points:[],entries:[...e]},n}replaySetServerEntry(e){let r=[0,0];this.state.score.sets.forEach(i=>{i.winningSide===1&&r[0]++,i.winningSide===2&&r[1]++});let n=Hu(this.cachedFormatStructure,r),o=xP(this.state,this.cachedFormatStructure,n);this.state.serverFlip=e.side!==o}rebuildState(){let e=this.state.history?.points??[],r=ds({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles});this.initialScore&&(this.applyInitialScore(r,this.initialScore),r.matchUpStatus==="TO_BE_PLAYED"&&(r.matchUpStatus="IN_PROGRESS"));for(let n of e)r=xs(r,{winner:n.winner,server:n.server,timestamp:n.timestamp,rallyLength:n.rallyLength,result:n.result},{pointMultipliers:this.pointMultipliers});this.state=r}applyInitialScore(e,r){e.score.sets=[];for(let n=0;n<r.sets.length;n++){let o=r.sets[n],i={setNumber:n+1,side1Score:o.side1Score,side2Score:o.side2Score};if(o.side1TiebreakScore!==void 0&&(i.side1TiebreakScore=o.side1TiebreakScore),o.side2TiebreakScore!==void 0&&(i.side2TiebreakScore=o.side2TiebreakScore),o.winningSide===void 0){let s=this.cachedFormatStructure,c=(s?.finalSetFormat&&n===(s.bestOf??s.exactly??3)-1?s.finalSetFormat:s?.setFormat)?.setTo;c&&(o.side1Score>=c||o.side2Score>=c)&&(o.side1Score>o.side2Score?i.winningSide=1:o.side2Score>o.side1Score&&(i.winningSide=2))}else i.winningSide=o.winningSide;e.score.sets.push(i)}if(r.currentSetScore){let n={setNumber:e.score.sets.length+1,side1Score:r.currentSetScore.side1Score,side2Score:r.currentSetScore.side2Score,side1GameScores:[],side2GameScores:[]};r.currentGameScore?(n.side1GameScores=[r.currentGameScore.side1Points],n.side2GameScores=[r.currentGameScore.side2Points]):(n.side1GameScores=[0],n.side2GameScores=[0]),e.score.sets.push(n)}}};var Av={};_t(Av,{addPoint:()=>xs,calculatePointsTo:()=>Vm,createMatchUp:()=>ds,inferServeSide:()=>xS,resolvePointValue:()=>wS});var kv={};_t(kv,{keyValueScore:()=>Fv,parseMatchUpFormat:()=>ne,stringifyMatchUpFormat:()=>sm});var SG="COMPLETED";var QQ="WO/WO";var wP=["RET","DEF","WO",QQ,"ABN","SUS","INT"];var LP="DEFAULTED";var Pv="WALKOVER";var FP="ABANDONED",kP="SUSPENDED",Nv="RETIRED",GP="INTERRUPTED";var TG=[Nv,LP,Pv],JQ="Enter Score",Ia="()",ha="[]",Dv=["up","left","shift+tab"],Uv=["enter","down","tab","right"],mg="backspace",Rv="r",bv="s",Cv="a",Mv="d",vv="w",Ov="i",lg=[Rv,Mv,vv,Cv,bv,Ov],Bm="space",VP=["[","("],fg=[...Dv,...Uv,Bm,"]"],yG="-",XQ="/",nc=yG,Fi=yG,_v=[XQ],EG=0,ZQ=["=","+","num_1","num_2","shift+=","shift+-"],rc=["0","1","2","3","4","5","6","7","8","9"].concat(lg),AG=rc.map(t=>`shift+${t}`),xv=[nc,mg].concat(fg,_v),wv=[rc,AG,xv].join(","),t7=[wv,Dv,Uv,ZQ].join(","),Eee=[].concat(...rc,...rc,...xv,...rc,...rc,...rc,...rc,...rc,...rc),PG={OUTCOMEKEYS:lg,SIDE1KEYS:rc,SIDE2KEYS:AG,MODIFIERS:xv,PROMPT:JQ,MOVEUP:Dv,MOVEDOWN:Uv,HOTKEYS:t7};function Hm({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=NG({scoreString:t}),e===2){let o=t?.[t.length-1]===" "?"":" ";return t+o+r}else return r+" "+t}function NG({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of wP){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+" ":n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function e7({newScore:t,scoreString:e,lastMatchTiebreakOpenBracketIndex:r,lastSet:n,lowSide:o,NoAD:i,tiebreakTo:s}){let c=t.slice(r+1).split(Fi),u=c?.length>0&&c[0]!==void 0&&!Number.isNaN(Number.parseInt(c[0]))&&Number.parseInt(c[0])||void 0,p=c?.length>1&&c[1]!==void 0&&!Number.isNaN(Number.parseInt(c[1]))&&Number.parseInt(c[1])||void 0,d=[u,p],m=!1;if(p){let l=o===1?1:0;d[l]=(d?.[1-l]||0)+(i?1:2),(d[l]||0)<s&&(d[l]=s),t=e.slice(0,r+1),t+=d.join(Fi)}else u===void 0?(t=e.slice(0,r),m=!0):(t=e.slice(0,r+1),t+=u);return n.side1TiebreakScore=d[0]||0,n.side2TiebreakScore=d[1]||0,{newScore:t,isIncompleteScore:m}}function r7({lastSet:t,sets:e,analysis:r}){let n=t.side1Score?.toString();if(n){let i=n?.slice(0,-1);t.side1Score=Number.parseInt(i)&&!Number.isNaN(Number.parseInt(i))||void 0,t.side1Score===void 0&&(t.side2Score=void 0)}let o;return r.isTimedSet?(o=t.side1Score?e:e?.slice(0,-1)??[],o[e.length-1]=t):o=e?.slice(0,-1)??[],o}function n7({lastSet:t,sets:e,analysis:r}){let n=t.side2Score?.toString(),o=t.side1Score?.toString();if(!r.isTiebreakEntry&&!r.isMatchTiebreak)if(t.side2Score){let s=n?.slice(0,-1);t.side2Score=!isNaN(s)&&parseInt(s)||void 0}else{let s=o?.slice(0,-1);t.side1Score=!isNaN(s)&&parseInt(s)||void 0}let i;return r.isTimedSet?t.side1Score?(i=e??[],i[e.length-1]=t):i=e?.slice(0,e.length-1)??[]:(i=e??[],i[e.length-1]=t),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0}),i}function GS({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=NG({scoreString:e});if(e=s,a)return{scoreString:e,sets:r,outcomeRemoved:!0};let c=r.at(-1)??{},u=Object.values(c).filter(g=>g!==void 0).length;c.setNumber&&u===1&&(r=r.slice(0,-1),c=r.at(-1)??{});let{tiebreakSet:p}=t.setFormat,{tiebreakTo:d,NoAD:m}=p??{},{isTiebreakEntry:l}=hd({brackets:ha,scoreString:e}),f=o7(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=hd({brackets:Ia,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=hd({brackets:ha,scoreString:o}),S=o?.length?o[o.length-1].trim():void 0,T=o&&!isNaN(S),y=t.isIncompleteSetScore;return l&&h&&({newScore:o,isIncompleteScore:y}=e7({newScore:o,scoreString:e,lastMatchTiebreakOpenBracketIndex:I,lastSet:c,lowSide:n,NoAD:m,tiebreakTo:d})),o.length||(o=void 0),y?i=r7({lastSet:c,sets:r,analysis:t}):T?i=n7({lastSet:c,sets:r,analysis:t}):g?(i=r??[],Object.assign(i[i.length-1]??{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(l&&!h?i=r?.slice(0,-1)??[]:(i=r,i[r.length-1]=c),l||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0)),{scoreString:o,sets:i}}return{scoreString:e,sets:r}}function hd({brackets:t=Ia,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...Is(r,o)),s=Math.max(...Is(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function DG({scoreString:t}){if(!t)return!1;let e=t?.[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=ha.split(""),i=t.split(""),s=Math.max(...Is(n,i)),a=Math.max(...Is(o,i)),c=Math.max(...Is(Fi,i));return r&&s>a&&c>s}function o7(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function BP(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t??{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function Lv({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=ne(t),{bestOf:i}=o,s=Math.ceil(i/2),c=n?.reduce((u,p)=>{let{winningSide:d}=p;return d&&u[d-1]++,u},[0,0])?.indexOf(s)+1||void 0;return TG.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Wm({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,isTimedSet:i,set:s}){if(!s)return{error:nt,info:"missing set"};e=e||r&&ne(r);let a=o&&e.finalSetFormat||(e?.setFormat??{}),{side1Score:c,side2Score:u}=s,{setTo:p,tiebreakAt:d}=a,m=c||u,l=jm({set:s}),f=Math.abs(c-u),g=c>=p||u>=p,I=n||c>=p&&u>=p||d&&d<p&&(c===d||u===d),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&&m||g&&(T||I)||n)&&(!I||h))}function jm({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 gg({analysis:t,set:e}){let r=jm({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Wm({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function UG({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=st(n);let{validSide2Score:s,requiresTiebreak:a}=i7({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=gg({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=Ia.split("")[0];e+=u}else t.isDecidingSet||(e+=" ")}return{sets:r,scoreString:e,updated:o}}function i7({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 HP({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===Rv?n?(s=!0,n=Hm({scoreString:n,lowSide:t,outcome:"RET"}),o=t===2?1:2,i=Nv):(s=!0,n=Hm({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=LP):e===Mv?(s=!0,n=Hm({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=LP):e===vv?(s=!0,r=[],n="WO",o=t===2?1:2,i=Pv):e===bv&&n?(s=!0,n=Hm({scoreString:n,lowSide:t,outcome:"SUS"}),i=kP,o=void 0):e===Cv?(s=!0,n=Hm({scoreString:n,lowSide:t,outcome:"ABN"}),i=FP,o=void 0):e===Ov&&n&&(s=!0,n=Hm({scoreString:n,lowSide:t,outcome:"INT"}),i=GP,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function CG(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!==mg&&(e=[{setNumber:1}]);let d=e.length-1;if(lg.includes(c))({sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=p7({sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i,analysis:s,lowSide:a,value:c}));else if(c===mg)({scoreString:n,sets:e,outcomeRemoved:p}=GS({analysis:s,scoreString:n,sets:e})),{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=d7({sets:e,scoreString:n,outcomeRemoved:p});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"};c===Bm?{sets:e,scoreString:n,updated:u}=m7({sets:e,scoreString:n,winningSide:o,analysis:s}):c===nc&&e[d].side1Score!==void 0&&e[d].side2Score===void 0&&n&&s.isNumericEnding?(n+="-",e[d].side2Score=0,i=void 0,o=void 0,u=!0):Number.isNaN(Number(c))||({sets:e,scoreString:n,updated:u}=l7({sets:e,setIndex:d,value:c,scoreString:n}))}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function p7({sets:t,info:e,scoreString:r,winningSide:n,matchUpStatus:o,analysis:i,lowSide:s,value:a}){let c,u=t.at(-1)??{},{side1Score:p,side2Score:d}=u;return p&&!d?e="missing side2Score":i.finalSetIsComplete||n?e="final set is already complete":i.isIncompleteSetScore?e="incomplete set scoreString":{sets:t,scoreString:r,winningSide:n,matchUpStatus:o,updated:c}=HP({lowSide:s,value:a,sets:t,scoreString:r,matchUpStatus:o,winningSide:n}),{sets:t,info:e,scoreString:r,winningSide:n,matchUpStatus:o,updated:c}}function d7({sets:t,scoreString:e,outcomeRemoved:r}){let n=e,o=t;if(n?.trim()===""&&(n=n.trim()),n||(o=[]),r){let i=o.at(-1)??{},{side1Score:s,side2Score:a}=i;if(s&&a){let c=s>a&&1||a>s&&2||void 0;c&&(i.winningSide=c,o.push({setNumber:o.length+1}))}}return{sets:o,scoreString:n,winningSide:void 0,matchUpStatus:void 0,updated:!0}}function m7({sets:t,scoreString:e,winningSide:r,analysis:n}){let o,i=e,s=t.at(-1)??{},{side1Score:a,side2Score:c}=s,u=a>c&&1||c>a&&2||void 0;return u&&!r&&!n.isIncompleteSetScore&&(t.at(-1).winningSide=u,t.push({setNumber:t.length+1}),i+=" ",o=!0),{sets:t,scoreString:i,updated:o}}function l7({sets:t,setIndex:e,value:r,scoreString:n}){let o,i,s=n;if(t[e].side2Score===void 0){let a=st((t[e].side1Score||0).toString()+r).toString().slice(0,2);t[e].side1Score=st(a),o=t[e].side1Score.toString(),i=!0}else{let a=st((t[e].side2Score||0).toString()+r).toString().slice(0,2);t[e].side2Score=st(a),o=[t[e].side1Score,t[e].side2Score].join("-"),i=!0}if(i){let a=(t.slice(0,e)??[]).filter(c=>c).map(c=>[c.side1Score,c.side2Score].join("-")).join(" ");s=a?a+" "+o:o}return{sets:t,scoreString:s,updated:i}}function MG({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=ha.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:m}=hd({brackets:ha,scoreString:n}),f=(n.slice((m??0)+1)+(e?"":i)).split(Fi);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=>st(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,(m??0)+1),n+=I.join(Fi),s=!0}else{let I=[f[0]||0,f[1]||0].map(S=>st(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let m=BP({lowValue:st(i||0),tiebreakTo:c,NoAD:u}),l=[st(i),m];r===2&&l.reverse();let f={side1TiebreakScore:l[0],side2TiebreakScore:l[1],setNumber:o?.length+1||1};o.push(f),n+=l.join(Fi),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function vG({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&&!a||n>o)return{scoreString:r};let c=g(),u=[n,c];e===2&&u.reverse();let d=Ia.split("")[0],m=u.join(nc)+(a?d:" ");r=(r||"")+m;let l={side1Score:u[0],side2Score:u[1]},f=gg({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 OG({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter($=>$?.winningSide)?.length||0)+(r?0:1),a=ne(t),c=s===a?.bestOf,u=c&&a?.finalSetFormat||(a?.setFormat??{}),p=u?.timed,d=c&&o[a?.bestOf-1],m=d?.winningSide,{isTiebreakEntry:l}=hd({brackets:Ia,scoreString:e}),{isTiebreakEntry:f}=hd({brackets:ha,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===nc,y=l&&VP.includes(h),E=f&&VP.includes(h),A=f&&h===Fi,N=e?.split(""),[D]=ha.split(""),R=N&&Math.max(...Is(D,N)),U=N&&Math.max(...Is(Fi,N)),b=N&&U>R,C=o[o.length-1]?.winningSide,_=o?.length&&!C,v=wP.find($=>e?.indexOf($)>=0),x=!isNaN(n),w=n===Bm,F=fg.includes(n),L=e?.split("").find($=>VP.includes($)),k=F&&f&&!E&&(A||!DG({scoreString:e}));return{isTiebreakSetValue:I&&x,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:b,isGameScoreEntry:_,isSpace:w,isCloser:F,isTiebreakCloser:F&&L&&g&&S,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:S,isNumericValue:x,hasOpener:L,hasOutcome:v,finalSet:d,finalSetIsComplete:m,lastSetIsComplete:C,isInvalidSetTiebreakValue:w&&g&&y,isInvalidMatchTiebreakValue:k,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:E,isPartialMatchTiebreakValue:A}}function f7({analysis:t,lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s}){let a,c;return t.finalSetIsComplete||i?a="final set is already complete":!t.isTiebreakEntry&&!t.isIncompleteSetScore?{sets:r,scoreString:n,matchUpStatus:o,winningSide:i,updated:c}=HP({lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s}):t.isTiebreakEntry||t.isIncompleteSetScore?a="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:s}),{info:a,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,updated:c}}function g7({analysis:t,scoreString:e,sets:r,lowSide:n}){return{scoreString:e,sets:r}=GS({analysis:t,scoreString:e,sets:r,lowSide:n}),e||(r=[]),{scoreString:e,sets:r,updated:!0,matchUpStatus:void 0,winningSide:void 0}}function I7({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;return(!t.isSetTiebreakEntry||t.isSetTiebreakEntry&&!t.isNumericEnding)&&(o=!0,{scoreString:e,sets:r}=GS({analysis:t,scoreString:e,sets:r,lowSide:n}),i=void 0),{scoreString:e,sets:r,updated:o,matchUpStatus:i}}function h7({analysis:t,scoreString:e}){let r,n;return t.matchTiebreakHasJoiner?r="existing joiner":t.isNumericEnding&&(n=!0,e+=Fi),{info:r,scoreString:e,updated:n}}function S7({analysis:t,scoreString:e,sets:r}){let n=t.isSetTiebreakEntry?Ia:ha,o=n.split("").reverse()[0],i=n.split("")[0],s=r[r.length-1],{tiebreakFormat:a}=t.setFormat,{tiebreakTo:c,NoAD:u}=a??{},p=jm({set:s});if(!t.isTiebreakSet){let m=Number.parseInt(e.split(i).reverse()[0]),l=BP({lowValue:m,tiebreakTo:c,NoAD:u});p===1?(s.side1TiebreakScore=l,s.side2TiebreakScore=m):(s.side1TiebreakScore=m,s.side2TiebreakScore=l)}e=(e||"")+o,t.isDecidingSet||(e+=" ");let d=gg({analysis:t,set:s});return s.winningSide=d||void 0,{scoreString:e,sets:r,updated:!0}}function T7({analysis:t,scoreString:e,value:r}){let n,o,[i]=Ia.split(""),s=Math.max(...Is(i,e.split(""))),a=e.slice(s+1),c=a&&st(a)===EG,u=st(a?a+r:r),{tiebreakFormat:p}=t.setFormat,{tiebreakTo:d,NoAD:m}=p??{};return!c&&a.length<2?m&&u>d-1?n="invalid low value for NoAD tiebreak":(o=!0,e=(e||"")+r):n=c?"tiebreak begins with zero":"tiebreak digit limit",{info:n,scoreString:e,updated:o}}function y7({analysis:t,lowSide:e,scoreString:r,sets:n,value:o}){let{scoreString:i,set:s}=vG({analysis:t,lowSide:e,scoreString:r,value:st(o)});return s&&(s.setNumber=n?.length+1||1),n=n?.concat(s).filter(Boolean)||[s],r=i||void 0,{scoreString:r,sets:n,updated:!0}}function E7({sets:t,winningSide:e,matchUpStatus:r,matchUpFormat:n,scoreString:o,info:i}){t=t?.filter(Boolean);let{matchUpWinningSide:s}=Lv({sets:t,winningSide:e,matchUpStatus:r,matchUpFormat:n});return e=s,s&&(!r||[Jt,Zr].includes(r))?(r=SG,t=t.filter(a=>{let{side1Score:c,side2Score:u,side1TiebreakScore:p,side2TiebreakScore:d}=a;return c||u||p||d})):o&&!e&&![kP,FP,GP].includes(r)&&(r=void 0),{updated:!0,scoreString:o,sets:t,winningSide:e,matchUpStatus:r,info:i}}function Fv(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;if(!wv.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let p=c&&e===2||!c&&e===1,{matchUpWinningSide:d}=Lv({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=d;let m=OG({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});({value:r,scoreString:n}=A7({analysis:m,value:r,scoreString:n,isShifted:p}));let l=P7({analysis:m,lowSide:e,sets:o,scoreString:n,matchUpStatus:s,winningSide:i,value:r,auto:u});if(l.earlyReturn)return{updated:l.updated,info:l.info};({sets:o,scoreString:n,matchUpStatus:s,winningSide:i}=l);let{updated:f,info:g}=l;return f?E7({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a,scoreString:n,info:g}):{updated:f,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:g}}function A7({analysis:t,value:e,scoreString:r,isShifted:n}){let o=e,i=r;if(_v.includes(o)&&(o=nc),t.hasOpener&&t.isTiebreakEntry&&!t.isTiebreakSet&&n&&st(o)===0&&(t.isTiebreakCloser=!0),fg.includes(o)&&t.hasOpener&&(o=""),fg.includes(o)&&(o=Bm),t.lastSetIsComplete){let s=i?.length&&i.at(-1);i&&s!==" "&&(i+=" ")}return{value:o,scoreString:i}}function P7({analysis:t,lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s,auto:a}){let c,u,p=r,d=n,m=o,l=i;if(t.isTimedSet)({info:c,sets:p,scoreString:d,updated:u,matchUpStatus:m,winningSide:l}=CG({analysis:t,lowSide:e,scoreString:n,sets:r,matchUpStatus:o,winningSide:i,value:s}));else if(lg.includes(s))({info:c,sets:p,scoreString:d,matchUpStatus:m,winningSide:l,updated:u}=f7({analysis:t,lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s}));else if(s===mg)({scoreString:d,sets:p,updated:u,matchUpStatus:m,winningSide:l}=g7({analysis:t,scoreString:n,sets:r,lowSide:e}));else if(t.hasOutcome)c="has outcome";else if(s===nc&&!t.isMatchTiebreakEntry)({scoreString:d,sets:p,updated:u,matchUpStatus:m}=I7({analysis:t,scoreString:n,sets:r,lowSide:e}));else if(s===Fi&&t.isMatchTiebreakEntry&&!t.isSetTiebreakEntry)({info:c,scoreString:d,updated:u}=h7({analysis:t,scoreString:n}));else if([nc,Fi].includes(s))c="invalid location for joiner";else{if(i)return{earlyReturn:!0,updated:!1,info:"matchUp is complete"};({info:c,updated:u,sets:p,scoreString:d}=N7({analysis:t,auto:a,lowSide:e,scoreString:n,sets:r,value:s}))}return{info:c,updated:u,sets:p,scoreString:d,matchUpStatus:m,winningSide:l}}function N7({analysis:t,auto:e,lowSide:r,scoreString:n,sets:o,value:i}){let s,a,c=o,u=n;return t.isIncompleteSetScore?t.isNumericValue&&({sets:c,scoreString:u,updated:a}=UG({analysis:t,scoreString:n,sets:o,value:i})):t.isInvalidMatchTiebreakValue?s="invalid matchUp tiebreak character":t.isInvalidSetTiebreakValue?s="invalid set tiebreak character":t.isTiebreakCloser?{scoreString:u,sets:c,updated:a}=S7({analysis:t,scoreString:n,sets:o}):t.isTiebreakSetValue?{info:s,scoreString:u,sets:c,updated:a}=MG({analysis:t,auto:e,lowSide:r,scoreString:n,sets:o,value:i}):t.isSetTiebreakEntry?{info:s,scoreString:u,updated:a}=T7({analysis:t,scoreString:n,value:i}):t.isCloser?s=`invalid key: ${i}`:t.isGameScoreEntry?s="game scoreString entry":t.lastSetIsComplete||!o.length?{scoreString:u,sets:c,updated:a}=y7({analysis:t,lowSide:r,scoreString:n,sets:o,value:i}):console.log("error: unknown outcome"),{info:s,updated:a,sets:c,scoreString:u}}var Bv={};_t(Bv,{analyzeScore:()=>VS,analyzeSet:()=>Sd,calculateMatchStatistics:()=>pg,checkScoreHasValue:()=>le,checkSetIsComplete:()=>Wm,deduceMatchUpFormat:()=>Km,enrichPointHistory:()=>gv,getEpisodes:()=>vS,getQuickStats:()=>Iv,getScore:()=>ms,getScoreboard:()=>MS,getSetComplement:()=>HS,getTiebreakComplement:()=>qm,getWinner:()=>_S,isComplete:()=>OS,isValidMatchUpFormat:()=>Or,parseScoreString:()=>$m,toStatObjects:()=>dg,validateMatchUpScore:()=>Gv,validateScore:()=>BS,validateSetScore:()=>WP,validateTieFormat:()=>ur});function D7(t,e,r,n,o,i=!1){return o?{isValid:!0}:t===0&&e===0?{isValid:!1,error:"Tiebreak-only set requires both scores"}:t<n?{isValid:!1,error:`Tiebreak-only set winner must reach at least ${n}, got ${t}`}:r<(i?1:2)?{isValid:!1,error:i?`Tiebreak-only set (NoAD) must be won by at least 1 point, got ${t}-${e}`:`Tiebreak-only set must be won by at least 2 points, got ${t}-${e}`}:i?{isValid:!0}:t===n&&e>n-2?{isValid:!1,error:`Tiebreak-only set at ${n}-${e} requires playing past ${n}`}:t>n&&r!==2?{isValid:!1,error:`Tiebreak-only set past ${n} must be won by exactly 2 points, got ${t}-${e}`}:{isValid:!0}}function U7(t,e,r,n){let o=n===r?r+1:r,i=n;return t!==o?{isValid:!1,error:`Tiebreak set winner must have ${o} games, got ${t}`}:e!==i?{isValid:!1,error:`Tiebreak set loser must have ${i} games, got ${e}`}:{isValid:!0}}function R7(t,e,r){let n=Math.max(t||0,e||0),o=Math.min(t||0,e||0),i=n-o,s=r.tiebreakTo||7;return n<s?{isValid:!1,error:`Tiebreak winner must reach ${s} points, got ${n}`}:i<2?{isValid:!1,error:`Tiebreak must be won by 2 points, got ${n}-${o}`}:o>=s-1&&i>2?{isValid:!1,error:`Tiebreak score ${n}-${o} is invalid`}:{isValid:!0}}function b7(t,e,r,n){return n?t===r+1&&e<r-1?{isValid:!1,error:`With tiebreak format, if side 1 has ${r+1} games, side 2 must be at least ${r-1}, got ${e}`}:e===r+1&&t<r-1?{isValid:!1,error:`With tiebreak format, if side 2 has ${r+1} games, side 1 must be at least ${r-1}, got ${t}`}:{isValid:!0}:{isValid:!0}}function C7(t,e,r,n,o,i=2){if(t<n)return{isValid:!1,error:`Set winner must reach ${n} games, got ${t}`};let s=o&&t===n&&e===o&&r===1;if(r<i&&!s)return{isValid:!1,error:`Set must be won by at least ${i} game${i===1?"":"s"}, got ${t}-${e}`};if(o){if(e>=o&&!s)return{isValid:!1,error:`When tied at ${o}-${o}, must play tiebreak. Use format like ${o+1}-${o}(5)`};let a=o===n?n+1:n;if(t>a)return{isValid:!1,error:`With tiebreak format, set score cannot exceed ${a}-${o}. Got ${t}-${e}`}}else if(t>n+10)return{isValid:!1,error:`Set score ${t}-${e} exceeds reasonable limits`};return{isValid:!0}}function M7(t,e,r){let n=t.side1TiebreakScore,o=t.side2TiebreakScore,i=e&&r?n:t.side1Score||t.side1||0,s=e&&r?o:t.side2Score||t.side2||0;return{side1Score:i,side2Score:s,side1TiebreakScore:n,side2TiebreakScore:o}}function v7(t,e,r,n,o,i,s){if(r&&n){let c=U7(t,e,r,n);if(!c.isValid)return c}return(o!==void 0||i!==void 0)&&s?R7(o,i,s):{isValid:!0}}function O7(t,e,r){return r&&(t>r+10||e>r+10)?{isValid:!1,error:`Set score ${t}-${e} exceeds expected range for ${r}-game sets`}:{isValid:!0}}function _7(t,e,r){let{side1:n,side2:o,winner:i,loser:s,diff:a}=t,{setTo:c,tiebreakAt:u,winBy:p}=e;if(c&&u){let d=b7(n,o,c,u);if(!d.isValid)return d}return r?O7(i,s,c):c?C7(i,s,a,c,u,p):{isValid:!0}}function WP(t,e,r,n){if(!e)return{isValid:!0};let o=ne(e);if(!o)return{isValid:!0};let i=r&&o.finalSetFormat?o.finalSetFormat:o.setFormat;if(!i)return{isValid:!0};if(i.timed){if(!n){let N=t.side1Score??0,D=t.side2Score??0;if(N===0&&D===0)return{isValid:!1,error:"Timed set requires at least one side to have scored"};if(i.based==="P"&&N===D&&N>0&&i.tiebreakFormat&&!(t.side1TiebreakScore!==void 0||t.side2TiebreakScore!==void 0))return{isValid:!1,error:"Tied timed set requires tiebreak"}}return{isValid:!0}}let{setTo:s,tiebreakAt:a,tiebreakFormat:c,tiebreakSet:u}=i,p=u?.tiebreakTo,d=!!p&&!s,m=t.side1TiebreakScore!==void 0&&t.side2TiebreakScore!==void 0,{side1Score:l,side2Score:f,side1TiebreakScore:g,side2TiebreakScore:I}=M7(t,d,m),h=Math.max(l,f),S=Math.min(l,f),T=h-S;if(d){let N=t.NoAD??i.tiebreakSet?.NoAD??!1;return D7(h,S,T,p,n??!1,N)}let y=g!==void 0||I!==void 0,E=s&&h===s+1&&S===s;return y||E?v7(h,S,s,a,g,I,c):_7({side1:l,side2:f,winner:h,loser:S,diff:T},{setTo:s,tiebreakAt:a,winBy:i.winBy},n)}function Gv(t,e,r){if(!t||t.length===0)return{isValid:!0};let n=e?.match(/SET(\d+)/)?.[1],o=n?Number.parseInt(n):3,i=[ve,vt,Mt].includes(r||"");for(let s=0;s<t.length;s++){let a=t[s],c=s+1===o,u=a.winningSide!==void 0,m=WP(a,e,c,i||r===void 0&&!u);if(!m.isValid)return{isValid:!1,error:`Set ${s+1}: ${m.error}`}}return{isValid:!0}}function Ym(t){return!!t?.aggregate}function x7(t,e,r,n,o,i){let{tiebreakTo:s,NoAD:a}=t??{},c=Math.max(e??0,r??0);return!(a&&c>s||c<s&&n&&(o&&!i||!o))}function w7(t,e,r,n,o,i){let a=e+1===n,{side1Score:c,side2Score:u,side1TiebreakScore:p,side2TiebreakScore:d,winningSide:m}=t,l=Math.max(c??0,u??0),f=p??d,{finalSetFormat:g,setFormat:I}=r,h=a&&g||I;return f&&!x7(h?.tiebreakFormat,p,d,m,o,i)?!1:h.setTo?!(!h.noTiebreak&&l>h.setTo+1):!0}function L7(t){let e=t.reduce((r,n)=>((n.side1Score!==void 0||n.side2Score!==void 0)&&(r[0]+=n.side1Score??0,r[1]+=n.side2Score??0),r),[0,0]);return e[0]>e[1]?1:e[1]>e[0]?2:t.find(n=>n.side1TiebreakScore!==void 0||n.side2TiebreakScore!==void 0)?.winningSide}function F7(t,e,r,n,o){return(!o||t===e)&&r===1&&n.indexOf(t)+1||void 0}function VS({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(U=>U?.winningSide)??[]).reduce((U,b)=>{let{winningSide:C}=b;if(!C)return U;let _=C-1;return U[_]++,U},[0,0]),c=n?n-1:void 0,u=c!==void 0&&[0,1].includes(c)?1-c:void 0,p=c!==void 0&&a[c],d=u!==void 0&&a[u],m=e?ne(e):void 0,l=Math.max(...a),f=dn(a)[l],g=m?.setFormat?.timed||m?.finalSetFormat?.timed,I=m?.bestOf||m?.exactly,h=I&&Math.ceil(I/2)||1,S=r??t,T=!!(S&&[Mt,ve,vt].includes(S)),y=!m||!i.length||i.every((U,b)=>w7(U,b,m,I??0,b===i.length-1,T)),E=m?.exactly,A=!E||!S||S!==ae||T||i.length>=E,N=Ym(m),D=N&&i.length>0?L7(i):F7(l,h,f,a,e);return{valid:!!(y&&A&&(n&&N&&n===D||n&&!N&&p>d&&n===D||n&&T||!n&&!D&&(![ae,Mt,ve,vt].includes(S)||g&&S===ae)))}}function BS({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:O};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:O,info:c};if(a!==void 0&&typeof a!="string")return{error:O,info:c};if(i!==void 0&&!Array.isArray(i))return{error:O,info:xi("sets")};if(i?.length){let u=i.map(d=>d?.setNumber).filter(Boolean);if(u.length!==ct(u).length)return{error:O,info:"setNumbers not unique"};for(let d of i){let{side1Score:m,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,side1PointScore:I,side2PointScore:h,winningSide:S,setNumber:T}=d;if(![[m,l],[f,g]].filter(D=>D.some(R=>![void 0,null].includes(R))).every(D=>D.every(R=>It(R))))return{error:O,info:"non-numeric values"};let E=[I,h];if(E.some(D=>D!=null)&&!E.every(D=>D!=null))return{error:O,info:"both sides must have point scores if one does"};if(![T,S].filter(D=>![void 0,null].includes(D)).every(D=>It(D)))return{error:O,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:O,info:"winningSide must be 1 or 2"}}let{valid:p}=VS({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:iR,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var HS=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i,winBy:s}=t;if(r===void 0)return!1;let a=st(r);a?.toString().length>2&&(a=Number.parseInt(a.toString().slice(0,2))),o&&o<n&&a>o&&(a=o);let c;return!o&&s===1?c=n:i&&!o?a>n?c=n:c=a<n?n:n-1:c=a+1<n&&n||o&&o<n&&a===o&&n||!o&&a+2||n+1,[e?a:c,e?c:a]},qm=t=>{let{isSide1:e,lowValue:r,tiebreakTo:n,tiebreakNoAd:o}=t;if(r===void 0)return!1;let i=typeof r=="string"?Number.parseInt(r):r;i?.toString().length>2&&(i=Number.parseInt(i.toString().slice(0,2))),o&&i>n-1&&(i=n-1);let s=k7({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function k7(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function Vv(t,e){return t>e&&1||t<e&&2||void 0}function G7(t,e){return e?{side1Score:t[0],side2Score:t[1],winningSide:Vv(t[0],t[1])}:{side1TiebreakScore:t[0],side2TiebreakScore:t[1],winningSide:Vv(t[0],t[1])}}function $m({tiebreakTo:t=7,scoreString:e="",matchUpFormat:r}){let n,o=3;if(r)try{n=ne(r);let p=/SET(\d+)/.exec(r)?.[1];o=p?Number.parseInt(p):3}catch{}return e?.split(" ").filter(Boolean).map((p,d)=>u({set:p,setNumber:d+1}));function i(p,d){if(!n||!d)return!1;let l=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;if(!l)return!1;let f=l.tiebreakSet?.tiebreakTo,g=l.setTo;return!!f&&!g}function s(p){if(!n)return t;let m=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;return m?.tiebreakSet?.tiebreakTo??m?.tiebreakFormat?.tiebreakTo??t}function a(p,d,m){let l=p[1],f=s(m),g=qm({lowValue:l,isSide1:d===2,tiebreakTo:f});return Array.isArray(g)?[g[0],g[1]]:[void 0,void 0]}function c(p,d,m,l){let g=(d&&p.replace(d[0],"")||m&&p.replace(m[0],"")||p).split("-").map(E=>Number.parseInt(E)),I=g[0],h=g[1],S=Vv(I,h),T,y;if(d&&([T,y]=a(d,S,l)),m){let E=m[1].split("-").map(A=>Number.parseInt(A));T=E[0],y=E[1]}return{side1Score:I,side2Score:h,side1TiebreakScore:T,side2TiebreakScore:y,winningSide:S}}function u({set:p,setNumber:d}){let m=/\(([^)]+)\)/,l=/\[([^\]]+)\]/,f=m.exec(p),g=l.exec(p),I=p?.startsWith("[")&&g,h=i(d,!!I),S=s(d),T=h&&S===1,y;if(I){let E=g[1].split("-").map(A=>Number.parseInt(A));y=G7(E,h)}else y=c(p,f,g,d);return{side1Score:y.side1Score,side2Score:y.side2Score,side1TiebreakScore:y.side1TiebreakScore,side2TiebreakScore:y.side2TiebreakScore,winningSide:y.winningSide,setNumber:d,...T&&{NoAD:!0},...h&&{tiebreakSet:!0}}}}function _G({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=jm({set:o});return Wm({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function Sd(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:CI};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,d=!u&&!p,m=!!(n&&s&&n<=s),l=V7(e),{sideGameScores:f,sidePointScores:g,sideTiebreakScores:I}=l,h=f.filter(k=>k!==void 0).length,S=g.filter(k=>k!==void 0).length,T=I.filter(k=>k!==void 0).length,y=f?.filter(k=>typeof k=="number"&&!Number.isNaN(k)).length,E=I?.filter(k=>typeof k=="number"&&!Number.isNaN(k)).length,{tiebreakAt:A}=c??{},N=A&&f.filter(k=>k>=A).length===2,D=B7(N,f),R=!!(E&&!y),U=!!e?.winningSide,{error:b,result:C}=j7({sideTiebreakScores:I,sideGameScores:f,setFormat:c,setObject:e}),{error:_,result:v}=q7({sideTiebreakScores:I,setObject:e,setFormat:c}),x=H7({isValidStandardSetOutcome:C,isValidTiebreakSetOutcome:v,expectStandardSet:d,expectTiebreakSet:u,expectTimedSet:p,isTiebreakSet:R}),w=m&&!(u&&!R)&&!(d&&R)&&(!U||x),F=_G({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:R,setObject:e}),L={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:N,isCompletedSet:U,isDecidingSet:a,isTiebreakSet:R,isValidSet:w,isValidSetNumber:m,isValidSetOutcome:x,leadingSide:D,setFormat:c,sideGameScores:f,sideGameScoresCount:h,sidePointScores:g,sidePointScoresCount:S,sideTiebreakScores:I,sideTiebreakScoresCount:T,winningSide:F};return e?.winningSide!==void 0&&W7({isValidStandardSetOutcome:C,isValidTiebreakSetOutcome:v,standardSetError:b,tiebreakSetError:_,isTiebreakSet:R,analysis:L}),L}function V7(t){return{sideGameScores:[t?.side1Score,t?.side2Score],sidePointScores:[t?.side1PointScore,t?.side2PointScore],sideTiebreakScores:[t?.side1TiebreakScore,t?.side2TiebreakScore]}}function B7(t,e){if(t){if(e[0]>e[1])return 1;if(e[1]>e[0])return 2}}function H7({isValidStandardSetOutcome:t,isValidTiebreakSetOutcome:e,expectStandardSet:r,expectTiebreakSet:n,expectTimedSet:o,isTiebreakSet:i}){return r&&!i&&t||n&&i&&e||o}function W7({isValidStandardSetOutcome:t,isValidTiebreakSetOutcome:e,standardSetError:r,tiebreakSetError:n,isTiebreakSet:o,analysis:i}){o?(i.isValidTiebreakSetOutcome=e,e||(i.tiebreakSetError=n)):(i.isValidStandardSetOutcome=t,t||(i.standardSetError=r))}function j7({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:CI};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:O};if(!(r?.filter(R=>typeof R=="number"&&!Number.isNaN(R)).length===2))return{result:!1,error:wy};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e??{};if(!!!(a&&r?.find(R=>R>=a)))return{result:!1,error:wy};let l=new Set([1,2]).has(t?.winningSide);if(!t||!l)return{result:!1,error:Gl};let f=t?.winningSide-1,g=1-f,I=r[f],h=r[g],S=I-h;if(!(I>h))return{result:!1,error:{message:"winningSide game scoreString is not high"}};let y=Y7({winningSideGameScore:I,sideTiebreakScores:n,winningSideIndex:f,losingSideIndex:g,sideGameScores:r,gamesDifference:S,tiebreakFormat:u,tiebreakAt:c,setTo:a});if(y)return y;let E=c&&r.filter(R=>R>=c).length===2,A=p?1:2,N=h>=a-1;return S&&N&&!E&&S<A?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:S>A&&I>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function Y7({winningSideGameScore:t,sideTiebreakScores:e,winningSideIndex:r,losingSideIndex:n,sideGameScores:o,gamesDifference:i,tiebreakFormat:s,tiebreakAt:a,setTo:c}){if(!(a&&s))return;let p=e?.filter(h=>typeof h=="number"&&!Number.isNaN(h)).length===2,d=e?.[r],m=e?.[n],l=a&&o.filter(h=>h>=a).length===2,{NoAD:f,tiebreakTo:g}=s;if(l){if(i>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!p)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(typeof g!="number"||Number.isNaN(g))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(g&&e?.find(N=>N>=g)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let S=a<c?c:c+1;if(t>S)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!d||!m||d<m)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let T=f?1:2,y=d-m,E=m>=g-1;if(y&&E&&y<T)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(t>c&&!l)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}function q7({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:CI};let n=!!e?.tiebreakSet,o=!!e?.timed;if(!e||!n||o)return{result:!1,error:{message:"not tiebreak set"}};let s=new Set([1,2]).has(t?.winningSide);if(!t||!s)return{result:!1,error:Gl};let{tiebreakSet:a}=e??{},{NoAD:c,tiebreakTo:u}=a??{};if(!(r?.filter(y=>typeof y=="number"&&!Number.isNaN(y)).length===2))return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(Number.isNaN(u))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!r?.find(y=>y>=u))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let m=t?.winningSide-1,l=1-m,f=r[m],g=r[l];if(!f||!g||f<g)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let I=c?1:2,h=f-g,S=g>=u-1;return h&&S&&h<I?{result:!1,error:{message:"invalid tiebreak scores (3)"}}:{result:!0}}var xG="SET3-S:6/TB7";function Km(t){let e=t.split(/[\s,]+/).filter(s=>s.length>0);if(e.length===0)return xG;let r=$7(e.length),n=K7(e,r);if(n)return n;let o=z7(e);if(o===void 0)return xG;let i=X7(e,o);return Z7(r,o,i)}function $7(t){return t===1?1:t===2?3:5}function jP(t){return t.replaceAll(/\([^)]*\)/g,"").match(/(\d+)/g)?.map(r=>Number.parseInt(r,10))??[]}function K7(t,e){for(let r of t){let n=jP(r);if(n.length===2){let o=Math.max(...n),i=Math.min(...n),s=o-i;if(o===10||o>10&&s<=2)return`SET${e}-S:TB10`}}}function z7(t){let e=t.find(r=>/\(/.test(r));return e?Q7(e):J7(t)}function Q7(t){let e=jP(t);if(e.length===0)return;let r=Math.max(...e),n=Math.min(...e);return r===n+1?n:r-1}function J7(t){let e=[];for(let n of t){let o=jP(n);o.length>0&&e.push(Math.max(...o))}if(e.length===0)return;let r=Math.max(...e);return r>=6?6:r}function X7(t,e){if(t.length<3)return!1;let r=t.at(-1),n=jP(r);if(n.length!==2)return!1;let o=Math.max(...n),i=Math.min(...n);return o>e+1&&o-i===2}function Z7(t,e,r){let n;return e===6?n=`SET${t}-S:6/TB7`:e===4?n=`SET${t}-S:4/TB7`:n=`SET${t}-S:${e}/TB7`,r&&(n+=`-F:${e}`),n}function Hv(t){let{matchUp:e,expectedScore:r}=t;if(!e)return{isValid:!1,errors:["No matchUp provided"],warnings:[],actual:{sets:[],scoreString:""},expected:{sets:r?.sets,scoreString:r?.scoreString},pointsProcessed:0,pointsRejected:0};let n=[],o=[],i=ds({matchUpFormat:e?.matchUpFormat,matchUpId:e?.matchUpId,participants:e?.sides?.map(p=>p.participant).filter(p=>p!==void 0)}),s=e?.history?.points??[];s.length===0&&o.push("No points found to validate");let a=0,c=0;for(let p of s)try{i=xs(i,{winner:p.winner,server:p.server}),a++}catch(d){c++;let m=d instanceof Error?d.message:String(d);n.push(`Point ${p.pointNumber||a+1}: ${m}`)}let u=ms(i);return r&&(r.sets&&(u.sets.length!==r.sets.length&&n.push(`Set count mismatch: expected ${r.sets.length}, got ${u.sets.length}`),r.sets.forEach((p,d)=>{let m=u.sets[d];if(!m){n.push(`Missing set ${d+1}`);return}p.side1Score!==void 0&&m.side1Score!==p.side1Score&&n.push(`Set ${d+1} side1Score: expected ${p.side1Score}, got ${m.side1Score}`),p.side2Score!==void 0&&m.side2Score!==p.side2Score&&n.push(`Set ${d+1} side2Score: expected ${p.side2Score}, got ${m.side2Score}`),p.side1TiebreakScore!==void 0&&m.side1TiebreakScore!==p.side1TiebreakScore&&n.push(`Set ${d+1} side1TiebreakScore: expected ${p.side1TiebreakScore}, got ${m.side1TiebreakScore}`),p.side2TiebreakScore!==void 0&&m.side2TiebreakScore!==p.side2TiebreakScore&&n.push(`Set ${d+1} side2TiebreakScore: expected ${p.side2TiebreakScore}, got ${m.side2TiebreakScore}`)})),r.scoreString&&u.scoreString!==r.scoreString&&n.push(`Score string mismatch: expected "${r.scoreString}", got "${u.scoreString}"`)),{isValid:n.length===0,errors:n,warnings:o,actual:{sets:u.sets,scoreString:u.scoreString},expected:{sets:r?.sets,scoreString:r?.scoreString},pointsProcessed:a,pointsRejected:c}}function wG(t){let e=t?.side1Score||0,r=t?.side2Score||0;if(t?.side1TiebreakScore!==void 0||t?.side2TiebreakScore!==void 0){let n=t?.side1TiebreakScore||0,o=t?.side2TiebreakScore||0;return e>r?`${e}-${r}(${o})`:`${e}(${n})-${r}`}return`${e}-${r}`}function LG(t){let{points:e,matchUpFormat:r,expectedGames:n,expectedTiebreak:o}=t,i={matchUpId:"validation",matchUpFormat:r,matchUpStatus:"TO_BE_PLAYED",matchUpType:"SINGLES",sides:[{sideNumber:1},{sideNumber:2}],score:{sets:[]},history:{points:e?.map((s,a)=>({...s,pointNumber:a+1,timestamp:"",winner:s.winner,server:s.server}))}};return Hv({matchUp:i,expectedScore:{sets:[{side1Score:n?.[0],side2Score:n?.[1],side1TiebreakScore:o?.[0],side2TiebreakScore:o?.[1]}]}})}function kG(t){let{points:e,expectedScore:r,matchUpFormat:n,allowExtraPoints:o=!1,debug:i=!1}=t,s=[],a=[],c=[],u,p=!1;n?u=n:r?(u=Km(r),p=!0,i&&console.log(`Deduced format: ${u} from score: ${r}`)):(u="SET3-S:6/TB7",p=!0,a.push("No format provided, using default SET3-S:6/TB7"));let d=ds({matchUpFormat:u}),m=e?.split("").map(S=>{let T=Number.parseInt(S,10);return Number.isNaN(T)||T!==0&&T!==1?null:T}).filter(S=>S!==null);if(m?.length===0)return s.push("No valid points found in point string"),{valid:!1,errors:s,warnings:a,pointsProcessed:0,pointsRejected:[],actualScore:"0-0",matchUpFormat:u,formatDeduced:p,sets:[]};let l=0;for(let S=0;S<m?.length;S++){let T=m[S];if(d.matchUpStatus==="COMPLETED"&&!o){c.push(T),i&&console.log(`Point ${S+1}: Rejected (match complete)`);continue}try{if(d=xs(d,{winner:T}),l++,i){let y=ms(d);console.log(`Point ${S+1}: ${T} \u2192 ${y.scoreString}`)}}catch(y){c.push(T);let E=y instanceof Error?y.message:String(y);s.push(`Point ${S+1}: ${E}`),i&&console.log(`Point ${S+1}: Error - ${E}`)}}let f=ms(d),g=f.scoreString,I=f.sets.map(S=>{let T=[S.side1Score||0,S.side2Score||0],y=S.side1TiebreakScore===void 0?void 0:[S.side1TiebreakScore,S.side2TiebreakScore||0],E=`${T[0]}-${T[1]}`;return y&&(E=T[0]>T[1]?`${T[0]}-${T[1]}(${y[1]})`:`${T[0]}(${y[0]})-${T[1]}`),{games:T,tiebreak:y,scoreString:E}}),h=!0;if(r){let S=FG(r),T=FG(g);S!==T&&(h=!1,s.push(`Score mismatch: expected "${r}", got "${g}"`))}return c.length>0&&a.push(`${c.length} excess points after match complete`),s.length>0&&(h=!1),{valid:h,errors:s,warnings:a,pointsProcessed:l,pointsRejected:c,expectedScore:r,actualScore:g,matchUpFormat:u,formatDeduced:p,sets:I}}function FG(t){return t.replace(/\s+/g,"").replace(/,/g,", ").toLowerCase()}var t8={4:"Wide",5:"Body",6:"T"},GG={f:"Forehand",r:"Forehand Slice",v:"Forehand Volley",o:"Overhead Smash",u:"Forehand Drop Shot",l:"Forehand Lob",h:"Forehand Half-volley",j:"Forehand Drive Volley"},VG={b:"Backhand",s:"Backhand Slice",z:"Backhand Volley",p:"Backhand Overhead Smash",y:"Backhand Drop Shot",m:"Backhand Lob",i:"Backhand Half-volley",k:"Backhand Drive Volley"},e8={t:"Trick Shot",q:"Unknown Shot"},r8={...GG,...VG,...e8},n8={7:"shallow",8:"deep",9:"very deep"},o8={1:1,2:2,3:3},i8={"+":"approach","-":"net","=":"baseline"},zm={n:"Net",w:"Out Wide",d:"Out Long",x:"Out Wide and Long",g:"Foot Fault",e:"Unknown","!":"Shank"};function s8(t,e){return t.PtWinner===t.Svr?e:1-e}function jv(t){let e=[],r="",n="fbrsvzouymlhijkpqt";for(let i=0;i<t.length;i++){let s=t[i];s&&(n.includes(s)||"456".includes(s)?(r&&e.push(r),r=s):r+=s)}return r&&e.push(r),e}function a8(t){if(t.includes("*"))return"*";if(t.includes("#"))return"#";if(t.includes("@"))return"@"}function oc(t){if(t){for(let e of Object.keys(zm))if(t.includes(e))return e}}function c8(t){let e=[];for(let r of t){if(!r)continue;let n=r[0];if(n&&/[456]/.test(n))e.push(r);else break}return e}function Yv(t){if(!wt(t))return{serves:[],rally:[]};let e,r,n,o=t.split("c").length-1;t=t.split("c").join("");let i=jv(t),s=i;for(let p=i.length-1;p>=0;p--){let d=i[p];if(d&&(r=a8(d),r)){s=i.slice(0,p+1),n=i.slice(p+1),e=d;break}}let a=c8(s),c=a.length?s.slice(a.length):s;if(!r&&!a.length&&c.length===1){let p=c[0];p&&["S","P","Q","R"].includes(p)&&(e=p,c.length=0)}let u={serves:a,rally:c};return o&&(u.lets=o),r&&(u.terminator=r),e&&(u.result=e),n?.length,u}function qv(t){let e=t.join("|"),r=YP(t[0],1);if(r.winner==="S"||!t[1])return r.serve=1,r.code=e,r;let n=YP(t[1],2);return n.serve=2,n.first_serve={serves:r.serves},r.lets&&(n.first_serve.lets=r.lets),r.error&&(n.first_serve.error=r.error),r.parse_notes&&(n.first_serve.parse_notes=r.parse_notes),n.code=e,n}function YP(t,e){let r=Yv(t);if(["Q","S"].includes(r.result||""))return r.winner="S",r;if(["P","R"].includes(r.result||"")||!r.terminator&&!oc(r.serves[0])&&r.serves.length>2)return r.winner="R",r;let n=(r.serves.length+r.rally.length)%2===0?"R":"S",o;return r.rally.length>0?o=r.rally[r.rally.length-1]:r.serves.length>0&&(o=r.serves[r.serves.length-1]),o?r.rally.length?p8(r,n,o):u8(r,e):{...r,winner:void 0}}function u8(t,e){if(t.terminator==="*")t.result="Ace",t.winner="S";else if(t.terminator==="#")t.result="Serve Winner",t.winner="S";else{let r=oc(t.serves[0]);r?(t.error=zm[r],e===2&&(t.result="Double Fault",t.winner="R")):(t.parse_notes="treated as a fault",e===2&&(t.result="Double Fault",t.winner="R"))}return t}function p8(t,e,r){if(t.rally.length===1&&r.includes("#")){t.result="Serve Winner",t.winner="S";let n=oc(r);return n&&(t.error=zm[n]),t}return r.includes("#")?(t.result="Forced Error",t.error=zm[oc(r)],t.winner=e==="R"?"S":"R"):r.includes("*")?(t.result="Winner",t.winner=e):r.includes("@")?(t.result="Unforced Error",t.error=zm[oc(r)],t.winner=e==="R"?"S":"R"):oc(t.serves[0])?t.rally.length===1&&oc(r)&&(t.error=zm[oc(r)],t.winner=e==="R"?"S":"R"):t.serves.length&&t.rally.length?(t.parse_notes="no terminator: receiver wins point",t.result="Unknown",t.winner="R"):t.rally.length===1&&oc(r)&&(t.error=zm[oc(r)],t.winner=e==="R"?"S":"R"),t}function Wv(t){if(t)for(let e of t){let r=r8[e];if(r)return r}}function d8(t){if(t)for(let e of t){let r=t8[e];if(r)return r}}function m8(t,e,r){let n=[],o=1,i=r;if(t.length>0&&!oc(t[t.length-1])){let s=t[t.length-1],a=Wv(s)||"Forehand";n.push({shotNumber:o++,player:i,stroke:a,code:s}),i=1-i}for(let s of e){let a=Wv(s);if(!a)continue;let c={shotNumber:o++,player:i,stroke:a,code:s};for(let u of s){let p=o8[u];p!==void 0&&(c.direction=p)}for(let u of s){let p=n8[u];p&&(c.depth=p)}for(let u of s){let p=i8[u];p&&(c.position=p)}n.push(c),i=1-i}return n}function qP(t,e){let r=s8(t,e),n=t["1st"]||"",o=t["2nd"]||"";if(!n&&!o)return{winner:r,server:e,result:"Unknown"};let i=qv([n,o]),s={winner:r,server:e};i.result&&(s.result=i.result),i.serve&&(s.serve=i.serve);let a=i.serve===1?n:o,c=d8(a);c&&(s.serveLocation=c);let u=i.rally[i.rally.length-1];if(u){let d=Wv(u);d&&(s.stroke=d,Object.values(GG).includes(d)?s.hand="Forehand":Object.values(VG).includes(d)&&(s.hand="Backhand"))}let p=m8(i.serves,i.rally,e);return p.length>0&&(s.rally=p,s.rallyLength=p.length),i.code&&(s.code=i.code),s}function $P(t){if(!t||!wt(t))return[];let e=t.trim().split(`
|
|
5
|
-
`);if(e.length<2)return[];let r=e[0]?.split(",")??[],n=[];for(let o=1;o<e.length;o++){let i=e[o];if(!i)continue;let s=i.split(","),a={};for(let c=0;c<r.length;c++){let u=r[c];u&&(a[u]=s[c]||"")}n.push(a)}return n}function KP(t){if(!Array.isArray(t))return[];let e=new Map;for(let r of t){let n=r.match_id;e.has(n)||e.set(n,[]),e.get(n).push(r)}return Array.from(e.entries()).map(([r,n])=>({match_id:r,points:n}))}function l8(t){let e=t?.split("-")??[];if(e.length<6)return{player1:"Player 1",player2:"Player 2"};let r=e[0],n=e[2]?.replaceAll("_"," "),o=e[4]?.replaceAll("_"," ")||"Player 1",i=e[5]?.replaceAll("_"," ")||"Player 2";return{player1:o,player2:i,date:r,tournament:n}}function f8(t){if(!t||t.length===0)return;let e=t.at(-1);if(!e)return;let r=e.Set1,n=e.Set2,o=e.Set3,i=e.Set4,s=e.Set5,a=[];return r&&a.push(`${r}-${n}`),o&&a.push(`${o}-${n||"0"}`),i&&a.push(`${i}-${n||"0"}`),s&&a.push(`${s}-${n||"0"}`),a.length>0?a.join(", "):void 0}function $v(t,e={}){let{matchUpFormat:r,validateScore:n=!0,debug:o=!1}=e,i=[],s=[],a=l8(t.match_id),c=f8(t.points),u,p=!1;r?u=r:c?(u=Km(c),p=!0,o&&console.log(`Deduced format: ${u} from score: ${c}`)):(u="SET3-S:6/TB7",p=!0,s.push("No format provided, using default SET3-S:6/TB7")),o&&(console.log(`Validating match: ${a.player1} vs ${a.player2}`),console.log(`Format: ${u}`),console.log(`Total points: ${t.points.length}`),c&&console.log(`Expected score: ${c}`));let d=ds({matchUpFormat:u,matchUpId:t.match_id});d.sides[0]&&(d.sides[0].participant={participantId:"player1",participantName:a.player1,participantType:"INDIVIDUAL",participantRole:"COMPETITOR"}),d.sides[1]&&(d.sides[1].participant={participantId:"player2",participantName:a.player2,participantType:"INDIVIDUAL",participantRole:"COMPETITOR"});let m=S8(t.points,d,{errors:i,debug:o});d=m.matchUp;let l=T8(d,c,{errors:i,warnings:s,validateScore:n,debug:o});return{valid:i.length===0,errors:i,warnings:s,matchUp:d,pointsProcessed:m.pointsProcessed,expectedScore:c,actualScore:l.actualScore,scoreMatches:l.scoreMatches,formatDeduced:p,aces:m.aces,doubleFaults:m.doubleFaults,winners:m.winners,unforcedErrors:m.unforcedErrors,forcedErrors:m.forcedErrors}}function g8(t,e){if(t.history?.points&&t.history.points.length>0){let r=t.history.points.at(-1);r&&(e.result&&(r.result=e.result),e.stroke&&(r.stroke=e.stroke),e.hand&&(r.hand=e.hand),e.serve&&(r.serve=e.serve),e.serveLocation&&(r.serveLocation=e.serveLocation),e.rally&&(r.rally=e.rally),e.rallyLength&&(r.rallyLength=e.rallyLength),e.code&&(r.code=e.code))}}function I8(t,e){t==="Ace"&&e.aces++,t==="Double Fault"&&e.doubleFaults++,t==="Winner"&&e.winners++,t==="Unforced Error"&&e.unforcedErrors++,t==="Forced Error"&&e.forcedErrors++}function h8(t,e,r,n,o,i,s){let a=t.Svr==="1"?0:1;try{let c=qP(t,a),u={winner:c.winner,server:c.server};if(e=xs(e,u),g8(e,c),I8(c.result,s),o&&(r<5||r===n-1)){let p=ms(e);console.log(`Point ${r+1}: ${c.result||"Rally"} \u2192 ${p.scoreString}`)}return{matchUp:e,processed:!0}}catch(c){let u=c instanceof Error?c.message:String(c);return i.push(`Point ${r+1}: ${u}`),o&&console.error(`Point ${r+1} failed:`,u),{matchUp:e,processed:!1}}}function S8(t,e,r){let{errors:n,debug:o}=r,i=e,s=0,a={aces:0,doubleFaults:0,winners:0,unforcedErrors:0,forcedErrors:0};for(let c=0;c<t?.length;c++){let u=t[c];if(!u)continue;let p=h8(u,i,c,t.length,o,n,a);i=p.matchUp,p.processed&&s++}return{matchUp:i,pointsProcessed:s,...a}}function T8(t,e,r){let{errors:n,warnings:o,validateScore:i,debug:s}=r,c=ms(t).scoreString,u=t.matchUpStatus==="COMPLETED";u||o.push(`Match not complete. Final score: ${c}`);let p;if(i&&e){let d=BG(e),m=BG(c);p=d===m,p||n.push(`Score mismatch: expected "${e}", got "${c}"`),s&&(console.log(`Expected: ${e} \u2192 ${d}`),console.log(`Actual: ${c} \u2192 ${m}`),console.log(`Score matches: ${p}`))}return s&&(console.log(`Final score: ${c}`),console.log(`Match complete: ${u}`),console.log("Stats logged in processValidationPoints")),{actualScore:c,scoreMatches:p}}function BG(t){return t.replaceAll(/\s+/g,"").replaceAll(",",", ").toLowerCase()}function HG(t){let{csvData:e,matchId:r,matchUpFormat:n,debug:o=!1}=t,i=[],s=[],a=[],c;try{c=$P(e)}catch(h){let S=h instanceof Error?h.message:String(h);return i.push(`Failed to parse CSV: ${S}`),{valid:!1,errors:i,warnings:s,matchesProcessed:0,pointsProcessed:0,matchUps:[],totalAces:0,totalDoubleFaults:0,totalWinners:0,totalUnforcedErrors:0,totalForcedErrors:0}}let u=KP(c);o&&console.log(`Parsed ${c.length} points from ${u.length} matches`);let p=r?u.filter(h=>h.match_id===r):u;if(p.length===0)return i.push(r?`Match ID not found: ${r}`:"No matches found in CSV data"),{valid:!1,errors:i,warnings:s,matchesProcessed:0,pointsProcessed:0,matchUps:[],totalAces:0,totalDoubleFaults:0,totalWinners:0,totalUnforcedErrors:0,totalForcedErrors:0};let d=0,m=0,l=0,f=0,g=0,I=0;for(let h of p){let S=$v(h,{matchUpFormat:n,debug:o});S.valid||i.push(...S.errors),s.push(...S.warnings),a.push(S.matchUp),d+=S.pointsProcessed,m+=S.aces,l+=S.doubleFaults,f+=S.winners,g+=S.unforcedErrors,I+=S.forcedErrors}return{valid:i.length===0,errors:i,warnings:s,matchesProcessed:p.length,pointsProcessed:d,matchUps:a,totalAces:m,totalDoubleFaults:l,totalWinners:f,totalUnforcedErrors:g,totalForcedErrors:I}}function WG(t){return JSON.stringify(t,null,2)}function jG(t){let{existingDrawDefinition:e,hydrateCollections:r,enforceGender:n,tieFormatName:o,tieFormatId:i,matchUpType:s,eventType:a,isMock:c,event:u}=t,{tieFormat:p,matchUpFormat:d}=t;if(s===Ce&&a===Ce){let m=e?.structures?.find(({stage:g})=>g===j)?.tieFormat,l=i&&u?.tieFormats?.find(g=>g.tieFormatId===i),f=Qo(u);p=p||l||m||o&&u?.tieFormats?.find(g=>g.tieFormatName===o)||o&&f?.tieFormatName===o&&f||o&&Eo({namedFormat:o,hydrateCollections:r,isMock:c,event:u})||f||Eo({event:u,isMock:c,hydrateCollections:r}),d=void 0}else d||(p=void 0,u?.matchUpFormat||(d=kn));if(p){let m=ur({gender:u?.gender,enforceGender:n,tieFormat:p});if(m.error)return m}return{tieFormat:p,matchUpFormat:d}}function YG(t){let e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:r,appliedPolicies:n,qualifyingOnly:o,drawEntries:i,structureId:s,tieFormat:a,idPrefix:c,isMock:u,event:p}=t,d=t.qualifyingProfiles,m=d?.length?DP({hasExistingDrawDefinition:!0,uuids:t.uuids,qualifyingProfiles:d,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,idPrefix:c,isMock:u}):void 0;if(m?.error)return m;e.structures=e.structures?.filter(({structureId:h})=>h!==r),e.links=e.links?.filter(({source:h})=>h.structureId!==r);let{qualifyingDrawPositionsCount:l,qualifyingDetails:f}=m??{};l&&(m?.structures&&e.structures?.push(...m.structures),m?.links&&e.links?.push(...m.links));let g=e.structures?.find(({stage:h,stageSequence:S})=>h===j&&S===1);y8({drawDefinition:e,drawEntries:i,event:p});let I=E8({mainStructure:g,qualifyingDetails:f,drawDefinition:e});return I.error?I:{drawDefinition:e,structureId:s}}function y8({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===rt)){let o={...n,entryStage:n.entryStage??j,drawDefinition:t,event:r};Ff(o)}}function E8({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&&la({targetStructureId:t.structureId,sourceStructureId:i,sourceRoundNumber:o,finishingPositions:a,targetEntryRound:s,linkType:c})?.link;if(u?.error)return u;u&&(r.links??=[],r.links.push(u))}return{error:void 0}}function Ig(t){let{participantIds:e}=t,r=t.targetStage,n=t.drawDefinition?.entries?.filter(o=>{let i=o.entryStatus;return!(t.restrictEntryStatus&&!yr.includes(i)||r&&(o.entryStage??j)!==r)}).map(lt)??[];if(e){let o=e.filter(i=>!n?.includes(i));if(o?.length)return M({result:{error:Hr},info:{invalidParticipantIds:o}})}else e=n;return t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>e.length-1&&(!t.enableDoubleRobin||t.roundsCount>(e.length-1)*2)?{error:O,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:O,info:"roundsCount must be less than 32"}:{participantIds:e}}function hg(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=Ig(t);if(p.error)return p;for(let d of J(1,r+1)){let m=Vc({restrictMatchUpsCount:t.restrictMatchUpsCount,ignoreLastRoundNumber:!!u,newRound:!u,drawDefinition:n,matchUpsCount:o,structureId:i,roundNumber:u,idPrefix:s,isMock:a,event:c});if(m.error)return M({result:m,info:{iteration:d}});m.matchUps?.length&&e.push(...m.matchUps),u=(m?.roundNumber??1)+1}return{matchUps:e}}function Td(t){let e=P8(t);if(e?.error)return e;let r=Ig(t);if(r.error)return r;let n=A8(t);if(n.error)return n;let o=uf(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of J(1,(t.roundsCount??1)+1)){let d=ug({...t,participantIds:r.participantIds,structure:n.structure,ignoreLastRoundNumber:!0,iterationMatchUps:a,adHocRatings:o,roundNumber:u,eventType:s,isMock:i});if(d.error)return d;let{matchUps:m,...l}=d;l.modifiedScaleValues&&(o=l.modifiedScaleValues),c.push({...l,iteration:p,matchUpsCount:m?.length}),u=(l?.roundNumber??1)+1,m?.length&&a.push(...m)}return{...P,matchUps:a,roundResults:c}}function A8(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&&ka[s.stage];return De({structure:s})&&a>(ka[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?De({structure:n})?{structure:n}:{error:Ua}:{error:Pt}}function P8(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:O,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"?{error:Ua}:!t.structureId&&t.drawDefinition.drawType&&!En(t.drawDefinition.drawType)?{error:Ua}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:O,info:"Missing Entries"}:{error:void 0}}function qG(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,idPrefix:o,isMock:i,event:s}=t,a=s?.entries?.filter(({entryStage:p,entryStatus:d})=>(!p||p===j)&&d&&yr.includes(d)),c=a?.map(lt),u=a?Math.floor(a.length/2):0;if(t.automated)return N8({...t,participantIds:c});{let p=hg({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&md({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...P}}function N8(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s,convertToELO:a,dynamicRatings:c}=t.drawMatic??{},u=Td({...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,dynamicRatings:c,convertToELO:a,structureId:n,matchUpIds:o});return u.error?u:(u?.matchUps?.length&&md({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:u.matchUps,event:t.event,structureId:n}),{...P})}function $G({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=tt({drawDefinition:s,structureId:c});if(p.error)return p;let d=p.structure;if(!d)return{error:Pt};let{positionAssignments:m}=pe({structure:d}),l=m?.length||0;if(u>l)return{error:wU};let f=d.structures?.length,g=It(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=sS({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=Id({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[Xn]&&u>h&&e&&(u=h),d.seedLimit=u,d.seedAssignments=J(1,u+1).map(S=>{let T=I?.find(A=>A.includes(S)),y=T&&Math.min(...T),E=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:E}}),Lt({drawDefinition:s,structureIds:[c]}),{...P,seedLimit:u}}function ic({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:Y};i=i??s?.entries??[];let c=i.filter(f=>(!a||!f.entryStage||f.entryStage===a)&&(!o||!f.entryStageSequence||f.entryStageSequence===o)&&yr.includes(f.entryStatus)),u={...r};return{scaledEntries:c.map(f=>{let{participantId:g}=f,{scaleItem:I}=as({tournamentRecord:e,scaleAttributes:r,participantId:g});return{...f,...I}}).filter(f=>{let g=f.scaleValue;return!n&&(Number.isNaN(g)||!Number.parseFloat(g))?!1:g}).sort(n||(t||u?.ascending===!1?m:d))};function d(f,g){return l(f)-l(g)}function m(f,g){return l(g)-l(f)}function l(f){return Number.parseFloat(f.scaleValue||(t?-1:1e5))}}function zP(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=hn({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 M({result:{error:Pt},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=O8({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&R8({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&!En(t.drawType)&&!(t.qualifyingOnly&&t.stage!==rt),d=(n?.length||0)>1,m=p?U8({...t,multipleStructures:d,seedLimit:u,structureId:s}):{};if(m?.error)return M({result:m,stack:e});if(!p&&En(t.drawType)&&i?.positionAssignments?.length){let l=t.qualifiersCount||0;if(l>0){let f=i.positionAssignments.filter(g=>!g.participantId&&!g.qualifier&&!g.bye);for(let g=0;g<l&&g<f.length;g++)f[g].qualifier=!0}}return{...m,stageEntries:c,structureId:s,seedsCount:a}}function D8({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=qt({name:Xr,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&rs.includes(o.entryStatus)})}function U8(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Gu({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function R8(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(lt);e?b8({...t,enteredParticipantIds:i}):(o||r)&&C8({...t,enteredParticipantIds:i})}function b8(t){let{provisionalPositioning:e,enteredParticipantIds:r,seededParticipants:n,tournamentRecord:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,structure:u,event:p}=t,d=u?Ai({provisionalPositioning:e,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structure:u}):void 0;n.filter(({participantId:m})=>r.includes(m)).filter(m=>!m.seedNumber||m.seedNumber<=n.length).sort((m,l)=>m.seedNumber<l.seedNumber?-1:m.seedNumber<l.seedNumber?1:0).forEach(m=>{let{participantId:l,seedNumber:f,seedValue:g}=m;Qa({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:d,structureId:c,seedNumber:f,seedValue:g,event:p})})}function C8(t){let e=t.seedsCount,{provisionalPositioning:r,enteredParticipantIds:n,seedAssignmentProfile:o,assignSeedsCount:i,tournamentRecord:s,drawDefinition:a,seedByRanking:c,seedingProfile:u,structureId:p,event:d}=t,{categoryName:m,ageCategoryCode:l}=d?.category??{},f=d?.eventType,g=M8({...t,ageCategoryCode:l,categoryName:m,eventType:f})||c&&v8({...t,ageCategoryCode:l,categoryName:m,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:E}=h,A=o?.[T]||E||T;Qa({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:A,event:d})})}function M8(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:_o,eventType:u};return ic({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function v8(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category??{},c=n?.eventType;return ic({scaleAttributes:{scaleName:s||a,scaleType:co,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function O8(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=D8(t);e>r.length&&(e=r.length);let{seedLimit:n}=$G({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 KG(t){let e=ag({...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:d,drawType:m,entries:l}=t,f=[],g=[],I=_8({suppressDuplicateEntries:n,ignoreStageSpace:o,qualifyingOnly:s,drawDefinition:r,drawEntries:u,drawType:m,entries:l});if(I.error)return I;let{qualifyingPlaceholder:h,qualifyingProfiles:S,qualifiersCount:T}=t,y=r?.structures?.find(R=>R.stage===j&&R.stageSequence===1)?.structureId,E=y&&r?.links?.some(R=>R.target?.structureId===y&&R.source?.structureId);if(h&&!S?.length&&T&&r&&y&&!E){let R=gr({structureName:Be(rt),stage:rt,qualifyingOnly:s,tieFormat:t.tieFormat}),{link:U}=la({sourceStructureId:R.structureId,targetStructureId:y,qualifyingPositions:T,sourceRoundNumber:0,linkType:fn});r.structures??=[],r.structures.push(R),r.links??=[],r.links.push(U)}let A=cn(m)?0:st(t.seedsCount??0),N=zP({...t,qualifyingOnly:!d||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:j,seedsCount:A,placeByes:p,drawSize:d,entries:l});if(N.error&&!N.conflicts)return N;N.positioningReport?.length&&f.push({[j]:N.positioningReport});let D=N.structureId;return N.conflicts&&(g=N.conflicts),En(m)&&t.roundsCount&&qG({...t,drawDefinition:r,structureId:D}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:D}}function _8(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,qualifyingOnly:i,entries:s}=t;for(let a of s){if(a.entryStatus===On||n&&a.entryStage&&a.entryStage!==j&&!(i&&a.entryStage===rt))continue;let c={...a,ignoreStageSpace:e??En(o),entryStage:a.entryStage??j,event:t.event,drawDefinition:r,drawType:o},u=Ff(c);if(n&&u.error)return u}return{error:void 0}}var x8=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var zG=x8;function QG(t){let{drawId:e=ot(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=zG();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function Sg(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=X(t,[{[zt]:!0,[tf]:!0}]);if(c.error)return c;if(!Or({matchUpFormat:o}))return{error:nu};let u="setMatchUpFormat";if(s){let p=Ft({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let d=p.matchUp;if(d?.matchUpType===Ce)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:mr};d&&(d.matchUpFormat=o,mt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:d}))}else if(Array.isArray(e)){if(a?.eventType===Ce)return{error:so};for(let p of e){let d=tt({drawDefinition:n,structureId:p});if(d.error)return d;d.structure&&(d.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===Ce)return{error:so};let p=tt({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),Lt({drawDefinition:n,structureIds:e}),{...P}}function JG({tieFormat:t}){let e=ur({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId??=ot();return{tieFormat:t}}function XG({existingQualifyingStructures:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUpType:o,tieFormat:i,event:s}){if((n||i)&&!(n&&s?.matchUpFormat===n||s?.tieFormat&&i&&JSON.stringify(s.tieFormat)===JSON.stringify(i))){if(i){let c=JG({tieFormat:i});if(c.error)return c;let u=t?.every(p=>p.tieFormat);(!t?.length||u)&&(r.tieFormat=c.tieFormat??i)}else if(n){let c=Sg({tournamentRecord:e,drawDefinition:r,matchUpFormat:n,event:s});if(c.error)return{info:"matchUpFormat or tieFormat error",error:c.error}}o&&(r.matchUpType=o)}return{error:void 0}}var Jv={};_t(Jv,{attachPolicies:()=>_s,findPolicy:()=>Uo,getAppliedPolicies:()=>gt,getPolicyDefinitions:()=>Do,mutate:()=>zv,query:()=>Qv,removePolicy:()=>Kv});var zv={};_t(zv,{attachPolicies:()=>_s,removePolicy:()=>Kv});function Kv(t){let e=X(t,[{[CF]:!0,_anyOf:{[Ne]:!1,[Z]:!1,[zt]:!1,[me]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return ZG(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:Y};for(let i of o){let s=t.tournamentRecords[i],a=ZG(t,s);if(a.error)return a;r=!0}}else return{error:Y};return r?{...P}:{error:lp}}function ZG(t,e){let r=gt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?Qt({element:e,extension:{name:wp,value:r}}):Mn({element:e,name:wp}),{...P}):{error:lp}}var Qv={};_t(Qv,{findPolicy:()=>Uo,getAppliedPolicies:()=>gt,getPolicyDefinitions:()=>Do});var Xv={[Xn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[sn]:{positioning:qi},[_r]:{positioning:qi}},positioning:Ub},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}]}},jS=Xv;function tV({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return M({info:"policyDefinitions must be an object",result:{error:O},stack:n});let o={[Nc]:t?.[Nc]};return e?w8({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&_s({drawDefinition:r,policyDefinitions:o}),!t?.[Xn]&&!e?.[Xn]&&(_s({policyDefinitions:jS,drawDefinition:r}),t&&Object.assign(t,jS)),{error:void 0}}function w8({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&&(_s({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function eV(t){let{tournamentRecord:e,policyDefinitions:r,appliedPolicies:n,matchUpFormat: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,d=p?.structures?.find(h=>h.stage===j&&h.stageSequence===1)?.structureId,m=p?p.structures?.filter(h=>h.stage===rt):[],l=m?.length===1&&!m[0].matchUps?.length&&m[0].structureId;p&&a!==p.drawType&&!l&&(p.drawType=a);let f=p??QG({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),g=XG({existingQualifyingStructures:m,tournamentRecord:e,drawDefinition:f,matchUpFormat:o,matchUpType:i,tieFormat:s,event:u});if(g.error)return M({result:g,stack:c});let I=tV({appliedPolicies:n,policyDefinitions:r,drawDefinition:f,stack:c});return I.error?I:{drawDefinition:f,structureId:d,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:l}}function rV(t){let e="generateOrGetExisting",r=[],n=[],o=eV(t);if(o.error)return M({result:o,stack:e});let i=o.existingDrawDefinition,s,a,c=t.drawEntries??t.eventEntries??[],u=o.existingQualifyingPlaceholderStructureId&&YG({...t,...o})||KG({...t,...o,entries:c});return u.error?M({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 nV(t){let{qualifyingPlaceholder:e,existingDrawDefinition:r,positioningReports:n,qualifyingProfiles:o,appliedPolicies:i,qualifyingOnly:s,drawDefinition:a,seedingProfile:c,participants:u,structureId:p,tieFormat:d,entries:m,stack:l}=t,f=e&&!o?.length&&!r,g=[];if(o){let I=L8({qualifyingProfiles:o,qualifyingConflicts:g,positioningReports:n,seedingProfile:c,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,participants:u,entries:m,params:t,stack:l});if(I?.error)return I}else if(p&&f&&!a.structures?.find(h=>h.stage===rt&&!h.matchUps?.length)){let h=gr({structureName:Be(rt),stage:rt,qualifyingOnly:s,tieFormat:d}),S=t.qualifiersCount,{link:T}=la({sourceStructureId:h.structureId,targetStructureId:p,sourceRoundNumber:0,qualifyingPositions:S,linkType:fn});a.structures??=[],a.structures.push(h),a.links??=[],a.links.push(T)}return{qualifyingConflicts:g,error:void 0}}function L8({qualifyingProfiles:t,qualifyingConflicts:e,positioningReports:r,seedingProfile:n,appliedPolicies:o,drawDefinition:i,qualifyingOnly:s,participants:a,entries:c,params:u,stack:p}){let d=(g,I)=>g.stageSequence-I.stageSequence,m=(g,I)=>g.roundTarget-I.roundTarget,l=[],f=1;t.sort(m);for(let g of t){if(!Array.isArray(g.structureProfiles))return M({info:xi("structureProfiles"),result:{error:nt},stack:p});f=g.roundTarget||f;let I=g.structureProfiles?.sort(d)??[],h=1;for(let S of I){let T=F8({structureProfile:S,preparedStructureIds:l,seedingProfile:n,appliedPolicies:o,drawDefinition:i,qualifyingOnly:s,participants:a,roundTarget:f,sequence:h,entries:c,params:u});if(T.error)return T;T.structureId&&l.push(T.structureId),h+=1,T.conflicts?.length&&e.push(...T.conflicts),T.positioningReport?.length&&r.push({[rt]:T.positioningReport})}f+=1}}function F8({structureProfile:t,preparedStructureIds:e,seedingProfile:r,appliedPolicies:n,drawDefinition:o,qualifyingOnly:i,participants:s,roundTarget:a,sequence:c,entries:u,params:p}){let{qualifyingRoundNumber:d,qualifyingPositions:m,seededParticipants:l,seedingScaleName:f,seedsCount:g=0,seedByRanking:I,placeByes:h,drawSize:S}=t;return zP({...p,seedingProfile:t.seedingProfile??r,stageSequence:c,qualifyingRoundNumber:d,preparedStructureIds:e,qualifyingPositions:m,seededParticipants:l,stage:rt,seedingScaleName:f,appliedPolicies:n,drawDefinition:o,qualifyingOnly:i,seedByRanking:I,participants:s,roundTarget:a,seedsCount:g,placeByes:h,drawSize:S,entries:u})}function QP(t){let{drawDefinition:e,appliedPolicies:r}=t,n=r?.[$o],o=ye({drawDefinition:e});return e.structures?.forEach(i=>{let s=Jo({structureId:i.structureId,matchUpsMap:o}),a=rA({roundNamingPolicy:n,drawDefinition:e,structure:i,matchUps:s}),{roundNamingProfile:c,roundProfile:u}=a;(i.structures||[i]).forEach(d=>{(d.matchUps??[]).forEach(m=>{let l=m?.roundNumber?.toString();if(l){let f=c?.[l]?.roundName,g=c?.[l]?.abbreviatedRoundName,I=u?.[l]?.feedRound;Object.assign(m,{abbreviatedRoundName:g,feedRound:I,roundName:f})}})})}),{drawDefinition:e}}var TO={};_t(TO,{addGoesTo:()=>bs,allCompetitionMatchUps:()=>un,allDrawMatchUps:()=>sr,allEventMatchUps:()=>_n,allPlayoffPositionsFilled:()=>BA,allTournamentMatchUps:()=>jt,analyzeDraws:()=>dd,analyzeMatchUp:()=>rl,analyzeTournament:()=>mN,bulkUpdatePublishedEventIds:()=>fN,calculateMatchUpMargin:()=>Lm,calculateWinCriteria:()=>Sa,categoryCanContain:()=>Dp,checkMatchUpIsComplete:()=>ia,checkValidEntries:()=>ig,cleanExpiredMutationLocks:()=>oN,compareTieFormats:()=>Pi,competitionScheduleMatchUps:()=>Pd,courtGridRows:()=>Rg,credits:()=>oV,drawMatchUps:()=>ON,eventMatchUps:()=>vg,filterMatchUps:()=>os,filterParticipants:()=>rd,findDrawDefinition:()=>iP,findExtension:()=>qt,findVenue:()=>Wn,getAggregateTeamResults:()=>aN,getAllDrawMatchUps:()=>re,getAllEventData:()=>IN,getAllStructureMatchUps:()=>ht,getAllowedDrawTypes:()=>Tg,getAllowedMatchUpFormats:()=>nN,getApplicableAwardProfileLevels:()=>Jm,getAppliedPolicies:()=>gt,getAssignedParticipantIds:()=>ss,getAvailableMatchUpsCount:()=>Zf,getAvailablePlayoffProfiles:()=>sd,getCategoryAgeDetails:()=>Es,getCheckedInParticipantIds:()=>ta,getCompetitionDateRange:()=>Eg,getCompetitionFormat:()=>DN,getCompetitionLeaderboard:()=>LE,getCompetitionMatchUps:()=>el,getCompetitionParticipantState:()=>wE,getCompetitionParticipants:()=>JP,getCompetitionPenalties:()=>iN,getCompetitionPolicy:()=>wo,getCompetitionState:()=>Ko,getCompetitionVenues:()=>km,getCourtInfo:()=>Mf,getCourts:()=>_N,getDraftState:()=>PP,getDrawData:()=>eg,getDrawDefinitionTimeItem:()=>qE,getDrawParticipantRepresentativeIds:()=>eP,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>gd,getEligibleVoluntaryConsolationParticipants:()=>tP,getEntriesAndSeedsCount:()=>bg,getEvent:()=>LN,getEventData:()=>fd,getEventMatchUpFormatTiming:()=>EN,getEventProperties:()=>xN,getEventPublishStatus:()=>br,getEventRankingPoints:()=>Xm,getEventStructures:()=>lS,getEventTimeItem:()=>$p,getEvents:()=>wN,getFlightProfile:()=>Gt,getHomeParticipantId:()=>bN,getLinkedTournamentIds:()=>Bp,getLuckyDrawRoundStatus:()=>zf,getMatchUpCompetitiveProfile:()=>Xs,getMatchUpContextIds:()=>RN,getMatchUpDailyLimits:()=>_g,getMatchUpDailyLimitsUpdate:()=>NN,getMatchUpDependencies:()=>en,getMatchUpFormat:()=>CN,getMatchUpFormatTiming:()=>Qp,getMatchUpFormatTimingUpdate:()=>yN,getMatchUpScheduleDetails:()=>vf,getMatchUpType:()=>Of,getMatchUpsMap:()=>ye,getMatchUpsStats:()=>MN,getMatchUpsToSchedule:()=>Dg,getMaxEntryPosition:()=>SN,getModifiedMatchUpFormatTiming:()=>Cg,getMutationLocks:()=>lN,getPairedParticipant:()=>yn,getParticipantEventDetails:()=>XP,getParticipantIdFinishingPositions:()=>rg,getParticipantMembership:()=>ZP,getParticipantPaymentStatus:()=>eN,getParticipantResults:()=>Zp,getParticipantScaleItem:()=>as,getParticipantSchedules:()=>tN,getParticipantSignInStatus:()=>rN,getParticipantTimeItem:()=>$E,getParticipants:()=>Nt,getPersonRequests:()=>ls,getPolicyDefinitions:()=>Do,getPositionAssignments:()=>Bu,getPositionsPlayedOff:()=>wu,getPredictiveAccuracy:()=>UN,getProfileRounds:()=>Ug,getPublishState:()=>da,getRandomQualifierList:()=>SP,getRegistrationProfile:()=>sN,getRoundMatchUps:()=>_e,getRoundVisibilityState:()=>gN,getRounds:()=>vN,getScaleValues:()=>Pc,getScaledEntries:()=>ic,getScheduledRoundsDetails:()=>Ad,getSchedulingProfile:()=>Ho,getSchedulingProfileIssues:()=>hN,getSeedingThresholds:()=>PA,getSeedsCount:()=>Id,getStructureSeedAssignments:()=>Dr,getSwissChart:()=>AP,getSwissStandings:()=>TP,getTally:()=>EP,getTeamLineUp:()=>oa,getTieFormat:()=>Ng,getTimeItem:()=>Fr,getTournamentIds:()=>Sm,getTournamentInfo:()=>fa,getTournamentPenalties:()=>yg,getTournamentPersons:()=>cN,getTournamentPoints:()=>ws,getTournamentPublishStatus:()=>Lc,getTournamentStructures:()=>VA,getTournamentTimeItem:()=>If,getValidGroupSizes:()=>Cm,getVenueData:()=>Ru,getVenuesAndCourts:()=>qn,hasLuckyRounds:()=>Wh,isAdHoc:()=>De,isCompletedStructure:()=>Bo,isEmbargoed:()=>Vo,isValidForQualifying:()=>yP,isValidMatchUpFormat:()=>Or,isVisiblyPublished:()=>go,matchUpActions:()=>ng,participantScaleItem:()=>Lo,participantScheduledMatchUps:()=>PN,positionActions:()=>hP,predictDrawCompetitiveBands:()=>ld,predictMatchUpCompetitiveBands:()=>AN,publicFindCourt:()=>mA,publicFindVenue:()=>dA,suggestFormatPlans:()=>dN,tallyParticipantResults:()=>pa,tieFormatGenderValidityCheck:()=>Yl,tournamentMatchUps:()=>Og,validMatchUp:()=>Hh,validMatchUps:()=>Ur,validateCollectionDefinition:()=>Up,validateLineUp:()=>Hf,validatePlayoffGroups:()=>Yf});function oV(){return`
|
|
5
|
+
`);if(e.length<2)return[];let r=e[0]?.split(",")??[],n=[];for(let o=1;o<e.length;o++){let i=e[o];if(!i)continue;let s=i.split(","),a={};for(let c=0;c<r.length;c++){let u=r[c];u&&(a[u]=s[c]||"")}n.push(a)}return n}function KP(t){if(!Array.isArray(t))return[];let e=new Map;for(let r of t){let n=r.match_id;e.has(n)||e.set(n,[]),e.get(n).push(r)}return Array.from(e.entries()).map(([r,n])=>({match_id:r,points:n}))}function l8(t){let e=t?.split("-")??[];if(e.length<6)return{player1:"Player 1",player2:"Player 2"};let r=e[0],n=e[2]?.replaceAll("_"," "),o=e[4]?.replaceAll("_"," ")||"Player 1",i=e[5]?.replaceAll("_"," ")||"Player 2";return{player1:o,player2:i,date:r,tournament:n}}function f8(t){if(!t||t.length===0)return;let e=t.at(-1);if(!e)return;let r=e.Set1,n=e.Set2,o=e.Set3,i=e.Set4,s=e.Set5,a=[];return r&&a.push(`${r}-${n}`),o&&a.push(`${o}-${n||"0"}`),i&&a.push(`${i}-${n||"0"}`),s&&a.push(`${s}-${n||"0"}`),a.length>0?a.join(", "):void 0}function $v(t,e={}){let{matchUpFormat:r,validateScore:n=!0,debug:o=!1}=e,i=[],s=[],a=l8(t.match_id),c=f8(t.points),u,p=!1;r?u=r:c?(u=Km(c),p=!0,o&&console.log(`Deduced format: ${u} from score: ${c}`)):(u="SET3-S:6/TB7",p=!0,s.push("No format provided, using default SET3-S:6/TB7")),o&&(console.log(`Validating match: ${a.player1} vs ${a.player2}`),console.log(`Format: ${u}`),console.log(`Total points: ${t.points.length}`),c&&console.log(`Expected score: ${c}`));let d=ds({matchUpFormat:u,matchUpId:t.match_id});d.sides[0]&&(d.sides[0].participant={participantId:"player1",participantName:a.player1,participantType:"INDIVIDUAL",participantRole:"COMPETITOR"}),d.sides[1]&&(d.sides[1].participant={participantId:"player2",participantName:a.player2,participantType:"INDIVIDUAL",participantRole:"COMPETITOR"});let m=S8(t.points,d,{errors:i,debug:o});d=m.matchUp;let l=T8(d,c,{errors:i,warnings:s,validateScore:n,debug:o});return{valid:i.length===0,errors:i,warnings:s,matchUp:d,pointsProcessed:m.pointsProcessed,expectedScore:c,actualScore:l.actualScore,scoreMatches:l.scoreMatches,formatDeduced:p,aces:m.aces,doubleFaults:m.doubleFaults,winners:m.winners,unforcedErrors:m.unforcedErrors,forcedErrors:m.forcedErrors}}function g8(t,e){if(t.history?.points&&t.history.points.length>0){let r=t.history.points.at(-1);r&&(e.result&&(r.result=e.result),e.stroke&&(r.stroke=e.stroke),e.hand&&(r.hand=e.hand),e.serve&&(r.serve=e.serve),e.serveLocation&&(r.serveLocation=e.serveLocation),e.rally&&(r.rally=e.rally),e.rallyLength&&(r.rallyLength=e.rallyLength),e.code&&(r.code=e.code))}}function I8(t,e){t==="Ace"&&e.aces++,t==="Double Fault"&&e.doubleFaults++,t==="Winner"&&e.winners++,t==="Unforced Error"&&e.unforcedErrors++,t==="Forced Error"&&e.forcedErrors++}function h8(t,e,r,n,o,i,s){let a=t.Svr==="1"?0:1;try{let c=qP(t,a),u={winner:c.winner,server:c.server};if(e=xs(e,u),g8(e,c),I8(c.result,s),o&&(r<5||r===n-1)){let p=ms(e);console.log(`Point ${r+1}: ${c.result||"Rally"} \u2192 ${p.scoreString}`)}return{matchUp:e,processed:!0}}catch(c){let u=c instanceof Error?c.message:String(c);return i.push(`Point ${r+1}: ${u}`),o&&console.error(`Point ${r+1} failed:`,u),{matchUp:e,processed:!1}}}function S8(t,e,r){let{errors:n,debug:o}=r,i=e,s=0,a={aces:0,doubleFaults:0,winners:0,unforcedErrors:0,forcedErrors:0};for(let c=0;c<t?.length;c++){let u=t[c];if(!u)continue;let p=h8(u,i,c,t.length,o,n,a);i=p.matchUp,p.processed&&s++}return{matchUp:i,pointsProcessed:s,...a}}function T8(t,e,r){let{errors:n,warnings:o,validateScore:i,debug:s}=r,c=ms(t).scoreString,u=t.matchUpStatus==="COMPLETED";u||o.push(`Match not complete. Final score: ${c}`);let p;if(i&&e){let d=BG(e),m=BG(c);p=d===m,p||n.push(`Score mismatch: expected "${e}", got "${c}"`),s&&(console.log(`Expected: ${e} \u2192 ${d}`),console.log(`Actual: ${c} \u2192 ${m}`),console.log(`Score matches: ${p}`))}return s&&(console.log(`Final score: ${c}`),console.log(`Match complete: ${u}`),console.log("Stats logged in processValidationPoints")),{actualScore:c,scoreMatches:p}}function BG(t){return t.replaceAll(/\s+/g,"").replaceAll(",",", ").toLowerCase()}function HG(t){let{csvData:e,matchId:r,matchUpFormat:n,debug:o=!1}=t,i=[],s=[],a=[],c;try{c=$P(e)}catch(h){let S=h instanceof Error?h.message:String(h);return i.push(`Failed to parse CSV: ${S}`),{valid:!1,errors:i,warnings:s,matchesProcessed:0,pointsProcessed:0,matchUps:[],totalAces:0,totalDoubleFaults:0,totalWinners:0,totalUnforcedErrors:0,totalForcedErrors:0}}let u=KP(c);o&&console.log(`Parsed ${c.length} points from ${u.length} matches`);let p=r?u.filter(h=>h.match_id===r):u;if(p.length===0)return i.push(r?`Match ID not found: ${r}`:"No matches found in CSV data"),{valid:!1,errors:i,warnings:s,matchesProcessed:0,pointsProcessed:0,matchUps:[],totalAces:0,totalDoubleFaults:0,totalWinners:0,totalUnforcedErrors:0,totalForcedErrors:0};let d=0,m=0,l=0,f=0,g=0,I=0;for(let h of p){let S=$v(h,{matchUpFormat:n,debug:o});S.valid||i.push(...S.errors),s.push(...S.warnings),a.push(S.matchUp),d+=S.pointsProcessed,m+=S.aces,l+=S.doubleFaults,f+=S.winners,g+=S.unforcedErrors,I+=S.forcedErrors}return{valid:i.length===0,errors:i,warnings:s,matchesProcessed:p.length,pointsProcessed:d,matchUps:a,totalAces:m,totalDoubleFaults:l,totalWinners:f,totalUnforcedErrors:g,totalForcedErrors:I}}function WG(t){return JSON.stringify(t,null,2)}function jG(t){let{existingDrawDefinition:e,hydrateCollections:r,enforceGender:n,tieFormatName:o,tieFormatId:i,matchUpType:s,eventType:a,isMock:c,event:u}=t,{tieFormat:p,matchUpFormat:d}=t;if(s===Ce&&a===Ce){let m=e?.structures?.find(({stage:g})=>g===j)?.tieFormat,l=i&&u?.tieFormats?.find(g=>g.tieFormatId===i),f=Qo(u);p=p||l||m||o&&u?.tieFormats?.find(g=>g.tieFormatName===o)||o&&f?.tieFormatName===o&&f||o&&Eo({namedFormat:o,hydrateCollections:r,isMock:c,event:u})||f||Eo({event:u,isMock:c,hydrateCollections:r}),d=void 0}else d||(p=void 0,u?.matchUpFormat||(d=kn));if(p){let m=ur({gender:u?.gender,enforceGender:n,tieFormat:p});if(m.error)return m}return{tieFormat:p,matchUpFormat:d}}function YG(t){let e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:r,appliedPolicies:n,qualifyingOnly:o,drawEntries:i,structureId:s,tieFormat:a,idPrefix:c,isMock:u,event:p}=t,d=t.qualifyingProfiles,m=d?.length?DP({hasExistingDrawDefinition:!0,uuids:t.uuids,qualifyingProfiles:d,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,idPrefix:c,isMock:u}):void 0;if(m?.error)return m;e.structures=e.structures?.filter(({structureId:S})=>S!==r);let l=new Set((e.structures??[]).map(S=>S.structureId));e.links=e.links?.filter(({source:S})=>S.structureId!==r&&l.has(S.structureId));let{qualifyingDrawPositionsCount:f,qualifyingDetails:g}=m??{};f&&(m?.structures&&e.structures?.push(...m.structures),m?.links&&e.links?.push(...m.links));let I=e.structures?.find(({stage:S,stageSequence:T})=>S===j&&T===1);y8({drawDefinition:e,drawEntries:i,event:p});let h=E8({mainStructure:I,qualifyingDetails:g,drawDefinition:e});return h.error?h:{drawDefinition:e,structureId:s}}function y8({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===rt)){let o={...n,entryStage:n.entryStage??j,drawDefinition:t,event:r};Ff(o)}}function E8({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&&la({targetStructureId:t.structureId,sourceStructureId:i,sourceRoundNumber:o,finishingPositions:a,targetEntryRound:s,linkType:c})?.link;if(u?.error)return u;u&&(r.links??=[],r.links.push(u))}return{error:void 0}}function Ig(t){let{participantIds:e}=t,r=t.targetStage,n=t.drawDefinition?.entries?.filter(o=>{let i=o.entryStatus;return!(t.restrictEntryStatus&&!yr.includes(i)||r&&(o.entryStage??j)!==r)}).map(lt)??[];if(e){let o=e.filter(i=>!n?.includes(i));if(o?.length)return M({result:{error:Hr},info:{invalidParticipantIds:o}})}else e=n;return t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>e.length-1&&(!t.enableDoubleRobin||t.roundsCount>(e.length-1)*2)?{error:O,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:O,info:"roundsCount must be less than 32"}:{participantIds:e}}function hg(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=Ig(t);if(p.error)return p;for(let d of J(1,r+1)){let m=Vc({restrictMatchUpsCount:t.restrictMatchUpsCount,ignoreLastRoundNumber:!!u,newRound:!u,drawDefinition:n,matchUpsCount:o,structureId:i,roundNumber:u,idPrefix:s,isMock:a,event:c});if(m.error)return M({result:m,info:{iteration:d}});m.matchUps?.length&&e.push(...m.matchUps),u=(m?.roundNumber??1)+1}return{matchUps:e}}function Td(t){let e=P8(t);if(e?.error)return e;let r=Ig(t);if(r.error)return r;let n=A8(t);if(n.error)return n;let o=uf(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of J(1,(t.roundsCount??1)+1)){let d=ug({...t,participantIds:r.participantIds,structure:n.structure,ignoreLastRoundNumber:!0,iterationMatchUps:a,adHocRatings:o,roundNumber:u,eventType:s,isMock:i});if(d.error)return d;let{matchUps:m,...l}=d;l.modifiedScaleValues&&(o=l.modifiedScaleValues),c.push({...l,iteration:p,matchUpsCount:m?.length}),u=(l?.roundNumber??1)+1,m?.length&&a.push(...m)}return{...P,matchUps:a,roundResults:c}}function A8(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&&ka[s.stage];return De({structure:s})&&a>(ka[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?De({structure:n})?{structure:n}:{error:Ua}:{error:Pt}}function P8(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:O,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"?{error:Ua}:!t.structureId&&t.drawDefinition.drawType&&!En(t.drawDefinition.drawType)?{error:Ua}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:O,info:"Missing Entries"}:{error:void 0}}function qG(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,idPrefix:o,isMock:i,event:s}=t,a=s?.entries?.filter(({entryStage:p,entryStatus:d})=>(!p||p===j)&&d&&yr.includes(d)),c=a?.map(lt),u=a?Math.floor(a.length/2):0;if(t.automated)return N8({...t,participantIds:c});{let p=hg({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&md({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...P}}function N8(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s,convertToELO:a,dynamicRatings:c}=t.drawMatic??{},u=Td({...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,dynamicRatings:c,convertToELO:a,structureId:n,matchUpIds:o});return u.error?u:(u?.matchUps?.length&&md({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:u.matchUps,event:t.event,structureId:n}),{...P})}function $G({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=tt({drawDefinition:s,structureId:c});if(p.error)return p;let d=p.structure;if(!d)return{error:Pt};let{positionAssignments:m}=pe({structure:d}),l=m?.length||0;if(u>l)return{error:wU};let f=d.structures?.length,g=It(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=sS({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=Id({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[Xn]&&u>h&&e&&(u=h),d.seedLimit=u,d.seedAssignments=J(1,u+1).map(S=>{let T=I?.find(A=>A.includes(S)),y=T&&Math.min(...T),E=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:E}}),Lt({drawDefinition:s,structureIds:[c]}),{...P,seedLimit:u}}function ic({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:Y};i=i??s?.entries??[];let c=i.filter(f=>(!a||!f.entryStage||f.entryStage===a)&&(!o||!f.entryStageSequence||f.entryStageSequence===o)&&yr.includes(f.entryStatus)),u={...r};return{scaledEntries:c.map(f=>{let{participantId:g}=f,{scaleItem:I}=as({tournamentRecord:e,scaleAttributes:r,participantId:g});return{...f,...I}}).filter(f=>{let g=f.scaleValue;return!n&&(Number.isNaN(g)||!Number.parseFloat(g))?!1:g}).sort(n||(t||u?.ascending===!1?m:d))};function d(f,g){return l(f)-l(g)}function m(f,g){return l(g)-l(f)}function l(f){return Number.parseFloat(f.scaleValue||(t?-1:1e5))}}function zP(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=hn({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 M({result:{error:Pt},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=O8({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&R8({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&!En(t.drawType)&&!(t.qualifyingOnly&&t.stage!==rt),d=(n?.length||0)>1,m=p?U8({...t,multipleStructures:d,seedLimit:u,structureId:s}):{};if(m?.error)return M({result:m,stack:e});if(!p&&En(t.drawType)&&i?.positionAssignments?.length){let l=t.qualifiersCount||0;if(l>0){let f=i.positionAssignments.filter(g=>!g.participantId&&!g.qualifier&&!g.bye);for(let g=0;g<l&&g<f.length;g++)f[g].qualifier=!0}}return{...m,stageEntries:c,structureId:s,seedsCount:a}}function D8({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=qt({name:Xr,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&rs.includes(o.entryStatus)})}function U8(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Gu({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function R8(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(lt);e?b8({...t,enteredParticipantIds:i}):(o||r)&&C8({...t,enteredParticipantIds:i})}function b8(t){let{provisionalPositioning:e,enteredParticipantIds:r,seededParticipants:n,tournamentRecord:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,structure:u,event:p}=t,d=u?Ai({provisionalPositioning:e,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structure:u}):void 0;n.filter(({participantId:m})=>r.includes(m)).filter(m=>!m.seedNumber||m.seedNumber<=n.length).sort((m,l)=>m.seedNumber<l.seedNumber?-1:m.seedNumber<l.seedNumber?1:0).forEach(m=>{let{participantId:l,seedNumber:f,seedValue:g}=m;Qa({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:d,structureId:c,seedNumber:f,seedValue:g,event:p})})}function C8(t){let e=t.seedsCount,{provisionalPositioning:r,enteredParticipantIds:n,seedAssignmentProfile:o,assignSeedsCount:i,tournamentRecord:s,drawDefinition:a,seedByRanking:c,seedingProfile:u,structureId:p,event:d}=t,{categoryName:m,ageCategoryCode:l}=d?.category??{},f=d?.eventType,g=M8({...t,ageCategoryCode:l,categoryName:m,eventType:f})||c&&v8({...t,ageCategoryCode:l,categoryName:m,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:E}=h,A=o?.[T]||E||T;Qa({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:A,event:d})})}function M8(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:_o,eventType:u};return ic({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function v8(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category??{},c=n?.eventType;return ic({scaleAttributes:{scaleName:s||a,scaleType:co,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function O8(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=D8(t);e>r.length&&(e=r.length);let{seedLimit:n}=$G({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 KG(t){let e=ag({...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:d,drawType:m,entries:l}=t,f=[],g=[],I=_8({suppressDuplicateEntries:n,ignoreStageSpace:o,qualifyingOnly:s,drawDefinition:r,drawEntries:u,drawType:m,entries:l});if(I.error)return I;let{qualifyingPlaceholder:h,qualifyingProfiles:S,qualifiersCount:T}=t,y=r?.structures?.find(R=>R.stage===j&&R.stageSequence===1)?.structureId,E=y&&r?.links?.some(R=>R.target?.structureId===y&&R.source?.structureId);if(h&&!S?.length&&T&&r&&y&&!E){let R=gr({structureName:Be(rt),stage:rt,qualifyingOnly:s,tieFormat:t.tieFormat}),{link:U}=la({sourceStructureId:R.structureId,targetStructureId:y,qualifyingPositions:T,sourceRoundNumber:0,linkType:fn});r.structures??=[],r.structures.push(R),r.links??=[],r.links.push(U)}let A=cn(m)?0:st(t.seedsCount??0),N=zP({...t,qualifyingOnly:!d||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:j,seedsCount:A,placeByes:p,drawSize:d,entries:l});if(N.error&&!N.conflicts)return N;N.positioningReport?.length&&f.push({[j]:N.positioningReport});let D=N.structureId;return N.conflicts&&(g=N.conflicts),En(m)&&t.roundsCount&&qG({...t,drawDefinition:r,structureId:D}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:D}}function _8(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,qualifyingOnly:i,entries:s}=t;for(let a of s){if(a.entryStatus===On)continue;let c=!!(n&&a.entryStage&&a.entryStage!==j&&!(i&&a.entryStage===rt)),u={...a,ignoreStageSpace:e??(c||En(o)),entryStage:a.entryStage??j,event:t.event,drawDefinition:r,drawType:o},p=Ff(u);if(n&&!c&&p.error)return p}return{error:void 0}}var x8=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var zG=x8;function QG(t){let{drawId:e=ot(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=zG();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function Sg(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=X(t,[{[zt]:!0,[tf]:!0}]);if(c.error)return c;if(!Or({matchUpFormat:o}))return{error:nu};let u="setMatchUpFormat";if(s){let p=Ft({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let d=p.matchUp;if(d?.matchUpType===Ce)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:mr};d&&(d.matchUpFormat=o,mt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:d}))}else if(Array.isArray(e)){if(a?.eventType===Ce)return{error:so};for(let p of e){let d=tt({drawDefinition:n,structureId:p});if(d.error)return d;d.structure&&(d.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===Ce)return{error:so};let p=tt({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),Lt({drawDefinition:n,structureIds:e}),{...P}}function JG({tieFormat:t}){let e=ur({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId??=ot();return{tieFormat:t}}function XG({existingQualifyingStructures:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUpType:o,tieFormat:i,event:s}){if((n||i)&&!(n&&s?.matchUpFormat===n||s?.tieFormat&&i&&JSON.stringify(s.tieFormat)===JSON.stringify(i))){if(i){let c=JG({tieFormat:i});if(c.error)return c;let u=t?.every(p=>p.tieFormat);(!t?.length||u)&&(r.tieFormat=c.tieFormat??i)}else if(n){let c=Sg({tournamentRecord:e,drawDefinition:r,matchUpFormat:n,event:s});if(c.error)return{info:"matchUpFormat or tieFormat error",error:c.error}}o&&(r.matchUpType=o)}return{error:void 0}}var Jv={};_t(Jv,{attachPolicies:()=>_s,findPolicy:()=>Uo,getAppliedPolicies:()=>gt,getPolicyDefinitions:()=>Do,mutate:()=>zv,query:()=>Qv,removePolicy:()=>Kv});var zv={};_t(zv,{attachPolicies:()=>_s,removePolicy:()=>Kv});function Kv(t){let e=X(t,[{[CF]:!0,_anyOf:{[Ne]:!1,[Z]:!1,[zt]:!1,[me]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return ZG(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:Y};for(let i of o){let s=t.tournamentRecords[i],a=ZG(t,s);if(a.error)return a;r=!0}}else return{error:Y};return r?{...P}:{error:lp}}function ZG(t,e){let r=gt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?Qt({element:e,extension:{name:wp,value:r}}):Mn({element:e,name:wp}),{...P}):{error:lp}}var Qv={};_t(Qv,{findPolicy:()=>Uo,getAppliedPolicies:()=>gt,getPolicyDefinitions:()=>Do});var Xv={[Xn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[sn]:{positioning:qi},[_r]:{positioning:qi}},positioning:Ub},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}]}},jS=Xv;function tV({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return M({info:"policyDefinitions must be an object",result:{error:O},stack:n});let o={[Nc]:t?.[Nc]};return e?w8({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&_s({drawDefinition:r,policyDefinitions:o}),!t?.[Xn]&&!e?.[Xn]&&(_s({policyDefinitions:jS,drawDefinition:r}),t&&Object.assign(t,jS)),{error:void 0}}function w8({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&&(_s({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function eV(t){let{tournamentRecord:e,policyDefinitions:r,appliedPolicies:n,matchUpFormat: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,d=p?.structures?.find(h=>h.stage===j&&h.stageSequence===1)?.structureId,m=p?p.structures?.filter(h=>h.stage===rt):[],l=m?.length===1&&!m[0].matchUps?.length&&m[0].structureId;p&&a!==p.drawType&&!l&&(p.drawType=a);let f=p??QG({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),g=XG({existingQualifyingStructures:m,tournamentRecord:e,drawDefinition:f,matchUpFormat:o,matchUpType:i,tieFormat:s,event:u});if(g.error)return M({result:g,stack:c});let I=tV({appliedPolicies:n,policyDefinitions:r,drawDefinition:f,stack:c});return I.error?I:{drawDefinition:f,structureId:d,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:l}}function rV(t){let e="generateOrGetExisting",r=[],n=[],o=eV(t);if(o.error)return M({result:o,stack:e});let i=o.existingDrawDefinition,s,a,c=t.drawEntries??t.eventEntries??[],u=!!(o.existingDrawDefinition&&o.structureId&&!o.existingQualifyingPlaceholderStructureId&&t.qualifyingProfiles?.length),p=(o.existingQualifyingPlaceholderStructureId||u)&&YG({...t,...o})||KG({...t,...o,entries:c});return p.error?M({result:p,stack:e}):(p.positioningReports?.length&&r.push(...p.positioningReports??[]),p.conflicts?.length&&n.push(...p.conflicts??[]),s=p.drawDefinition,a=p.structureId,{existingDrawDefinition:i,positioningReports:r,drawDefinition:s,structureId:a,conflicts:n,entries:c})}function nV(t){let{qualifyingPlaceholder:e,existingDrawDefinition:r,positioningReports:n,qualifyingProfiles:o,appliedPolicies:i,qualifyingOnly:s,drawDefinition:a,seedingProfile:c,participants:u,structureId:p,tieFormat:d,entries:m,stack:l}=t,f=e&&!o?.length&&!r,g=[];if(o){let I=L8({qualifyingProfiles:o,qualifyingConflicts:g,positioningReports:n,seedingProfile:c,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,participants:u,entries:m,params:t,stack:l});if(I?.error)return I}else if(p&&f&&!a.structures?.find(h=>h.stage===rt&&!h.matchUps?.length)){let h=gr({structureName:Be(rt),stage:rt,qualifyingOnly:s,tieFormat:d}),S=t.qualifiersCount,{link:T}=la({sourceStructureId:h.structureId,targetStructureId:p,sourceRoundNumber:0,qualifyingPositions:S,linkType:fn});a.structures??=[],a.structures.push(h),a.links??=[],a.links.push(T)}return{qualifyingConflicts:g,error:void 0}}function L8({qualifyingProfiles:t,qualifyingConflicts:e,positioningReports:r,seedingProfile:n,appliedPolicies:o,drawDefinition:i,qualifyingOnly:s,participants:a,entries:c,params:u,stack:p}){let d=(g,I)=>g.stageSequence-I.stageSequence,m=(g,I)=>g.roundTarget-I.roundTarget,l=[],f=1;t.sort(m);for(let g of t){if(!Array.isArray(g.structureProfiles))return M({info:xi("structureProfiles"),result:{error:nt},stack:p});f=g.roundTarget||f;let I=g.structureProfiles?.sort(d)??[],h=1;for(let S of I){let T=F8({structureProfile:S,preparedStructureIds:l,seedingProfile:n,appliedPolicies:o,drawDefinition:i,qualifyingOnly:s,participants:a,roundTarget:f,sequence:h,entries:c,params:u});if(T.error)return T;T.structureId&&l.push(T.structureId),h+=1,T.conflicts?.length&&e.push(...T.conflicts),T.positioningReport?.length&&r.push({[rt]:T.positioningReport})}f+=1}}function F8({structureProfile:t,preparedStructureIds:e,seedingProfile:r,appliedPolicies:n,drawDefinition:o,qualifyingOnly:i,participants:s,roundTarget:a,sequence:c,entries:u,params:p}){let{qualifyingRoundNumber:d,qualifyingPositions:m,seededParticipants:l,seedingScaleName:f,seedsCount:g=0,seedByRanking:I,placeByes:h,drawSize:S}=t;return zP({...p,seedingProfile:t.seedingProfile??r,stageSequence:c,qualifyingRoundNumber:d,preparedStructureIds:e,qualifyingPositions:m,seededParticipants:l,stage:rt,seedingScaleName:f,appliedPolicies:n,drawDefinition:o,qualifyingOnly:i,seedByRanking:I,participants:s,roundTarget:a,seedsCount:g,placeByes:h,drawSize:S,entries:u})}function QP(t){let{drawDefinition:e,appliedPolicies:r}=t,n=r?.[$o],o=ye({drawDefinition:e});return e.structures?.forEach(i=>{let s=Jo({structureId:i.structureId,matchUpsMap:o}),a=rA({roundNamingPolicy:n,drawDefinition:e,structure:i,matchUps:s}),{roundNamingProfile:c,roundProfile:u}=a;(i.structures||[i]).forEach(d=>{(d.matchUps??[]).forEach(m=>{let l=m?.roundNumber?.toString();if(l){let f=c?.[l]?.roundName,g=c?.[l]?.abbreviatedRoundName,I=u?.[l]?.feedRound;Object.assign(m,{abbreviatedRoundName:g,feedRound:I,roundName:f})}})})}),{drawDefinition:e}}var TO={};_t(TO,{addGoesTo:()=>bs,allCompetitionMatchUps:()=>un,allDrawMatchUps:()=>sr,allEventMatchUps:()=>_n,allPlayoffPositionsFilled:()=>BA,allTournamentMatchUps:()=>jt,analyzeDraws:()=>dd,analyzeMatchUp:()=>rl,analyzeTournament:()=>mN,bulkUpdatePublishedEventIds:()=>fN,calculateMatchUpMargin:()=>Lm,calculateWinCriteria:()=>Sa,categoryCanContain:()=>Dp,checkMatchUpIsComplete:()=>ia,checkValidEntries:()=>ig,cleanExpiredMutationLocks:()=>oN,compareTieFormats:()=>Pi,competitionScheduleMatchUps:()=>Pd,courtGridRows:()=>Rg,credits:()=>oV,drawMatchUps:()=>ON,eventMatchUps:()=>vg,filterMatchUps:()=>os,filterParticipants:()=>rd,findDrawDefinition:()=>iP,findExtension:()=>qt,findVenue:()=>Wn,getAggregateTeamResults:()=>aN,getAllDrawMatchUps:()=>re,getAllEventData:()=>IN,getAllStructureMatchUps:()=>ht,getAllowedDrawTypes:()=>Tg,getAllowedMatchUpFormats:()=>nN,getApplicableAwardProfileLevels:()=>Jm,getAppliedPolicies:()=>gt,getAssignedParticipantIds:()=>ss,getAvailableMatchUpsCount:()=>Zf,getAvailablePlayoffProfiles:()=>sd,getCategoryAgeDetails:()=>Es,getCheckedInParticipantIds:()=>ta,getCompetitionDateRange:()=>Eg,getCompetitionFormat:()=>DN,getCompetitionLeaderboard:()=>LE,getCompetitionMatchUps:()=>el,getCompetitionParticipantState:()=>wE,getCompetitionParticipants:()=>JP,getCompetitionPenalties:()=>iN,getCompetitionPolicy:()=>wo,getCompetitionState:()=>Ko,getCompetitionVenues:()=>km,getCourtInfo:()=>Mf,getCourts:()=>_N,getDraftState:()=>PP,getDrawData:()=>eg,getDrawDefinitionTimeItem:()=>qE,getDrawParticipantRepresentativeIds:()=>eP,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>gd,getEligibleVoluntaryConsolationParticipants:()=>tP,getEntriesAndSeedsCount:()=>bg,getEvent:()=>LN,getEventData:()=>fd,getEventMatchUpFormatTiming:()=>EN,getEventProperties:()=>xN,getEventPublishStatus:()=>br,getEventRankingPoints:()=>Xm,getEventStructures:()=>lS,getEventTimeItem:()=>$p,getEvents:()=>wN,getFlightProfile:()=>Gt,getHomeParticipantId:()=>bN,getLinkedTournamentIds:()=>Bp,getLuckyDrawRoundStatus:()=>zf,getMatchUpCompetitiveProfile:()=>Xs,getMatchUpContextIds:()=>RN,getMatchUpDailyLimits:()=>_g,getMatchUpDailyLimitsUpdate:()=>NN,getMatchUpDependencies:()=>en,getMatchUpFormat:()=>CN,getMatchUpFormatTiming:()=>Qp,getMatchUpFormatTimingUpdate:()=>yN,getMatchUpScheduleDetails:()=>vf,getMatchUpType:()=>Of,getMatchUpsMap:()=>ye,getMatchUpsStats:()=>MN,getMatchUpsToSchedule:()=>Dg,getMaxEntryPosition:()=>SN,getModifiedMatchUpFormatTiming:()=>Cg,getMutationLocks:()=>lN,getPairedParticipant:()=>yn,getParticipantEventDetails:()=>XP,getParticipantIdFinishingPositions:()=>rg,getParticipantMembership:()=>ZP,getParticipantPaymentStatus:()=>eN,getParticipantResults:()=>Zp,getParticipantScaleItem:()=>as,getParticipantSchedules:()=>tN,getParticipantSignInStatus:()=>rN,getParticipantTimeItem:()=>$E,getParticipants:()=>Nt,getPersonRequests:()=>ls,getPolicyDefinitions:()=>Do,getPositionAssignments:()=>Bu,getPositionsPlayedOff:()=>wu,getPredictiveAccuracy:()=>UN,getProfileRounds:()=>Ug,getPublishState:()=>da,getRandomQualifierList:()=>SP,getRegistrationProfile:()=>sN,getRoundMatchUps:()=>_e,getRoundVisibilityState:()=>gN,getRounds:()=>vN,getScaleValues:()=>Pc,getScaledEntries:()=>ic,getScheduledRoundsDetails:()=>Ad,getSchedulingProfile:()=>Ho,getSchedulingProfileIssues:()=>hN,getSeedingThresholds:()=>PA,getSeedsCount:()=>Id,getStructureSeedAssignments:()=>Dr,getSwissChart:()=>AP,getSwissStandings:()=>TP,getTally:()=>EP,getTeamLineUp:()=>oa,getTieFormat:()=>Ng,getTimeItem:()=>Fr,getTournamentIds:()=>Sm,getTournamentInfo:()=>fa,getTournamentPenalties:()=>yg,getTournamentPersons:()=>cN,getTournamentPoints:()=>ws,getTournamentPublishStatus:()=>Lc,getTournamentStructures:()=>VA,getTournamentTimeItem:()=>If,getValidGroupSizes:()=>Cm,getVenueData:()=>Ru,getVenuesAndCourts:()=>qn,hasLuckyRounds:()=>Wh,isAdHoc:()=>De,isCompletedStructure:()=>Bo,isEmbargoed:()=>Vo,isValidForQualifying:()=>yP,isValidMatchUpFormat:()=>Or,isVisiblyPublished:()=>go,matchUpActions:()=>ng,participantScaleItem:()=>Lo,participantScheduledMatchUps:()=>PN,positionActions:()=>hP,predictDrawCompetitiveBands:()=>ld,predictMatchUpCompetitiveBands:()=>AN,publicFindCourt:()=>mA,publicFindVenue:()=>dA,suggestFormatPlans:()=>dN,tallyParticipantResults:()=>pa,tieFormatGenderValidityCheck:()=>Yl,tournamentMatchUps:()=>Og,validMatchUp:()=>Hh,validMatchUps:()=>Ur,validateCollectionDefinition:()=>Up,validateLineUp:()=>Hf,validatePlayoffGroups:()=>Yf});function oV(){return`
|
|
6
6
|
This project would not have been possible without the generous input and patience
|
|
7
7
|
of tournament organizers and directors who worked with early versions of CourtHive/TMX.
|
|
8
8
|
|