tods-competition-factory 2.2.46 → 2.2.48
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 +3 -3
- package/dist/tods-competition-factory.development.cjs.js +9 -12
- 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 +4 -4
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var yL=Object.defineProperty;var Xt=(t,e)=>{for(var r in e)yL(t,r,{get:e[r],enumerable:!0})};function Ka(){return"2.2.46"}var bE={};Xt(bE,{competitionGovernor:()=>kU,drawsGovernor:()=>GN,entriesGovernor:()=>qN,eventGovernor:()=>iM,generationGovernor:()=>pM,matchUpFormatGovernor:()=>jy,matchUpGovernor:()=>bM,mocksGovernor:()=>PI,participantGovernor:()=>sR,policyGovernor:()=>gN,publishingGovernor:()=>gR,queryGovernor:()=>FN,reportGovernor:()=>IR,scheduleGovernor:()=>RR,scoreGovernor:()=>Jg,tieFormatGovernor:()=>kR,tournamentGovernor:()=>XR,venueGovernor:()=>aC});var kU={};Xt(kU,{getLinkedTournamentIds:()=>fu,getTournamentIds:()=>Np,linkTournaments:()=>_U,mutate:()=>LU,query:()=>FU,unlinkTournament:()=>wU,unlinkTournaments:()=>xU});var LU={};Xt(LU,{linkTournaments:()=>_U,unlinkTournament:()=>wU,unlinkTournaments:()=>xU});var Ia="SINGLES",Lt="SINGLES",Gi="DOUBLES",vt="DOUBLES",xr="TEAM",Wt="TEAM",IC={SINGLES_MATCHUP:Ia,SINGLES:Lt,DOUBLES_MATCHUP:Gi,DOUBLES:vt,TEAM_MATCHUP:xr,TEAM:Wt};var vI={[Lt]:[Lt,"S"],[vt]:[vt,"D"],[Wt]:[Wt,"T"],S:[Lt,"S"],D:[vt,"D"],T:[Wt,"T"]};function le(t,e){return(t??0)-(e??0)}function dt(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function Ln(t){return isNaN(t)?!1:t&&(t&t-1)===0}function xE(t){if(!t.length)return;let e=[...t].sort(le),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function hC(t){if(!Ln(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Rm(t){return isNaN(t)?0:t%2&&t+1||t}function Cm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Jt(t){return!isNaN(parseFloat(t))}function _I(t){let e=dt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function us(t){if(isNaN(t))return!1;for(;!Ln(t);)t++;return t}function Io(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function It(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function SC(t=1,e=3,r=!0){let n=0;for(let o=0;o<e;o++)n+=Math.random()*(t/e);return r&&t>1?Math.round(n):n}function EL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function wE(t,e,r,n,o=2){let i=1-Math.random(),s=1-Math.random(),a=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s);return a=a/10+.5,a>1||a<0?a=wE(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=EL(a,n)),parseFloat(a.toFixed(o))}function Hl(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function TC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function Tr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function za(t){return It(t)?t:1/0}function Er(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function yC(t){return LE(Er(t))}function LE(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function AL(t,e,r){return r.indexOf(t)===e}function xI(t){return t.filter(AL)}function tn(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function Un(t){let e=Math.floor(Math.random()*t.length);return t[e]}function tt(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function ho(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function jt(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 FE(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function ke(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function EC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function AC(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 kE(t,[e,...r]){return t.length?[t.slice(0,e),...kE(t.slice(e),[...r,e])]:[]}function UC(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 wI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function LI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Wl(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 PC(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return tt(r,n+1).filter(o=>!t.includes(o))}function Yr(t){return typeof t=="function"}function kt(t){return typeof t=="string"}function ht(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function DC(t,e){if(!ht(t)||!ht(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o of r)if(t[o]!==e[o])return!1;return!0}function kI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var NC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function FI(t,e){if(t===void 0)return null;if(!ht(t)||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>FI(i))}:{[o]:e?n(t[o]):FI(t[o])}))}function GE(t){return Array.isArray(t)?t.length+t.map(GE).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>GE(t[e])).reduce((e,r)=>e+r,0):0}function MC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=GE(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function Yc(t,e){return!Array.isArray(t)||!kt(e)?!1:jt(t,vI[e]).length}var C={success:!0},VE="error",RC={SUCCESS:C,ERROR:VE};function GI({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!==pt(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...C}}var BC={};Xt(BC,{addNotice:()=>lt,callListener:()=>wm,createInstanceState:()=>KA,cycleMutationStatus:()=>Tf,deepCopyEnabled:()=>Sf,deleteNotice:()=>eh,deleteNotices:()=>Yi,disableNotifications:()=>zA,enableNotifications:()=>hf,getDevContext:()=>Dr,getMethods:()=>yf,getNotices:()=>th,getProvider:()=>rh,getTopics:()=>Lr,getTournamentId:()=>ms,getTournamentRecord:()=>Ef,getTournamentRecords:()=>qo,globalLog:()=>JA,handleCaughtError:()=>fp,hasTopic:()=>dp,removeTournamentRecord:()=>XA,setDeepCopy:()=>Xc,setDevContext:()=>Qc,setGlobalLog:()=>kC,setGlobalMethods:()=>GC,setGlobalSubscriptions:()=>JL,setMethods:()=>VC,setStateMethods:()=>ZA,setStateProvider:()=>QL,setSubscriptions:()=>ZL,setTournamentId:()=>lp,setTournamentRecord:()=>QA,setTournamentRecords:()=>Lm,timeKeeper:()=>XL});var VI={message:"Chronological error; time violation.",code:"ANACHRONISM"},bm={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},BE={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},BI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},xt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},q={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Qa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ha={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},Sa={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},HE={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},br={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},si={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},jl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Yl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Xa={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},WE={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},jE={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},UL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},ql={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ja={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},rp={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},CC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Ls={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Fs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Om={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},np={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},HI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Za={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},cn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},YE={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},qE={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},$E={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},KE={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},zE={message:"Invalid action",code:"ERR_INVALID_ACTION"},WI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},QE={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},XE={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},JE={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},$l={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},ZE={message:"Existing round",code:"ERR_EXISTING_ROUND"},PL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Pr={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},_t={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Kl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Si={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},zl={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},tA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},$n={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Ot={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},qr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},eA={message:"Event exists",code:"ERR_EXISTING_EVENT"},rA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},nA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Ql={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},oA={message:"Missing stage",code:"ERR_MISSING_STAGE"},Vi={message:"Invalid stage",code:"ERR_INVALID_STAGE"},iA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},sA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},aA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},jI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},tc={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Xl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},bC={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},Ta={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Yo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Jl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Zl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},cA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},ks={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},sr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ps={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},we={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},no={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},mr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},dr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},YI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},op={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},DL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},uA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},qI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},pA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},$I={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},NL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},qc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},ML={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},tf={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},RL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},ef={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},CL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},bL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Bi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},st={message:"Missing value",code:"ERR_MISSING_VALUE"},mA={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},dA={message:"Missing date",code:"ERR_MISSING_DATE"},lA={message:"No valid dates",code:"ERR_NO_VALID_DATES"},vm={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},rf={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},fA={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},Ye={message:"Invalid Date",code:"ERR_INVALID_DATE"},Co={message:"Invalid time",code:"ERR_INVALID_TIME"},gA={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var KI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},IA={message:"Invalid score",code:"ERR_INVALID_SCORE"},_m={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var OC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},nf={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},hA={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},ip={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},zI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},xm={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Hi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},ln={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},wr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},SA={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Pn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},TA={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Wi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},ec={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},se={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},yA={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},re={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},EA={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},OL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},AA={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},bo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},UA={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},PA={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},DA={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Gs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},sp={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},of={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},sf={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},QI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},vC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},_C={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},NA={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},MA={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},XI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},af={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},cf={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},RA={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},uf={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},$c={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},CA={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Vs={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},bA={message:"Court exists",code:"ERR_EXISTING_COURT"},OA={message:"Venue exists",code:"ERR_EXISTING_VENUE"},ji={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},ai={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},vA={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},JI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},_A={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},xA={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},xC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},pf={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},wA={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},mf={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},df={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Kc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},LA={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},rc={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},FA={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Bs={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},kA={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},ap={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},GA={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},VA={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},So={message:"Invalid object",code:"ERR_INVALID_OBJECT"},cp={message:"Invalid gender",code:"ERR_INVALID_GENDER"},zc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},B={message:"Invalid values",code:"ERR_INVALID_VALUES"},BA={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},lf={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},HA={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},up={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},ff={message:"Value unchanged",code:"ABORT_UNCHANGED"},Oe={message:"Not found",code:"ERR_NOT_FOUND"},pp={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},WA={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},gf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},jA={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},YA={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},ZI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},If={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},nc={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},qA={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},oc={message:"Scores present",code:"ERR_SCORES_PRESENT"},wC={ANACHRONISM:VI,CANNOT_CHANGE_WINNING_SIDE:xm,CANNOT_MODIFY_TIEFORMAT:nf,CANNOT_MODIFY_PARTICIPANT_TYPE:hA,CANNOT_REMOVE_MAIN_STRUCTURE:BE,CANNOT_REMOVE_PARTICIPANTS:ip,CATEGORY_MISMATCH:zI,COURT_EXISTS:bA,COURT_NOT_FOUND:Vs,DRAW_DEFINITION_NOT_FOUND:br,DRAW_ID_EXISTS:YE,DRAW_POSITION_ACTIVE:rp,DRAW_POSITION_ASSIGNED:Xa,DRAW_POSITION_NOT_CLEARED:jE,DRAW_POSITION_NOT_FOUND:UL,DRAW_SIZE_MISMATCH:HI,DUPLICATE_ENTRY:bm,DUPLICATE_VALUE:BA,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:MA,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:NA,EVENT_EXISTS:eA,EVENT_NOT_FOUND:qr,EXISTING_DRAW_DEFINITIONS:HE,EXISTING_END_TIME:JI,EXISTING_FLIGHT:WA,EXISTING_MATCHUP_ID:YA,EXISTING_OUTCOME:jA,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Gs,EXISTING_PARTICIPANT:sp,EXISTING_POLICY_TYPE:$I,EXISTING_PROFILE:gf,EXISTING_ROUND:ZE,EXISTING_STAGE:ZI,EXISTING_STRUCTURE:If,INCOMPATIBLE_MATCHUP_STATUS:Xl,INCOMPLETE_SOURCE_STRUCTURE:jl,INSUFFICIENT_DRAW_POSITIONS:cf,INVALID_ACTION:zE,INVALID_ASSIGNMENT:WI,INVALID_BOOKINGS:vm,INVALID_CATEGORY:zc,INVALID_COLLECTION_DEFINITION:VA,INVALID_CONFIGURATION:GA,INVALID_DATE_AVAILABILITY:rf,INVALID_DATE:Ye,INVALID_DRAW_DEFINITION:Sa,INVALID_DRAW_POSITION_FOR_SEEDING:Yl,INVALID_DRAW_POSITION:Ls,INVALID_DRAW_SIZE:np,INVALID_END_TIME:vA,INVALID_ENTRIES:nA,INVALID_EVENT_TYPE:$n,INVALID_GAME_SCORES:KI,INVALID_GENDER:cp,INVALID_MATCHUP_FORMAT:Jl,INVALID_MATCHUP_STATUS:Ta,INVALID_MATCHUP_STATUS_BYE:aA,INVALID_MATCHUP:dr,INVALID_OBJECT:So,INVALID_PARTICIPANT_ID:ln,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:SA,INVALID_PARTICIPANT_SEEDING:qE,INVALID_PARTICIPANT_TYPE:Pn,INVALID_PARTICIPANT:Hi,INVALID_POLICY_DEFINITION:pA,INVALID_RECORDS:BI,INVALID_SCALE_ITEM:rc,INVALID_SEED_NUMBER:XE,INVALID_SEED_POSITION:JE,INVALID_SET_NUMBER:RL,INVALID_SIDE_NUMBER:tf,INVALID_SCORE:IA,INVALID_STAGE:Vi,INVALID_START_TIME:xA,INVALID_STRUCTURE:si,INVALID_STOP_TIME:_A,INVALID_TIE_FORMAT:Yo,INVALID_TIME:Co,INVALID_TIME_ITEM:pf,INVALID_TOURNAMENT_DATES:gA,INVALID_TOURNAMENT_RECORD:Qa,INVALID_VALUES:B,INVALID_WINNING_SIDE:_m,MATCHUP_NOT_FOUND:we,METHOD_NOT_FOUND:nc,MISSING_ASSIGNMENTS:Ql,MISSING_ASYNC_STATE_PROVIDER:wA,MISSING_AVOIDANCE_POLICY:uA,MISSING_BIRTH_DATE:mA,MISSING_COLLECTION_DEFINITION:cA,MISSING_COURT_ID:Bi,MISSING_COURTS_INFO:CA,MISSING_DATE_AVAILABILITY:fA,MISSING_DATE:dA,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:cn,MISSING_DRAW_POSITION:Fs,MISSING_DRAW_POSITIONS:Ja,MISSING_DRAW_SIZE:Za,MISSING_ENTRIES:rA,MISSING_EVENT:Ot,MISSING_QUALIFIED_PARTICIPANTS:yA,MISSING_MATCHUP_FORMAT:Zl,MISSING_MATCHUP_ID:sr,MISSING_MATCHUP_IDS:ps,MISSING_MATCHUP:mr,MISSING_MATCHUPS:no,MISSING_PARTICIPANT_COUNT:UA,MISSING_PARTICIPANT_ID:se,MISSING_PARTICIPANT_IDS:bo,MISSING_PARTICIPANT_ROLE:TA,MISSING_PARTICIPANT:Wi,MISSING_PARTICIPANTS:ec,MISSING_PENALTY_ID:uf,MISSING_PENALTY_TYPE:RA,MISSING_PERSON_DETAILS:DA,MISSING_POLICY_ATTRIBUTES:qI,MISSING_POLICY_DEFINITION:op,MISSING_POLICY_TYPE:YI,MISSING_POSITION_ASSIGNMENTS:sA,MISSING_ROUND_NUMBER:PL,MISSING_SCHEDULE:LA,MISSING_SCORING_POLICY:ML,MISSING_SEED_ASSIGNMENTS:QE,MISSING_SEEDCOUNT_THRESHOLDS:KE,MISSING_SEEDING_POLICY:DL,MISSING_SET_NUMBER:CL,MISSING_SET_OBJECT:ef,MISSING_SIDE_NUMBER:bL,MISSING_STAGE:oA,MISSING_STRUCTURE_ID:Pr,MISSING_STRUCTURE:Si,MISSING_MAIN_STRUCTURE:zl,MISSING_STRUCTURES:Kl,MISSING_TARGET_LINK:$l,MISSING_TIE_FORMAT:ks,MISSING_TIME_ITEM:mf,MISSING_TIME_ITEMS:df,MISSING_TOURNAMENT_ID:ha,MISSING_TOURNAMENT_RECORD:q,MISSING_TOURNAMENT_RECORDS:xt,MISSING_VALUE:st,MISSING_VENUE_ID:ai,MODIFICATIONS_FAILED:FA,NO_CANDIDATES:ap,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:af,NO_MODIFICATIONS_APPLIED:Bs,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:XI,NO_PARTICIPANT_REMOVED:AA,NO_VALID_ACTIONS:HA,NO_VALID_ATTRIBUTES:up,NO_VALID_DATES:lA,NOT_FOUND:Oe,NOT_IMPLEMENTED:pp,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:of,PARTICIPANT_ID_EXISTS:EA,PARTICIPANT_NOT_CHECKED_IN:PA,PARTICIPANT_NOT_FOUND:re,PARTICIPANT_PAIR_EXISTS:OL,PENALTY_NOT_FOUND:$c,POLICY_NOT_ATTACHED:NL,POLICY_NOT_FOUND:qc,SCHEDULE_NOT_CLEARED:WE,SCHEDULED_MATCHUPS:qA,SCORES_PRESENT:oc,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:$E,STAGE_SEQUENCE_LIMIT:iA,STRUCTURE_NOT_FOUND:_t,TEAM_NOT_FOUND:lf,UNABLE_TO_ASSIGN_COURT:kA,UNLINKED_STRUCTURES:tA,UNRECOGNIZED_DRAW_TYPE:ql,UNRECOGNIZED_MATCHUP_FORMAT:tc,UNRECOGNIZED_MATCHUP_STATUS:jI,VALUE_UNCHANGED:ff,VENUE_EXISTS:OA};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},$A={addNotice:WL,callListener:KL,cycleMutationStatus:HL,deleteNotice:qL,deleteNotices:YL,disableNotifications:vL,enableNotifications:_L,getMethods:mp,getNotices:jL,getTopics:$L,getTournamentId:LC,getTournamentRecord:xL,getTournamentRecords:wL,removeTournamentRecord:GL,setMethods:BL,setSubscriptions:VL,setTournamentId:FL,setTournamentRecord:LL,setTournamentRecords:kL,handleCaughtError:zL};function vL(){Ze.disableNotifications=!0}function _L(){Ze.disableNotifications=!1}function LC(){return Ze.tournamentId}function xL(t){return Ze.tournamentRecords[t]}function wL(){return Ze.tournamentRecords}function LL(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Qa}}function FL(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:q}:(Ze.tournamentId=void 0,{success:!0})}function kL(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function GL(t){if(typeof t!="string")return{error:B};if(!Ze.tournamentRecords[t])return{error:Oe};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function VL(t){return typeof t.subscriptions!="object"?{error:B}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ze.subscriptions[e]=t.subscriptions[e]:delete Ze.subscriptions[e]}),{...C})}function BL(t){return typeof t!="object"?{error:B}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...C})}function HL(){let t=Ze.modified;return Ze.modified=!1,t}function WL({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...C}}function mp(){return Ze.methods??{}}function jL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function YL(){Ze.notices=[]}function qL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function $L(){return{topics:Object.keys(Ze.subscriptions)}}function KL({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function zL({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:LC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var ve={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},un=$A,FC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function QL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(jt(Object.keys(t),FC).length!==FC.length)throw new Error("Global state provider is missing required methods");return un=t,{success:!0}}function KA(){if(un.createInstanceState){try{un.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:wA}}function Dr(t){return!t||typeof t!="object"?ve.devContext??!1:typeof ve.devContext!="object"?!1:Object.keys(t).every(e=>ve.devContext?.[e]===t[e])&&ve.devContext}function XL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(ve.timers).filter(o=>o!=="default"||ve.timers[o].startTime).map(o=>{let i=ve.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:ve.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=ve.timers[e].state==="stopped"?0:(r-(ve.timers[e]?.startTime??0))/1e3,o=ve.timers[e].elapsedTime+n;return{state:ve.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!ve.timers[e]||t==="reset"){if(e==="allTimers")return ve.timers={default:{elapsedTime:0}},!0;ve.timers[e]={startTime:r,state:"active",elapsedTime:0}}return ve.timers[e].elapsedTime||(ve.timers[e].elapsedTime=0),t==="stop"&&ve.timers[e].state!=="stopped"&&(ve.timers[e].state="stopped")&&(ve.timers[e].elapsedTime+=(r-(ve.timers[e]?.startTime??0))/1e3),t==="start"&&(ve.timers[e].startTime=r)&&(ve.timers[e].state="active"),ve.timers[e]}function kC(t){Yr(t)?ve.globalLog=t:delete ve.globalLog}function Qc(t){ve.devContext=t}function zA(){un.disableNotifications()}function hf(){un.enableNotifications()}function Xc(t,e){typeof t=="boolean"&&(ve.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(ve.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(ve.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(ve.deepCopyAttributes.stringify=e.stringify),e.threshold&&(ve.deepCopyAttributes.threshold=e.threshold))}function Sf(){return{enabled:ve.deepCopy,...ve.deepCopyAttributes}}function JL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{ve.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:st,info:"missing subscriptions"}}function ZL(t){return t?.subscriptions?un.setSubscriptions({subscriptions:t.subscriptions}):{error:st,info:"missing subscriptions"}}function GC(t){return t?typeof t!="object"?{error:B}:(Object.keys(t).forEach(e=>{Yr(t[e])&&(ve.globalMethods[e]=t[e])}),{...C}):{error:st,info:"missing method declarations"}}function VC(t){return t?typeof t!="object"?{error:B}:un.setMethods(t):{error:st,info:"missing method declarations"}}function Tf(){return un.cycleMutationStatus()}function lt(t){if(typeof t?.topic!="string")return;let e=ve.globalSubscriptions[t.topic];return un.addNotice(t,e)}function yf(){return{...ve.globalMethods,...un.getMethods()}}function th(t){return un.getNotices(t)}function eh({key:t,topic:e}){return un.deleteNotice({key:t,topic:e})}function Yi(){return un.deleteNotices()}function Lr(){return un.getTopics()}function dp(t){return Lr()?.topics?.includes(t)}async function wm(t){return un.callListener(t,ve.globalSubscriptions)}function ms(){return un.getTournamentId()}function Ef(t){return un.getTournamentRecord(t)}function qo(){return un.getTournamentRecords()}function QA(t){return un.setTournamentRecord(t)}function Lm(t){return un.setTournamentRecords(t)}function lp(t){return un.setTournamentId(t)}function XA(t){return un.removeTournamentRecord(t)}function rh(){return un}function fp({engineName:t,methodName:e,params:r,err:n}){let o=Yr(un.handleCaughtError)&&un.handleCaughtError||$A.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function JA(t,e){if(ve.globalLog)try{ve.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),kC()}else console.log(e,t)}function ZA(t,e,r,n){if(!ht(t))return{error:B};Jt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Yr(a[u])?i[u]=a[u]:ht(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?GC(i):VC(i),{methods:i}}function tF(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function nt(t,e,r,n){if(typeof t!="object"||t===null)return t;Sf()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=tF(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>nt(c))}:{[a]:n?t[a]:nt(t[a])}))}function _({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||(e.context={}),Object.assign(e.context,nt(t))),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var lr="FEMALE",$o="OTHER",qi="MIXED",Le="MALE";var Fm={FEMALE_ABBR:"F",OTHER_ABBR:"O",MIXED_ABBR:"X",MALE_ABBR:"M",ANY_ABBR:"A",FEMALE:lr,MIXED:qi,OTHER:$o,MALE:Le,ANY:"ANY"};function $i(t){return[lr,"F"].includes(t)}function Hs(t){return[Le,"M"].includes(t)}function en(t){return[qi,"X"].includes(t)}function To(t){return["ANY","A"].includes(t)}function yr(t){if(t){if($i(t))return lr;if(en(t))return qi;if(Hs(t))return Le;if(To(t))return"ANY"}return $o}function Dn(t){return $i(t)||Hs(t)}var iF="MIXED events can not contain mixed singles or { gender: ANY } collections",sF="events with { gender: ANY } can not contain MIXED singles collections";function km(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&Dn(r)&&yr(r)!==yr(o)?_({result:{valid:!1,error:cp},context:{gender:o},stack:e}):en(r)&&(To(o)||en(o)&&n!==vt)?_({result:{error:cp,valid:!1},info:iF,stack:e}):To(r)&&en(o)&&n!==vt?_({result:{error:cp,valid:!1},info:sF,stack:e}):{valid:!0}}var aF="normal",tU="timed",cF="final",Af="NOAD";var HC={S:aF,F:cF};function gp(t,e){if(ht(t)&&(t?.bestOf||t?.exactly)&&t?.setFormat)return uF(t,e)}function Uf(t){return!Number.isNaN(Number(t))&&Number(t)}function YC(t){let e=`T${t.minutes}`;return t.based==="A"?e+="A":t.based==="P"&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function uF(t,e){let r=Uf(t.bestOf)||void 0,n=Uf(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return YC(t.setFormat);let s=o&&`${"SET"}${o}${n&&n!==1?"X":""}`||"",a=WC(t.setFormat,e),c=a&&`S:${a}`||"",u=WC(t.finalSetFormat,e),p=o&&o>1&&u&&a!==u&&`F:${u}`||"";if(s&&a)return[s,c,p].filter(Boolean).join("-")}function WC(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return YC(t);if(t.tiebreakSet)return jC(t.tiebreakSet);let r=Uf(t.setTo);if(r){let n=t.NoAD&&Af||"",o=jC(t.tiebreakFormat),i=o&&`/${o}`||"",s=Uf(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function jC(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&Uf(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Af:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ne(t){if(kt(t)){let e=t.startsWith("T")&&tU||t.startsWith("SET")&&"SET"||"";if(e===tU){let r=zC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e==="SET")return pF(t)}}function pF(t){let e=t.split("-"),r=e[0].slice(3),n=r.endsWith("X"),o=n?r.slice(0,-1):r,i=Gm(o),s=n&&i!==1?void 0:i,a=n&&i!==1?i:void 0,c=e&&qC(e[1]),u=e&&qC(e[2]),p=c&&c.timed||u&&u.timed,m=s&&s<6||p&&a,d=!e[2]||u,l=c,f=nt({setFormat:c,exactly:a,bestOf:s});if(u&&(f.finalSetFormat=u),m&&l&&d)return f}function qC(t){if(t?.[1]!==":")return;let e=t.split(":"),r=HC[e[0]],n=e[1];if(!(!r||!n))return mF(t,n)}function mF(t,e){return e.startsWith("TB")?dF(e):e.startsWith("T")?zC(e):lF(t,e)}function dF(t){let e=KC(t);return e===!1?!1:typeof e=="object"?{tiebreakSet:e}:void 0}function lF(t,e){let r=/^[FS]:(\d+)([A-Za-z]*)/.exec(t),n=r&&QC(r[2])||!1,o=!r?.[2]||n,i=r?Gm(r[1]):void 0,s=$C(e),a=s!==!1,c=a&&s||i,u=KC(e.split("/")[1]);return!i||!o||!(u!==!1)||!a?!1:fF(i,n,u,c)}function fF(t,e,r,n){let o={setTo:t};return e&&(o.NoAD=!0),r?(o.tiebreakFormat=r,o.tiebreakAt=n):o.noTiebreak=!0,o}function $C(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Gm(r[1]):r[1])||!1}function KC(t){if(t)return t.startsWith("TB")?gF(t):!1}function gF(t){let e=$C(t,!1),r=/^TB(\d+)([A-Za-z]*)/.exec(t),n=r?.[1],o=r&&QC(r[2]),i=!r?.[2]||o,s=Gm(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 zC(t){let e=t.slice(1),r=/^(\d+)([PGA])?(?:\/TB(\d+))?(@?[A-Za-z]*)?/.exec(e),n=Gm(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2];i==="A"?o.based="A":i==="P"?o.based="P":i==="G"&&(o.based="G");let s=r?.[3];if(s){let u=Gm(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 QC(t){return t?.includes(Af)}function Gm(t){let e=Number(t);return Number.isNaN(e)?0:e}function Nr({matchUpFormat:t}){if(!kt(t)||t==="")return!1;let e=Ne(t),r=/-S:([1-9])+\/TB(\d{1,2})@?([1-9]?)/.exec(t),n=r?.[1],o=r?.[2],i=r?.[3],s=/-F:([1-9])+\/TB(\d{1,2})@?([1-9]?)/.exec(t),a=s?.[1],c=s?.[2],u=s?.[3];return gp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var Vm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,nh=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Oo=/^([\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?$/,Ws=/^([\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 Bm(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Ut(t.scheduledTime)),!e)return;let r=zt(t.scheduledTime),n=Ut(e);return n&&r&&(n+=`T${r}`),n}function XC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Jc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||Ws.test(ac(t,!0,!0)))}function Mr(t){return sc(t)||Vm.test(t)}function IF(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+3600*e.getHours();return hF(r,{displaySeconds:!1})}function hF(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(oo).join(":")}var Mf=t=>{let e=Df(t)||sc(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${oo(n)}-${oo(e.getUTCDate())}`};function SF(t){let e=Df(t)||sc(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Kn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function oh(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function TF(t){return oh(t).getTime()}function Df(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function js(t,e){if(!Mr(t)||!Mr(e))return[];let r=Ut(t)+"T00:00",n=Ut(e)+"T00:00",o=new Date(r),i=new Date(n),s=Df(i)&&Df(o)&&u(o,i),a=[],c=0;if(s){let p=o,m=p.getTime();for(;m<=i.getTime()&&c<300;)c+=1,a.push(new Date(p)),m=p.setDate(p.getDate()+1)}return a.map(p=>Kn(p));function u(p,m){return p<=m}}var yF=/^([+-]?\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 sc(t){return typeof t!="string"?!1:yF.test(t)}function sh(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function Yt(t){let e=zt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function JC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[oo(e),oo(r)].join(":")}function Nf(t){return sh(t)?t.split(":").slice(0,2).map(oo).join(":"):void 0}function zt(t){return sc(t)&&t.indexOf("T")>0?Nf(t.split("T").reverse()[0]):Nf(t)}function Ut(t){return sc(t)||Oo.test(t)?t.split("T")[0]:void 0}function Ip(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Ut(r.toISOString())}function ih(t){t=typeof t!="string"?"00:00":t;let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:r.hours,1:r.minutes}=e.time.split(":")||[],r.ampm=e.ampm,isNaN(r.hours)||isNaN(r.minutes)||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function EF(t){let e=ih(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(oo).join(":")}function AF(t){let e=ih(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 ac(t,e,r){let n=Ut(t),o=zt(t),i=n?o:t;return t?e&&(n&&r&&t||EF(i))||AF(i):void 0}function ah(t,e){let r=ih(t),n=ih(e);if(parseInt(r.hours)<parseInt(n.hours))return-1;if(parseInt(r.hours)>parseInt(n.hours))return 1;if(r.hours===n.hours){if(parseInt(r.minutes)<parseInt(n.minutes))return-1;if(parseInt(r.minutes)>parseInt(n.minutes))return 1}return 0}function ch(t,e=7){let r=Ut(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Kn(o)}function UF(t){return ch(t)}function PF(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())),Kn(o,r)}function ZC(t,e,r){let n=new Date(t,0);return Kn(new Date(n.setDate(e)),r)}function Ge(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(oo),o=oh(e).setHours(r,n,0,0);return oh(o)}function ya(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 $r(t,e){let r=zt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return zt(Rf(Ge(r),n).toISOString())}function Rf(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function oo(t){return t.toString()[1]?t:"0"+t}function zn(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 uh={addDays:ch,addWeek:UF,addMinutesToTimeString:$r,convertTime:ac,getIsoDateString:Bm,getUTCdateString:Mf,DateHHMM:IF,extractDate:Ut,extractTime:zt,formatDate:Kn,getDateByWeek:PF,isISODateString:sc,isDate:Df,isTimeString:sh,offsetDate:oh,offsetTime:TF,sameDay:zn,timeStringMinutes:Yt,timeToDate:Ge,timeUTC:SF,validTimeValue:Jc,validDateString:Vm,timeValidation:Ws,dateValidation:Oo};var DF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),NF=t=>t.filter(Boolean).every(Jt);function Ys(t){let e=t.category;if(typeof e!="object")return{error:zc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(DF([r,n,o,a],"string")&&NF([i,s])&&[n,o].filter(Boolean).every(Mr)))return{error:zc};let p=t.consideredDate??Ut(new Date().toLocaleDateString("sv"));if(!Mr(p))return{error:Ye};let[m]=p.split("-").slice(0,3).map(k=>parseInt(k)),d=Ip(p,-1),[l,f]=d.split("-").slice(1,3).map(k=>parseInt(k)),g=`${oo(l)}-${oo(f)}`,I=Ip(p,1),[h,S]=I.split("-").slice(1,3).map(k=>parseInt(k)),T=`${oo(h)}-${oo(S)}`,y=s&&Ip(p,-1*365*s),E=i&&Ip(p,-1*365*i),P=[],A=k=>!P.includes(k)&&P.push(k);r=r??a;let U=/^([UO]?)(\d{1,2})([UO]?)$/,N=/^C(\d{1,2})-(\d{1,2})$/,D=r?.includes("-"),M=D&&r?.match(N),R=r?.match(U),b=(k,G)=>`${k}-${G}`,O=k=>{let G=m-k,H=b(G,T);e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==k-1&&(A(`Invalid submitted ageMax: ${i}`),E=void 0),i=k-1)},v=k=>{let G=m-k-1,H=b(G,T);e.ageMin&&e.ageMin>k&&A(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>k&&A(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==k&&(A(`Invalid submitted ageMax: ${i}`),y=void 0),i=k)},x=k=>{let G=m-k,H=b(G,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==k+1&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=k+1)},F=k=>{let G=m-k-1,H=b(G,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==k&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=k)},w=k=>{let[G,H,K]=(k.match(U)||[]).slice(1),Y=parseInt(H);G==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),O(Y)):G==="O"&&x(Y),K==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(Y)):K==="O"&&F(Y),n=n??y,o=o??E};if(M){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=m-e.ageMin;n=b(H,g)}if(e.ageMax){let H=m-e.ageMax-1;o=b(H,T)}let[k,G]=(r?.match(N)??[]).slice(1).map(H=>parseInt(H));k<=G?(s=k,i=G,c=!0):A(`Invalid combined age range ${r}`)}else D?r?.split("-").forEach(w):R?w(r):(s&&x(s),i&&v(i));i&&e.ageMin&&e.ageMin>i&&(A(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=nt({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return P.length&&(L.errors=P),L}function Zc({category:t}){if(!ht(t))return{error:B};let e=Ys({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Jt(r)?_({result:{error:B},context:{ratingMax:r}}):n&&!Jt(n)?_({result:{error:B},context:{ratingMin:n}}):{...e}}function tu({childCategory:t,withDetails:e,category:r}){let n=Zc({category:r}),o=Zc({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=nt({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function eu({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}`),_({result:{errors:c,error:So},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Yc([Lt,vt],I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`),[!!u?.length].concat([g,m,h,S].map(It)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let P=GI({collectionValueProfiles:u,matchUpCount:l});P.errors&&c.push(...P.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Nr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let P=km({referenceGender:i,matchUpType:I,gender:y});if(P.error)return _({context:{referenceGender:i,gender:y},result:P,stack:a})}if(t&&o&&T){let P=tu({category:o,childCategory:T});if(!P.valid)return _({result:{error:zc},context:P,stack:a})}return c.length?_({result:{errors:c,error:VA},stack:a}):{valid:!0}}function ar(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=MF({...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}=eu({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)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),_({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:Yo},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===pt(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:_({result:{error:Yo},context:{tieFormat:o,errors:a},stack:s})}function MF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?_({result:{error:Yo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:Yo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:Yo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var cc="resourceSubType",uc="resourceType",pc="identifier",tb={RESOURCE_SUB_TYPE:cc,RESOURCE_TYPE:uc,IDENTIFIER:pc};function J(t,e,r,n,o=0){if(rh().makeDeepCopy)return rh().makeDeepCopy(t,e,r,n);let i=Sf(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Yr(t)||t===null||typeof i?.threshold=="number"&&o>=i.threshold)return t;let p=Array.isArray(t)?[]:{},m=Object.keys(t).filter(l=>!r||!c||Array.isArray(c)&&!c.includes(l)||Yr(c)&&!c(l)),d=(l,f)=>{p[l]=Yr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Yr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Cf(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?d(l,f):Array.isArray(a)&&a.includes(l)&&Yr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:XC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Cf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function ph(t=1,e){return tt(0,t).map(()=>Nt(e))}function Nt(t){let e=[];for(let a=0;a<256;a++)e[a]=(a<16?"0":"")+a.toString(16);let r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0,i=Math.random()*4294967295|0,s=e[r&255]+e[r>>8&255]+e[r>>16&255]+e[r>>24&255]+"-"+e[n&255]+e[n>>8&255]+"-"+e[n>>16&15|64]+e[n>>24&255]+"-"+e[o&63|128]+e[o>>8&255]+"-"+e[o>>16&255]+e[o>>24&255]+e[i&255]+e[i>>8&255]+e[i>>16&255]+e[i>>24&255];return typeof t=="string"?`${t}_${s.replace(/-/g,"")}`:s}var mh={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 dh={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 lh={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 fh={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 gh={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 Ih={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Pro Circuit",winCriteria:{aggregateValue:!0}};var hh={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 Sh={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:3},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:3},{scoreValue:1,matchUpType:"DOUBLES",collectionName:"Men's Doubles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Women's Doubles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Dual",winCriteria:{aggregateValue:!0}};var Th={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"USTA_BREWER_CUP",winCriteria:{valueGoal:4}};var yh={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 bn="SET3-S:6/TB7",kF="SET3-S:6NOAD",eU="SET3-S:6/TB7-F:TB10",GF="SET3-S:4/TB7",VF="SET3-S:4/TB5@3",BF="SET1-S:T20",HF="SET1-S:8/TB7",WF="SET1-S:8/TB7@7",eb={FORMAT_STANDARD:bn,FORMAT_STANDARD_NOAD:kF,FORMAT_ATP_DOUBLES:eU,FORMAT_SHORT_SETS:GF,FORMAT_FAST4:VF,FORMAT_PRO_SET:HF,FORMAT_COLLEGE_PRO_SET:WF,TIMED20:BF};var Eh={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 Ah={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA_COLLEGE",winCriteria:{valueGoal:4}};var Uh={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 Ph={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_WTT_ITT",winCriteria:{aggregateValue:!0}};var Dh={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 Nh={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}};var Mh={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var Hm="COLLEGE_DEFAULT",Rh="COLLEGE_JUCO",Ch="COLLEGE_D3",rU="DOMINANT_DUO",nU="DOMINANT_DUO_MIXED",oU="LAVER_CUP",iU="TEAM_DOUBLES_3_AGGREGATION",sU="TIME_TENNIS_DUAL",aU="TIME_TENNIS_PRO_CIRCUIT",cU="USTA_BREWER_CUP",uU="USTA_OZAKI_CUP",pU="USTA_COLLEGE",mU="USTA_GOLD_TEAM_CHALLENGE",dU="USTA_LEVEL_1",lU="USTA_INTERSECTIONAL",fU="USTA_SECTION_BATTLE",gU="USTA_SOUTHERN_LEVEL_5",IU="USTA_TOC",hU="USTA_WTT_ITT",SU="USTA_ZONAL",rb={COLLEGE_D3:Ch,COLLEGE_DEFAULT:Hm,COLLEGE_JUCO:Rh,DOMINANT_DUO:rU,DOMINANT_DUO_MIXED:nU,LAVER_CUP:oU,TEAM_DOUBLES_3_AGGREGATION:iU,TIME_TENNIS_DUAL:sU,TIME_TENNIS_PRO_CIRCUIT:aU,USTA_BREWER_CUP:cU,USTA_OZAKI_CUP:uU,USTA_COLLEGE:pU,USTA_GOLD_TEAM_CHALLENGE:mU,USTA_INTERSECTIONAL:lU,USTA_LEVEL_1:dU,USTA_SECTION_BATTLE:fU,USTA_SOUTHERN_LEVEL_5:gU,USTA_TOC:IU,USTA_WTT_ITT:hU,USTA_ZONAL:SU};var ob="STANDARD",nb={[ob]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Ch]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Ch,valueGoal:5},[Hm]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Hm,valueGoal:4},[Rh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Rh,valueGoal:5},[oU]:Nh,[rU]:Eh,[nU]:hh,[iU]:dh,[sU]:Sh,[aU]:Ih,[cU]:Th,[uU]:yh,[pU]:Ah,[mU]:mh,[lU]:gh,[dU]:Uh,[fU]:fh,[gU]:lh,[hU]:Ph,[IU]:Mh,[SU]:Dh},XF=t=>{let e=t?.namedFormat&&Object.keys(nb).includes(t.namedFormat)?t.namedFormat:ob,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(nb[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Nt();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:eU,collectionName:"Doubles",matchUpType:vt,...s.doubles},{collectionId:a(1),matchUpFormat:bn,collectionName:"Singles",matchUpType:Lt,...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},io=XF;var Qn="SINGLES",qs="SINGLES",Kr="DOUBLES",Ko="DOUBLES",_e="TEAM",Or="TEAM";var JF="RATING",ZF="BOTH",ib={AGE:"AGE",BOTH:ZF,DOUBLES:Kr,DOUBLES_EVENT:Ko,RATING:JF,SINGLES:Qn,SINGLES_EVENT:qs,TEAM_EVENT:Or,TEAM:_e};var rt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",fe="PLAY_OFF",ru=[rt,ct,qe,fe,$e],$s={[ct]:1,[rt]:2,[fe]:3,[qe]:3,[$e]:4},TU="finishingPositions",yU="aggregateEventStructures",EU={[rt]:1,[fe]:2,[qe]:3,[ct]:4,[$e]:5},sb={[fe]:1,[rt]:2,[qe]:3,[ct]:4,[$e]:5},nu="CLUSTER",ab="SEPARATE",Ti="WATERFALL",hp="ITEM",Ve="CONTAINER",fn="DRAW",Sp="RANDOM",Nn="TOP_DOWN",yi="BOTTOM_UP",Fn="POSITION",Xn="WINNER",so="LOSER",kn="FIRST_MATCHUP",Fr="AD_HOC",tk="AD_HOC",Ea="FEED_IN",ou="COMPASS",iu="OLYMPIC",ek="SINGLE_ELIMINATION";var yo="SINGLE_ELIMINATION",su="DOUBLE_ELIMINATION",au="FIRST_MATCH_LOSER_CONSOLATION",Tp="FIRST_ROUND_LOSER_CONSOLATION",Ki="LUCKY_DRAW",bf="CURTIS_CONSOLATION",cb="CURTIS_CONSOLATION",bh="FEED_IN_CHAMPIONSHIP_TO_SF",Wm="FEED_IN_CHAMPIONSHIP_TO_SF",Oh="FEED_IN_CHAMPIONSHIP_TO_QF",jm="FEED_IN_CHAMPIONSHIP_TO_QF",vh="FEED_IN_CHAMPIONSHIP_TO_R16",Ym="FEED_IN_CHAMPIONSHIP_TO_R16",AU="MODIFIED_FEED_IN_CHAMPIONSHIP",qm="MODIFIED_FEED_IN_CHAMPIONSHIP",yp="FEED_IN_CHAMPIONSHIP",ub="DOUBLE_ROUND_ROBIN",On="ROUND_ROBIN",Eo="ROUND_ROBIN_WITH_PLAYOFF",UU="DECIDER",PU="BACKDRAW",Of={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"}},vf={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Ei="WIN_RATIO",zi="ROUND_OUTCOME",DU=[ou,bf,jm,Ym,Wm,yp,Oh,vh,bh,au,Tp,Ki,qm,iu,fe,Eo],rk=[Fr,ou,bf,su,jm,Ym,Wm,yp,Ea,au,Tp,Ki,qm,iu,fe,On,Eo,yo],NU={MAIN:rt,QUALIFYING:ct,CONSOLATION:qe,ITEM:hp,CONTAINER:Ve,FIRST_MATCHUP:kn,WINNER:Xn,LOSER:so,AD_HOC:Fr,FEED_IN:Ea,FLEX_ROUNDS:tk,COMPASS:ou,PLAY_OFF:fe,OLYMPIC:iu,KNOCKOUT:ek,SINGLE_ELIMINATION:yo,DOUBLE_ELIMINATION:su,CURTIS:bf,FICSF:bh,FICQF:Oh,FICR16:vh,MFIC:AU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:au,FIRST_ROUND_LOSER_CONSOLATION:Tp,MODIFIED_FEED_IN_CHAMPIONSHIP:qm,FEED_IN_CHAMPIONSHIP_TO_R16:Ym,FEED_IN_CHAMPIONSHIP_TO_QF:jm,FEED_IN_CHAMPIONSHIP_TO_SF:Wm,FEED_IN_CHAMPIONSHIP:yp,LUCKY_DRAW:Ki,ROUND_ROBIN_WITH_PLAYOFF:Eo,ROUND_ROBIN:On,DECIDER:UU,BACKDRAW:PU,COMPASS_ATTRIBUTES:Of,OLYMPIC_ATTRIBUTES:vf,DRAW:fn,RANDOM:Sp,TOP_DOWN:Nn,BOTTOM_UP:yi,WATERFALL:Ti,WIN_RATIO:Ei,ROUND_OUTCOME:zi,MULTI_STRUCTURE_DRAWS:DU,generatedDrawTypes:rk,stageOrder:$s,finishOrder:EU,AGGREGATE_EVENT_STRUCTURES:yU,FINISHING_POSITIONS:TU},pb=NU;var Re="tournamentRecords",_f="policyDefinitions",ne="tournamentRecord",_h="onlineResource",Ce="drawDefinition",xh="tieFormatName",$m="matchUpFormat",ao="participantId",wh="scheduleDates",mb="tournamentId",db="scheduleDate",lb="roundNumber",cu="structureId",xf="participant",mc="matchUpIds",Lh="entryStage",fb="policyType",MU="structures",wf="eventType",gn="matchUpId",Km="tieFormat",uu="inContext",Ep="structure",Ap="courtIds",gb="personId",Up="venueIds",Lf="matchUps",Fh="courtId",kh="eventId",Gn="matchUp",Gh="drawId",In="error",co="event",ds="param",Ff="uuids",Ib="averageMatchUpMinutes",hb="recoveryMinutes",Sb="periodLength",Tb="number";var zr="object",Be="array";var tr="_validate",Vh="_message",kr="_invalid",He="_ofType",zm="_anyOf",Ks="_oneOf";var yb={[_h]:t=>jt(Object.keys(t),[cc,uc,pc]).length===3,[xh]:t=>t&&io({namedFormat:t}),[Ff]:t=>!t||Array.isArray(t)&&t.every(kt),[Km]:t=>!ar({tieFormat:t}).error,[wf]:t=>[Qn,Kr,_e].includes(t),[Lh]:t=>ru.includes(t)},nk={[Re]:xt,[ne]:q,[_f]:op,[Ce]:Z,[ao]:se,[$m]:Zl,[mb]:ha,[cu]:Pr,[mc]:ps,[xf]:Wi,[_h]:So,[wf]:$n,[MU]:Kl,[gn]:sr,[Km]:Yo,[Ep]:Si,[Fh]:Bi,[Lf]:no,[kh]:qr,[Gn]:mr,[Ap]:st,[Up]:st,[Gh]:cn,[co]:Ot},ok={[Re]:zr,[_f]:zr,[ne]:zr,[Ce]:zr,[_h]:zr,[wh]:Be,[xf]:zr,[mc]:Be,[MU]:Be,[Km]:zr,[Ep]:zr,[Ap]:Be,[Up]:Be,[Lf]:Be,[Gn]:zr,[co]:zr,[Ff]:Be};function et(t,e,r){if(!t&&!ht(t))return{error:B};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:B};let{paramError:n,errorParam:o}=ak(t,e);if(!n)return{valid:!0};let i=n[tr]&&(n[In]||n[kr])||t?.[o]===void 0&&(n[In]||n[kr]||nk[o]||B)||B,s=o??(n[Ks]&&Object.keys(n[Ks]).join(", "));return _({info:{param:s,message:n[Vh]},result:{error:i},stack:r})}function Eb(t,e){let r=Object.keys(t),n=Object.keys(e);return jt(r,n)}function ik(t,e){if(!e)return;let r=Eb(t,e);return r.length!==1?{error:B}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function sk(t,e){if(!e)return;let r=Eb(t,e).filter(n=>t[n]);return r.length<1?{error:B}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function ak(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&ik(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&sk(t,a);if(d?.error)return d.error;d&&Object.assign(p,d);let l=Object.keys(p).filter(g=>typeof p[g]=="boolean"),f=l.find(g=>{let I=c&&!Yr(c),h=t[g]!==void 0&&!c&&ck(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!uk(t[g],c)||yb[g]&&!yb[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function ck(t,e,r){return r=r||ok[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function uk(t,e){return Yr(e)?e(t):!0}var Qm="DYNAMIC",Ai="RANKING",Ui="RATING",Pi="SCALE",Ao="SEEDING",Ab={RANKING:Ai,RATING:Ui,SCALE:Pi,SEEDING:Ao};function Aa(t){let e=et(t,[{[xf]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Pi)&&[Ai,Ui,Ao].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=pt(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===Ao&&"seedings"||c===Ai&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Qi(t){if(t===null)return{};let{source:e,template:r}=t||{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let h=I.map(S=>{let T={};return o(S,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=h}else I&&(a[l]={},o(I,g,a[l]));else{let h=i[l];if(Array.isArray(g)&&!g.includes(h))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=h)}}}}var Bh="voluntaryConsolation",Di="competitiveBands",kf="roundRobinTally",Jn="positionActions",er="matchUpActions",Gf="rankingPoints",vo="roundNaming",zs="participant",pu="progression",_o="scheduling",mu="avoidance",pk="participant",mk="display",rn="scoring",Vn="seeding",dc="feedIn",dk="audit",Xm="draws",Ub={POLICY_TYPE_VOLUNTARY_CONSOLATION:Bh,POLICY_TYPE_COMPETITIVE_BANDS:Di,POLICY_TYPE_ROUND_ROBIN_TALLY:kf,POLICY_TYPE_POSITION_ACTIONS:Jn,POLICY_TYPE_MATCHUP_ACTIONS:er,POLICY_TYPE_RANKING_POINTS:Gf,POLICY_TYPE_ROUND_NAMING:vo,POLICY_TYPE_PARTICIPANT:zs,POLICY_TYPE_PROGRESSION:pu,POLICY_TYPE_SCHEDULING:_o,POLICY_TYPE_AVOIDANCE:mu,POLICY_TYPE_DISPLAY:mk,POLICY_TYPE_PRIVACY:pk,POLICY_TYPE_FEED_IN:dc,POLICY_TYPE_SCORING:rn,POLICY_TYPE_SEEDING:Vn,POLICY_TYPE_AUDIT:dk,POLICY_TYPE_DRAWS:Xm};function zo({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[zs];if(r?.withScaleValues){let{ratings:u,rankings:p}=Aa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Qi({template:c.participant,source:a})}return a}var Pb="element required",Db="missing name";function Ir(t){if(!t||typeof t!="object")return{error:st};if(t.element&&typeof t?.element!="object")return{error:B};if(!t?.name)return{error:st,info:Db};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=Ir({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...C}}return{error:st,info:Pb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:Oe}}function Bn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function At(t){if(typeof t!="object")return{error:st};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:B},stack:e});if(!Bn({extension:t.extension}))return _({result:{error:B,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=At({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...C}}else return _({result:{error:st},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...C}}function Vf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:q}}function Pp(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:br}}function xo(t){return!t||typeof t!="object"?{error:st}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:qr}}function RU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:se};let e=t.tournamentRecord?.participants||[],r=zo({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:re}}function Bf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?Ir({element:t.tournamentRecord,name:t.name}):{error:q}}function CU(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?Ir({element:t.drawDefinition,name:t.name}):{error:br}}function Dp(t){return!t||typeof t!="object"?{error:st}:t?.event?Ir({element:t.event,name:t.name}):{error:qr}}function bU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:se};let e=t.tournamentRecord?.participants||[],r=zo({participantId:t.participantId,tournamentParticipants:e});return r?Ir({element:r,name:t.name}):{error:re}}function Np({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var lk="extensionQueries";function mt({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:Oe}}return _({result:{error:st},stack:lk})}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:Oe}}var fk="activeSuspension",du="appliedPolicies",OU="context",Jm="delegatedOutcome",uo="disabled",Ua="disableAutoCalc",Zm="disableLinks",td="display",Pa="drawDeletions",gk="drawProfile",ed="entryProfile",Ik="eventProfile",hk="eventWithdrawalRequests",Sk="factory",pn="flightProfile",Hh="groupingAttribute",wo="lineUps",Qs="linkedTournamentsIds",rd="matchUpHistory",Wh="participantRepresentatives",Da="personRequests",lc="positionActions",Tk="rankingPoints",yk="registration",vn="roundTarget",lu="scheduleLimits",Qo="scheduleTiming",Na="schedulingProfile",Ek="statusDetail",fc="subOrder",Lo="tally",nd="tieFormatModification",jh={ACTIVE_SUSPENSION:fk,APPLIED_POLICIES:du,CONTEXT:OU,DELEGATED_OUTCOME:Jm,DISABLED:uo,DISABLE_LINKS:Zm,DISABLE_AUTO_CALC:Ua,DISPLAY:td,DRAW_DELETIONS:Pa,DRAW_PROFILE:gk,ENTRY_PROFILE:ed,EVENT_PROFILE:Ik,EVENT_WITHDRAWAL_REQUESTS:hk,FLIGHT_PROFILE:pn,GROUPING_ATTRIBUTE:Hh,LINEUPS:wo,LINKED_TOURNAMENTS:Qs,MATCHUP_HISTORY:rd,PARTICIPANT_REPRESENTATIVES:Wh,PERSON_REQUESTS:Da,POSITION_ACTIONS:lc,RANKING_POINTS:Tk,REGISTRATION:yk,ROUND_TARGET:vn,SCHEDULE_LIMITS:lu,SCHEDULE_TIMING:Qo,SCHEDULING_PROFILE:Na,STATUS_DETAIL:Ek,SUB_ORDER:fc,TALLY:Lo,TIE_FORMAT_MODIFICATIONS:nd,FACTORY:Sk},vU=[Jm,uo,Ua,Zm,pn,wo,Qs,rd,Wh,Da,vn,lu,Qo,Na,fc,Lo,nd];function _U({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=Np({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:Qs,value:{tournamentIds:r}}}):{...C}}function xU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=Ir({name:Qs,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function wU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:B};if(!e)return{error:ha};let r=Np({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ha};let o;return n.every(i=>{let s=t[i],{extension:a}=mt({element:s,name:Qs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=Bf({name:Qs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Vf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var FU={};Xt(FU,{getLinkedTournamentIds:()=>fu,getTournamentIds:()=>Np});function fu({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:xt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=mt({element:n,name:Qs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var GN={};Xt(GN,{adHocPositionSwap:()=>zP,addAdHocMatchUps:()=>Gd,addDrawDefinitionTimeItem:()=>Og,addFinishingRounds:()=>ba,addGoesTo:()=>rs,addPlayoffStructures:()=>Kp,addQualifyingStructure:()=>KP,addVoluntaryConsolationStage:()=>HP,addVoluntaryConsolationStructure:()=>Eg,allPlayoffPositionsFilled:()=>WS,alternateDrawPositionAssignment:()=>bP,assignDrawPosition:()=>uD,assignDrawPositionBye:()=>Wr,attachConsolationStructures:()=>iD,attachPlayoffStructures:()=>Vg,attachQualifyingStructure:()=>bg,attachStructures:()=>Bg,autoSeeding:()=>ux,automatedPlayoffPositioning:()=>na,automatedPositioning:()=>Mc,checkValidEntries:()=>Hd,deleteAdHocMatchUps:()=>pD,drawMatic:()=>tl,findDrawDefinition:()=>gT,generateAdHocMatchUps:()=>Wu,generateAdHocRounds:()=>Zd,generateAndPopulatePlayoffStructures:()=>kd,generateDrawDefinition:()=>Wa,generateDrawMaticRound:()=>qd,generateDrawStructuresAndLinks:()=>Wd,generateDrawTypeAndModifyDrawDefinition:()=>jd,generateQualifyingStructure:()=>_d,generateVoluntaryConsolation:()=>LT,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getMatchUpsMap:()=>Pe,getParticipantIdFinishingPositions:()=>fT,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getRandomQualifierList:()=>RT,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getValidGroupSizes:()=>Gp,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,luckyLoserDrawPositionAssignment:()=>NP,modifyDrawDefinition:()=>sD,modifyDrawName:()=>Hg,modifySeedAssignment:()=>FP,mutate:()=>lD,positionActions:()=>MT,pruneDrawDefinition:()=>cD,qualifierDrawPositionAssignment:()=>Cg,qualifierProgression:()=>kP,query:()=>PD,removeDrawPositionAssignment:()=>Ou,removeRoundMatchUps:()=>mD,removeSeededParticipant:()=>$P,removeStructure:()=>BP,renameStructures:()=>VP,resetDrawDefinition:()=>aD,resetQualifyingStructure:()=>WP,resetVoluntaryConsolationStructure:()=>KU,setDrawParticipantRepresentativeIds:()=>VU,setPositionAssignments:()=>RP,setStructureOrder:()=>GP,setSubOrder:()=>dD,shiftAdHocRounds:()=>MP,swapAdHocRounds:()=>CP,swapDrawPositionAssignments:()=>qP,updateTeamLineUp:()=>os,withdrawParticipantAtDrawPosition:()=>PP});var lD={};Xt(lD,{adHocPositionSwap:()=>zP,addAdHocMatchUps:()=>Gd,addDrawDefinitionTimeItem:()=>Og,addPlayoffStructures:()=>Kp,addQualifyingStructure:()=>KP,addVoluntaryConsolationStage:()=>HP,addVoluntaryConsolationStructure:()=>Eg,alternateDrawPositionAssignment:()=>bP,assignDrawPosition:()=>uD,assignDrawPositionBye:()=>Wr,attachConsolationStructures:()=>iD,attachPlayoffStructures:()=>Vg,attachQualifyingStructure:()=>bg,attachStructures:()=>Bg,automatedPlayoffPositioning:()=>na,automatedPositioning:()=>Mc,deleteAdHocMatchUps:()=>pD,luckyLoserDrawPositionAssignment:()=>NP,modifyDrawDefinition:()=>sD,modifyDrawName:()=>Hg,modifySeedAssignment:()=>FP,pruneDrawDefinition:()=>cD,qualifierDrawPositionAssignment:()=>Cg,qualifierProgression:()=>kP,removeDrawPositionAssignment:()=>Ou,removeRoundMatchUps:()=>mD,removeSeededParticipant:()=>$P,removeStructure:()=>BP,renameStructures:()=>VP,resetDrawDefinition:()=>aD,resetQualifyingStructure:()=>WP,resetVoluntaryConsolationStructure:()=>KU,setDrawParticipantRepresentativeIds:()=>VU,setPositionAssignments:()=>RP,setStructureOrder:()=>GP,setSubOrder:()=>dD,shiftAdHocRounds:()=>MP,swapAdHocRounds:()=>CP,swapDrawPositionAssignments:()=>qP,updateTeamLineUp:()=>os,withdrawParticipantAtDrawPosition:()=>PP});var GU=t=>e=>t[e],od=(t=[])=>t.map(Ue).filter(Boolean),Hf=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>GU(t)("participantId");var Ue=(t={})=>GU(t)("matchUpId"),gu=(t={})=>GU(t)("drawId");function VU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:br};if(!Array.isArray(t))return{error:B};let r=Hf(e?.entries||[]);return t.length&&jt(t,r).length<t.length?{error:B}:Pp({drawDefinition:e,extension:{name:Wh,value:t}})}var vr="ABANDONED",gc="AWAITING_RESULT";var po="CANCELLED",ge="COMPLETED",Iu="DEAD_RUBBER",Gt="DEFAULTED",be="DOUBLE_DEFAULT",oe="DOUBLE_WALKOVER",Hn="IN_PROGRESS",mn="INCOMPLETE",BU="NOT_PLAYED",Me="RETIRED",ls="SUSPENDED",Qt="TO_BE_PLAYED",Bt="WALKOVER",Nb=[gc,ge,Gt,Hn,mn,Me,ls],Yh=[gc,ge,Gt,oe,be,Hn,mn,Me,ls,Bt],qh=[vr,gc,"BYE",po,ge,Iu,Gt,oe,be,Hn,mn,BU,Me,ls,Qt,Bt],$h=["BYE",oe,be,ge,Gt,Me,Bt],Kh=[vr,gc,po,Iu,Hn,mn,BU,ls,Qt,void 0],ae=[po,vr,ge,Iu,Gt,oe,be,Me,Bt],id=[vr,ge,Gt,oe,be,Hn,Me,Bt],zh=[Hn,mn,ls,Qt],Qh={ABANDONED:vr,AWAITING_RESULT:gc,BYE:"BYE",CANCELLED:po,COMPLETED:ge,DEAD_RUBBER:Iu,DEFAULTED:Gt,DOUBLE_WALKOVER:oe,DOUBLE_DEFAULT:be,IN_PROGRESS:Hn,INCOMPLETE:mn,NOT_PLAYED:BU,RETIRED:Me,SUSPENDED:ls,TO_BE_PLAYED:Qt,WALKOVER:Bt};function Ni(t,e,r){let n=m=>mt({element:m,name:vn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===yU&&sb,s=r?.mode===TU&&EU,a=s||i||$s,c=m=>m?.stage===rt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ae.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(Wf(t)||0)-(Wf(e)||0)}function Wf(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function at(t){let e=et(t,[{[Ce]:!0,[cu]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=hn({drawDefinition:r}),i=o?.map(c=>c.structures?[...c.structures].concat(c):c).flat(),s=i?.find(c=>c.structureId===n);if(!s)return{error:_t};let a=s.structureType===hp?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&&Z||!e?.structures&&Kl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=mt({element:f,name:vn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Ni(f,g,i))??[],m=t?Object.assign({},...ru.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:m};function d(f){return!a&&!Array.isArray(s)||a&&f.stage===a||Array.isArray(s)&&s.includes(f.stage)}function l(f){return!n&&!Array.isArray(r)||n&&f.stageSequence===n||Array.isArray(r)&&r.includes(f.stageSequence)}}function Xh({drawDefinition:t}){if(!t)return{error:Z};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=Ct({structure:n}),s=i?.map(St).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Ct({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:Z};if({structure:r,error:n}=at({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>Ct({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=sA,{positionAssignments:o,error:n}}function Ie({drawDefinition:t,structureId:e,structure:r}){let n=Ct({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var jf="addDrawDefinition",Mp="addMatchUps",ci="addParticipants",Yf="addScaleItems",HU="addEvent",Jh="addVenue",Mi="audit",Zh="dataIssue",qf="deleteParticipants",$f="deleteVenue",Kf="deletedDrawIds",zf="deletedMatchUpIds",Qf="modifyDrawDefinition",WU="modifyDrawEntries",jU="modifyEventEntries",Xf="modifyMatchUp",rr="modifyParticipants",Jf="modifyPositionAssignments",Zf="modifySeedAssignments",Xi="modifyTournamentDetail",Ri="modifyVenue",sd="mutations",tS="publishEvent",YU="publishEventSeeding",qU="publishOrderOfPlay",$U="publishParticipants",tg="unPublishEvent",eg="unPublishEventSeeding",rg="unPublishOrderOfPlay",Mb="unPublishParticipants",Rp="updateInContextMatchUp",Rb={ADD_DRAW_DEFINITION:jf,ADD_MATCHUPS:Mp,ADD_PARTICIPANTS:ci,ADD_SCALE_ITEMS:Yf,ADD_EVENT:HU,ADD_VENUE:Jh,AUDIT:Mi,DATA_ISSUE:Zh,DELETE_PARTICIPANTS:qf,DELETE_VENUE:$f,DELETED_DRAW_IDS:Kf,DELETED_MATCHUP_IDS:zf,MODIFY_DRAW_DEFINITION:Qf,MODIFY_DRAW_ENTRIES:WU,MODIFY_EVENT_ENTRIES:jU,MODIFY_MATCHUP:Xf,MODIFY_PARTICIPANTS:rr,MODIFY_POSITION_ASSIGNMENTS:Jf,MODIFY_SEED_ASSIGNMENTS:Zf,MODIFY_TOURNAMENT_DETAIL:Xi,MODIFY_VENUE:Ri,MUTATIONS:sd,PUBLISH_EVENT_SEEDING:YU,PUBLISH_EVENT:tS,PUBLISH_ORDER_OF_PLAY:qU,PUBLISH_PARTICIPANTS:$U,UNPUBLISH_EVENT_SEEDING:eg,UNPUBLISH_EVENT:tg,UNPUBLISH_ORDER_OF_PLAY:rg,UPDATE_INCONTEXT_MATCHUP:Rp};function eS(t,e){if(!t)return{error:Z};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...C}}function Fo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&eS(t),lt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Mp}),{...C}}function _n({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&eS(t),lt({topic:zf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)eh({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&bt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),lt({topic:Xf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(mr),{error:mr})}function Cb({tournamentId:t,inContextMatchUp:e}){return e?(lt({payload:{inContextMatchUp:e,tournamentId:t},topic:Rp,key:e.matchUpId}),{...C}):{error:mr}}function Ma({tournamentId:t,eventId:e,drawDefinition:r}){return r?(eS(r),lt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:jf,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function bb({tournamentId:t,eventId:e,drawId:r}){return lt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Kf,key:r}),eh({key:r}),{...C}}function bt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(eS(t,r),lt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Qf,key:t.drawId}),{...C}):{error:Z}}function rS({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:Si};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return lt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:Zf,key:t.drawId}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function ko({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:Si};let o=Ct({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return lt({topic:Jf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function KU({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:Z};let o=e.structures?.find(s=>s.stage===$e);if(!o)return{error:_t};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],_n({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),bt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function ad({drawPositions:t,structure:e}){if([ct,rt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Ct({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,extension:{name:Zm,value:!0}})})}function hu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[lc]===!1)return;let{extension:o}=mt({name:lc,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===rt);if(a){let c=Ct({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:lc};At({element:n,extension:s})}function fs({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function Su(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===vt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===vt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Rr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var Ic="SIGN_IN_STATUS",zU="SIGNED_OUT",Tu="SIGNED_IN",Ar="TEAM",Et="INDIVIDUAL",Qr="GROUP",ft="PAIR",wt="TEAM",yu={TEAM_PARTICIPANT:Ar,INDIVIDUAL:Et,GROUP:Qr,TEAM:wt,PAIR:ft},Ob={INDIVIDUAL:Et,GROUP:Qr,PAIR:ft,TEAM:wt,SIGN_IN_STATUS:Ic,SIGNED_OUT:zU,SIGNED_IN:Tu};function Eu({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===wt),s=o.filter(c=>c.participantType===Qr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===Et){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function QU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function vb(t){let e=Object.assign({},...ui.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return QU(e[t])}var ui=[{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 nS({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=ui.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 _b({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?Qi({template:e,source:s}):s)}}}}function Uo(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:re}}function oS(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Uo({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:st}}function nn(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=oS(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:B,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:df};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=J(i.pop(),!1,!0);if(s){let a={timeItem:s,...C};return e&&Object.assign(a,{previousItems:i}),a}else return{info:Oe}}function iS({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:cn};if(!e.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Au({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Ot};if(!n.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function cd({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:q};if(!e.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function sS({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:q};if(!r)return{error:se};let i=Uo({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Oe};let{timeItem:a,previousItems:c,info:u}=nn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var Ak={[Qr]:"groupParticipantIds",[ft]:"pairParticipantIds",[wt]:"teamParticipantIds"},Uk={[Qr]:"groups",[wt]:"teams"};function aS({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,withGroupings:i,internalUse:s,withISO2:a,withIOC:c}){let u=[],p={};for(let d of r.participants??[]){let l=d?.participantId;l&&Nk({participantMap:p,participantId:l})}for(let d of r.participants??[]){let l=J(d,e,s),{participantId:f,individualParticipantIds:g,participantType:I}=l;if(!p[f]){u.push(f);continue}if(Object.assign(p[f].participant,l),g){let h=Dk({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=Pk(l)),o){let{ratings:h,rankings:S,seedings:T}=Aa({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&nS({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=ht(t)?t:void 0;_b({participantMap:p,template:d})}let m;return i&&(m=Eu({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function Pk(t){let{timeItem:e}=nn({itemType:Ic,element:t});return e?.itemValue===Tu}function Dk({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[Ak[n]].push(o),[wt,Qr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=Uk[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===ft){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function Nk({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[Lt]:{...r},[vt]:{...r},[wt]:{...r},...r}}}function Xo({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return aS({...t,...n,tournamentRecord:r});let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>nS({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Eu({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=Aa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function Tt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:YI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...C};function a(c){let p=c?.extensions?.find(m=>m.name===du)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function Go({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:YI};let{appliedPolicies:i}=Tt({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:qc.message}}var cS="WALKOVER",XU="RETIRED",ud="COMPETITIVE",hc="ROUTINE",Sc="DECISIVE",pd="winRatio";var Mk={[Di]:{policyName:"Competitive Bands Default",profileBands:{[Sc]:20,[hc]:50}}},md=Mk;function Zn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=Go({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[Di]??s?.[Di]??md[Di];i.policies[Di]=a}return i}function pi({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:q};let{appliedPolicies:i}=Tt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:qc?.message}}function Ra({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}=pi({policyType:_o,tournamentRecord:t,event:n}),s=(t?mt({element:t,name:Qo}).extension:void 0)?.value,c=(n&&mt({name:Qo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function ng({drawDefinition:t,attributes:e}){let{extension:r}=mt({element:t,name:ed}),n=r?.value||{};return e.forEach(o=>{Object.keys(o).forEach(i=>{n[i]?Object.assign(n[i],o[i]):n[i]=o[i]})}),r={name:ed,value:n},Pp({drawDefinition:t,extension:r}),{entryProfile:n}}function Uu({drawDefinition:t}){let{extension:e}=mt({element:t,name:ed});return{entryProfile:e?.value||{}}}var on="ALTERNATE",og="CONFIRMED",Gr="DIRECT_ACCEPTANCE",dd="FEED_IN",ig="JUNIOR_EXEMPT",gs="LUCKY_LOSER",sg="ORGANISER_ACCEPTANCE",ld="QUALIFIER",Rk="REGISTERED",ag="SPECIAL_EXEMPT",Vr="UNGROUPED",Ci="UNPAIRED",Pu="WILDCARD",mo="WITHDRAWN",cg=[og,Gr,ig,sg,ag],JU=[dd,gs,ld],mi=[og,Gr,dd,ig,sg,ag,Pu],Xr=[og,Gr,ig,gs,ld,sg,ag,Pu],ZU=[on,og,Gr,dd,ig,gs,sg,ld,Rk,ag,Vr,Ci,Pu,mo],xb={ALTERNATE:on,CONFIRMED:og,DIRECT_ACCEPTANCE:Gr,DIRECT_ENTRY_STATUSES:mi,DRAW_SPECIFIC_STATUSES:JU,EQUIVALENT_ACCEPTANCE_STATUSES:cg,FEED_IN:dd,JUNIOR_EXEMPT:ig,LUCKY_LOSER:gs,ORGANISER_ACCEPTANCE:sg,QUALIFIER:ld,SPECIAL_EXEMPT:ag,STRUCTURE_SELECTED_STATUSES:Xr,UNGROUPED:Vr,UNPAIRED:Ci,VALID_ENTRY_STATUSES:ZU,WILDCARD:Pu,WITHDRAWN:mo};function ug({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&ru.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return ng({drawDefinition:e,attributes:o}),!0}return n}function wb({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e});return r[t]?.alternates||0}function Lb({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e});return r[t]?.wildcardsCount||0}function uS({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function bi({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=mt({name:vn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===fe){let{playoffEntries:p,error:m}=Ck({provisionalPositioning:t,drawDefinition:r,structureId:i});return m&&console.log("playoff entries error"),(p?.length?p:u).filter(d=>!e||d.placementGroup===e)}return u}function Ck({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}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===Ve&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=mt({element:h,name:Lo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],y=T.groupOrder||t&&T.provisionalOrder;return h.includes(y)||h.push(y),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:y,GEMscore:E}=S,P=T||t&&y,A=[...i??[]].sort(le).indexOf(P)+1;n.push({entryStage:fe,entryStatus:dd,placementGroup:A,groupingValue:d,participantId:h,GEMscore:E})})})}return{playoffEntries:n}}function Fb({stage:t,drawDefinition:e}){return mi.reduce((r,n)=>(uS({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function sn({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=Ct({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:_t};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===fe&&r&&bi({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let h=I+1;return{participantId:g.participantId,seedValue:h,seedProxy:!0,seedNumber:h}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=QE;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function di(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 Cp({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r.tieFormat)return r.tieFormat;if(r.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function We({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:Cp({item:r,drawDefinition:t,structure:e,event:n})||Cp({item:e,drawDefinition:t,structure:e,event:n})||di(t)||di(n)}}function kb({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 Pe({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function Vo({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}function pS({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(le);return n.map(i=>o.indexOf(i)+1)}function pg(t){if(!ht(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>It(i)||i===void 0||i===null);return n&&o}function Br(t){return Array.isArray(t)?t.every(pg):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Br(t))return{roundMatchUps:[],error:B};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?dt(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(le).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Wt)?l.filter(({matchUpType:h})=>h===Wt):l,I=h=>h.sort((S,T)=>le(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?dt(l.roundNumber):l.roundNumber;return d[f]||(d[f]=nt({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>dt(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&Ln(l)){let f=d+1,g=f+l/2;tt(f,g).forEach((h,S)=>{o[h]=tt(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ae.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>dt(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(le),I=Ae(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ae(I,h),T=l.map(y=>{let{roundPosition:E}=y,P=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!E)return P;let A=P?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return P?.slice().sort(le);let U=jt(I,A).length!==A?.length;if(A?.length&&U)return A?.length===1?[A[0],void 0]:P?.slice().sort(le);let N=(E-1)*2;return S.slice(N,N+2).map(M=>A?.find(R=>M.includes(R)))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]&&s[d+1].matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).find(({matchUpsCount:d})=>!Ln(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function fd(t){if(!Array.isArray(t))return"";let e=t.filter(Jt);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function Gb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:Z};if(!e)return{error:Pr};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==qe)return{error:Vi,info:"Structure is not CONSOLATION stage"};let{links:o}=t,i=o?.filter(m=>m.target.structureId===e)||[],s=i?.reduce((m,d)=>{let{structureId:l}=d.source;return m.includes(l)?m:m.concat(l)},[])||[],a=Object.assign({},...s.map(m=>{let d=Vo({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=Vo({matchUpsMap:r,structureId:e}),{roundProfile:u}=Ke({matchUps:c}),p={};return i?.forEach(m=>{let{structureId:d,roundNumber:l}=m.source,{feedProfile:f,groupedOrder:g,positionInterleave:I,roundNumber:h}=m.target,S=a[d],T=S[1]?.drawPositions,E=S[l]?.matchUpsCount;if(!E)return;let P=E?T.length/E:0,A=T.length/P,U=T.slice(),N=pS({roundPositionsCount:A,groupedOrder:g}),D=N?.length||1;if(D<=A){let O=T.length/D,v=Ae(U,O);f===yi&&v.forEach(x=>x.reverse()),U=N?.length&&N?.map(x=>v[x-1]).flat()||v.flat()}let M=Ae(U,P);if(I){let O=tt(0,I.interleave).map(()=>{}),v=tt(0,I.offset).map(()=>{});M=M.map(F=>[F,...O]),M.unshift(v),M=M.flat(1);let x=M.length-I.offset;M=M.slice(0,x)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;M.forEach((O,v)=>{let x=1+v*b;p[h][x]||(p[h][x]=fd(O))})}),{sourceDrawPositionRanges:p}}function mS({drawDefinition:t}){if(typeof t!="object")return{error:Sa};let e={},{structures:r=[],links:n=[]}=t||{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[qe,fe].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,h=r.find(T=>T.structureId===I).stage,S=[h,I,g,f].join("|");if(p[S])return;p[S]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:h})}}}function Vb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Pr};if(!e){let c=Vo({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ke({matchUps:c}),!e)return{error:st}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ae(p,p.length/u),d=m.map(fd),l=m.map(S=>S.map(T=>T-i)).map(fd),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ae(T,T.length/u)}).filter(Boolean),g=tt(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(le)).map(S=>pt(S)),I=g.map(S=>UC(S).map(fd).join(", ")),h=Object.assign({},...tt(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function gd({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Ke({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Ki)&&!r?.structures&&t&&o}function cr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var mg={[vo]:{policyName:"Round Naming Default",namingConventions:{round:"Round",pre:"Pre"},qualifyingFinishMap:{1:"Final"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q",preQualifying:"P"},stageConstants:{[rt]:"",[fe]:"P",[ct]:"Q",[qe]:"C"}}},Bb=mg;function dS({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=cr({structure:r}),u=gd({structure:r}),p=r.structures,m={},d=mg[vo],l=r.stage===ct,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===ct).map(({stageSequence:b})=>b??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,P=(t?.namingConventions||d.namingConventions).round,A=a&&a!==rt?a[0]:"",U=t?.stageConstants||d.stageConstants,N=a&&U?.[a]||A,D=`${I}${N}${g}`,M=o?Object.keys(o):[],R=l&&U?.[ct]?`${U?.[ct]}-`:"";if(p||c||u)Object.assign(m,...M.map(b=>{let O=`${R}${P} ${b}`,v=`${y}${b}`;return{[b]:{roundName:O,abbreviatedRoundName:v}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...M.map(O=>{if(!o?.[O])return;let{matchUpsCount:v,preFeedRound:x}=o[O],F=v*2,w=b?.[o?.[O].finishingRound]||b&&`${y}${F}`||h[v]||`${y}${F}`,L=x?`-${T}`:"",k=`${w}${L}`,G=[D,s,k].filter(Boolean).join("-"),K=`${S[v]||`${y}${F}`}${L}`,Y=[D,s,K].filter(Boolean).join("-");return{[O]:{abbreviatedRoundName:Y,roundName:G}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var bk=(t,e)=>(t||0)+(e||0);function lS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&cS||r<=e[Sc]&&Sc||r<=e[hc]&&hc||ud}function fS({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(bk)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function Ok(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function gS(t){return t.map(Ok).sort().map(e=>parseFloat(e.toFixed(2)))}function Du({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:mr};let{score:n,winningSide:o}=r;if(!o)return{error:B};let i=!e&&t&&pi({policyType:Di,tournamentRecord:t}).policy,s=e||i?.profileBands||md[Di].profileBands,a=fS({score:n}),c=gS([a]),u=lS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function IS({matchUp:t}){if(!t)return{error:mr};if(t&&!t.sides)return{error:dr};if(t&&!t.hasContext)return{error:Kc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Et).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=pt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...C}}var Id="CHECK_IN",hd="CHECK_OUT",vk="SCHEDULE",Ji="SCHEDULE.ASSIGNMENT.VENUE",lo="SCHEDULE.ALLOCATION.COURTS",Jo="SCHEDULE.ASSIGNMENT.COURT",bp="SCHEDULE.COURT.ORDER",Zi="SCHEDULE.DATE",_k="COMPLETED.DATE",Sd="HOME_PARTICIPANT_ID",dg="SCHEDULE.ASSIGN.OFFICIAL",ts="SCHEDULE.TIME.SCHEDULED",Bo="SCHEDULE.TIME.START",es="SCHEDULE.TIME.STOP",Oi="SCHEDULE.TIME.RESUME",vi="SCHEDULE.TIME.END",Op="SCHEDULE.TIME.MODIFIERS",Hb="TO_BE_ANNOUNCED",Wb="NEXT_AVAILABLE",jb="FOLLOWED_BY",Yb="AFTER_REST",qb="RAIN_DELAY",xk="NOT_BEFORE",hS=[Hb,Wb,jb,Yb,qb],wk="ELIGIBILITY",Lk="REGISTRATION",Fk="SUSPENSION",kk="MEDICAL",Gk="PENALTY",tP="SCALE",eP="RATING",rP="RANKING",lg="SEEDING",Ho="PUBLISH",Cr="PUBLIC",Wo="STATUS",Vk="MODIFICATION",Bk="RETRIEVAL",Hk="other",$b={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:hS,AFTER_REST:Yb,ALLOCATE_COURTS:lo,ASSIGN_COURT:Jo,ASSIGN_OFFICIAL:dg,ASSIGN_VENUE:Ji,CHECK_IN:Id,CHECK_OUT:hd,COMPLETED_DATE:_k,COURT_ORDER:bp,ELIGIBILITY:wk,END_TIME:vi,FOLLOWED_BY:jb,MEDICAL:kk,MODIFICATION:Vk,NEXT_AVAILABLE:Wb,NOT_BEFORE:xk,OTHER:Hk,PENALTY:Gk,PUBLIC:Cr,PUBLISH:Ho,RANKING:rP,RATING:eP,RAIN_DELAY:qb,REGISTRATION:Lk,RESUME_TIME:Oi,RETRIEVAL:Bk,SCALE:tP,SCHEDULE:vk,SCHEDULED_DATE:Zi,SCHEDULED_TIME:ts,SEEDING:lg,START_TIME:Bo,STATUS:Wo,STOP_TIME:es,SUSPENSION:Fk,TIME_MODIFIERS:Op,TO_BE_ANNOUNCED:Hb};function Is({matchUp:t}){if(!t)return{error:mr};if(!t.hasContext)return{error:Kc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:dr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=IS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Id,hd].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===Id);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...C}}var de=t=>e=>{let r=ht(e)&&e?.matchUpType||kt(e)&&e;return r&&vI[t].includes(r)};function vp(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 _p(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 SS({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 Kb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&_p({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&_p({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&_p({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return SS({categoryName:i,categoryType:s,timesBlockArray:m})}function zb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&vp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&vp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&vp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return SS({categoryName:e,categoryType:r,timesBlockArray:p})}var nP="DOUBLES_SINGLES",oP="SINGLES_DOUBLES",fo="total",TS="participantConflict",Ca="matchUpConflict",iP="ISSUE_IDS",Tc="CONFLICT",yc="WARNING",yS="ERROR",ES="ISSUE",fg="STATE",Qb={SINGLES_DOUBLES:oP,DOUBLES_SINGLES:nP,TOTAL:fo,CONFLICT_MATCHUP_ORDER:Ca,CONFLICT_PARTICIPANTS:TS,SCHEDULE_ISSUE_IDS:iP,SCHEDULE_CONFLICT:Tc,SCHEDULE_WARNING:yc,SCHEDULE_ERROR:yS,SCHEDULE_ISSUE:ES,SCHEDULE_STATE:fg};function Nu({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:q};s=s??a?.eventType??qs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Ra({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return xp({eventType:s,timingDetails:p})}function xp({timingDetails:t,eventType:e}){let r=zb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Kb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=de(qs)(e)?oP:nP,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function sP(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Zo({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>sP(o)-sP(i)).pop(),n=r&&sP(r);return{itemValue:r?.itemValue,timeStamp:n}}function AS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:ts});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Xs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Zi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function wp(t){if(nh.test(t)){let e=Mf();return new Date(`${e}T${t}`)}else return new Date(t)}function Xb({matchUp:t}){if(!t)return{error:mr};if(!t.timeItems)return{error:df};let e=t.timeItems.filter(n=>[Bo,es,Oi,vi].includes(n?.itemType)).sort((n,o)=>wp(n.itemValue).getTime()-wp(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 Bo:i=0;break;case vi:if(n.lastValue&&[Bo,Oi].includes(n.lastType)){let u=wp(o.itemValue).getTime()-wp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case es:if([Bo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=wp(o.itemValue).getTime()-wp(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([Bo,Oi].includes(r.lastType)){let n=new Date().getTime()-wp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:Wk(r.milliseconds),relevantTimeItems:e}}function Wk(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 Jb({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===Bo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function Ec(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:B};let o=Rr(t);r.venueId||(r.venueId=Nt());let i;for(let s of Object.values(o)){let a=jk({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||lt({topic:Jh,payload:{venue:r}}),nt({...C,venue:i})}function jk({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Nt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:OA}:(r&&At({element:n,extension:{value:r,name:OU}}),t.venues.push(n),e||lt({payload:{venue:n,tournamentId:t.tournamentId},topic:Jh}),{...C,venue:J(n)})):{error:st,info:"missing venue"}:{error:q}}function ti({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:q};if(!r)return{error:ai};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(fu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=ti({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return Ec({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:ji}}function US({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=ti({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function hs({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:q};if(!r)return{error:Bi};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...C,court:o,venue:i};if(t){let a=(fu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=hs({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&Ec({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:Vs},stack:n})}function PS(t){return J(hs(t),!1,!0)}function Td({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:q};if(!r)return{error:Bi};let n=hs({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...C,courtInfo:J(o,!1,e)}}function Ac(t){let e=et(t,[{[ne]:!0},{venueId:!0,[In]:ai}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=ti({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(Td({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:m})=>({venueAbbreviation:m,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...C,venueData:J(c,!1,!0)}}function Zb({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===vi&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:Ot};let n=mt({name:pn,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function ze(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Ht({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,..._({result:{error:qr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:br},context:{drawId:n,eventId:r},stack:o})}}function yd(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:mr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let P=t.drawDefinition||e?.drawDefinitions?.find(U=>U.drawId===p.drawId);!P&&i&&({drawDefinition:P,event:e}=ze({drawId:p.drawId,tournamentRecord:i}));let A=p.structureId&&P?.structures?.find(({structureId:U})=>U===p.structureId);r=t.matchUpType||A?.matchUpType||P?.matchUpType||e?.eventType!==_e&&e?.eventType}let{milliseconds:m,time:d}=Xb({matchUp:p}),{startTime:l}=Jb({matchUp:p}),{endTime:f}=Zb({matchUp:p}),g,{eventIds:I,drawIds:h}=n??{};if((!I||I.includes(p.eventId))&&(!h||h.includes(p.drawId))){let P=Q=>Q.createdAt?new Date(Q.createdAt).getTime():0,A=new Map,U=p.timeItems?.toSorted((Q,ut)=>P(Q)-P(ut))??[];for(let Q of U)A.set(Q.itemType,Q.itemValue);let N=A.get(Sd),D=A.get(lo),M=A.get(ts),R=A.get(Op),b=A.get(Zi),O=A.get(dg),v=A.get(bp),x=A.get(Ji),F=A.get(Jo),w,L,k,G,H,K=p.matchUpType??r;if(a&&M&&o&&K){let Q={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:L=0,recoveryMinutes:k=0,typeChangeRecoveryMinutes:G=0}=xp({timingDetails:Q,eventType:K})),(L||k)&&(w=f?$r(zt(f),k):$r(M,L+k)),G&&(H=f?$r(zt(f),G):$r(M,L+G))}!b&&M&&(b=Ut(M));let Y=Bm({scheduledDate:b,scheduledTime:M}),j={},V=(i&&x&&Ac({tournamentRecord:i,venueId:x}))?.venueData||{};x&&(j[x]=V);let{venueName:$,venueAbbreviation:X,courtsInfo:W}=V,z=(F&&W?.find(Q=>Q.courtId===F))?.courtName;for(let Q of D||[]){if(!i)break;Q.venueId&&!j[Q.venueid]&&(j[Q.venueId]=Ac({venueId:Q.venueId,tournamentRecord:i})?.venueData);let ut=j[Q.venueId];Q.venueName=ut?.venueName;let ot=ut?.courtsInfo?.find(Dt=>Dt.courtId===Q.courtId);Q.courtName=ot?.courtName}g=nt({typeChangeTimeAfterRecovery:H,timeAfterRecovery:w,scheduledDate:b,scheduledTime:M,isoDateString:Y,homeParticipantId:N,venueAbbreviation:X,allocatedCourts:D,timeModifiers:R,venueName:$,venueId:x,courtOrder:v,courtName:z,courtId:F,official:O,typeChangeRecoveryMinutes:G,recoveryMinutes:k,averageMinutes:L,milliseconds:m,startTime:l,endTime:f,time:d})}else g=nt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Xs({matchUp:p}),{scheduledTime:T}=AS({matchUp:p});if(s&&u?.displaySettings?.draws){let P=u.displaySettings.draws,A=(P?.[p.drawId]??P?.default)?.scheduleDetails;if(A){let U=(A.find(N=>S&&N.dates?.includes(S))??A.find(N=>!N.dates?.length))?.attributes;if(U){let N=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),U);g=Qi({source:g,template:N})}}}let E=p.matchUpStatus&&ae.includes(p.matchUpStatus)&&(Ut(f)||Ut(S)||Ut(T))||void 0;return{schedule:g,endDate:E}}function tO({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(LI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>ke(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(wI(t)){let c=[...t].sort(le);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(dt(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Lp({collectionPosition:t,collectionId:e,lineUp:r}){let n=[],o=[];if(r){let i=a=>a===void 0?-1:a,s=r.map(a=>{let{collectionAssignments:c,participantId:u}=a,p=c?.find(m=>m.collectionPosition===t&&m.collectionId===e);return p&&{participantId:u,...p}}).filter(Boolean).sort((a,c)=>i(a.substitutionOrder)-i(c.substitutionOrder));for(let a of s){let{participantId:c,previousParticipantId:u,substitutionOrder:p}=a;n.includes(c)||(u&&o.push({previousParticipantId:u,substitutionOrder:p,participantId:c}),n=n.filter(m=>m!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function Sn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:q};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return _({result:{error:bo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===ft&&jt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:re},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function Ss({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:se};let{extension:r}=mt({element:t,name:wo});return{lineUp:(r?.value||{})[e]}}function eO({tournamentParticipants:t,positionAssignments:e,collectionPosition:r,drawPositions:n=[],participantMap:o,drawDefinition:i,collectionId:s,sideLineUps:a,matchUpType:c}){if(!s||!r)return{};let u=({attribute:m,lineUp:d,teamParticipant:l})=>{let{assignedParticipantIds:f,substitutions:g}=Lp({collectionPosition:r,collectionId:s,lineUp:d});if(c===vt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||Sn({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[m]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[m]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[m]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let m=a?.map(d=>{let{teamParticipant:l,sideNumber:f}=d,g=d.lineUp||Ss({participantId:l.teamParticipantId,drawDefinition:i})?.lineUp;return u({attribute:f,lineUp:g,teamParticipant:l})}).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...m)}}let p=n?.map(m=>{let d=e.find(I=>I.drawPosition===m)?.participantId,l=a?.find(I=>I?.drawPosition===m),f=l?.teamParticipant||d&&o?.[d]?.participant||t?.find(({participantId:I})=>I===d),g=l?.lineUp||Ss({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function Ed(t){let e=et(t,[{[Gn]:!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===Et&&Lt||s===ft&&vt||s===wt&&wt||void 0}return{matchUpType:n}}function rO({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:r,displaySideNumber:n,seedAssignments:o,drawPosition:i,isFeedRound:s,sideNumber:a}){let c=r.find(l=>l.drawPosition&&l.drawPosition===i),u=i&&t,p=a&&e,m=u?u[i]?.participantId:c?.participantId,d=c?Yk({displaySideNumber:n,seedAssignments:o,participantId:m,assignment:c,sideNumber:a}):{...p?.[a]};if(s&&(a===1?Object.assign(d,{participantFed:!0}):Object.assign(d,{participantAdvanced:!0})),i&&u){let l=u[i]?.teamParticipant,f=u[i]?.participant,g=u[i]?.substitutions;f&&(d.participant=f),g&&(d.substitutions=g),l&&(d.teamParticipant=l)}return d}function Yk({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=qk({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 qk({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function aP({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:m,appliedPolicies:d,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,publishStatus:E,scoringActive:P,matchUpTieId:A,isRoundRobin:U,roundProfile:N,sideLineUps:D,structure:M,context:R,matchUp:b,event:O}){c=c??{};let v=We({drawDefinition:y,structure:M,matchUp:b,event:O})?.tieFormat,{roundOffset:x,structureId:F,structureName:w,stage:L,stageSequence:k}=M,{drawId:G,drawName:H,drawType:K}=y??{},Y=v?.collectionDefinitions,j=b.collectionId&&Y?.find(me=>me.collectionId===b.collectionId),V=b.collectionId?j?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??O?.matchUpFormat,$=b.matchUpType||j?.matchUpType||M?.matchUpType||y?.matchUpType||!de(_e)(O?.eventType)&&O?.eventType,X=l?"BYE":b.matchUpStatus,{schedule:W,endDate:it}=yd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:V,publishStatus:E,matchUpType:$,matchUp:b,event:O}),z=m??b.drawPositions??[],{collectionPosition:Q,collectionId:ut,roundPosition:ot}=b,Dt=b.roundNumber??c.roundNumber,Rt=ut?eO({tournamentParticipants:r,positionAssignments:n,collectionPosition:Q,participantMap:I,drawDefinition:y,drawPositions:z,collectionId:ut,sideLineUps:D,matchUpType:$}):void 0,De=u?.[Dt]?.roundName||c.roundName,qt=u?.[Dt]?.abbreviatedRoundName||c.abbreviatedRoundName,Se=N?.[Dt]?.feedRound,_r=N?.[Dt]?.preFeedRound,dn=N?.[Dt]?.roundFactor,hr=o?.[Dt],Xe=ot?hr?.[ot]:void 0,Zt=e?.[Dt],Pt=j?.category?{...R?.category,...j.category}:R?.category??O?.category,ce=b.processCodes?.length&&b.processCodes||j?.processCodes?.length&&j?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||O?.processCodes?.length&&O?.processCodes||p?.processCodes,ue=T?.withCompetitiveness&&Du({...h,matchUp:b}),Fe=b.finishingPositionRange??c.finishingPositionRange,te=L!==ct&&It(a)&&a+(Dt||0),Je=me=>nt(me,void 0,!0),$t={...Je(R),...Je({matchUpFormat:$===_e?void 0:V,tieFormat:$===_e?v:void 0,gender:j?.gender??O?.gender,endDate:b.endDate??it,discipline:O?.discipline,category:Pt,finishingPositionRange:Fe,abbreviatedRoundName:qt,drawPositionsRange:Xe,competitiveProfile:ue,structureName:w,stageSequence:k,drawPositions:z,matchUpStatus:X,processCodes:ce,isRoundRobin:U,matchUpTieId:A,preFeedRound:_r,matchUpType:$,roundFactor:dn,roundOffset:x,structureId:F,roundNumber:Dt,roundOfPlay:te,feedRound:Se,roundName:De,drawName:H,drawType:K,schedule:W,drawId:G,stage:L}),...J(Je(b),!0,!0)};if(V&&b.score?.scoreStringSide1){let me=Ne(V),{bestOf:Sr,finalSetFormat:jr,setFormat:Kt}=me??{};(jr?.tiebreakSet||Kt?.tiebreakSet||Kt?.timed)&&($t.score.sets=$t.score.sets.sort((Te,gr)=>Te.setNumber-gr.setNumber).map((Te,gr)=>{let ee=gr+1===Sr&&jr?jr:Kt,Ur=ee?.tiebreakSet&&!ee?.timed,Cn=ee?.timed;return Ur?(Te.tiebreakSet=!0,[1,2].includes(Te.winningSide)&&(Te.side1Score=Te.winningSide===1?1:0,Te.side2Score=Te.winningSide===2?1:0)):Cn&&(Te.timed=!0),Te}))}if(Array.isArray(z)){let{orderedDrawPositions:me,displayOrder:Sr}=tO({drawPositions:z,roundProfile:N,roundNumber:Dt}),jr=N?.[Dt]?.feedRound,Kt=Sr[0]!==me[0],gr=me.concat(void 0,void 0).slice(0,2).map((Ee,Rn)=>{let ee=Rn+1,Ur=Kt?3-ee:ee,Cn=rO({...Rt,positionAssignments:n,displaySideNumber:Ur,seedAssignments:f,drawPosition:Ee,isFeedRound:jr,sideNumber:ee}),An=b.sides?.find(ep=>ep.sideNumber===ee),hi=ot?(ot-1)*2+Rn+1:void 0,ga=hi?Zt?.[hi]:void 0;return Je({sourceDrawPositionRange:ga,...An,...Cn})});Object.assign($t,J({sides:gr},!0,!0))}if(r&&$t.sides){let me=d?.[zs],Sr=Kt=>{let Te=I?.[Kt]?.participant;return Te&&Qi({template:me?.participant,source:Te})};if($t.sides.filter(Boolean).forEach(Kt=>{if(Kt.participantId){let Te=J(Sr(Kt.participantId)||(r?zo({policyDefinitions:d,participantId:Kt.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(Te){let gr,Ee;if(y?.entries){let Rn=y.entries.find(Ur=>Ur.participantId===Kt.participantId),ee=O?.entries?.find(Ur=>Ur.participantId===Kt.participantId);gr=Rn?.entryStatus||ee?.entryStatus,Te.entryStatus=gr,Rn?.entryStage&&(Ee=Rn.entryStage,Te.entryStage=Ee)}i===!1?Object.assign(Kt,{participant:{entryStage:Ee,entryStatus:gr}}):Object.assign(Kt,{participant:Te})}}if(Kt?.participant?.individualParticipantIds?.length&&!Kt.participant.individualParticipants?.length){let Te=Kt.participant.individualParticipantIds.map(gr=>Sr(gr)||(r?zo({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:gr}):void 0));i!==!1&&Object.assign(Kt.participant,{individualParticipants:Te})}}),!$t.matchUpType){let{matchUpType:Kt}=Ed({matchUp:$t});Kt&&Object.assign($t,{matchUpType:Kt})}if(T?.inferGender&&(!$t.gender||$t.gender===qi)&&$t.sides?.length===2&&$t.matchUpType!==_e){let Kt=$t.sides.map(Te=>{if(de(Lt)($t.matchUpType))return Te.participant?.person?.sex;if(Te.participant?.individualParticipants?.length===2){let gr=pt(Te.participant.individualParticipants.map(Ee=>Ee.person?.sex)).filter(Boolean);if(gr.length===1)return gr[0]}});if(Kt.filter(Boolean).length===2&&pt(Kt).length===1){let Te=Kt[0];$t.inferredGender=Te}}}if($t.tieMatchUps){let me=$t.matchUpStatus==="BYE",Sr=$t.sides?.map(({participant:jr,drawPosition:Kt,sideNumber:Te,lineUp:gr})=>{let Ee=jr?.participantType===_e&&jr;return{teamParticipant:Ee&&nt({participantRoleResponsibilities:Ee.participantRoleResponsibilities,participantOtherName:Ee.participanOthertName,participantName:Ee.participantName,participantId:Ee.participantId,teamId:Ee.teamId}),drawPosition:Kt,sideNumber:Te,lineUp:gr}});$t.tieMatchUps=$t.tieMatchUps.map(jr=>{let Kt=$t.matchUpId,gr={finishingPositionRange:$t.finishingPositionRange,abbreviatedRoundName:qt,roundNumber:Dt,roundName:De};return aP({tieDrawPositions:z,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:Sr,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:gr,appliedPolicies:d,isCollectionBye:me,usePublishState:g,publishStatus:E,matchUpTieId:Kt,isRoundRobin:U,roundProfile:N,matchUp:jr,event:O,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:P,structure:M,context:R})})}let ir=$t.sides?.filter(me=>me?.participantId).length===2,fr=!$t.winningSide;if(Object.assign($t,{readyToScore:P&&ir&&fr,hasContext:!0}),ir){let{allParticipantsCheckedIn:me,checkedInParticipantIds:Sr}=Is({matchUp:$t});Object.assign($t,{allParticipantsCheckedIn:me,checkedInParticipantIds:Sr})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(me=>delete $t[me]),$t}function nO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:lo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function oO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Jo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function iO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function _i(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:E,tournamentIds:P,matchUpTypes:A,structureIds:U,readyToScore:N,courtIds:D,eventIds:M,venueIds:R,drawIds:b,stages:O}=t,v=Array.isArray(y)?y.filter(Boolean):[],x=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],w=Array.isArray(O)?O.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],k=Array.isArray(p)?p.filter(Boolean):[],G=Array.isArray(f)?f.filter(Boolean):[],H=Array.isArray(d)?d.filter(Boolean):[],K=Array.isArray(c)?c.filter(Boolean):[],Y=Array.isArray(l)&&I?l.filter(Boolean):[],j=Array.isArray(A)&&g?A.filter(Boolean):[],V=Array.isArray(D)?D.filter(Boolean):[],$=Array.isArray(R)?R.filter(Boolean):[],X=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],W=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],it=Array.isArray(P)?P.filter(Boolean):[],z=Array.isArray(M)?M.filter(Boolean):[],Q=Array.isArray(b)?b.filter(Boolean):[],ut=Array.isArray(U)?U.filter(Boolean):[];return e.filter(ot=>{if(N&&!de(xr)(ot)&&!ot.readyToScore||ot.winningSide&&s&&![1,2].includes(ot.winningSide)||m!==void 0&&(m&&!ot.tieMatchUps||!m&&ot.tieMatchUps)||o!==void 0&&(o&&!ot.collectionId||!o&&ot.collectionId)||w.length&&!w.includes(ot.stage)||L.length&&!L.includes(ot.stageSequence)||k.length&&(!ot.collectionId||!k.includes(ot.collectionId))||G.length&&(!ot.roundName||!G.includes(ot.roundName))||H.length&&(!ot.roundNumber||!H.includes(ot.roundNumber))||K.length&&(!ot.roundPosition||!K.includes(ot.roundPosition))||x.length&&(!ot.matchUpStatus||!x.includes(ot.matchUpStatus))||F.length&&ot.matchUpStatus&&F.includes(ot.matchUpStatus)||Y.length&&!Y.includes(ot.matchUpId)||j.length&&(!ot.matchUpType||!Yc(j,ot.matchUpType))||X.length&&(!ot.matchUpFormat||!X.includes(ot.matchUpFormat)))return!1;if(W?.length){let{scheduledTime:Dt}=AS({matchUp:ot}),{scheduledDate:Rt}=Xs({matchUp:ot}),qt=Ut(Dt)||Rt;if(!W.find(Se=>zn(Se,qt)))return!1}if(V.length){let{courtId:Dt}=oO({matchUp:ot}),{allocatedCourts:Rt}=nO({matchUp:ot}),De=Rt?.map(({courtId:qt})=>qt);if(!V.filter(Boolean).includes(Dt)||De?.includes(Dt))return!1}if($.length){let{venueId:Dt}=iO({matchUp:ot});if(!$.filter(Boolean).includes(Dt))return!1}if(E){if(it.length&&!it.includes(ot.tournamentId)||z.length&&!z.includes(ot.eventId)||Q.length&&!Q.includes(ot.drawId)||ut.length&&!ut.includes(ot.structureId))return!1;let Dt=ot.sides?.map(({participantId:Rt})=>Rt).filter(Boolean)??[];if(n&&Dt.length<n||v.length&&!v.some(De=>Dt.includes(De)))return!1}return!0})}function yt(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:m,contextContent:d,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:Si,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),P=!s||!T?.length||T.includes(s.drawId);if(!y||!E||!P)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=Zn({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:A}=Tt({drawDefinition:s}),U={...t.tournamentAppliedPolicies,...A,...t.policyDefinitions},N=U?.scoring?.structures,D=c.stage&&N?.stage?.[c.stage],M=c.stageSequence&&D?.stageSequence?.[c.stageSequence],R=U?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned;f||(f=Pe({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:O}=Ie({structure:c}),v=!R||O,{seedAssignments:x}=sn({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??x;let{structureId:F}=c;l=l||s&&mS({drawDefinition:s}).exitProfiles;let w=l?.[F],L=w?.length&&(w[0].split("-").map(V=>parseInt(V)).reduce((V,$)=>V+$)||0),k=!!c.structures,G=Vo({matchUpsMap:f,structureId:F,inContext:u}),H=U?.[vo],K=dS({roundNamingPolicy:H,drawDefinition:s,structure:c,matchUps:G}),{roundNamingProfile:Y,roundProfile:j}=K;if(I=K?.roundMatchUps??[],o&&(G=_i({matchUps:G,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:V}=Gb({drawDefinition:s,matchUpsMap:f,structureId:F}),$=s?Vb({drawDefinition:s,roundProfile:j,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0,X=t.tournamentParticipants,W=t.participantMap;!X?.length&&!W&&r&&({participants:X=[],participantMap:W}=Xo({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:r,contextProfile:i,inContext:u})),G=G.map(z=>aP({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:V,tournamentParticipants:X,positionAssignments:b,drawPositionsRanges:$,initialRoundOfPlay:L,roundNamingProfile:Y,tournamentRecord:r,appliedPolicies:U,seedAssignments:m,contextContent:d,participantMap:W,contextProfile:i,drawDefinition:s,scoringActive:v,isRoundRobin:k,roundProfile:j,structure:c,context:a,matchUp:z,event:p})),(G?.filter(z=>Array.isArray(z.tieMatchUps))).forEach(z=>{let Q=z.tieMatchUps;G=G.concat(...Q)}),n&&(G=_i({processContext:!0,...n,matchUps:G}))}else(G?.filter($=>Array.isArray($.tieMatchUps))).forEach($=>{let X=$.tieMatchUps;G=G.concat(...X)});return o&&(G=_i({matchUps:G,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(G=_i({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:G})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ke({matchUps:G}).roundMatchUps??[]),We({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=kb({matchUps:G})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:k,roundProfile:j,matchUpsMap:f,matchUps:G}}function Ts({matchUp:t}){return t?ae.includes(t?.matchUpStatus)||t?.winningSide:!1}function Mu({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structureId:T,inContext:y,structure:E,context:P,event:A}){!E&&T&&({structure:E}=at({drawDefinition:I,structureId:T}));let U=yt({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structure:E,inContext:y,context:P,event:A}),N=[],D=[],M=[],R=[],b=[];if(U.error)return U;let{matchUps:O}=U,{assignedPositions:v}=Ie({structure:E}),x=v?.filter(w=>w.participantId).map(w=>w.drawPosition),F;return O.filter(w=>{let L=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===Wt;return!(w.matchUpType!==Wt&&L)}).forEach(w=>{if(w.matchUpStatus===vr){N.push(w);return}w.matchUpType===Wt&&(F=!0);let L=!!w.collectionId,k=L&&w.sides?.every($=>$.participantId),G=!L&&w.drawPositions?.filter(Boolean).length===2,H=!L&&w.drawPositions?.every($=>x?.includes($)),K=v?.filter($=>$.bye).map($=>$.drawPosition),Y=!L&&w.drawPositions?.find($=>K?.includes($)),V=zh.includes(w.matchUpStatus)&&(k||G&&(!t||H));return Y?b.push(w):Ts({matchUp:w})?D.push(w):V?M.push(w):R.push(w)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:E}}function sO({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Pr};let{links:n}=Js({drawDefinition:t,structureId:r}),o=n.source.reduce((s,a)=>!a.source.roundNumber||a.source.roundNumber===e?s.concat(a):s,[]),i=n.target.reduce((s,a)=>!a.target.roundNumber||a.target.roundNumber===e?s.concat(a):s,[]);return{links:{source:o,target:i}}}function DS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||ke(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Xn,so].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:B},stack:"getTargetLink",context:o}):o}function Js({drawDefinition:t,structureId:e,roundNumber:r}){return t?e?{links:(t.links||[]).filter(Boolean).reduce((i,s)=>(s.source?.structureId===e&&(!r||s.source.roundNumber===r)&&(i.source=i.source.concat(s)),s.target?.structureId===e&&(!r||s.target.roundNumber===r)&&(i.target=i.target.concat(s)),i),{source:[],target:[]})}:{error:Pr}:{error:Z}}function aO({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 NS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:$l};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({drawDefinition:n,structureId:i}),{positionAssignments:m}=Ct({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=tt(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let D=u.offset+(r-1)*u.interleave,M=r+D;h=Math.ceil(M/2),S=1-M%2}let T=g,y=g[h-1],E=pS({roundPositionsCount:g.length,groupedOrder:a}),P=E?.length||1;if(P<=g.length){let D=f/P,M=Ae(g,D);s===yi&&M.forEach(R=>R.reverse()),T=E?.length&&E?.map(R=>M[R-1]).flat()||T}s===Nn?y=T[h-1]:s===yi?((!E?.length||P>g.length)&&(h=l.length+1-h),y=T[h-1]):s===Sp&&Dr()&&console.log(pp,{feedProfile:s});let A=y&&l.reduce((D,M)=>M.roundPosition===y?M:D,void 0),U;A?.feedRound?(S=0,U=Math.min(...(A.drawPositions||[]).filter(Boolean))):U=A?.drawPositions?.length===2&&A?.drawPositions[S];let N=m?.find(({drawPosition:D})=>D===U);if(N){let{extension:D}=mt({element:N,name:Zm});if(D?.value)return{disabledDrawPosition:U}}return{matchUp:A,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function ur({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===zi?$k({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Kk({matchUp:i})}function $k({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=sO({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=DS({source:c,linkType:Xn}),p=DS({linkCondition:kn,linkType:so,source:c}),m=DS({source:c,linkType:so}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,E,P,A,U,N;if(e&&(i||s)&&(P=i&&l!==fn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==fn&&t.find(({matchUpId:R})=>R===s),P||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:P}};let{roundPosition:D}=o;N=N||t.filter(R=>R.structureId===n.structureId);let M=N.reduce((R,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?R+1:R,0);return m&&!T&&f!==fn&&({matchUpDrawPositionIndex:E,targetDrawPosition:y,matchUp:T}=NS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==fn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=NS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!P&&l!==fn&&({matchUpDrawPositionIndex:U,targetDrawPosition:A,matchUp:P}=NS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),P||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:P}=aO({structureMatchUps:N,matchUp:o})),nt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:E,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:P,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function Kk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function cO({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=at({drawDefinition:t,structureId:i});if(a?.finishingPosition===Ei){let{roundNumber:c}=n,u=c&&dt(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Ke({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(le).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=ur({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=cP({upcomingMatchUp:u}),d=cP({upcomingMatchUp:p});if(n.matchUpStatus!=="BYE"&&p?.matchUpStatus==="BYE"){let{matchUp:f}=uO({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&cP({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&Yt(m.schedule.scheduledTime)<Yt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&Yt(d.schedule.scheduledTime)<Yt(l)&&(r[d.matchUpId]=n.matchUpId,d.schedule.scheduleConflict=n.matchUpId)),Object.assign(n,{winnerTo:m,loserTo:d}),n.drawPositions?.filter(Boolean).length){let g=c.targetLinks?.loserTargetLink?.linkCondition===kn,I=zk(n);if(I.length){let h=Hf(u?.sides),S=Hf(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,P=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&P.length<2&&P.push({bye:!0,tbd:!0}),y?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:A})=>A===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(y)),P?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(P))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function zk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function uO({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Qt)return{matchUp:t};if(o==="BYE"){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=ur({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},uO({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function cP(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 ie(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=Zs(t);if(r.error)return _({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 Zs(t){if(!t?.drawDefinition)return{error:Z};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:y,context:E,event:P}=t,A=[],U=[],N=[],D=[],M=[];h&&!r&&(r=Zn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:P}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=Eu({participants:e,participantsProfile:a})));let{structures:b}=hn({drawDefinition:S});if(!b)return{error:_t};n||(n=Pe({drawDefinition:S}));let O=S&&mS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:w=[],pendingMatchUps:L=[],upcomingMatchUps:k=[],completedMatchUps:G=[],abandonedMatchUps:H=[]}=Mu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||T||d,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:O,matchUpsMap:n,structure:F,context:E,event:P});A=A.concat(...H),U=U.concat(...G),N=N.concat(...k),D=D.concat(...L),M=M.concat(...w)});let v=F=>(!l&&!T&&!d||(l&&(F=_i({matchUps:F,...l})),d&&(F=_i({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:v(A),completedMatchUps:v(U),upcomingMatchUps:v(N),pendingMatchUps:v(D),byeMatchUps:v(M),matchUpsMap:n,...C,groupInfo:R};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:w,completed:L,upcoming:k,pending:G,bye:H}=F,K=[].concat(...w&&A||[],...L&&U||[],...k&&N||[],...G&&D||[],...H&&M||[]);cO({inContextDrawMatchUps:K,drawDefinition:S})}return x}function to(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:h,event:S}=t;if(!S)return{error:Ot};let{eventId:T,eventName:y,endDate:E,eventType:P,category:A,gender:U,matchUpFormat:N}=S??{},D={...h,...nt({indoorOutDoor:S.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:S.surfaceCategory??p?.surfaceCategory,endDate:S.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:N,eventName:y,eventType:P,category:A,eventId:T,gender:U})};E&&(D.endDate=E),f&&!r&&(r=Zn({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:S}));let M;if(!e?.length&&!n&&p){let v=Xo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=v.participantMap,e=v.participants??[],M=v.groupInfo}let R=S.drawDefinitions??[],b=Ra({tournamentRecord:p,event:S}).scheduleTiming;return{matchUps:R.flatMap(v=>{let{matchUps:x}=ie({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:D,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:v,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:b,nextMatchUps:g,inContext:I,event:S});return x??[]}),groupInfo:M}}function ye(t){let e=et(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:q};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:m,contextProfile:d,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,h=t.tournamentId??u.tournamentId,S=u?.events??[];n||({participants:n,participantMap:r}=Xo({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:d,inContext:p}));let{appliedPolicies:T}=Tt({tournamentRecord:u}),y={...I,tournamentId:h,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},E=Zn({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:S.flatMap(A=>(y.eventDrawsCount=A.drawDefinitions?.length??0,to({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:m,contextContent:E,contextFilters:f,contextProfile:d,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:A}).matchUps??[])).concat(...u.matchUps??[])}}function Mn({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:xt};let m=Object.keys(n).map(d=>{let l=n[d];return ye({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...C,matchUps:m}}function xi(t,e){return Qk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Qk(t,e){return($s[t?.stage]||0)-($s[e?.stage]||0)}function nr(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:y,endDate:E,eventType:P,category:A,gender:U,matchUpFormat:N}=S??{},D={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:N,eventType:P,eventName:y,category:A,eventId:T,endDate:E,gender:U},M;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:M}=Xo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=Zn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...ie({context:D,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:d,contextProfile:l,matchUpFilters:m,participantMap:r,nextMatchUps:g,inContext:I,event:S}),groupInfo:M}}function ys({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=J(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}var uP=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:ys({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:ys({element:e,accessor:r})?.value}))||(typeof t=="string"&&ys({element:e,accessor:t}))?.value,Hr=uP;function ba({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Br(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Ke({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,m=p&&c?.[n-p]?.matchUpsCount,d=c&&Object.values(c).map(Hr("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},y=d?.slice(I-1).reduce((R,b)=>R+(b||0),0),E=a&&I!==1,P=1+t+(E?r??0:0),A=1,U=tt(P,s?P+S*2:y+P+A),N=y+A-S,D=l(U.slice(N)),M=l(U.slice(0,N),!0);return T.finishingPositionRange={loser:D,winner:M},{[I]:T}})),g=Dr({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 rs({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=ie({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];ba({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=ur({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=Vo({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function an(t){let e=Rr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:no};if(!Array.isArray(n))return{error:cn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ps};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(E=>(E.drawDefinitions||[]).map(P=>P.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===Fn),g=r;if(f.length){g=Mn({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,E)=>{let P=E.source?.structureId,A=E.target?.structureId;return P&&A&&(p[A]=P),P&&!y.includes(P)&&y.push(P),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let E=y.containerStructureId||y.structureId;T.includes(E)&&c[E].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(P=>{u[y].matchUpIds.push(P)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(P=>u[y].participantIds.push(P))},S=T=>{let y=Object.keys(c).length;for(let E of T||[]){let{matchUpId:P,winnerMatchUpId:A,loserMatchUpId:U}=E;if(!a.length||a.includes(P)){if(I(P),o){let{individualParticipantIds:M}=Su(E);u[P].participantIds=M}A&&(I(A),h(P,A),m[A].push(P)),U&&(I(U),h(P,U),m[U].push(P)),u[P].sources.push(m[P]);let N=m[P].map(M=>u[M].sources[0]).flat(),D=m[P].map(M=>u[M].sources[1]).flat();if(u[P].sources.push(N,D),y){let M=E.containerStructureId||E.structureId,R=p[M];if(c[R])for(let b of c[R])I(b),h(b,P),m[b].push(P)}}}};if(s)rs({drawDefinition:s}),g?.length||(g=nr({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=Mn({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:E=[]})=>E.map(({drawId:P})=>P))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(P=>P.drawId===T).sort(xi);if(!y?.find(({roundPosition:P})=>!P)){let P=y?.find(({tournamentId:U})=>U),{drawDefinition:A}=ze({tournamentRecord:e[P?.tournamentId],drawId:T});A&&rs({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function he(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 Oa({matchUpStatus:t}){return $h.includes(t)}function pO({matchUpStatus:t}){return id.includes(t)}function gg({matchUpStatus:t}){return Kh.includes(t)}function Ig({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(Ig)?.length;return he({score:o})||s||e&&i||t&&pO({matchUpStatus:t})&&![Gt,Bt,Hn].includes(t)}function va(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=fs({drawDefinition:e}),a=n?s[n]||[]:[],c={isCollectionMatchUp:!1};if(!i){let A=at({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(cr({structure:i}))return{structure:i,isAdHoc:!0,error:Ls};let{matchUps:u}=ie({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||a.includes(A.structureId)),{matchUpDependencies:m}=an({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let A of u??[]){if(A.structureId===n||a.includes(A.structureId)){l.push(...A.drawPositions??[]);let U=A.roundNumber;for(let N of(A.drawPositions??[]).filter(Boolean))(!f[N]||U&&f[N]>U)&&(f[N]=U)}Ig(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=pt(l.filter(Boolean)).sort(le),h=pt(d),S=pt(p?.map(({matchUpId:A,drawPositions:U})=>h.includes(A)?U:[]).flat().filter(Boolean)).sort(le),{positionAssignments:T}=Ct({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),E=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),P=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:E,inactiveDrawPositions:P,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function Es({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(le)[0]}}var _a={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 MS=[];function Tn(t,e){kt(t)&&(t={method:t}),(e||Dr())&&MS.push(t)}function Xk(t){let e=MS.slice();return t&&(MS.length=0),e}function mO(t){let r=Xk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(_a).includes(o)?_a[o]:_a.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&_a[i[d]]?_a[i[d]]:_a.brightwhite;return`${_a.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
1
|
+
var yL=Object.defineProperty;var Xt=(t,e)=>{for(var r in e)yL(t,r,{get:e[r],enumerable:!0})};function Ka(){return"2.2.48"}var bE={};Xt(bE,{competitionGovernor:()=>kU,drawsGovernor:()=>GN,entriesGovernor:()=>qN,eventGovernor:()=>iM,generationGovernor:()=>pM,matchUpFormatGovernor:()=>jy,matchUpGovernor:()=>bM,mocksGovernor:()=>PI,participantGovernor:()=>sR,policyGovernor:()=>gN,publishingGovernor:()=>gR,queryGovernor:()=>FN,reportGovernor:()=>IR,scheduleGovernor:()=>RR,scoreGovernor:()=>Jg,tieFormatGovernor:()=>kR,tournamentGovernor:()=>XR,venueGovernor:()=>aC});var kU={};Xt(kU,{getLinkedTournamentIds:()=>fu,getTournamentIds:()=>Np,linkTournaments:()=>_U,mutate:()=>LU,query:()=>FU,unlinkTournament:()=>wU,unlinkTournaments:()=>xU});var LU={};Xt(LU,{linkTournaments:()=>_U,unlinkTournament:()=>wU,unlinkTournaments:()=>xU});var Ia="SINGLES",Lt="SINGLES",Gi="DOUBLES",vt="DOUBLES",xr="TEAM",Wt="TEAM",IC={SINGLES_MATCHUP:Ia,SINGLES:Lt,DOUBLES_MATCHUP:Gi,DOUBLES:vt,TEAM_MATCHUP:xr,TEAM:Wt};var vI={[Lt]:[Lt,"S"],[vt]:[vt,"D"],[Wt]:[Wt,"T"],S:[Lt,"S"],D:[vt,"D"],T:[Wt,"T"]};function le(t,e){return(t??0)-(e??0)}function dt(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function Ln(t){return isNaN(t)?!1:t&&(t&t-1)===0}function xE(t){if(!t.length)return;let e=[...t].sort(le),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function hC(t){if(!Ln(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function Rm(t){return isNaN(t)?0:t%2&&t+1||t}function Cm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Jt(t){return!isNaN(parseFloat(t))}function _I(t){let e=dt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function us(t){if(isNaN(t))return!1;for(;!Ln(t);)t++;return t}function Io(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function It(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function SC(t=1,e=3,r=!0){let n=0;for(let o=0;o<e;o++)n+=Math.random()*(t/e);return r&&t>1?Math.round(n):n}function EL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function wE(t,e,r,n,o=2){let i=1-Math.random(),s=1-Math.random(),a=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s);return a=a/10+.5,a>1||a<0?a=wE(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=EL(a,n)),parseFloat(a.toFixed(o))}function Hl(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function TC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function Tr(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function za(t){return It(t)?t:1/0}function Er(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function yC(t){return LE(Er(t))}function LE(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function AL(t,e,r){return r.indexOf(t)===e}function xI(t){return t.filter(AL)}function tn(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function Un(t){let e=Math.floor(Math.random()*t.length);return t[e]}function tt(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function ho(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function jt(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 FE(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function ke(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function EC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function AC(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 kE(t,[e,...r]){return t.length?[t.slice(0,e),...kE(t.slice(e),[...r,e])]:[]}function UC(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 wI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function LI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function Wl(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 PC(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return tt(r,n+1).filter(o=>!t.includes(o))}function Yr(t){return typeof t=="function"}function kt(t){return typeof t=="string"}function ht(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function DC(t,e){if(!ht(t)||!ht(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o of r)if(t[o]!==e[o])return!1;return!0}function kI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var NC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function FI(t,e){if(t===void 0)return null;if(!ht(t)||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>FI(i))}:{[o]:e?n(t[o]):FI(t[o])}))}function GE(t){return Array.isArray(t)?t.length+t.map(GE).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>GE(t[e])).reduce((e,r)=>e+r,0):0}function MC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=GE(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function Yc(t,e){return!Array.isArray(t)||!kt(e)?!1:jt(t,vI[e]).length}var C={success:!0},VE="error",RC={SUCCESS:C,ERROR:VE};function GI({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!==pt(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...C}}var BC={};Xt(BC,{addNotice:()=>lt,callListener:()=>wm,createInstanceState:()=>KA,cycleMutationStatus:()=>Tf,deepCopyEnabled:()=>Sf,deleteNotice:()=>eh,deleteNotices:()=>Yi,disableNotifications:()=>zA,enableNotifications:()=>hf,getDevContext:()=>Dr,getMethods:()=>yf,getNotices:()=>th,getProvider:()=>rh,getTopics:()=>Lr,getTournamentId:()=>ms,getTournamentRecord:()=>Ef,getTournamentRecords:()=>qo,globalLog:()=>JA,handleCaughtError:()=>fp,hasTopic:()=>dp,removeTournamentRecord:()=>XA,setDeepCopy:()=>Xc,setDevContext:()=>Qc,setGlobalLog:()=>kC,setGlobalMethods:()=>GC,setGlobalSubscriptions:()=>JL,setMethods:()=>VC,setStateMethods:()=>ZA,setStateProvider:()=>QL,setSubscriptions:()=>ZL,setTournamentId:()=>lp,setTournamentRecord:()=>QA,setTournamentRecords:()=>Lm,timeKeeper:()=>XL});var VI={message:"Chronological error; time violation.",code:"ANACHRONISM"},bm={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},BE={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},BI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},xt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},q={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Qa={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ha={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},Sa={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},HE={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},br={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},si={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},jl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Yl={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Xa={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},WE={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},jE={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},UL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},ql={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ja={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},rp={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},CC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Ls={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Fs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Om={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},np={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},HI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Za={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},cn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},YE={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},qE={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},$E={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},KE={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},zE={message:"Invalid action",code:"ERR_INVALID_ACTION"},WI={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},QE={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},XE={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},JE={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},$l={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},ZE={message:"Existing round",code:"ERR_EXISTING_ROUND"},PL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Pr={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},_t={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Kl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Si={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},zl={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},tA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},$n={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var Ot={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},qr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},eA={message:"Event exists",code:"ERR_EXISTING_EVENT"},rA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},nA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Ql={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},oA={message:"Missing stage",code:"ERR_MISSING_STAGE"},Vi={message:"Invalid stage",code:"ERR_INVALID_STAGE"},iA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},sA={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},aA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},jI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},tc={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Xl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},bC={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},Ta={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Yo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Jl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Zl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},cA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},ks={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},sr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},ps={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},we={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},no={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},mr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},dr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},YI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},op={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},DL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},uA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},qI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},pA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},$I={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},NL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},qc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},ML={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},tf={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},RL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},ef={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},CL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},bL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},Bi={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},st={message:"Missing value",code:"ERR_MISSING_VALUE"},mA={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},dA={message:"Missing date",code:"ERR_MISSING_DATE"},lA={message:"No valid dates",code:"ERR_NO_VALID_DATES"},vm={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},rf={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},fA={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},Ye={message:"Invalid Date",code:"ERR_INVALID_DATE"},Co={message:"Invalid time",code:"ERR_INVALID_TIME"},gA={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var KI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},IA={message:"Invalid score",code:"ERR_INVALID_SCORE"},_m={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var OC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},nf={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},hA={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},ip={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},zI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},xm={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Hi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},ln={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},wr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},SA={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Pn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},TA={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Wi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},ec={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},se={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},yA={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},re={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},EA={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},OL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},AA={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},bo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},UA={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},PA={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},DA={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Gs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},sp={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},of={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},sf={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},QI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},vC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},_C={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},NA={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},MA={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},XI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},af={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},cf={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},RA={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},uf={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},$c={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},CA={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Vs={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},bA={message:"Court exists",code:"ERR_EXISTING_COURT"},OA={message:"Venue exists",code:"ERR_EXISTING_VENUE"},ji={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},ai={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},vA={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},JI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},_A={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},xA={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},xC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},pf={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},wA={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},mf={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},df={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Kc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},LA={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},rc={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},FA={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Bs={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},kA={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},ap={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},GA={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},VA={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},So={message:"Invalid object",code:"ERR_INVALID_OBJECT"},cp={message:"Invalid gender",code:"ERR_INVALID_GENDER"},zc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},B={message:"Invalid values",code:"ERR_INVALID_VALUES"},BA={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},lf={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},HA={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},up={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},ff={message:"Value unchanged",code:"ABORT_UNCHANGED"},Oe={message:"Not found",code:"ERR_NOT_FOUND"},pp={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},WA={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},gf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},jA={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},YA={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},ZI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},If={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},nc={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},qA={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},oc={message:"Scores present",code:"ERR_SCORES_PRESENT"},wC={ANACHRONISM:VI,CANNOT_CHANGE_WINNING_SIDE:xm,CANNOT_MODIFY_TIEFORMAT:nf,CANNOT_MODIFY_PARTICIPANT_TYPE:hA,CANNOT_REMOVE_MAIN_STRUCTURE:BE,CANNOT_REMOVE_PARTICIPANTS:ip,CATEGORY_MISMATCH:zI,COURT_EXISTS:bA,COURT_NOT_FOUND:Vs,DRAW_DEFINITION_NOT_FOUND:br,DRAW_ID_EXISTS:YE,DRAW_POSITION_ACTIVE:rp,DRAW_POSITION_ASSIGNED:Xa,DRAW_POSITION_NOT_CLEARED:jE,DRAW_POSITION_NOT_FOUND:UL,DRAW_SIZE_MISMATCH:HI,DUPLICATE_ENTRY:bm,DUPLICATE_VALUE:BA,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:MA,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:NA,EVENT_EXISTS:eA,EVENT_NOT_FOUND:qr,EXISTING_DRAW_DEFINITIONS:HE,EXISTING_END_TIME:JI,EXISTING_FLIGHT:WA,EXISTING_MATCHUP_ID:YA,EXISTING_OUTCOME:jA,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Gs,EXISTING_PARTICIPANT:sp,EXISTING_POLICY_TYPE:$I,EXISTING_PROFILE:gf,EXISTING_ROUND:ZE,EXISTING_STAGE:ZI,EXISTING_STRUCTURE:If,INCOMPATIBLE_MATCHUP_STATUS:Xl,INCOMPLETE_SOURCE_STRUCTURE:jl,INSUFFICIENT_DRAW_POSITIONS:cf,INVALID_ACTION:zE,INVALID_ASSIGNMENT:WI,INVALID_BOOKINGS:vm,INVALID_CATEGORY:zc,INVALID_COLLECTION_DEFINITION:VA,INVALID_CONFIGURATION:GA,INVALID_DATE_AVAILABILITY:rf,INVALID_DATE:Ye,INVALID_DRAW_DEFINITION:Sa,INVALID_DRAW_POSITION_FOR_SEEDING:Yl,INVALID_DRAW_POSITION:Ls,INVALID_DRAW_SIZE:np,INVALID_END_TIME:vA,INVALID_ENTRIES:nA,INVALID_EVENT_TYPE:$n,INVALID_GAME_SCORES:KI,INVALID_GENDER:cp,INVALID_MATCHUP_FORMAT:Jl,INVALID_MATCHUP_STATUS:Ta,INVALID_MATCHUP_STATUS_BYE:aA,INVALID_MATCHUP:dr,INVALID_OBJECT:So,INVALID_PARTICIPANT_ID:ln,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:SA,INVALID_PARTICIPANT_SEEDING:qE,INVALID_PARTICIPANT_TYPE:Pn,INVALID_PARTICIPANT:Hi,INVALID_POLICY_DEFINITION:pA,INVALID_RECORDS:BI,INVALID_SCALE_ITEM:rc,INVALID_SEED_NUMBER:XE,INVALID_SEED_POSITION:JE,INVALID_SET_NUMBER:RL,INVALID_SIDE_NUMBER:tf,INVALID_SCORE:IA,INVALID_STAGE:Vi,INVALID_START_TIME:xA,INVALID_STRUCTURE:si,INVALID_STOP_TIME:_A,INVALID_TIE_FORMAT:Yo,INVALID_TIME:Co,INVALID_TIME_ITEM:pf,INVALID_TOURNAMENT_DATES:gA,INVALID_TOURNAMENT_RECORD:Qa,INVALID_VALUES:B,INVALID_WINNING_SIDE:_m,MATCHUP_NOT_FOUND:we,METHOD_NOT_FOUND:nc,MISSING_ASSIGNMENTS:Ql,MISSING_ASYNC_STATE_PROVIDER:wA,MISSING_AVOIDANCE_POLICY:uA,MISSING_BIRTH_DATE:mA,MISSING_COLLECTION_DEFINITION:cA,MISSING_COURT_ID:Bi,MISSING_COURTS_INFO:CA,MISSING_DATE_AVAILABILITY:fA,MISSING_DATE:dA,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:cn,MISSING_DRAW_POSITION:Fs,MISSING_DRAW_POSITIONS:Ja,MISSING_DRAW_SIZE:Za,MISSING_ENTRIES:rA,MISSING_EVENT:Ot,MISSING_QUALIFIED_PARTICIPANTS:yA,MISSING_MATCHUP_FORMAT:Zl,MISSING_MATCHUP_ID:sr,MISSING_MATCHUP_IDS:ps,MISSING_MATCHUP:mr,MISSING_MATCHUPS:no,MISSING_PARTICIPANT_COUNT:UA,MISSING_PARTICIPANT_ID:se,MISSING_PARTICIPANT_IDS:bo,MISSING_PARTICIPANT_ROLE:TA,MISSING_PARTICIPANT:Wi,MISSING_PARTICIPANTS:ec,MISSING_PENALTY_ID:uf,MISSING_PENALTY_TYPE:RA,MISSING_PERSON_DETAILS:DA,MISSING_POLICY_ATTRIBUTES:qI,MISSING_POLICY_DEFINITION:op,MISSING_POLICY_TYPE:YI,MISSING_POSITION_ASSIGNMENTS:sA,MISSING_ROUND_NUMBER:PL,MISSING_SCHEDULE:LA,MISSING_SCORING_POLICY:ML,MISSING_SEED_ASSIGNMENTS:QE,MISSING_SEEDCOUNT_THRESHOLDS:KE,MISSING_SEEDING_POLICY:DL,MISSING_SET_NUMBER:CL,MISSING_SET_OBJECT:ef,MISSING_SIDE_NUMBER:bL,MISSING_STAGE:oA,MISSING_STRUCTURE_ID:Pr,MISSING_STRUCTURE:Si,MISSING_MAIN_STRUCTURE:zl,MISSING_STRUCTURES:Kl,MISSING_TARGET_LINK:$l,MISSING_TIE_FORMAT:ks,MISSING_TIME_ITEM:mf,MISSING_TIME_ITEMS:df,MISSING_TOURNAMENT_ID:ha,MISSING_TOURNAMENT_RECORD:q,MISSING_TOURNAMENT_RECORDS:xt,MISSING_VALUE:st,MISSING_VENUE_ID:ai,MODIFICATIONS_FAILED:FA,NO_CANDIDATES:ap,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:af,NO_MODIFICATIONS_APPLIED:Bs,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:XI,NO_PARTICIPANT_REMOVED:AA,NO_VALID_ACTIONS:HA,NO_VALID_ATTRIBUTES:up,NO_VALID_DATES:lA,NOT_FOUND:Oe,NOT_IMPLEMENTED:pp,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:of,PARTICIPANT_ID_EXISTS:EA,PARTICIPANT_NOT_CHECKED_IN:PA,PARTICIPANT_NOT_FOUND:re,PARTICIPANT_PAIR_EXISTS:OL,PENALTY_NOT_FOUND:$c,POLICY_NOT_ATTACHED:NL,POLICY_NOT_FOUND:qc,SCHEDULE_NOT_CLEARED:WE,SCHEDULED_MATCHUPS:qA,SCORES_PRESENT:oc,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:$E,STAGE_SEQUENCE_LIMIT:iA,STRUCTURE_NOT_FOUND:_t,TEAM_NOT_FOUND:lf,UNABLE_TO_ASSIGN_COURT:kA,UNLINKED_STRUCTURES:tA,UNRECOGNIZED_DRAW_TYPE:ql,UNRECOGNIZED_MATCHUP_FORMAT:tc,UNRECOGNIZED_MATCHUP_STATUS:jI,VALUE_UNCHANGED:ff,VENUE_EXISTS:OA};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},$A={addNotice:WL,callListener:KL,cycleMutationStatus:HL,deleteNotice:qL,deleteNotices:YL,disableNotifications:vL,enableNotifications:_L,getMethods:mp,getNotices:jL,getTopics:$L,getTournamentId:LC,getTournamentRecord:xL,getTournamentRecords:wL,removeTournamentRecord:GL,setMethods:BL,setSubscriptions:VL,setTournamentId:FL,setTournamentRecord:LL,setTournamentRecords:kL,handleCaughtError:zL};function vL(){Ze.disableNotifications=!0}function _L(){Ze.disableNotifications=!1}function LC(){return Ze.tournamentId}function xL(t){return Ze.tournamentRecords[t]}function wL(){return Ze.tournamentRecords}function LL(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Qa}}function FL(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:q}:(Ze.tournamentId=void 0,{success:!0})}function kL(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function GL(t){if(typeof t!="string")return{error:B};if(!Ze.tournamentRecords[t])return{error:Oe};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function VL(t){return typeof t.subscriptions!="object"?{error:B}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ze.subscriptions[e]=t.subscriptions[e]:delete Ze.subscriptions[e]}),{...C})}function BL(t){return typeof t!="object"?{error:B}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...C})}function HL(){let t=Ze.modified;return Ze.modified=!1,t}function WL({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...C}}function mp(){return Ze.methods??{}}function jL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function YL(){Ze.notices=[]}function qL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function $L(){return{topics:Object.keys(Ze.subscriptions)}}function KL({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function zL({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:LC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var ve={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},un=$A,FC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function QL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(jt(Object.keys(t),FC).length!==FC.length)throw new Error("Global state provider is missing required methods");return un=t,{success:!0}}function KA(){if(un.createInstanceState){try{un.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:wA}}function Dr(t){return!t||typeof t!="object"?ve.devContext??!1:typeof ve.devContext!="object"?!1:Object.keys(t).every(e=>ve.devContext?.[e]===t[e])&&ve.devContext}function XL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(ve.timers).filter(o=>o!=="default"||ve.timers[o].startTime).map(o=>{let i=ve.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:ve.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=ve.timers[e].state==="stopped"?0:(r-(ve.timers[e]?.startTime??0))/1e3,o=ve.timers[e].elapsedTime+n;return{state:ve.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!ve.timers[e]||t==="reset"){if(e==="allTimers")return ve.timers={default:{elapsedTime:0}},!0;ve.timers[e]={startTime:r,state:"active",elapsedTime:0}}return ve.timers[e].elapsedTime||(ve.timers[e].elapsedTime=0),t==="stop"&&ve.timers[e].state!=="stopped"&&(ve.timers[e].state="stopped")&&(ve.timers[e].elapsedTime+=(r-(ve.timers[e]?.startTime??0))/1e3),t==="start"&&(ve.timers[e].startTime=r)&&(ve.timers[e].state="active"),ve.timers[e]}function kC(t){Yr(t)?ve.globalLog=t:delete ve.globalLog}function Qc(t){ve.devContext=t}function zA(){un.disableNotifications()}function hf(){un.enableNotifications()}function Xc(t,e){typeof t=="boolean"&&(ve.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(ve.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(ve.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(ve.deepCopyAttributes.stringify=e.stringify),e.threshold&&(ve.deepCopyAttributes.threshold=e.threshold))}function Sf(){return{enabled:ve.deepCopy,...ve.deepCopyAttributes}}function JL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{ve.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:st,info:"missing subscriptions"}}function ZL(t){return t?.subscriptions?un.setSubscriptions({subscriptions:t.subscriptions}):{error:st,info:"missing subscriptions"}}function GC(t){return t?typeof t!="object"?{error:B}:(Object.keys(t).forEach(e=>{Yr(t[e])&&(ve.globalMethods[e]=t[e])}),{...C}):{error:st,info:"missing method declarations"}}function VC(t){return t?typeof t!="object"?{error:B}:un.setMethods(t):{error:st,info:"missing method declarations"}}function Tf(){return un.cycleMutationStatus()}function lt(t){if(typeof t?.topic!="string")return;let e=ve.globalSubscriptions[t.topic];return un.addNotice(t,e)}function yf(){return{...ve.globalMethods,...un.getMethods()}}function th(t){return un.getNotices(t)}function eh({key:t,topic:e}){return un.deleteNotice({key:t,topic:e})}function Yi(){return un.deleteNotices()}function Lr(){return un.getTopics()}function dp(t){return Lr()?.topics?.includes(t)}async function wm(t){return un.callListener(t,ve.globalSubscriptions)}function ms(){return un.getTournamentId()}function Ef(t){return un.getTournamentRecord(t)}function qo(){return un.getTournamentRecords()}function QA(t){return un.setTournamentRecord(t)}function Lm(t){return un.setTournamentRecords(t)}function lp(t){return un.setTournamentId(t)}function XA(t){return un.removeTournamentRecord(t)}function rh(){return un}function fp({engineName:t,methodName:e,params:r,err:n}){let o=Yr(un.handleCaughtError)&&un.handleCaughtError||$A.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function JA(t,e){if(ve.globalLog)try{ve.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),kC()}else console.log(e,t)}function ZA(t,e,r,n){if(!ht(t))return{error:B};Jt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Yr(a[u])?i[u]=a[u]:ht(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?GC(i):VC(i),{methods:i}}function tF(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function nt(t,e,r,n){if(typeof t!="object"||t===null)return t;Sf()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=tF(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>nt(c))}:{[a]:n?t[a]:nt(t[a])}))}function _({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||(e.context={}),Object.assign(e.context,nt(t))),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var lr="FEMALE",$o="OTHER",qi="MIXED",Le="MALE";var Fm={FEMALE_ABBR:"F",OTHER_ABBR:"O",MIXED_ABBR:"X",MALE_ABBR:"M",ANY_ABBR:"A",FEMALE:lr,MIXED:qi,OTHER:$o,MALE:Le,ANY:"ANY"};function $i(t){return[lr,"F"].includes(t)}function Hs(t){return[Le,"M"].includes(t)}function en(t){return[qi,"X"].includes(t)}function To(t){return["ANY","A"].includes(t)}function yr(t){if(t){if($i(t))return lr;if(en(t))return qi;if(Hs(t))return Le;if(To(t))return"ANY"}return $o}function Dn(t){return $i(t)||Hs(t)}var iF="MIXED events can not contain mixed singles or { gender: ANY } collections",sF="events with { gender: ANY } can not contain MIXED singles collections";function km(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&Dn(r)&&yr(r)!==yr(o)?_({result:{valid:!1,error:cp},context:{gender:o},stack:e}):en(r)&&(To(o)||en(o)&&n!==vt)?_({result:{error:cp,valid:!1},info:iF,stack:e}):To(r)&&en(o)&&n!==vt?_({result:{error:cp,valid:!1},info:sF,stack:e}):{valid:!0}}var aF="normal",tU="timed",cF="final",Af="NOAD";var HC={S:aF,F:cF};function gp(t,e){if(ht(t)&&(t?.bestOf||t?.exactly)&&t?.setFormat)return uF(t,e)}function Uf(t){return!Number.isNaN(Number(t))&&Number(t)}function YC(t){let e=`T${t.minutes}`;return t.based==="A"?e+="A":t.based==="P"&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function uF(t,e){let r=Uf(t.bestOf)||void 0,n=Uf(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return YC(t.setFormat);let s=o&&`${"SET"}${o}${n&&n!==1?"X":""}`||"",a=WC(t.setFormat,e),c=a&&`S:${a}`||"",u=WC(t.finalSetFormat,e),p=o&&o>1&&u&&a!==u&&`F:${u}`||"";if(s&&a)return[s,c,p].filter(Boolean).join("-")}function WC(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return YC(t);if(t.tiebreakSet)return jC(t.tiebreakSet);let r=Uf(t.setTo);if(r){let n=t.NoAD&&Af||"",o=jC(t.tiebreakFormat),i=o&&`/${o}`||"",s=Uf(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function jC(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&Uf(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Af:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ne(t){if(kt(t)){let e=t.startsWith("T")&&tU||t.startsWith("SET")&&"SET"||"";if(e===tU){let r=zC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e==="SET")return pF(t)}}function pF(t){let e=t.split("-"),r=e[0].slice(3),n=r.endsWith("X"),o=n?r.slice(0,-1):r,i=Gm(o),s=n&&i!==1?void 0:i,a=n&&i!==1?i:void 0,c=e&&qC(e[1]),u=e&&qC(e[2]),p=c&&c.timed||u&&u.timed,m=s&&s<6||p&&a,d=!e[2]||u,l=c,f=nt({setFormat:c,exactly:a,bestOf:s});if(u&&(f.finalSetFormat=u),m&&l&&d)return f}function qC(t){if(t?.[1]!==":")return;let e=t.split(":"),r=HC[e[0]],n=e[1];if(!(!r||!n))return mF(t,n)}function mF(t,e){return e.startsWith("TB")?dF(e):e.startsWith("T")?zC(e):lF(t,e)}function dF(t){let e=KC(t);return e===!1?!1:typeof e=="object"?{tiebreakSet:e}:void 0}function lF(t,e){let r=/^[FS]:(\d+)([A-Za-z]*)/.exec(t),n=r&&QC(r[2])||!1,o=!r?.[2]||n,i=r?Gm(r[1]):void 0,s=$C(e),a=s!==!1,c=a&&s||i,u=KC(e.split("/")[1]);return!i||!o||!(u!==!1)||!a?!1:fF(i,n,u,c)}function fF(t,e,r,n){let o={setTo:t};return e&&(o.NoAD=!0),r?(o.tiebreakFormat=r,o.tiebreakAt=n):o.noTiebreak=!0,o}function $C(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Gm(r[1]):r[1])||!1}function KC(t){if(t)return t.startsWith("TB")?gF(t):!1}function gF(t){let e=$C(t,!1),r=/^TB(\d+)([A-Za-z]*)/.exec(t),n=r?.[1],o=r&&QC(r[2]),i=!r?.[2]||o,s=Gm(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 zC(t){let e=t.slice(1),r=/^(\d+)([PGA])?(?:\/TB(\d+))?(@?[A-Za-z]*)?/.exec(e),n=Gm(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2];i==="A"?o.based="A":i==="P"?o.based="P":i==="G"&&(o.based="G");let s=r?.[3];if(s){let u=Gm(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 QC(t){return t?.includes(Af)}function Gm(t){let e=Number(t);return Number.isNaN(e)?0:e}function Nr({matchUpFormat:t}){if(!kt(t)||t==="")return!1;let e=Ne(t),r=/-S:([1-9])+\/TB(\d{1,2})@?([1-9]?)/.exec(t),n=r?.[1],o=r?.[2],i=r?.[3],s=/-F:([1-9])+\/TB(\d{1,2})@?([1-9]?)/.exec(t),a=s?.[1],c=s?.[2],u=s?.[3];return gp(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var Vm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,nh=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Oo=/^([\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?$/,Ws=/^([\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 Bm(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Ut(t.scheduledTime)),!e)return;let r=zt(t.scheduledTime),n=Ut(e);return n&&r&&(n+=`T${r}`),n}function XC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Jc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||Ws.test(ac(t,!0,!0)))}function Mr(t){return sc(t)||Vm.test(t)}function IF(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+3600*e.getHours();return hF(r,{displaySeconds:!1})}function hF(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(oo).join(":")}var Mf=t=>{let e=Df(t)||sc(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${oo(n)}-${oo(e.getUTCDate())}`};function SF(t){let e=Df(t)||sc(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Kn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function oh(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function TF(t){return oh(t).getTime()}function Df(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function js(t,e){if(!Mr(t)||!Mr(e))return[];let r=Ut(t)+"T00:00",n=Ut(e)+"T00:00",o=new Date(r),i=new Date(n),s=Df(i)&&Df(o)&&u(o,i),a=[],c=0;if(s){let p=o,m=p.getTime();for(;m<=i.getTime()&&c<300;)c+=1,a.push(new Date(p)),m=p.setDate(p.getDate()+1)}return a.map(p=>Kn(p));function u(p,m){return p<=m}}var yF=/^([+-]?\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 sc(t){return typeof t!="string"?!1:yF.test(t)}function sh(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function Yt(t){let e=zt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function JC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[oo(e),oo(r)].join(":")}function Nf(t){return sh(t)?t.split(":").slice(0,2).map(oo).join(":"):void 0}function zt(t){return sc(t)&&t.indexOf("T")>0?Nf(t.split("T").reverse()[0]):Nf(t)}function Ut(t){return sc(t)||Oo.test(t)?t.split("T")[0]:void 0}function Ip(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Ut(r.toISOString())}function ih(t){t=typeof t!="string"?"00:00":t;let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:r.hours,1:r.minutes}=e.time.split(":")||[],r.ampm=e.ampm,isNaN(r.hours)||isNaN(r.minutes)||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function EF(t){let e=ih(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(oo).join(":")}function AF(t){let e=ih(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 ac(t,e,r){let n=Ut(t),o=zt(t),i=n?o:t;return t?e&&(n&&r&&t||EF(i))||AF(i):void 0}function ah(t,e){let r=ih(t),n=ih(e);if(parseInt(r.hours)<parseInt(n.hours))return-1;if(parseInt(r.hours)>parseInt(n.hours))return 1;if(r.hours===n.hours){if(parseInt(r.minutes)<parseInt(n.minutes))return-1;if(parseInt(r.minutes)>parseInt(n.minutes))return 1}return 0}function ch(t,e=7){let r=Ut(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Kn(o)}function UF(t){return ch(t)}function PF(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())),Kn(o,r)}function ZC(t,e,r){let n=new Date(t,0);return Kn(new Date(n.setDate(e)),r)}function Ge(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(oo),o=oh(e).setHours(r,n,0,0);return oh(o)}function ya(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 $r(t,e){let r=zt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return zt(Rf(Ge(r),n).toISOString())}function Rf(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function oo(t){return t.toString()[1]?t:"0"+t}function zn(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 uh={addDays:ch,addWeek:UF,addMinutesToTimeString:$r,convertTime:ac,getIsoDateString:Bm,getUTCdateString:Mf,DateHHMM:IF,extractDate:Ut,extractTime:zt,formatDate:Kn,getDateByWeek:PF,isISODateString:sc,isDate:Df,isTimeString:sh,offsetDate:oh,offsetTime:TF,sameDay:zn,timeStringMinutes:Yt,timeToDate:Ge,timeUTC:SF,validTimeValue:Jc,validDateString:Vm,timeValidation:Ws,dateValidation:Oo};var DF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),NF=t=>t.filter(Boolean).every(Jt);function Ys(t){let e=t.category;if(typeof e!="object")return{error:zc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(DF([r,n,o,a],"string")&&NF([i,s])&&[n,o].filter(Boolean).every(Mr)))return{error:zc};let p=t.consideredDate??Ut(new Date().toLocaleDateString("sv"));if(!Mr(p))return{error:Ye};let[m]=p.split("-").slice(0,3).map(k=>parseInt(k)),d=Ip(p,-1),[l,f]=d.split("-").slice(1,3).map(k=>parseInt(k)),g=`${oo(l)}-${oo(f)}`,I=Ip(p,1),[h,S]=I.split("-").slice(1,3).map(k=>parseInt(k)),T=`${oo(h)}-${oo(S)}`,y=s&&Ip(p,-1*365*s),E=i&&Ip(p,-1*365*i),P=[],A=k=>!P.includes(k)&&P.push(k);r=r??a;let U=/^([UO]?)(\d{1,2})([UO]?)$/,N=/^C(\d{1,2})-(\d{1,2})$/,D=r?.includes("-"),M=D&&r?.match(N),R=r?.match(U),b=(k,G)=>`${k}-${G}`,O=k=>{let G=m-k,H=b(G,T);e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==k-1&&(A(`Invalid submitted ageMax: ${i}`),E=void 0),i=k-1)},v=k=>{let G=m-k-1,H=b(G,T);e.ageMin&&e.ageMin>k&&A(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>k&&A(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&A(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==k&&(A(`Invalid submitted ageMax: ${i}`),y=void 0),i=k)},x=k=>{let G=m-k,H=b(G,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==k+1&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=k+1)},F=k=>{let G=m-k-1,H=b(G,g);e.ageMaxDate&&e.ageMaxDate!==H&&A(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==k&&(A(`Invalid submitted ageMin: ${s}`),y=void 0),s=k)},w=k=>{let[G,H,K]=(k.match(U)||[]).slice(1),Y=parseInt(H);G==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),O(Y)):G==="O"&&x(Y),K==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&A(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(Y)):K==="O"&&F(Y),n=n??y,o=o??E};if(M){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=m-e.ageMin;n=b(H,g)}if(e.ageMax){let H=m-e.ageMax-1;o=b(H,T)}let[k,G]=(r?.match(N)??[]).slice(1).map(H=>parseInt(H));k<=G?(s=k,i=G,c=!0):A(`Invalid combined age range ${r}`)}else D?r?.split("-").forEach(w):R?w(r):(s&&x(s),i&&v(i));i&&e.ageMin&&e.ageMin>i&&(A(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=nt({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return P.length&&(L.errors=P),L}function Zc({category:t}){if(!ht(t))return{error:B};let e=Ys({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Jt(r)?_({result:{error:B},context:{ratingMax:r}}):n&&!Jt(n)?_({result:{error:B},context:{ratingMin:n}}):{...e}}function tu({childCategory:t,withDetails:e,category:r}){let n=Zc({category:r}),o=Zc({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=nt({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function eu({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}`),_({result:{errors:c,error:So},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Yc([Lt,vt],I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`),[!!u?.length].concat([g,m,h,S].map(It)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let P=GI({collectionValueProfiles:u,matchUpCount:l});P.errors&&c.push(...P.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Nr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let P=km({referenceGender:i,matchUpType:I,gender:y});if(P.error)return _({context:{referenceGender:i,gender:y},result:P,stack:a})}if(t&&o&&T){let P=tu({category:o,childCategory:T});if(!P.valid)return _({result:{error:zc},context:P,stack:a})}return c.length?_({result:{errors:c,error:VA},stack:a}):{valid:!0}}function ar(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=MF({...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}=eu({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)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),_({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:Yo},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===pt(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:_({result:{error:Yo},context:{tieFormat:o,errors:a},stack:s})}function MF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?_({result:{error:Yo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:Yo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:Yo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var cc="resourceSubType",uc="resourceType",pc="identifier",tb={RESOURCE_SUB_TYPE:cc,RESOURCE_TYPE:uc,IDENTIFIER:pc};function J(t,e,r,n,o=0){if(rh().makeDeepCopy)return rh().makeDeepCopy(t,e,r,n);let i=Sf(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Yr(t)||t===null||typeof i?.threshold=="number"&&o>=i.threshold)return t;let p=Array.isArray(t)?[]:{},m=Object.keys(t).filter(l=>!r||!c||Array.isArray(c)&&!c.includes(l)||Yr(c)&&!c(l)),d=(l,f)=>{p[l]=Yr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Yr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Cf(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?d(l,f):Array.isArray(a)&&a.includes(l)&&Yr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:XC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Cf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function ph(t=1,e){return tt(0,t).map(()=>Nt(e))}function Nt(t){let e=[];for(let a=0;a<256;a++)e[a]=(a<16?"0":"")+a.toString(16);let r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0,i=Math.random()*4294967295|0,s=e[r&255]+e[r>>8&255]+e[r>>16&255]+e[r>>24&255]+"-"+e[n&255]+e[n>>8&255]+"-"+e[n>>16&15|64]+e[n>>24&255]+"-"+e[o&63|128]+e[o>>8&255]+"-"+e[o>>16&255]+e[o>>24&255]+e[i&255]+e[i>>8&255]+e[i>>16&255]+e[i>>24&255];return typeof t=="string"?`${t}_${s.replace(/-/g,"")}`:s}var mh={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 dh={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 lh={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 fh={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 gh={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 Ih={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Pro Circuit",winCriteria:{aggregateValue:!0}};var hh={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 Sh={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:3},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:3},{scoreValue:1,matchUpType:"DOUBLES",collectionName:"Men's Doubles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Women's Doubles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Dual",winCriteria:{aggregateValue:!0}};var Th={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"USTA_BREWER_CUP",winCriteria:{valueGoal:4}};var yh={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 bn="SET3-S:6/TB7",kF="SET3-S:6NOAD",eU="SET3-S:6/TB7-F:TB10",GF="SET3-S:4/TB7",VF="SET3-S:4/TB5@3",BF="SET1-S:T20",HF="SET1-S:8/TB7",WF="SET1-S:8/TB7@7",eb={FORMAT_STANDARD:bn,FORMAT_STANDARD_NOAD:kF,FORMAT_ATP_DOUBLES:eU,FORMAT_SHORT_SETS:GF,FORMAT_FAST4:VF,FORMAT_PRO_SET:HF,FORMAT_COLLEGE_PRO_SET:WF,TIMED20:BF};var Eh={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 Ah={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA_COLLEGE",winCriteria:{valueGoal:4}};var Uh={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 Ph={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_WTT_ITT",winCriteria:{aggregateValue:!0}};var Dh={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 Nh={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}};var Mh={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var Hm="COLLEGE_DEFAULT",Rh="COLLEGE_JUCO",Ch="COLLEGE_D3",rU="DOMINANT_DUO",nU="DOMINANT_DUO_MIXED",oU="LAVER_CUP",iU="TEAM_DOUBLES_3_AGGREGATION",sU="TIME_TENNIS_DUAL",aU="TIME_TENNIS_PRO_CIRCUIT",cU="USTA_BREWER_CUP",uU="USTA_OZAKI_CUP",pU="USTA_COLLEGE",mU="USTA_GOLD_TEAM_CHALLENGE",dU="USTA_LEVEL_1",lU="USTA_INTERSECTIONAL",fU="USTA_SECTION_BATTLE",gU="USTA_SOUTHERN_LEVEL_5",IU="USTA_TOC",hU="USTA_WTT_ITT",SU="USTA_ZONAL",rb={COLLEGE_D3:Ch,COLLEGE_DEFAULT:Hm,COLLEGE_JUCO:Rh,DOMINANT_DUO:rU,DOMINANT_DUO_MIXED:nU,LAVER_CUP:oU,TEAM_DOUBLES_3_AGGREGATION:iU,TIME_TENNIS_DUAL:sU,TIME_TENNIS_PRO_CIRCUIT:aU,USTA_BREWER_CUP:cU,USTA_OZAKI_CUP:uU,USTA_COLLEGE:pU,USTA_GOLD_TEAM_CHALLENGE:mU,USTA_INTERSECTIONAL:lU,USTA_LEVEL_1:dU,USTA_SECTION_BATTLE:fU,USTA_SOUTHERN_LEVEL_5:gU,USTA_TOC:IU,USTA_WTT_ITT:hU,USTA_ZONAL:SU};var ob="STANDARD",nb={[ob]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Ch]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Ch,valueGoal:5},[Hm]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Hm,valueGoal:4},[Rh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:bn,matchUpCount:6,matchUpValue:1},tieFormatName:Rh,valueGoal:5},[oU]:Nh,[rU]:Eh,[nU]:hh,[iU]:dh,[sU]:Sh,[aU]:Ih,[cU]:Th,[uU]:yh,[pU]:Ah,[mU]:mh,[lU]:gh,[dU]:Uh,[fU]:fh,[gU]:lh,[hU]:Ph,[IU]:Mh,[SU]:Dh},XF=t=>{let e=t?.namedFormat&&Object.keys(nb).includes(t.namedFormat)?t.namedFormat:ob,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(nb[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Nt();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:eU,collectionName:"Doubles",matchUpType:vt,...s.doubles},{collectionId:a(1),matchUpFormat:bn,collectionName:"Singles",matchUpType:Lt,...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},io=XF;var Qn="SINGLES",qs="SINGLES",Kr="DOUBLES",Ko="DOUBLES",_e="TEAM",Or="TEAM";var JF="RATING",ZF="BOTH",ib={AGE:"AGE",BOTH:ZF,DOUBLES:Kr,DOUBLES_EVENT:Ko,RATING:JF,SINGLES:Qn,SINGLES_EVENT:qs,TEAM_EVENT:Or,TEAM:_e};var rt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",fe="PLAY_OFF",ru=[rt,ct,qe,fe,$e],$s={[ct]:1,[rt]:2,[fe]:3,[qe]:3,[$e]:4},TU="finishingPositions",yU="aggregateEventStructures",EU={[rt]:1,[fe]:2,[qe]:3,[ct]:4,[$e]:5},sb={[fe]:1,[rt]:2,[qe]:3,[ct]:4,[$e]:5},nu="CLUSTER",ab="SEPARATE",Ti="WATERFALL",hp="ITEM",Ve="CONTAINER",fn="DRAW",Sp="RANDOM",Nn="TOP_DOWN",yi="BOTTOM_UP",Fn="POSITION",Xn="WINNER",so="LOSER",kn="FIRST_MATCHUP",Fr="AD_HOC",tk="AD_HOC",Ea="FEED_IN",ou="COMPASS",iu="OLYMPIC",ek="SINGLE_ELIMINATION";var yo="SINGLE_ELIMINATION",su="DOUBLE_ELIMINATION",au="FIRST_MATCH_LOSER_CONSOLATION",Tp="FIRST_ROUND_LOSER_CONSOLATION",Ki="LUCKY_DRAW",bf="CURTIS_CONSOLATION",cb="CURTIS_CONSOLATION",bh="FEED_IN_CHAMPIONSHIP_TO_SF",Wm="FEED_IN_CHAMPIONSHIP_TO_SF",Oh="FEED_IN_CHAMPIONSHIP_TO_QF",jm="FEED_IN_CHAMPIONSHIP_TO_QF",vh="FEED_IN_CHAMPIONSHIP_TO_R16",Ym="FEED_IN_CHAMPIONSHIP_TO_R16",AU="MODIFIED_FEED_IN_CHAMPIONSHIP",qm="MODIFIED_FEED_IN_CHAMPIONSHIP",yp="FEED_IN_CHAMPIONSHIP",ub="DOUBLE_ROUND_ROBIN",On="ROUND_ROBIN",Eo="ROUND_ROBIN_WITH_PLAYOFF",UU="DECIDER",PU="BACKDRAW",Of={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"}},vf={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Ei="WIN_RATIO",zi="ROUND_OUTCOME",DU=[ou,bf,jm,Ym,Wm,yp,Oh,vh,bh,au,Tp,Ki,qm,iu,fe,Eo],rk=[Fr,ou,bf,su,jm,Ym,Wm,yp,Ea,au,Tp,Ki,qm,iu,fe,On,Eo,yo],NU={MAIN:rt,QUALIFYING:ct,CONSOLATION:qe,ITEM:hp,CONTAINER:Ve,FIRST_MATCHUP:kn,WINNER:Xn,LOSER:so,AD_HOC:Fr,FEED_IN:Ea,FLEX_ROUNDS:tk,COMPASS:ou,PLAY_OFF:fe,OLYMPIC:iu,KNOCKOUT:ek,SINGLE_ELIMINATION:yo,DOUBLE_ELIMINATION:su,CURTIS:bf,FICSF:bh,FICQF:Oh,FICR16:vh,MFIC:AU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:au,FIRST_ROUND_LOSER_CONSOLATION:Tp,MODIFIED_FEED_IN_CHAMPIONSHIP:qm,FEED_IN_CHAMPIONSHIP_TO_R16:Ym,FEED_IN_CHAMPIONSHIP_TO_QF:jm,FEED_IN_CHAMPIONSHIP_TO_SF:Wm,FEED_IN_CHAMPIONSHIP:yp,LUCKY_DRAW:Ki,ROUND_ROBIN_WITH_PLAYOFF:Eo,ROUND_ROBIN:On,DECIDER:UU,BACKDRAW:PU,COMPASS_ATTRIBUTES:Of,OLYMPIC_ATTRIBUTES:vf,DRAW:fn,RANDOM:Sp,TOP_DOWN:Nn,BOTTOM_UP:yi,WATERFALL:Ti,WIN_RATIO:Ei,ROUND_OUTCOME:zi,MULTI_STRUCTURE_DRAWS:DU,generatedDrawTypes:rk,stageOrder:$s,finishOrder:EU,AGGREGATE_EVENT_STRUCTURES:yU,FINISHING_POSITIONS:TU},pb=NU;var Re="tournamentRecords",_f="policyDefinitions",ne="tournamentRecord",_h="onlineResource",Ce="drawDefinition",xh="tieFormatName",$m="matchUpFormat",ao="participantId",wh="scheduleDates",mb="tournamentId",db="scheduleDate",lb="roundNumber",cu="structureId",xf="participant",mc="matchUpIds",Lh="entryStage",fb="policyType",MU="structures",wf="eventType",gn="matchUpId",Km="tieFormat",uu="inContext",Ep="structure",Ap="courtIds",gb="personId",Up="venueIds",Lf="matchUps",Fh="courtId",kh="eventId",Gn="matchUp",Gh="drawId",In="error",co="event",ds="param",Ff="uuids",Ib="averageMatchUpMinutes",hb="recoveryMinutes",Sb="periodLength",Tb="number";var zr="object",Be="array";var tr="_validate",Vh="_message",kr="_invalid",He="_ofType",zm="_anyOf",Ks="_oneOf";var yb={[_h]:t=>jt(Object.keys(t),[cc,uc,pc]).length===3,[xh]:t=>t&&io({namedFormat:t}),[Ff]:t=>!t||Array.isArray(t)&&t.every(kt),[Km]:t=>!ar({tieFormat:t}).error,[wf]:t=>[Qn,Kr,_e].includes(t),[Lh]:t=>ru.includes(t)},nk={[Re]:xt,[ne]:q,[_f]:op,[Ce]:Z,[ao]:se,[$m]:Zl,[mb]:ha,[cu]:Pr,[mc]:ps,[xf]:Wi,[_h]:So,[wf]:$n,[MU]:Kl,[gn]:sr,[Km]:Yo,[Ep]:Si,[Fh]:Bi,[Lf]:no,[kh]:qr,[Gn]:mr,[Ap]:st,[Up]:st,[Gh]:cn,[co]:Ot},ok={[Re]:zr,[_f]:zr,[ne]:zr,[Ce]:zr,[_h]:zr,[wh]:Be,[xf]:zr,[mc]:Be,[MU]:Be,[Km]:zr,[Ep]:zr,[Ap]:Be,[Up]:Be,[Lf]:Be,[Gn]:zr,[co]:zr,[Ff]:Be};function et(t,e,r){if(!t&&!ht(t))return{error:B};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:B};let{paramError:n,errorParam:o}=ak(t,e);if(!n)return{valid:!0};let i=n[tr]&&(n[In]||n[kr])||t?.[o]===void 0&&(n[In]||n[kr]||nk[o]||B)||B,s=o??(n[Ks]&&Object.keys(n[Ks]).join(", "));return _({info:{param:s,message:n[Vh]},result:{error:i},stack:r})}function Eb(t,e){let r=Object.keys(t),n=Object.keys(e);return jt(r,n)}function ik(t,e){if(!e)return;let r=Eb(t,e);return r.length!==1?{error:B}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function sk(t,e){if(!e)return;let r=Eb(t,e).filter(n=>t[n]);return r.length<1?{error:B}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function ak(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&ik(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&sk(t,a);if(d?.error)return d.error;d&&Object.assign(p,d);let l=Object.keys(p).filter(g=>typeof p[g]=="boolean"),f=l.find(g=>{let I=c&&!Yr(c),h=t[g]!==void 0&&!c&&ck(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!uk(t[g],c)||yb[g]&&!yb[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function ck(t,e,r){return r=r||ok[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function uk(t,e){return Yr(e)?e(t):!0}var Qm="DYNAMIC",Ai="RANKING",Ui="RATING",Pi="SCALE",Ao="SEEDING",Ab={RANKING:Ai,RATING:Ui,SCALE:Pi,SEEDING:Ao};function Aa(t){let e=et(t,[{[xf]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Pi)&&[Ai,Ui,Ao].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=pt(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===Ao&&"seedings"||c===Ai&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Qi(t){if(t===null)return{};let{source:e,template:r}=t||{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let h=I.map(S=>{let T={};return o(S,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=h}else I&&(a[l]={},o(I,g,a[l]));else{let h=i[l];if(Array.isArray(g)&&!g.includes(h))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=h)}}}}var Bh="voluntaryConsolation",Di="competitiveBands",kf="roundRobinTally",Jn="positionActions",er="matchUpActions",Gf="rankingPoints",vo="roundNaming",zs="participant",pu="progression",_o="scheduling",mu="avoidance",pk="participant",mk="display",rn="scoring",Vn="seeding",dc="feedIn",dk="audit",Xm="draws",Ub={POLICY_TYPE_VOLUNTARY_CONSOLATION:Bh,POLICY_TYPE_COMPETITIVE_BANDS:Di,POLICY_TYPE_ROUND_ROBIN_TALLY:kf,POLICY_TYPE_POSITION_ACTIONS:Jn,POLICY_TYPE_MATCHUP_ACTIONS:er,POLICY_TYPE_RANKING_POINTS:Gf,POLICY_TYPE_ROUND_NAMING:vo,POLICY_TYPE_PARTICIPANT:zs,POLICY_TYPE_PROGRESSION:pu,POLICY_TYPE_SCHEDULING:_o,POLICY_TYPE_AVOIDANCE:mu,POLICY_TYPE_DISPLAY:mk,POLICY_TYPE_PRIVACY:pk,POLICY_TYPE_FEED_IN:dc,POLICY_TYPE_SCORING:rn,POLICY_TYPE_SEEDING:Vn,POLICY_TYPE_AUDIT:dk,POLICY_TYPE_DRAWS:Xm};function zo({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[zs];if(r?.withScaleValues){let{ratings:u,rankings:p}=Aa({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Qi({template:c.participant,source:a})}return a}var Pb="element required",Db="missing name";function Ir(t){if(!t||typeof t!="object")return{error:st};if(t.element&&typeof t?.element!="object")return{error:B};if(!t?.name)return{error:st,info:Db};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=Ir({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...C}}return{error:st,info:Pb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:Oe}}function Bn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function At(t){if(typeof t!="object")return{error:st};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:B},stack:e});if(!Bn({extension:t.extension}))return _({result:{error:B,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=At({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...C}}else return _({result:{error:st},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...C}}function Vf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:q}}function Pp(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:br}}function xo(t){return!t||typeof t!="object"?{error:st}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:qr}}function RU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:se};let e=t.tournamentRecord?.participants||[],r=zo({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:re}}function Bf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?Ir({element:t.tournamentRecord,name:t.name}):{error:q}}function CU(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?Ir({element:t.drawDefinition,name:t.name}):{error:br}}function Dp(t){return!t||typeof t!="object"?{error:st}:t?.event?Ir({element:t.event,name:t.name}):{error:qr}}function bU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:se};let e=t.tournamentRecord?.participants||[],r=zo({participantId:t.participantId,tournamentParticipants:e});return r?Ir({element:r,name:t.name}):{error:re}}function Np({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var lk="extensionQueries";function mt({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:Oe}}return _({result:{error:st},stack:lk})}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:Oe}}var fk="activeSuspension",du="appliedPolicies",OU="context",Jm="delegatedOutcome",uo="disabled",Ua="disableAutoCalc",Zm="disableLinks",td="display",Pa="drawDeletions",gk="drawProfile",ed="entryProfile",Ik="eventProfile",hk="eventWithdrawalRequests",Sk="factory",pn="flightProfile",Hh="groupingAttribute",wo="lineUps",Qs="linkedTournamentsIds",rd="matchUpHistory",Wh="participantRepresentatives",Da="personRequests",lc="positionActions",Tk="rankingPoints",yk="registration",vn="roundTarget",lu="scheduleLimits",Qo="scheduleTiming",Na="schedulingProfile",Ek="statusDetail",fc="subOrder",Lo="tally",nd="tieFormatModification",jh={ACTIVE_SUSPENSION:fk,APPLIED_POLICIES:du,CONTEXT:OU,DELEGATED_OUTCOME:Jm,DISABLED:uo,DISABLE_LINKS:Zm,DISABLE_AUTO_CALC:Ua,DISPLAY:td,DRAW_DELETIONS:Pa,DRAW_PROFILE:gk,ENTRY_PROFILE:ed,EVENT_PROFILE:Ik,EVENT_WITHDRAWAL_REQUESTS:hk,FLIGHT_PROFILE:pn,GROUPING_ATTRIBUTE:Hh,LINEUPS:wo,LINKED_TOURNAMENTS:Qs,MATCHUP_HISTORY:rd,PARTICIPANT_REPRESENTATIVES:Wh,PERSON_REQUESTS:Da,POSITION_ACTIONS:lc,RANKING_POINTS:Tk,REGISTRATION:yk,ROUND_TARGET:vn,SCHEDULE_LIMITS:lu,SCHEDULE_TIMING:Qo,SCHEDULING_PROFILE:Na,STATUS_DETAIL:Ek,SUB_ORDER:fc,TALLY:Lo,TIE_FORMAT_MODIFICATIONS:nd,FACTORY:Sk},vU=[Jm,uo,Ua,Zm,pn,wo,Qs,rd,Wh,Da,vn,lu,Qo,Na,fc,Lo,nd];function _U({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=Np({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:Qs,value:{tournamentIds:r}}}):{...C}}function xU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=Ir({name:Qs,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function wU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:B};if(!e)return{error:ha};let r=Np({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ha};let o;return n.every(i=>{let s=t[i],{extension:a}=mt({element:s,name:Qs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=Bf({name:Qs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Vf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var FU={};Xt(FU,{getLinkedTournamentIds:()=>fu,getTournamentIds:()=>Np});function fu({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:xt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=mt({element:n,name:Qs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var GN={};Xt(GN,{adHocPositionSwap:()=>zP,addAdHocMatchUps:()=>Gd,addDrawDefinitionTimeItem:()=>Og,addFinishingRounds:()=>ba,addGoesTo:()=>rs,addPlayoffStructures:()=>Kp,addQualifyingStructure:()=>KP,addVoluntaryConsolationStage:()=>HP,addVoluntaryConsolationStructure:()=>Eg,allPlayoffPositionsFilled:()=>WS,alternateDrawPositionAssignment:()=>bP,assignDrawPosition:()=>uD,assignDrawPositionBye:()=>Wr,attachConsolationStructures:()=>iD,attachPlayoffStructures:()=>Vg,attachQualifyingStructure:()=>bg,attachStructures:()=>Bg,autoSeeding:()=>ux,automatedPlayoffPositioning:()=>na,automatedPositioning:()=>Mc,checkValidEntries:()=>Hd,deleteAdHocMatchUps:()=>pD,drawMatic:()=>tl,findDrawDefinition:()=>gT,generateAdHocMatchUps:()=>Wu,generateAdHocRounds:()=>Zd,generateAndPopulatePlayoffStructures:()=>kd,generateDrawDefinition:()=>Wa,generateDrawMaticRound:()=>qd,generateDrawStructuresAndLinks:()=>Wd,generateDrawTypeAndModifyDrawDefinition:()=>jd,generateQualifyingStructure:()=>_d,generateVoluntaryConsolation:()=>LT,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getMatchUpsMap:()=>Pe,getParticipantIdFinishingPositions:()=>fT,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getRandomQualifierList:()=>RT,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getValidGroupSizes:()=>Gp,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,luckyLoserDrawPositionAssignment:()=>NP,modifyDrawDefinition:()=>sD,modifyDrawName:()=>Hg,modifySeedAssignment:()=>FP,mutate:()=>lD,positionActions:()=>MT,pruneDrawDefinition:()=>cD,qualifierDrawPositionAssignment:()=>Cg,qualifierProgression:()=>kP,query:()=>PD,removeDrawPositionAssignment:()=>Ou,removeRoundMatchUps:()=>mD,removeSeededParticipant:()=>$P,removeStructure:()=>BP,renameStructures:()=>VP,resetDrawDefinition:()=>aD,resetQualifyingStructure:()=>WP,resetVoluntaryConsolationStructure:()=>KU,setDrawParticipantRepresentativeIds:()=>VU,setPositionAssignments:()=>RP,setStructureOrder:()=>GP,setSubOrder:()=>dD,shiftAdHocRounds:()=>MP,swapAdHocRounds:()=>CP,swapDrawPositionAssignments:()=>qP,updateTeamLineUp:()=>os,withdrawParticipantAtDrawPosition:()=>PP});var lD={};Xt(lD,{adHocPositionSwap:()=>zP,addAdHocMatchUps:()=>Gd,addDrawDefinitionTimeItem:()=>Og,addPlayoffStructures:()=>Kp,addQualifyingStructure:()=>KP,addVoluntaryConsolationStage:()=>HP,addVoluntaryConsolationStructure:()=>Eg,alternateDrawPositionAssignment:()=>bP,assignDrawPosition:()=>uD,assignDrawPositionBye:()=>Wr,attachConsolationStructures:()=>iD,attachPlayoffStructures:()=>Vg,attachQualifyingStructure:()=>bg,attachStructures:()=>Bg,automatedPlayoffPositioning:()=>na,automatedPositioning:()=>Mc,deleteAdHocMatchUps:()=>pD,luckyLoserDrawPositionAssignment:()=>NP,modifyDrawDefinition:()=>sD,modifyDrawName:()=>Hg,modifySeedAssignment:()=>FP,pruneDrawDefinition:()=>cD,qualifierDrawPositionAssignment:()=>Cg,qualifierProgression:()=>kP,removeDrawPositionAssignment:()=>Ou,removeRoundMatchUps:()=>mD,removeSeededParticipant:()=>$P,removeStructure:()=>BP,renameStructures:()=>VP,resetDrawDefinition:()=>aD,resetQualifyingStructure:()=>WP,resetVoluntaryConsolationStructure:()=>KU,setDrawParticipantRepresentativeIds:()=>VU,setPositionAssignments:()=>RP,setStructureOrder:()=>GP,setSubOrder:()=>dD,shiftAdHocRounds:()=>MP,swapAdHocRounds:()=>CP,swapDrawPositionAssignments:()=>qP,updateTeamLineUp:()=>os,withdrawParticipantAtDrawPosition:()=>PP});var GU=t=>e=>t[e],od=(t=[])=>t.map(Ue).filter(Boolean),Hf=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>GU(t)("participantId");var Ue=(t={})=>GU(t)("matchUpId"),gu=(t={})=>GU(t)("drawId");function VU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:br};if(!Array.isArray(t))return{error:B};let r=Hf(e?.entries||[]);return t.length&&jt(t,r).length<t.length?{error:B}:Pp({drawDefinition:e,extension:{name:Wh,value:t}})}var vr="ABANDONED",gc="AWAITING_RESULT";var po="CANCELLED",ge="COMPLETED",Iu="DEAD_RUBBER",Gt="DEFAULTED",be="DOUBLE_DEFAULT",oe="DOUBLE_WALKOVER",Hn="IN_PROGRESS",mn="INCOMPLETE",BU="NOT_PLAYED",Me="RETIRED",ls="SUSPENDED",Qt="TO_BE_PLAYED",Bt="WALKOVER",Nb=[gc,ge,Gt,Hn,mn,Me,ls],Yh=[gc,ge,Gt,oe,be,Hn,mn,Me,ls,Bt],qh=[vr,gc,"BYE",po,ge,Iu,Gt,oe,be,Hn,mn,BU,Me,ls,Qt,Bt],$h=["BYE",oe,be,ge,Gt,Me,Bt],Kh=[vr,gc,po,Iu,Hn,mn,BU,ls,Qt,void 0],ae=[po,vr,ge,Iu,Gt,oe,be,Me,Bt],id=[vr,ge,Gt,oe,be,Hn,Me,Bt],zh=[Hn,mn,ls,Qt],Qh={ABANDONED:vr,AWAITING_RESULT:gc,BYE:"BYE",CANCELLED:po,COMPLETED:ge,DEAD_RUBBER:Iu,DEFAULTED:Gt,DOUBLE_WALKOVER:oe,DOUBLE_DEFAULT:be,IN_PROGRESS:Hn,INCOMPLETE:mn,NOT_PLAYED:BU,RETIRED:Me,SUSPENDED:ls,TO_BE_PLAYED:Qt,WALKOVER:Bt};function Ni(t,e,r){let n=m=>mt({element:m,name:vn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===yU&&sb,s=r?.mode===TU&&EU,a=s||i||$s,c=m=>m?.stage===rt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ae.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(Wf(t)||0)-(Wf(e)||0)}function Wf(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function at(t){let e=et(t,[{[Ce]:!0,[cu]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=hn({drawDefinition:r}),i=o?.map(c=>c.structures?[...c.structures].concat(c):c).flat(),s=i?.find(c=>c.structureId===n);if(!s)return{error:_t};let a=s.structureType===hp?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&&Z||!e?.structures&&Kl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=mt({element:f,name:vn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Ni(f,g,i))??[],m=t?Object.assign({},...ru.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:m};function d(f){return!a&&!Array.isArray(s)||a&&f.stage===a||Array.isArray(s)&&s.includes(f.stage)}function l(f){return!n&&!Array.isArray(r)||n&&f.stageSequence===n||Array.isArray(r)&&r.includes(f.stageSequence)}}function Xh({drawDefinition:t}){if(!t)return{error:Z};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=Ct({structure:n}),s=i?.map(St).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Ct({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:Z};if({structure:r,error:n}=at({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>Ct({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=sA,{positionAssignments:o,error:n}}function Ie({drawDefinition:t,structureId:e,structure:r}){let n=Ct({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var jf="addDrawDefinition",Mp="addMatchUps",ci="addParticipants",Yf="addScaleItems",HU="addEvent",Jh="addVenue",Mi="audit",Zh="dataIssue",qf="deleteParticipants",$f="deleteVenue",Kf="deletedDrawIds",zf="deletedMatchUpIds",Qf="modifyDrawDefinition",WU="modifyDrawEntries",jU="modifyEventEntries",Xf="modifyMatchUp",rr="modifyParticipants",Jf="modifyPositionAssignments",Zf="modifySeedAssignments",Xi="modifyTournamentDetail",Ri="modifyVenue",sd="mutations",tS="publishEvent",YU="publishEventSeeding",qU="publishOrderOfPlay",$U="publishParticipants",tg="unPublishEvent",eg="unPublishEventSeeding",rg="unPublishOrderOfPlay",Mb="unPublishParticipants",Rp="updateInContextMatchUp",Rb={ADD_DRAW_DEFINITION:jf,ADD_MATCHUPS:Mp,ADD_PARTICIPANTS:ci,ADD_SCALE_ITEMS:Yf,ADD_EVENT:HU,ADD_VENUE:Jh,AUDIT:Mi,DATA_ISSUE:Zh,DELETE_PARTICIPANTS:qf,DELETE_VENUE:$f,DELETED_DRAW_IDS:Kf,DELETED_MATCHUP_IDS:zf,MODIFY_DRAW_DEFINITION:Qf,MODIFY_DRAW_ENTRIES:WU,MODIFY_EVENT_ENTRIES:jU,MODIFY_MATCHUP:Xf,MODIFY_PARTICIPANTS:rr,MODIFY_POSITION_ASSIGNMENTS:Jf,MODIFY_SEED_ASSIGNMENTS:Zf,MODIFY_TOURNAMENT_DETAIL:Xi,MODIFY_VENUE:Ri,MUTATIONS:sd,PUBLISH_EVENT_SEEDING:YU,PUBLISH_EVENT:tS,PUBLISH_ORDER_OF_PLAY:qU,PUBLISH_PARTICIPANTS:$U,UNPUBLISH_EVENT_SEEDING:eg,UNPUBLISH_EVENT:tg,UNPUBLISH_ORDER_OF_PLAY:rg,UPDATE_INCONTEXT_MATCHUP:Rp};function eS(t,e){if(!t)return{error:Z};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...C}}function Fo({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&eS(t),lt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Mp}),{...C}}function _n({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&eS(t),lt({topic:zf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)eh({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&bt({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),lt({topic:Xf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(mr),{error:mr})}function Cb({tournamentId:t,inContextMatchUp:e}){return e?(lt({payload:{inContextMatchUp:e,tournamentId:t},topic:Rp,key:e.matchUpId}),{...C}):{error:mr}}function Ma({tournamentId:t,eventId:e,drawDefinition:r}){return r?(eS(r),lt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:jf,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function bb({tournamentId:t,eventId:e,drawId:r}){return lt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Kf,key:r}),eh({key:r}),{...C}}function bt({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(eS(t,r),lt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Qf,key:t.drawId}),{...C}):{error:Z}}function rS({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:Si};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return lt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:Zf,key:t.drawId}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function ko({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:Si};let o=Ct({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return lt({topic:Jf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),bt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function KU({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:Z};let o=e.structures?.find(s=>s.stage===$e);if(!o)return{error:_t};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],_n({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),bt({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function ad({drawPositions:t,structure:e}){if([ct,rt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Ct({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,extension:{name:Zm,value:!0}})})}function hu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[lc]===!1)return;let{extension:o}=mt({name:lc,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===rt);if(a){let c=Ct({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:lc};At({element:n,extension:s})}function fs({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function Su(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===vt?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===vt&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Rr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var Ic="SIGN_IN_STATUS",zU="SIGNED_OUT",Tu="SIGNED_IN",Ar="TEAM",Et="INDIVIDUAL",Qr="GROUP",ft="PAIR",wt="TEAM",yu={TEAM_PARTICIPANT:Ar,INDIVIDUAL:Et,GROUP:Qr,TEAM:wt,PAIR:ft},Ob={INDIVIDUAL:Et,GROUP:Qr,PAIR:ft,TEAM:wt,SIGN_IN_STATUS:Ic,SIGNED_OUT:zU,SIGNED_IN:Tu};function Eu({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===wt),s=o.filter(c=>c.participantType===Qr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===Et){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function QU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function vb(t){let e=Object.assign({},...ui.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return QU(e[t])}var ui=[{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 nS({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=ui.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 _b({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?Qi({template:e,source:s}):s)}}}}function Uo(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:re}}function oS(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Uo({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:st}}function nn(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=oS(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:B,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:df};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=J(i.pop(),!1,!0);if(s){let a={timeItem:s,...C};return e&&Object.assign(a,{previousItems:i}),a}else return{info:Oe}}function iS({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:cn};if(!e.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Au({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:Ot};if(!n.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function cd({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:q};if(!e.timeItems)return{info:Oe};let{timeItem:o,previousItems:i,info:s}=nn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function sS({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:q};if(!r)return{error:se};let i=Uo({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:Oe};let{timeItem:a,previousItems:c,info:u}=nn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var Ak={[Qr]:"groupParticipantIds",[ft]:"pairParticipantIds",[wt]:"teamParticipantIds"},Uk={[Qr]:"groups",[wt]:"teams"};function aS({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,withGroupings:i,internalUse:s,withISO2:a,withIOC:c}){let u=[],p={};for(let d of r.participants??[]){let l=d?.participantId;l&&Nk({participantMap:p,participantId:l})}for(let d of r.participants??[]){let l=J(d,e,s),{participantId:f,individualParticipantIds:g,participantType:I}=l;if(!p[f]){u.push(f);continue}if(Object.assign(p[f].participant,l),g){let h=Dk({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});h.missingParticipantIds.length&&u.push(...h.missingParticipantIds)}if(n&&(p[f].participant.signedIn=Pk(l)),o){let{ratings:h,rankings:S,seedings:T}=Aa({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=S,p[f].participant.ratings=h}(c||a)&&nS({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=ht(t)?t:void 0;_b({participantMap:p,template:d})}let m;return i&&(m=Eu({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function Pk(t){let{timeItem:e}=nn({itemType:Ic,element:t});return e?.itemValue===Tu}function Dk({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[Ak[n]].push(o),[wt,Qr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=Uk[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===ft){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function Nk({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[Lt]:{...r},[vt]:{...r},[wt]:{...r},...r}}}function Xo({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return aS({...t,...n,tournamentRecord:r});let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>nS({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Eu({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=Aa({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function Tt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:YI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...C};function a(c){let p=c?.extensions?.find(m=>m.name===du)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function Go({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:YI};let{appliedPolicies:i}=Tt({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:qc.message}}var cS="WALKOVER",XU="RETIRED",ud="COMPETITIVE",hc="ROUTINE",Sc="DECISIVE",pd="winRatio";var Mk={[Di]:{policyName:"Competitive Bands Default",profileBands:{[Sc]:20,[hc]:50}}},md=Mk;function Zn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=Go({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[Di]??s?.[Di]??md[Di];i.policies[Di]=a}return i}function pi({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:q};let{appliedPolicies:i}=Tt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:qc?.message}}function Ra({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}=pi({policyType:_o,tournamentRecord:t,event:n}),s=(t?mt({element:t,name:Qo}).extension:void 0)?.value,c=(n&&mt({name:Qo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function ng({drawDefinition:t,attributes:e}){let{extension:r}=mt({element:t,name:ed}),n=r?.value||{};return e.forEach(o=>{Object.keys(o).forEach(i=>{n[i]?Object.assign(n[i],o[i]):n[i]=o[i]})}),r={name:ed,value:n},Pp({drawDefinition:t,extension:r}),{entryProfile:n}}function Uu({drawDefinition:t}){let{extension:e}=mt({element:t,name:ed});return{entryProfile:e?.value||{}}}var on="ALTERNATE",og="CONFIRMED",Gr="DIRECT_ACCEPTANCE",dd="FEED_IN",ig="JUNIOR_EXEMPT",gs="LUCKY_LOSER",sg="ORGANISER_ACCEPTANCE",ld="QUALIFIER",Rk="REGISTERED",ag="SPECIAL_EXEMPT",Vr="UNGROUPED",Ci="UNPAIRED",Pu="WILDCARD",mo="WITHDRAWN",cg=[og,Gr,ig,sg,ag],JU=[dd,gs,ld],mi=[og,Gr,dd,ig,sg,ag,Pu],Xr=[og,Gr,ig,gs,ld,sg,ag,Pu],ZU=[on,og,Gr,dd,ig,gs,sg,ld,Rk,ag,Vr,Ci,Pu,mo],xb={ALTERNATE:on,CONFIRMED:og,DIRECT_ACCEPTANCE:Gr,DIRECT_ENTRY_STATUSES:mi,DRAW_SPECIFIC_STATUSES:JU,EQUIVALENT_ACCEPTANCE_STATUSES:cg,FEED_IN:dd,JUNIOR_EXEMPT:ig,LUCKY_LOSER:gs,ORGANISER_ACCEPTANCE:sg,QUALIFIER:ld,SPECIAL_EXEMPT:ag,STRUCTURE_SELECTED_STATUSES:Xr,UNGROUPED:Vr,UNPAIRED:Ci,VALID_ENTRY_STATUSES:ZU,WILDCARD:Pu,WITHDRAWN:mo};function ug({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&ru.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return ng({drawDefinition:e,attributes:o}),!0}return n}function wb({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e});return r[t]?.alternates||0}function Lb({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e});return r[t]?.wildcardsCount||0}function uS({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function bi({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=mt({name:vn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===fe){let{playoffEntries:p,error:m}=Ck({provisionalPositioning:t,drawDefinition:r,structureId:i});return m&&console.log("playoff entries error"),(p?.length?p:u).filter(d=>!e||d.placementGroup===e)}return u}function Ck({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}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===Ve&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=mt({element:h,name:Lo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],y=T.groupOrder||t&&T.provisionalOrder;return h.includes(y)||h.push(y),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:y,GEMscore:E}=S,P=T||t&&y,A=[...i??[]].sort(le).indexOf(P)+1;n.push({entryStage:fe,entryStatus:dd,placementGroup:A,groupingValue:d,participantId:h,GEMscore:E})})})}return{playoffEntries:n}}function Fb({stage:t,drawDefinition:e}){return mi.reduce((r,n)=>(uS({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function sn({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=Ct({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:_t};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===fe&&r&&bi({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let h=I+1;return{participantId:g.participantId,seedValue:h,seedProxy:!0,seedNumber:h}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=QE;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function di(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 Cp({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r.tieFormat)return r.tieFormat;if(r.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function We({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:Cp({item:r,drawDefinition:t,structure:e,event:n})||Cp({item:e,drawDefinition:t,structure:e,event:n})||di(t)||di(n)}}function kb({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 Pe({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function Vo({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}function pS({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(le);return n.map(i=>o.indexOf(i)+1)}function pg(t){if(!ht(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>It(i)||i===void 0||i===null);return n&&o}function Br(t){return Array.isArray(t)?t.every(pg):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Br(t))return{roundMatchUps:[],error:B};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?dt(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(le).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===Wt)?l.filter(({matchUpType:h})=>h===Wt):l,I=h=>h.sort((S,T)=>le(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?dt(l.roundNumber):l.roundNumber;return d[f]||(d[f]=nt({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>dt(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&Ln(l)){let f=d+1,g=f+l/2;tt(f,g).forEach((h,S)=>{o[h]=tt(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ae.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>dt(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(le),I=Ae(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=Ae(I,h),T=l.map(y=>{let{roundPosition:E}=y,P=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!E)return P;let A=P?.filter(Boolean)||[];if(!A?.length)return[void 0,void 0];if(d<3&&A?.length===2)return P?.slice().sort(le);let U=jt(I,A).length!==A?.length;if(A?.length&&U)return A?.length===1?[A[0],void 0]:P?.slice().sort(le);let N=(E-1)*2;return S.slice(N,N+2).map(M=>A?.find(R=>M.includes(R)))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]&&s[d+1].matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).find(({matchUpsCount:d})=>!Ln(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function fd(t){if(!Array.isArray(t))return"";let e=t.filter(Jt);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function Gb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:Z};if(!e)return{error:Pr};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==qe)return{error:Vi,info:"Structure is not CONSOLATION stage"};let{links:o}=t,i=o?.filter(m=>m.target.structureId===e)||[],s=i?.reduce((m,d)=>{let{structureId:l}=d.source;return m.includes(l)?m:m.concat(l)},[])||[],a=Object.assign({},...s.map(m=>{let d=Vo({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=Vo({matchUpsMap:r,structureId:e}),{roundProfile:u}=Ke({matchUps:c}),p={};return i?.forEach(m=>{let{structureId:d,roundNumber:l}=m.source,{feedProfile:f,groupedOrder:g,positionInterleave:I,roundNumber:h}=m.target,S=a[d],T=S[1]?.drawPositions,E=S[l]?.matchUpsCount;if(!E)return;let P=E?T.length/E:0,A=T.length/P,U=T.slice(),N=pS({roundPositionsCount:A,groupedOrder:g}),D=N?.length||1;if(D<=A){let O=T.length/D,v=Ae(U,O);f===yi&&v.forEach(x=>x.reverse()),U=N?.length&&N?.map(x=>v[x-1]).flat()||v.flat()}let M=Ae(U,P);if(I){let O=tt(0,I.interleave).map(()=>{}),v=tt(0,I.offset).map(()=>{});M=M.map(F=>[F,...O]),M.unshift(v),M=M.flat(1);let x=M.length-I.offset;M=M.slice(0,x)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;M.forEach((O,v)=>{let x=1+v*b;p[h][x]||(p[h][x]=fd(O))})}),{sourceDrawPositionRanges:p}}function mS({drawDefinition:t}){if(typeof t!="object")return{error:Sa};let e={},{structures:r=[],links:n=[]}=t||{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[qe,fe].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,h=r.find(T=>T.structureId===I).stage,S=[h,I,g,f].join("|");if(p[S])return;p[S]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:h})}}}function Vb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Pr};if(!e){let c=Vo({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ke({matchUps:c}),!e)return{error:st}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=Ae(p,p.length/u),d=m.map(fd),l=m.map(S=>S.map(T=>T-i)).map(fd),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return Ae(T,T.length/u)}).filter(Boolean),g=tt(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(le)).map(S=>pt(S)),I=g.map(S=>UC(S).map(fd).join(", ")),h=Object.assign({},...tt(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function gd({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Ke({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==Ki)&&!r?.structures&&t&&o}function cr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var mg={[vo]:{policyName:"Round Naming Default",namingConventions:{round:"Round",pre:"Pre"},qualifyingFinishMap:{1:"Final"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q",preQualifying:"P"},stageConstants:{[rt]:"",[fe]:"P",[ct]:"Q",[qe]:"C"}}},Bb=mg;function dS({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=cr({structure:r}),u=gd({structure:r}),p=r.structures,m={},d=mg[vo],l=r.stage===ct,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===ct).map(({stageSequence:b})=>b??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,P=(t?.namingConventions||d.namingConventions).round,A=a&&a!==rt?a[0]:"",U=t?.stageConstants||d.stageConstants,N=a&&U?.[a]||A,D=`${I}${N}${g}`,M=o?Object.keys(o):[],R=l&&U?.[ct]?`${U?.[ct]}-`:"";if(p||c||u)Object.assign(m,...M.map(b=>{let O=`${R}${P} ${b}`,v=`${y}${b}`;return{[b]:{roundName:O,abbreviatedRoundName:v}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...M.map(O=>{if(!o?.[O])return;let{matchUpsCount:v,preFeedRound:x}=o[O],F=v*2,w=b?.[o?.[O].finishingRound]||b&&`${y}${F}`||h[v]||`${y}${F}`,L=x?`-${T}`:"",k=`${w}${L}`,G=[D,s,k].filter(Boolean).join("-"),K=`${S[v]||`${y}${F}`}${L}`,Y=[D,s,K].filter(Boolean).join("-");return{[O]:{abbreviatedRoundName:Y,roundName:G}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var bk=(t,e)=>(t||0)+(e||0);function lS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&cS||r<=e[Sc]&&Sc||r<=e[hc]&&hc||ud}function fS({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(bk)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function Ok(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function gS(t){return t.map(Ok).sort().map(e=>parseFloat(e.toFixed(2)))}function Du({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:mr};let{score:n,winningSide:o}=r;if(!o)return{error:B};let i=!e&&t&&pi({policyType:Di,tournamentRecord:t}).policy,s=e||i?.profileBands||md[Di].profileBands,a=fS({score:n}),c=gS([a]),u=lS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function IS({matchUp:t}){if(!t)return{error:mr};if(t&&!t.sides)return{error:dr};if(t&&!t.hasContext)return{error:Kc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Et).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=pt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...C}}var Id="CHECK_IN",hd="CHECK_OUT",vk="SCHEDULE",Ji="SCHEDULE.ASSIGNMENT.VENUE",lo="SCHEDULE.ALLOCATION.COURTS",Jo="SCHEDULE.ASSIGNMENT.COURT",bp="SCHEDULE.COURT.ORDER",Zi="SCHEDULE.DATE",_k="COMPLETED.DATE",Sd="HOME_PARTICIPANT_ID",dg="SCHEDULE.ASSIGN.OFFICIAL",ts="SCHEDULE.TIME.SCHEDULED",Bo="SCHEDULE.TIME.START",es="SCHEDULE.TIME.STOP",Oi="SCHEDULE.TIME.RESUME",vi="SCHEDULE.TIME.END",Op="SCHEDULE.TIME.MODIFIERS",Hb="TO_BE_ANNOUNCED",Wb="NEXT_AVAILABLE",jb="FOLLOWED_BY",Yb="AFTER_REST",qb="RAIN_DELAY",xk="NOT_BEFORE",hS=[Hb,Wb,jb,Yb,qb],wk="ELIGIBILITY",Lk="REGISTRATION",Fk="SUSPENSION",kk="MEDICAL",Gk="PENALTY",tP="SCALE",eP="RATING",rP="RANKING",lg="SEEDING",Ho="PUBLISH",Cr="PUBLIC",Wo="STATUS",Vk="MODIFICATION",Bk="RETRIEVAL",Hk="other",$b={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:hS,AFTER_REST:Yb,ALLOCATE_COURTS:lo,ASSIGN_COURT:Jo,ASSIGN_OFFICIAL:dg,ASSIGN_VENUE:Ji,CHECK_IN:Id,CHECK_OUT:hd,COMPLETED_DATE:_k,COURT_ORDER:bp,ELIGIBILITY:wk,END_TIME:vi,FOLLOWED_BY:jb,MEDICAL:kk,MODIFICATION:Vk,NEXT_AVAILABLE:Wb,NOT_BEFORE:xk,OTHER:Hk,PENALTY:Gk,PUBLIC:Cr,PUBLISH:Ho,RANKING:rP,RATING:eP,RAIN_DELAY:qb,REGISTRATION:Lk,RESUME_TIME:Oi,RETRIEVAL:Bk,SCALE:tP,SCHEDULE:vk,SCHEDULED_DATE:Zi,SCHEDULED_TIME:ts,SEEDING:lg,START_TIME:Bo,STATUS:Wo,STOP_TIME:es,SUSPENSION:Fk,TIME_MODIFIERS:Op,TO_BE_ANNOUNCED:Hb};function Is({matchUp:t}){if(!t)return{error:mr};if(!t.hasContext)return{error:Kc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:dr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=IS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Id,hd].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===Id);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...C}}var de=t=>e=>{let r=ht(e)&&e?.matchUpType||kt(e)&&e;return r&&vI[t].includes(r)};function vp(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 _p(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 SS({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 Kb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&_p({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&_p({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&_p({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return SS({categoryName:i,categoryType:s,timesBlockArray:m})}function zb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&vp({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&vp({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&vp({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return SS({categoryName:e,categoryType:r,timesBlockArray:p})}var nP="DOUBLES_SINGLES",oP="SINGLES_DOUBLES",fo="total",TS="participantConflict",Ca="matchUpConflict",iP="ISSUE_IDS",Tc="CONFLICT",yc="WARNING",yS="ERROR",ES="ISSUE",fg="STATE",Qb={SINGLES_DOUBLES:oP,DOUBLES_SINGLES:nP,TOTAL:fo,CONFLICT_MATCHUP_ORDER:Ca,CONFLICT_PARTICIPANTS:TS,SCHEDULE_ISSUE_IDS:iP,SCHEDULE_CONFLICT:Tc,SCHEDULE_WARNING:yc,SCHEDULE_ERROR:yS,SCHEDULE_ISSUE:ES,SCHEDULE_STATE:fg};function Nu({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:q};s=s??a?.eventType??qs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Ra({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return xp({eventType:s,timingDetails:p})}function xp({timingDetails:t,eventType:e}){let r=zb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=Kb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=de(qs)(e)?oP:nP,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function sP(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Zo({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>sP(o)-sP(i)).pop(),n=r&&sP(r);return{itemValue:r?.itemValue,timeStamp:n}}function AS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:ts});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Xs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Zi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function wp(t){if(nh.test(t)){let e=Mf();return new Date(`${e}T${t}`)}else return new Date(t)}function Xb({matchUp:t}){if(!t)return{error:mr};if(!t.timeItems)return{error:df};let e=t.timeItems.filter(n=>[Bo,es,Oi,vi].includes(n?.itemType)).sort((n,o)=>wp(n.itemValue).getTime()-wp(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 Bo:i=0;break;case vi:if(n.lastValue&&[Bo,Oi].includes(n.lastType)){let u=wp(o.itemValue).getTime()-wp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case es:if([Bo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=wp(o.itemValue).getTime()-wp(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([Bo,Oi].includes(r.lastType)){let n=new Date().getTime()-wp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:Wk(r.milliseconds),relevantTimeItems:e}}function Wk(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 Jb({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===Bo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function Ec(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:B};let o=Rr(t);r.venueId||(r.venueId=Nt());let i;for(let s of Object.values(o)){let a=jk({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||lt({topic:Jh,payload:{venue:r}}),nt({...C,venue:i})}function jk({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Nt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:OA}:(r&&At({element:n,extension:{value:r,name:OU}}),t.venues.push(n),e||lt({payload:{venue:n,tournamentId:t.tournamentId},topic:Jh}),{...C,venue:J(n)})):{error:st,info:"missing venue"}:{error:q}}function ti({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:q};if(!r)return{error:ai};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(fu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=ti({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return Ec({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:ji}}function US({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=ti({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function hs({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:q};if(!r)return{error:Bi};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...C,court:o,venue:i};if(t){let a=(fu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=hs({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&Ec({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:Vs},stack:n})}function PS(t){return J(hs(t),!1,!0)}function Td({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:q};if(!r)return{error:Bi};let n=hs({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...C,courtInfo:J(o,!1,e)}}function Ac(t){let e=et(t,[{[ne]:!0},{venueId:!0,[In]:ai}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=ti({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(Td({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:m})=>({venueAbbreviation:m,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...C,venueData:J(c,!1,!0)}}function Zb({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===vi&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:Ot};let n=mt({name:pn,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function ze(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Ht({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,..._({result:{error:qr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:br},context:{drawId:n,eventId:r},stack:o})}}function yd(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:mr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let P=t.drawDefinition||e?.drawDefinitions?.find(U=>U.drawId===p.drawId);!P&&i&&({drawDefinition:P,event:e}=ze({drawId:p.drawId,tournamentRecord:i}));let A=p.structureId&&P?.structures?.find(({structureId:U})=>U===p.structureId);r=t.matchUpType||A?.matchUpType||P?.matchUpType||e?.eventType!==_e&&e?.eventType}let{milliseconds:m,time:d}=Xb({matchUp:p}),{startTime:l}=Jb({matchUp:p}),{endTime:f}=Zb({matchUp:p}),g,{eventIds:I,drawIds:h}=n??{};if((!I||I.includes(p.eventId))&&(!h||h.includes(p.drawId))){let P=Q=>Q.createdAt?new Date(Q.createdAt).getTime():0,A=new Map,U=p.timeItems?.toSorted((Q,ut)=>P(Q)-P(ut))??[];for(let Q of U)A.set(Q.itemType,Q.itemValue);let N=A.get(Sd),D=A.get(lo),M=A.get(ts),R=A.get(Op),b=A.get(Zi),O=A.get(dg),v=A.get(bp),x=A.get(Ji),F=A.get(Jo),w,L,k,G,H,K=p.matchUpType??r;if(a&&M&&o&&K){let Q={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:L=0,recoveryMinutes:k=0,typeChangeRecoveryMinutes:G=0}=xp({timingDetails:Q,eventType:K})),(L||k)&&(w=f?$r(zt(f),k):$r(M,L+k)),G&&(H=f?$r(zt(f),G):$r(M,L+G))}!b&&M&&(b=Ut(M));let Y=Bm({scheduledDate:b,scheduledTime:M}),j={},V=(i&&x&&Ac({tournamentRecord:i,venueId:x}))?.venueData||{};x&&(j[x]=V);let{venueName:$,venueAbbreviation:X,courtsInfo:W}=V,z=(F&&W?.find(Q=>Q.courtId===F))?.courtName;for(let Q of D||[]){if(!i)break;Q.venueId&&!j[Q.venueid]&&(j[Q.venueId]=Ac({venueId:Q.venueId,tournamentRecord:i})?.venueData);let ut=j[Q.venueId];Q.venueName=ut?.venueName;let ot=ut?.courtsInfo?.find(Dt=>Dt.courtId===Q.courtId);Q.courtName=ot?.courtName}g=nt({typeChangeTimeAfterRecovery:H,timeAfterRecovery:w,scheduledDate:b,scheduledTime:M,isoDateString:Y,homeParticipantId:N,venueAbbreviation:X,allocatedCourts:D,timeModifiers:R,venueName:$,venueId:x,courtOrder:v,courtName:z,courtId:F,official:O,typeChangeRecoveryMinutes:G,recoveryMinutes:k,averageMinutes:L,milliseconds:m,startTime:l,endTime:f,time:d})}else g=nt({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Xs({matchUp:p}),{scheduledTime:T}=AS({matchUp:p});if(s&&u?.displaySettings?.draws){let P=u.displaySettings.draws,A=(P?.[p.drawId]??P?.default)?.scheduleDetails;if(A){let U=(A.find(N=>S&&N.dates?.includes(S))??A.find(N=>!N.dates?.length))?.attributes;if(U){let N=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),U);g=Qi({source:g,template:N})}}}let E=p.matchUpStatus&&ae.includes(p.matchUpStatus)&&(Ut(f)||Ut(S)||Ut(T))||void 0;return{schedule:g,endDate:E}}function tO({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(LI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>ke(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(wI(t)){let c=[...t].sort(le);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(dt(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Lp({collectionPosition:t,collectionId:e,lineUp:r}){let n=[],o=[];if(r){let i=a=>a===void 0?-1:a,s=r.map(a=>{let{collectionAssignments:c,participantId:u}=a,p=c?.find(m=>m.collectionPosition===t&&m.collectionId===e);return p&&{participantId:u,...p}}).filter(Boolean).sort((a,c)=>i(a.substitutionOrder)-i(c.substitutionOrder));for(let a of s){let{participantId:c,previousParticipantId:u,substitutionOrder:p}=a;n.includes(c)||(u&&o.push({previousParticipantId:u,substitutionOrder:p,participantId:c}),n=n.filter(m=>m!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function Sn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:q};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return _({result:{error:bo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===ft&&jt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:re},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function Ss({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:se};let{extension:r}=mt({element:t,name:wo});return{lineUp:(r?.value||{})[e]}}function eO({tournamentParticipants:t,positionAssignments:e,collectionPosition:r,drawPositions:n=[],participantMap:o,drawDefinition:i,collectionId:s,sideLineUps:a,matchUpType:c}){if(!s||!r)return{};let u=({attribute:m,lineUp:d,teamParticipant:l})=>{let{assignedParticipantIds:f,substitutions:g}=Lp({collectionPosition:r,collectionId:s,lineUp:d});if(c===vt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||Sn({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[m]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[m]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[m]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let m=a?.map(d=>{let{teamParticipant:l,sideNumber:f}=d,g=d.lineUp||Ss({participantId:l.teamParticipantId,drawDefinition:i})?.lineUp;return u({attribute:f,lineUp:g,teamParticipant:l})}).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...m)}}let p=n?.map(m=>{let d=e.find(I=>I.drawPosition===m)?.participantId,l=a?.find(I=>I?.drawPosition===m),f=l?.teamParticipant||d&&o?.[d]?.participant||t?.find(({participantId:I})=>I===d),g=l?.lineUp||Ss({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function Ed(t){let e=et(t,[{[Gn]:!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===Et&&Lt||s===ft&&vt||s===wt&&wt||void 0}return{matchUpType:n}}function rO({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:r,displaySideNumber:n,seedAssignments:o,drawPosition:i,isFeedRound:s,sideNumber:a}){let c=r.find(l=>l.drawPosition&&l.drawPosition===i),u=i&&t,p=a&&e,m=u?u[i]?.participantId:c?.participantId,d=c?Yk({displaySideNumber:n,seedAssignments:o,participantId:m,assignment:c,sideNumber:a}):{...p?.[a]};if(s&&(a===1?Object.assign(d,{participantFed:!0}):Object.assign(d,{participantAdvanced:!0})),i&&u){let l=u[i]?.teamParticipant,f=u[i]?.participant,g=u[i]?.substitutions;f&&(d.participant=f),g&&(d.substitutions=g),l&&(d.teamParticipant=l)}return d}function Yk({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=qk({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 qk({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function aP({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:m,appliedPolicies:d,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,publishStatus:E,scoringActive:P,matchUpTieId:A,isRoundRobin:U,roundProfile:N,sideLineUps:D,structure:M,context:R,matchUp:b,event:O}){c=c??{};let v=We({drawDefinition:y,structure:M,matchUp:b,event:O})?.tieFormat,{roundOffset:x,structureId:F,structureName:w,stage:L,stageSequence:k}=M,{drawId:G,drawName:H,drawType:K}=y??{},Y=v?.collectionDefinitions,j=b.collectionId&&Y?.find(me=>me.collectionId===b.collectionId),V=b.collectionId?j?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??O?.matchUpFormat,$=b.matchUpType||j?.matchUpType||M?.matchUpType||y?.matchUpType||!de(_e)(O?.eventType)&&O?.eventType,X=l?"BYE":b.matchUpStatus,{schedule:W,endDate:it}=yd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:V,publishStatus:E,matchUpType:$,matchUp:b,event:O}),z=m??b.drawPositions??[],{collectionPosition:Q,collectionId:ut,roundPosition:ot}=b,Dt=b.roundNumber??c.roundNumber,Rt=ut?eO({tournamentParticipants:r,positionAssignments:n,collectionPosition:Q,participantMap:I,drawDefinition:y,drawPositions:z,collectionId:ut,sideLineUps:D,matchUpType:$}):void 0,De=u?.[Dt]?.roundName||c.roundName,qt=u?.[Dt]?.abbreviatedRoundName||c.abbreviatedRoundName,Se=N?.[Dt]?.feedRound,_r=N?.[Dt]?.preFeedRound,dn=N?.[Dt]?.roundFactor,hr=o?.[Dt],Xe=ot?hr?.[ot]:void 0,Zt=e?.[Dt],Pt=j?.category?{...R?.category,...j.category}:R?.category??O?.category,ce=b.processCodes?.length&&b.processCodes||j?.processCodes?.length&&j?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||O?.processCodes?.length&&O?.processCodes||p?.processCodes,ue=T?.withCompetitiveness&&Du({...h,matchUp:b}),Fe=b.finishingPositionRange??c.finishingPositionRange,te=L!==ct&&It(a)&&a+(Dt||0),Je=me=>nt(me,void 0,!0),$t={...Je(R),...Je({matchUpFormat:$===_e?void 0:V,tieFormat:$===_e?v:void 0,gender:j?.gender??O?.gender,endDate:b.endDate??it,discipline:O?.discipline,category:Pt,finishingPositionRange:Fe,abbreviatedRoundName:qt,drawPositionsRange:Xe,competitiveProfile:ue,structureName:w,stageSequence:k,drawPositions:z,matchUpStatus:X,processCodes:ce,isRoundRobin:U,matchUpTieId:A,preFeedRound:_r,matchUpType:$,roundFactor:dn,roundOffset:x,structureId:F,roundNumber:Dt,roundOfPlay:te,feedRound:Se,roundName:De,drawName:H,drawType:K,schedule:W,drawId:G,stage:L}),...J(Je(b),!0,!0)};if(V&&b.score?.scoreStringSide1){let me=Ne(V),{bestOf:Sr,finalSetFormat:jr,setFormat:Kt}=me??{};(jr?.tiebreakSet||Kt?.tiebreakSet||Kt?.timed)&&($t.score.sets=$t.score.sets.sort((Te,gr)=>Te.setNumber-gr.setNumber).map((Te,gr)=>{let ee=gr+1===Sr&&jr?jr:Kt,Ur=ee?.tiebreakSet&&!ee?.timed,Cn=ee?.timed;return Ur?(Te.tiebreakSet=!0,[1,2].includes(Te.winningSide)&&(Te.side1Score=Te.winningSide===1?1:0,Te.side2Score=Te.winningSide===2?1:0)):Cn&&(Te.timed=!0),Te}))}if(Array.isArray(z)){let{orderedDrawPositions:me,displayOrder:Sr}=tO({drawPositions:z,roundProfile:N,roundNumber:Dt}),jr=N?.[Dt]?.feedRound,Kt=Sr[0]!==me[0],gr=me.concat(void 0,void 0).slice(0,2).map((Ee,Rn)=>{let ee=Rn+1,Ur=Kt?3-ee:ee,Cn=rO({...Rt,positionAssignments:n,displaySideNumber:Ur,seedAssignments:f,drawPosition:Ee,isFeedRound:jr,sideNumber:ee}),An=b.sides?.find(ep=>ep.sideNumber===ee),hi=ot?(ot-1)*2+Rn+1:void 0,ga=hi?Zt?.[hi]:void 0;return Je({sourceDrawPositionRange:ga,...An,...Cn})});Object.assign($t,J({sides:gr},!0,!0))}if(r&&$t.sides){let me=d?.[zs],Sr=Kt=>{let Te=I?.[Kt]?.participant;return Te&&Qi({template:me?.participant,source:Te})};if($t.sides.filter(Boolean).forEach(Kt=>{if(Kt.participantId){let Te=J(Sr(Kt.participantId)||(r?zo({policyDefinitions:d,participantId:Kt.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(Te){let gr,Ee;if(y?.entries){let Rn=y.entries.find(Ur=>Ur.participantId===Kt.participantId),ee=O?.entries?.find(Ur=>Ur.participantId===Kt.participantId);gr=Rn?.entryStatus||ee?.entryStatus,Te.entryStatus=gr,Rn?.entryStage&&(Ee=Rn.entryStage,Te.entryStage=Ee)}i===!1?Object.assign(Kt,{participant:{entryStage:Ee,entryStatus:gr}}):Object.assign(Kt,{participant:Te})}}if(Kt?.participant?.individualParticipantIds?.length&&!Kt.participant.individualParticipants?.length){let Te=Kt.participant.individualParticipantIds.map(gr=>Sr(gr)||(r?zo({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:gr}):void 0));i!==!1&&Object.assign(Kt.participant,{individualParticipants:Te})}}),!$t.matchUpType){let{matchUpType:Kt}=Ed({matchUp:$t});Kt&&Object.assign($t,{matchUpType:Kt})}if(T?.inferGender&&(!$t.gender||$t.gender===qi)&&$t.sides?.length===2&&$t.matchUpType!==_e){let Kt=$t.sides.map(Te=>{if(de(Lt)($t.matchUpType))return Te.participant?.person?.sex;if(Te.participant?.individualParticipants?.length===2){let gr=pt(Te.participant.individualParticipants.map(Ee=>Ee.person?.sex)).filter(Boolean);if(gr.length===1)return gr[0]}});if(Kt.filter(Boolean).length===2&&pt(Kt).length===1){let Te=Kt[0];$t.inferredGender=Te}}}if($t.tieMatchUps){let me=$t.matchUpStatus==="BYE",Sr=$t.sides?.map(({participant:jr,drawPosition:Kt,sideNumber:Te,lineUp:gr})=>{let Ee=jr?.participantType===_e&&jr;return{teamParticipant:Ee&&nt({participantRoleResponsibilities:Ee.participantRoleResponsibilities,participantOtherName:Ee.participanOthertName,participantName:Ee.participantName,participantId:Ee.participantId,teamId:Ee.teamId}),drawPosition:Kt,sideNumber:Te,lineUp:gr}});$t.tieMatchUps=$t.tieMatchUps.map(jr=>{let Kt=$t.matchUpId,gr={finishingPositionRange:$t.finishingPositionRange,abbreviatedRoundName:qt,roundNumber:Dt,roundName:De};return aP({tieDrawPositions:z,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:Sr,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:gr,appliedPolicies:d,isCollectionBye:me,usePublishState:g,publishStatus:E,matchUpTieId:Kt,isRoundRobin:U,roundProfile:N,matchUp:jr,event:O,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:P,structure:M,context:R})})}let ir=$t.sides?.filter(me=>me?.participantId).length===2,fr=!$t.winningSide;if(Object.assign($t,{readyToScore:P&&ir&&fr,hasContext:!0}),ir){let{allParticipantsCheckedIn:me,checkedInParticipantIds:Sr}=Is({matchUp:$t});Object.assign($t,{allParticipantsCheckedIn:me,checkedInParticipantIds:Sr})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(me=>delete $t[me]),$t}function nO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:lo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function oO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Jo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function iO({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function _i(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:E,tournamentIds:P,matchUpTypes:A,structureIds:U,readyToScore:N,courtIds:D,eventIds:M,venueIds:R,drawIds:b,stages:O}=t,v=Array.isArray(y)?y.filter(Boolean):[],x=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],w=Array.isArray(O)?O.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],k=Array.isArray(p)?p.filter(Boolean):[],G=Array.isArray(f)?f.filter(Boolean):[],H=Array.isArray(d)?d.filter(Boolean):[],K=Array.isArray(c)?c.filter(Boolean):[],Y=Array.isArray(l)&&I?l.filter(Boolean):[],j=Array.isArray(A)&&g?A.filter(Boolean):[],V=Array.isArray(D)?D.filter(Boolean):[],$=Array.isArray(R)?R.filter(Boolean):[],X=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],W=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],it=Array.isArray(P)?P.filter(Boolean):[],z=Array.isArray(M)?M.filter(Boolean):[],Q=Array.isArray(b)?b.filter(Boolean):[],ut=Array.isArray(U)?U.filter(Boolean):[];return e.filter(ot=>{if(N&&!de(xr)(ot)&&!ot.readyToScore||ot.winningSide&&s&&![1,2].includes(ot.winningSide)||m!==void 0&&(m&&!ot.tieMatchUps||!m&&ot.tieMatchUps)||o!==void 0&&(o&&!ot.collectionId||!o&&ot.collectionId)||w.length&&!w.includes(ot.stage)||L.length&&!L.includes(ot.stageSequence)||k.length&&(!ot.collectionId||!k.includes(ot.collectionId))||G.length&&(!ot.roundName||!G.includes(ot.roundName))||H.length&&(!ot.roundNumber||!H.includes(ot.roundNumber))||K.length&&(!ot.roundPosition||!K.includes(ot.roundPosition))||x.length&&(!ot.matchUpStatus||!x.includes(ot.matchUpStatus))||F.length&&ot.matchUpStatus&&F.includes(ot.matchUpStatus)||Y.length&&!Y.includes(ot.matchUpId)||j.length&&(!ot.matchUpType||!Yc(j,ot.matchUpType))||X.length&&(!ot.matchUpFormat||!X.includes(ot.matchUpFormat)))return!1;if(W?.length){let{scheduledTime:Dt}=AS({matchUp:ot}),{scheduledDate:Rt}=Xs({matchUp:ot}),qt=Ut(Dt)||Rt;if(!W.find(Se=>zn(Se,qt)))return!1}if(V.length){let{courtId:Dt}=oO({matchUp:ot}),{allocatedCourts:Rt}=nO({matchUp:ot}),De=Rt?.map(({courtId:qt})=>qt);if(!V.filter(Boolean).includes(Dt)||De?.includes(Dt))return!1}if($.length){let{venueId:Dt}=iO({matchUp:ot});if(!$.filter(Boolean).includes(Dt))return!1}if(E){if(it.length&&!it.includes(ot.tournamentId)||z.length&&!z.includes(ot.eventId)||Q.length&&!Q.includes(ot.drawId)||ut.length&&!ut.includes(ot.structureId))return!1;let Dt=ot.sides?.map(({participantId:Rt})=>Rt).filter(Boolean)??[];if(n&&Dt.length<n||v.length&&!v.some(De=>Dt.includes(De)))return!1}return!0})}function yt(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:m,contextContent:d,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:Si,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),P=!s||!T?.length||T.includes(s.drawId);if(!y||!E||!P)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=Zn({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:A}=Tt({drawDefinition:s}),U={...t.tournamentAppliedPolicies,...A,...t.policyDefinitions},N=U?.scoring?.structures,D=c.stage&&N?.stage?.[c.stage],M=c.stageSequence&&D?.stageSequence?.[c.stageSequence],R=U?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned;f||(f=Pe({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:O}=Ie({structure:c}),v=!R||O,{seedAssignments:x}=sn({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??x;let{structureId:F}=c;l=l||s&&mS({drawDefinition:s}).exitProfiles;let w=l?.[F],L=w?.length&&(w[0].split("-").map(V=>parseInt(V)).reduce((V,$)=>V+$)||0),k=!!c.structures,G=Vo({matchUpsMap:f,structureId:F,inContext:u}),H=U?.[vo],K=dS({roundNamingPolicy:H,drawDefinition:s,structure:c,matchUps:G}),{roundNamingProfile:Y,roundProfile:j}=K;if(I=K?.roundMatchUps??[],o&&(G=_i({matchUps:G,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:V}=Gb({drawDefinition:s,matchUpsMap:f,structureId:F}),$=s?Vb({drawDefinition:s,roundProfile:j,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0,X=t.tournamentParticipants,W=t.participantMap;!X?.length&&!W&&r&&({participants:X=[],participantMap:W}=Xo({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:r,contextProfile:i,inContext:u})),G=G.map(z=>aP({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:V,tournamentParticipants:X,positionAssignments:b,drawPositionsRanges:$,initialRoundOfPlay:L,roundNamingProfile:Y,tournamentRecord:r,appliedPolicies:U,seedAssignments:m,contextContent:d,participantMap:W,contextProfile:i,drawDefinition:s,scoringActive:v,isRoundRobin:k,roundProfile:j,structure:c,context:a,matchUp:z,event:p})),(G?.filter(z=>Array.isArray(z.tieMatchUps))).forEach(z=>{let Q=z.tieMatchUps;G=G.concat(...Q)}),n&&(G=_i({processContext:!0,...n,matchUps:G}))}else(G?.filter($=>Array.isArray($.tieMatchUps))).forEach($=>{let X=$.tieMatchUps;G=G.concat(...X)});return o&&(G=_i({matchUps:G,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(G=_i({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:G})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ke({matchUps:G}).roundMatchUps??[]),We({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=kb({matchUps:G})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:k,roundProfile:j,matchUpsMap:f,matchUps:G}}function Ts({matchUp:t}){return t?ae.includes(t?.matchUpStatus)||t?.winningSide:!1}function Mu({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structureId:T,inContext:y,structure:E,context:P,event:A}){!E&&T&&({structure:E}=at({drawDefinition:I,structureId:T}));let U=yt({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structure:E,inContext:y,context:P,event:A}),N=[],D=[],M=[],R=[],b=[];if(U.error)return U;let{matchUps:O}=U,{assignedPositions:v}=Ie({structure:E}),x=v?.filter(w=>w.participantId).map(w=>w.drawPosition),F;return O.filter(w=>{let L=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===Wt;return!(w.matchUpType!==Wt&&L)}).forEach(w=>{if(w.matchUpStatus===vr){N.push(w);return}w.matchUpType===Wt&&(F=!0);let L=!!w.collectionId,k=L&&w.sides?.every($=>$.participantId),G=!L&&w.drawPositions?.filter(Boolean).length===2,H=!L&&w.drawPositions?.every($=>x?.includes($)),K=v?.filter($=>$.bye).map($=>$.drawPosition),Y=!L&&w.drawPositions?.find($=>K?.includes($)),V=zh.includes(w.matchUpStatus)&&(k||G&&(!t||H));return Y?b.push(w):Ts({matchUp:w})?D.push(w):V?M.push(w):R.push(w)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:E}}function sO({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Pr};let{links:n}=Js({drawDefinition:t,structureId:r}),o=n.source.reduce((s,a)=>!a.source.roundNumber||a.source.roundNumber===e?s.concat(a):s,[]),i=n.target.reduce((s,a)=>!a.target.roundNumber||a.target.roundNumber===e?s.concat(a):s,[]);return{links:{source:o,target:i}}}function DS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||ke(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Xn,so].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:B},stack:"getTargetLink",context:o}):o}function Js({drawDefinition:t,structureId:e,roundNumber:r}){return t?e?{links:(t.links||[]).filter(Boolean).reduce((i,s)=>(s.source?.structureId===e&&(!r||s.source.roundNumber===r)&&(i.source=i.source.concat(s)),s.target?.structureId===e&&(!r||s.target.roundNumber===r)&&(i.target=i.target.concat(s)),i),{source:[],target:[]})}:{error:Pr}:{error:Z}}function aO({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 NS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:$l};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({drawDefinition:n,structureId:i}),{positionAssignments:m}=Ct({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=tt(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let D=u.offset+(r-1)*u.interleave,M=r+D;h=Math.ceil(M/2),S=1-M%2}let T=g,y=g[h-1],E=pS({roundPositionsCount:g.length,groupedOrder:a}),P=E?.length||1;if(P<=g.length){let D=f/P,M=Ae(g,D);s===yi&&M.forEach(R=>R.reverse()),T=E?.length&&E?.map(R=>M[R-1]).flat()||T}s===Nn?y=T[h-1]:s===yi?((!E?.length||P>g.length)&&(h=l.length+1-h),y=T[h-1]):s===Sp&&Dr()&&console.log(pp,{feedProfile:s});let A=y&&l.reduce((D,M)=>M.roundPosition===y?M:D,void 0),U;A?.feedRound?(S=0,U=Math.min(...(A.drawPositions||[]).filter(Boolean))):U=A?.drawPositions?.length===2&&A?.drawPositions[S];let N=m?.find(({drawPosition:D})=>D===U);if(N){let{extension:D}=mt({element:N,name:Zm});if(D?.value)return{disabledDrawPosition:U}}return{matchUp:A,targetDrawPosition:U,matchUpDrawPositionIndex:S}}function ur({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===zi?$k({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Kk({matchUp:i})}function $k({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=sO({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=DS({source:c,linkType:Xn}),p=DS({linkCondition:kn,linkType:so,source:c}),m=DS({source:c,linkType:so}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,E,P,A,U,N;if(e&&(i||s)&&(P=i&&l!==fn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==fn&&t.find(({matchUpId:R})=>R===s),P||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:P}};let{roundPosition:D}=o;N=N||t.filter(R=>R.structureId===n.structureId);let M=N.reduce((R,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?R+1:R,0);return m&&!T&&f!==fn&&({matchUpDrawPositionIndex:E,targetDrawPosition:y,matchUp:T}=NS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==fn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=NS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!P&&l!==fn&&({matchUpDrawPositionIndex:U,targetDrawPosition:A,matchUp:P}=NS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),P||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:P}=aO({structureMatchUps:N,matchUp:o})),nt({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:U,loserMatchUpDrawPositionIndex:E,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:A,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:P,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function Kk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function cO({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=at({drawDefinition:t,structureId:i});if(a?.finishingPosition===Ei){let{roundNumber:c}=n,u=c&&dt(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Ke({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(le).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=ur({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=cP({upcomingMatchUp:u}),d=cP({upcomingMatchUp:p});if(n.matchUpStatus!=="BYE"&&p?.matchUpStatus==="BYE"){let{matchUp:f}=uO({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&cP({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&Yt(m.schedule.scheduledTime)<Yt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&Yt(d.schedule.scheduledTime)<Yt(l)&&(r[d.matchUpId]=n.matchUpId,d.schedule.scheduleConflict=n.matchUpId)),Object.assign(n,{winnerTo:m,loserTo:d}),n.drawPositions?.filter(Boolean).length){let g=c.targetLinks?.loserTargetLink?.linkCondition===kn,I=zk(n);if(I.length){let h=Hf(u?.sides),S=Hf(p?.sides),y=I.find(({participantId:A})=>h.includes(A))?[]:I,P=I.find(({participantId:A})=>S.includes(A))?[]:I;p&&g&&P.length<2&&P.push({bye:!0,tbd:!0}),y?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:A})=>A===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(y)),P?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:A})=>A===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(P))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function zk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function uO({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Qt)return{matchUp:t};if(o==="BYE"){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=ur({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},uO({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function cP(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 ie(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=Zs(t);if(r.error)return _({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 Zs(t){if(!t?.drawDefinition)return{error:Z};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:y,context:E,event:P}=t,A=[],U=[],N=[],D=[],M=[];h&&!r&&(r=Zn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:P}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=Eu({participants:e,participantsProfile:a})));let{structures:b}=hn({drawDefinition:S});if(!b)return{error:_t};n||(n=Pe({drawDefinition:S}));let O=S&&mS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:w=[],pendingMatchUps:L=[],upcomingMatchUps:k=[],completedMatchUps:G=[],abandonedMatchUps:H=[]}=Mu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||T||d,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:O,matchUpsMap:n,structure:F,context:E,event:P});A=A.concat(...H),U=U.concat(...G),N=N.concat(...k),D=D.concat(...L),M=M.concat(...w)});let v=F=>(!l&&!T&&!d||(l&&(F=_i({matchUps:F,...l})),d&&(F=_i({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:v(A),completedMatchUps:v(U),upcomingMatchUps:v(N),pendingMatchUps:v(D),byeMatchUps:v(M),matchUpsMap:n,...C,groupInfo:R};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:w,completed:L,upcoming:k,pending:G,bye:H}=F,K=[].concat(...w&&A||[],...L&&U||[],...k&&N||[],...G&&D||[],...H&&M||[]);cO({inContextDrawMatchUps:K,drawDefinition:S})}return x}function to(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:h,event:S}=t;if(!S)return{error:Ot};let{eventId:T,eventName:y,endDate:E,eventType:P,category:A,gender:U,matchUpFormat:N}=S??{},D={...h,...nt({indoorOutDoor:S.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:S.surfaceCategory??p?.surfaceCategory,endDate:S.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:N,eventName:y,eventType:P,category:A,eventId:T,gender:U})};E&&(D.endDate=E),f&&!r&&(r=Zn({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:S}));let M;if(!e?.length&&!n&&p){let v=Xo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=v.participantMap,e=v.participants??[],M=v.groupInfo}let R=S.drawDefinitions??[],b=Ra({tournamentRecord:p,event:S}).scheduleTiming;return{matchUps:R.flatMap(v=>{let{matchUps:x}=ie({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:D,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:v,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:b,nextMatchUps:g,inContext:I,event:S});return x??[]}),groupInfo:M}}function ye(t){let e=et(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:q};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:m,contextProfile:d,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,h=t.tournamentId??u.tournamentId,S=u?.events??[];n||({participants:n,participantMap:r}=Xo({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:d,inContext:p}));let{appliedPolicies:T}=Tt({tournamentRecord:u}),y={...I,tournamentId:h,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},E=Zn({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:S.flatMap(A=>(y.eventDrawsCount=A.drawDefinitions?.length??0,to({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:m,contextContent:E,contextFilters:f,contextProfile:d,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:A}).matchUps??[])).concat(...u.matchUps??[])}}function Mn({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:xt};let m=Object.keys(n).map(d=>{let l=n[d];return ye({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...C,matchUps:m}}function xi(t,e){return Qk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Qk(t,e){return($s[t?.stage]||0)-($s[e?.stage]||0)}function nr(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:y,endDate:E,eventType:P,category:A,gender:U,matchUpFormat:N}=S??{},D={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:N,eventType:P,eventName:y,category:A,eventId:T,endDate:E,gender:U},M;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:M}=Xo({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=Zn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...ie({context:D,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:d,contextProfile:l,matchUpFilters:m,participantMap:r,nextMatchUps:g,inContext:I,event:S}),groupInfo:M}}function ys({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=J(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}var uP=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:ys({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:ys({element:e,accessor:r})?.value}))||(typeof t=="string"&&ys({element:e,accessor:t}))?.value,Hr=uP;function ba({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Br(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Ke({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,m=p&&c?.[n-p]?.matchUpsCount,d=c&&Object.values(c).map(Hr("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},y=d?.slice(I-1).reduce((R,b)=>R+(b||0),0),E=a&&I!==1,P=1+t+(E?r??0:0),A=1,U=tt(P,s?P+S*2:y+P+A),N=y+A-S,D=l(U.slice(N)),M=l(U.slice(0,N),!0);return T.finishingPositionRange={loser:D,winner:M},{[I]:T}})),g=Dr({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 rs({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=ie({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];ba({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=ur({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=Vo({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function an(t){let e=Rr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:no};if(!Array.isArray(n))return{error:cn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:ps};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(E=>(E.drawDefinitions||[]).map(P=>P.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===Fn),g=r;if(f.length){g=Mn({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,E)=>{let P=E.source?.structureId,A=E.target?.structureId;return P&&A&&(p[A]=P),P&&!y.includes(P)&&y.push(P),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let E=y.containerStructureId||y.structureId;T.includes(E)&&c[E].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(P=>{u[y].matchUpIds.push(P)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(P=>u[y].participantIds.push(P))},S=T=>{let y=Object.keys(c).length;for(let E of T||[]){let{matchUpId:P,winnerMatchUpId:A,loserMatchUpId:U}=E;if(!a.length||a.includes(P)){if(I(P),o){let{individualParticipantIds:M}=Su(E);u[P].participantIds=M}A&&(I(A),h(P,A),m[A].push(P)),U&&(I(U),h(P,U),m[U].push(P)),u[P].sources.push(m[P]);let N=m[P].map(M=>u[M].sources[0]).flat(),D=m[P].map(M=>u[M].sources[1]).flat();if(u[P].sources.push(N,D),y){let M=E.containerStructureId||E.structureId,R=p[M];if(c[R])for(let b of c[R])I(b),h(b,P),m[b].push(P)}}}};if(s)rs({drawDefinition:s}),g?.length||(g=nr({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=Mn({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:E=[]})=>E.map(({drawId:P})=>P))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(P=>P.drawId===T).sort(xi);if(!y?.find(({roundPosition:P})=>!P)){let P=y?.find(({tournamentId:U})=>U),{drawDefinition:A}=ze({tournamentRecord:e[P?.tournamentId],drawId:T});A&&rs({drawDefinition:A})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function he(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 Oa({matchUpStatus:t}){return $h.includes(t)}function pO({matchUpStatus:t}){return id.includes(t)}function gg({matchUpStatus:t}){return Kh.includes(t)}function Ig({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(Ig)?.length;return he({score:o})||s||e&&i||t&&pO({matchUpStatus:t})&&![Gt,Bt,Hn].includes(t)}function va(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=fs({drawDefinition:e}),a=n?s[n]||[]:[],c={isCollectionMatchUp:!1};if(!i){let A=at({drawDefinition:e,structureId:n});if(A.error)return A;i=r?A.containingStructure??A.structure:A.structure}if(cr({structure:i}))return{structure:i,isAdHoc:!0,error:Ls};let{matchUps:u}=ie({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(A=>A.structureId===n||a.includes(A.structureId)),{matchUpDependencies:m}=an({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let A of u??[]){if(A.structureId===n||a.includes(A.structureId)){l.push(...A.drawPositions??[]);let U=A.roundNumber;for(let N of(A.drawPositions??[]).filter(Boolean))(!f[N]||U&&f[N]>U)&&(f[N]=U)}Ig(A)&&(g.push(A),d.push(A.matchUpId,...m?.[A?.matchUpId]?.matchUpIds||[]))}let I=pt(l.filter(Boolean)).sort(le),h=pt(d),S=pt(p?.map(({matchUpId:A,drawPositions:U})=>h.includes(A)?U:[]).flat().filter(Boolean)).sort(le),{positionAssignments:T}=Ct({drawDefinition:e,structure:i}),y=T?.filter(A=>A.bye).map(A=>A.drawPosition),E=T?.filter(A=>A.qualifier).map(A=>A.drawPosition),P=I?.filter(A=>!S.includes(A))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:E,inactiveDrawPositions:P,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function Es({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(le)[0]}}var _a={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 MS=[];function Tn(t,e){kt(t)&&(t={method:t}),(e||Dr())&&MS.push(t)}function Xk(t){let e=MS.slice();return t&&(MS.length=0),e}function mO(t){let r=Xk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(_a).includes(o)?_a[o]:_a.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&_a[i[d]]?_a[i[d]]:_a.brightwhite;return`${_a.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
2
2
|
`:"",c,s,m,_a.white,p,_a.reset,`
|
|
3
3
|
`].join("")});r?.length&&console.log(...r)}function dO(){MS.length=0}function pr(t){return[Gt,Bt,Me].includes(t)}function Wr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,loserMatchUp:i,matchUpsMap:s,structureId:a,structure:c,event:u}){if(!n)return{error:Z};if(c||({structure:c}=at({drawDefinition:n,structureId:a})),!c)return{error:_t};a||({structureId:a}=c);let p="assignDrawPositionBye";Tn({method:p,color:"cyan",drawPosition:o}),s??=Pe({drawDefinition:n});let{positionAssignments:m}=Ct({structure:c}),{activeDrawPositions:d}=va({drawDefinition:n,structureId:a});if(m?.find(O=>O.drawPosition===o)?.bye)return{...C};let f=!!(i&&s.drawMatchUps.find(O=>O.loserMatchUpId===i?.matchUpId&&pr(O.matchUpStatus)));if(d?.includes(o)&&!f)return{error:rp};let I=m?.find(O=>O.drawPosition===o);if(!I)return{error:Ls};let{filled:h,containsBye:S,assignedParticipantId:T}=Jk(I);if(S)return{...C};if(h&&!S&&!f)return _({result:{error:Xa},stack:p});let y=Tt({tournamentRecord:r,drawDefinition:n,event:u}).appliedPolicies??{},E=ie({inContext:!0,drawDefinition:n,matchUpsMap:s}).matchUps??[],P={isCollectionMatchUp:!1},{matchUps:A}=yt({provisionalPositioning:t,drawDefinition:n,matchUpFilters:P,matchUpsMap:s,structure:c});if(m?.forEach(O=>{O.drawPosition===o&&(O.bye=!0,f&&(O.participantId=void 0))}),c.structureType===Ve)return Zk({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:A}),ko({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),lO({assignedParticipantId:T,isPositionAction:e,appliedPolicies:y,drawDefinition:n,drawPosition:o,structureId:a,stack:p});let{roundProfile:U,roundMatchUps:N}=Ke({matchUps:A}),M=(U&&Object.keys(U).map(O=>parseInt(O)).reverse())?.find(O=>U?.[O].drawPositions?.includes(o)),R=M?N?.[M].find(({drawPositions:O})=>O?.includes(o)):void 0;R&&fO({tournamentRecord:r,drawDefinition:n,matchUp:R,event:u});let b=R?.drawPositions?.find(O=>O!==o);if(R&&b){let O=RS({sourceDrawPositions:R.drawPositions,matchUpId:R.matchUpId,inContextDrawMatchUps:E,drawPositionToAdvance:b,tournamentRecord:r,drawDefinition:n,matchUpsMap:s});if(O.error)return O}return ko({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),lO({assignedParticipantId:T,isPositionAction:e,appliedPolicies:y,drawDefinition:n,drawPosition:o,structureId:a,stack:p})}function lO({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&hu({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),_({result:{...C},stack:s})}function Jk(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function fO({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:"BYE",score:void 0,winningSide:void 0}),gt({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function Zk({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&fO({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function RS({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Tn({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(E=>E.matchUpId===s),m=e.find(E=>E.matchUpId===s)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=Ct({structure:d}),f=l?.filter(E=>E.bye).map(E=>E.drawPosition),g=u?.drawPositions?.find(E=>E!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserTargetDrawPosition:y}}=ur({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s});if(T&&T.structureId===d?.structureId&&tG({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),S&&I&&S.structureId!==d?.structureId){let{roundNumber:E}=S;if(E===1){let P=Wr({structureId:h.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(P.error)return P}else gO({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...C}}function tG({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(w=>w.matchUpId===i.matchUpId),m=e.find(w=>w.matchUpId===i.matchUpId)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=Ct({structure:d}),g=l?.find(({drawPosition:w})=>w===t)?.bye,I=u.drawPositions?.filter(Boolean),h=l?.filter(w=>I?.includes(w.drawPosition)),S=l?.find(({drawPosition:w})=>w===t),T=r?.find(w=>w!==t),E=(T&&h?.find(({drawPosition:w})=>w===T))?.bye,P=g&&E;if(P&&console.log({isByeAdvancedBye:P}),I?.length>1&&g&&!E)return _({result:{error:Xa},stack:c});let A=I?.find(w=>w!==t),U=P,N=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),D=N.map(w=>!w&&!U||w===t?(U=!0,t):w).sort(le);if(!U)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),_({result:{error:Xa},stack:c});let M=l?.find(({drawPosition:w})=>w===A)?.bye,R=l?.find(({drawPosition:w})=>w===t)?.bye;Object.assign(u,{matchUpStatus:R||M?"BYE":Qt,score:void 0,winningSide:void 0,drawPositions:D});let O=u.drawPositions.find(w=>!N.includes(w));Tn({method:c,color:"brightyellow",changedDrawPosition:O,pairedDrawPositionIsBye:M,drawPositionIsBye:R}),gt({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:v},targetMatchUps:{loserMatchUp:x,loserTargetDrawPosition:F}}=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(M||R){let w=M?t:A;if(w)RS({drawPositionToAdvance:w,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(R&&v&&x)if(x.feedRound)gO({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:v,drawDefinition:o,loserMatchUp:x,matchUpsMap:s});else{let k=1-i.roundPosition%2,G=x.drawPositions[k],H=Wr({structureId:v.target.structureId,drawPosition:G,tournamentRecord:n,drawDefinition:o,event:a});if(H.error)return H}}}function gO({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Tn({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=Es({drawPosition:t,matchUps:p});if(m===a){let d=Wr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function CS({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=yt({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":Qt}),gt({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function Uc(t){let{inContextDrawMatchUps:e,participantId:r,drawPosition:n}=t,{tournamentRecord:o,drawDefinition:i,structureId:s,matchUpsMap:a,event:c}=t,{structure:u}=at({drawDefinition:i,structureId:s}),m=(Ie({drawDefinition:i,structure:u}).positionAssignments||[]).find(g=>r&&g.participantId===r||n&&g.drawPosition===n);if(m&&r&&!n&&(n=m?.drawPosition),!n)return{error:Fs};r||(r=m?.participantId);let{activeDrawPositions:d}=va({drawDefinition:i,structureId:s});return d.includes(n)?{error:rp}:(e||({matchUps:e}=ie({inContext:!0,drawDefinition:i,matchUpsMap:a})),pP({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(ko({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...C,participantId:r}):{error:jE})}function pP({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:i,event:s}){let{structure:a}=at({drawDefinition:r,structureId:i});if(!a)return{error:_t};let c=Ie({drawDefinition:r,structure:a}).positionAssignments||[],u=c.some(T=>{if(T.drawPosition===n)return delete T.participantId,delete T.qualifier,delete T.bye,!0});if(a.structureType===Ve)return CS({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...C};let p={isCollectionMatchUp:!1},{matchUps:m}=yt({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=Ke({matchUps:m}),g=(d&&Object.keys(d))?.map(T=>dt(T)),I=n,S=g?.map(T=>{let E=d?.[T]?.pairedDrawPositions?.find(O=>O.includes(I)),P=E?.find(O=>O!==I),A=c.find(O=>O.drawPosition===P),U=d?.[T+1],N=A?.bye,D=U?.pairedDrawPositions?.find(O=>O.includes(P)),M=N&&D&&U&&U.drawPositions?.includes(P),b=E&&{pairedDrawPositionByeAdvancedPair:!M&&D,pairedDrawPosition:P,targetDrawPosition:I,relevantPair:E,roundNumber:T};return M&&(I=P),b}).filter(T=>T?.targetDrawPosition)?.reduce((T,y)=>{let{roundNumber:E,relevantPair:P,targetDrawPosition:A,pairedDrawPosition:U,pairedDrawPositionByeAdvancedPair:N}=y,D={roundNumber:E,targetDrawPosition:A,relevantPair:P},M=N&&{roundNumber:E+1,targetDrawPosition:U,relevantPair:N,subsequentRoundRemoval:!0},R=[D,M].filter(Boolean);return T.concat(...R)},[]);return S?.forEach(({roundNumber:T,targetDrawPosition:y,relevantPair:E})=>{let P=l?.[T].find(A=>ke(A.drawPositions?.filter(Boolean),E.filter(Boolean)));P&&(eG({inContextDrawMatchUps:t,targetDrawPosition:y,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),IO({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:P,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function eG({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,roundNumber:i,structureId:s}){let{structure:a}=at({drawDefinition:n,structureId:s});if(!a)return{error:_t};if(a.structureType===Ve)return;o=o||Pe({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=Es({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=Ct({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>IO({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...C}}function IO({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u="removeDrawPosition",p=o.drawPositions?.slice(),m=o.matchUpStatus,d=o.winningSide;s=s??Pe({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=Es({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let D=(o.drawPositions??[]).map(M=>M===i?void 0:M);o.drawPositions=D}if(o.matchUpType===Wt){let R=(t?.find(b=>b.matchUpId===o.matchUpId)?.sides??[]).reduce((b,O,v)=>O.drawPosition===i?v:b,void 0);R!==void 0&&o.sides?.[R]?.lineUp&&(delete o.sides?.[R].lineUp,gt({tournamentId:r?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:o,drawDefinition:n}))}let I=ur({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,P=e.filter(({drawPosition:D})=>o.drawPositions?.includes(D)).filter(D=>D.bye).length,A=P&&"BYE"||o.matchUpStatus&&pr(o.matchUpStatus)&&o.matcHUpStatus||Qt;o.matchUpStatus=A,o.matchUpStatus&&pr(o.matchUpStatus)&&(o.winningSide=void 0);let U=p?.find(D=>!o.drawPositions?.includes(D));if(p?.includes(i)&&m===o.matchUpStatus&&d===o.winningSide||(U&&Tn({method:u,color:"brightyellow",removedDrawPosition:U}),gt({tournamentId:r?.tournamentId,context:`${u}-${i}`,eventId:c?.eventId,matchUp:o,drawDefinition:n})),S&&S.structureId!==I.matchUp.structureId&&!P){let{drawPositions:D,roundNumber:M}=S;if(M===1){let R=D[y];pP({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let R=Math.min(...D.filter(Boolean)),b=rG({loserMatchUpDrawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:S,matchUpsMap:s,event:c});if(b.error)return _({result:b,stack:u});let v=(s?.mappedMatchUps||{})[S.structureId].matchUps,{initialRoundNumber:x}=Es({drawPosition:R,matchUps:v});x===1&&(Tn({method:u,color:"brightyellow",loserMatchUpDrawPosition:R}),pP({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,fn),{...C}}function rG({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=at({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=Ct({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=Uc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...C}}function wi({drawDefinition:t,stages:e}){if(!t)return{error:Z};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=pt(r.map(o=>{let{positionAssignments:i}=Ct({structure:o});return i?i.map(St):[]}).flat().filter(Boolean));return{...C,assignedParticipantIds:n}}function eo(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||rt}${s||""}`;return n[a]||(n[a]=[]),n[a].push(o),n},{}),r=n=>isNaN(n)?1/0:n;return Object.keys(e).map(n=>e[n].sort((o,i)=>r(o.entryPosition)-r(i.entryPosition)).map((o,i)=>{let s=i+1;return{...o,entryPosition:s}})).flat()}function ta(t){return[Ci,Vr].includes(t)}function Ad({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:r,drawDefinition:n,participantIds:o,entryStatus:i,entryStage:s,extension:a,eventSync:c,drawId:u,stage:p,event:m}){if(!o||!Array.isArray(o))return{error:ln,method:"modifyEntriesStatus",participantIds:o};if(!n&&!m)return{error:Ot};if(i&&!ZU.includes(i))return{error:sf};if(s&&!ru.includes(s))return{error:Vi};let d="modifyEntriesStatus",l=[];if(!i&&!a)return _({result:{error:st},info:"Missing entryStatus",stack:d});if(a&&!Bn({extension:a,requiredAttributes:["name"]}))return _({result:{error:B},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(D=>{let M=wi({stages:p&&[p],drawDefinition:D}).assignedParticipantIds??[];f.push(...M)});let g=r?.participants??[];if(!o.every(D=>{let M=zo({tournamentParticipants:g,participantId:D})?.participantType;return!(M&&[ft,Ar].includes(M)&&ta(i))&&!(i&&m?.eventType&&M===Et&&[Kr,Or].includes(m.eventType)&&[on,...cg].includes(i))}))return{error:sf};let h=m&&Ht({event:m}).flightProfile,S=h?.flights?.find(D=>D.drawId===u),T=D=>{let M=(D||[]).filter(O=>!p||!O.entryStage||p===O.entryStage).filter(({participantId:O})=>o.includes(O)),R=O=>i&&f.includes(O.participantId)&&!(cg.includes(O.entryStatus)&&cg.includes(i));return M.every(O=>R(O)&&!e?!1:(i&&(O.entryStatus=i,delete O.entryPosition),s&&(O.entryStage=s,delete O.entryPosition),a&&(a.value?At({element:O,extension:a}):Ir({element:O,name:a.name})),!0))?{...C}:{error:Gs}},y=({flight:D,drawDefinition:M})=>{m&&(m.entries=eo({entries:m.entries??[]})),D&&(D.drawEntries=eo({entries:D.drawEntries})),M&&(M.entries=eo({entries:M.entries}))},E=D=>{let{flight:M,drawDefinition:R}=D,b="updateDrawEntries";if(M){let O=T(M.drawEntries);if(O.error)return _({result:O,stack:b})}if(R){let O=T(R.entries);if(O.error)return _({result:O,stack:b});l.includes(R.drawId)||l.push(R.drawId)}return{...C}},P=m?.entries?.find(({entryPosition:D})=>D)??(S?.drawEntries?.find(({entryPosition:D})=>D)||n?.entries?.find(({entryPosition:D})=>D));if(t&&!P&&y({flight:S,drawDefinition:n}),S||n){let D=E({flight:S,drawDefinition:n});if(D.error)return _({result:D,stack:d})}let A=m?.drawDefinitions?.map(({drawId:D})=>D)??[],U=h?.flights?.filter(D=>!A.includes(D.drawId))||[];for(let D of U){let M=D&&E({flight:D});if(M?.error)return _({result:M,stack:d})}let N=h?.flights?.length===1&&(m?.drawDefinitions?.length??0)<=h?.flights?.length;if(!S&&!n&&i&&JU.includes(i))return{error:MA};if(!S&&!n||i===mo||c&&N){let D=T(m?.entries);if(D?.error)return _({result:D,stack:d});let M;if(i===mo&&(h?.flights?.every(R=>{let b=T(R.drawEntries);return b.error?(M=b.error,!1):(R.drawEntries=R.drawEntries.filter(({participantId:O})=>!o.includes(O)),!0)}),m?.drawDefinitions?.every(R=>{let b=T(R.entries);return b.error?(M=b.error,!1):(R.entries=R.entries?.filter(({participantId:O})=>!o.includes(O)),!0)})),M)return _({result:{error:M},stack:d})}t&&y({flight:S,drawDefinition:n});for(let D of m?.drawDefinitions??[])l.length&&!l.includes(D.drawId)||bt({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:D});return{...C}}function Po({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Wi};if(!ht(e))return{error:B};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[Pi,o,i,s].join("."),u=r.timeItems.filter(p=>p?.itemType===a).filter(p=>!t||p?.itemDate).sort((p,m)=>(p.createdAt?new Date(p.createdAt).getTime():0)-(m.createdAt?new Date(m.createdAt).getTime():0)).pop();if(u){let[p,m,d,l]=u.itemType?.split(".")??[];if(p!==Pi)return{error:rc};let g=(n&&ys({element:u.itemValue,accessor:n}))?.value||u.itemValue,I={eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...C,scaleItem:I}}}return{...C,scaleItem:void 0}}function hO({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[Pi,Ao,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems||[]).filter(({itemType:m})=>m.split(".")[1]===Ao).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=jt(Object.keys(a),c);if(!!(!e||!Object.keys(a).length&&!t?.drawIds?.length||u.length)&&u.length){if(t?.stageSeedingScaleNames){let m=Object.keys(t.stageSeedingScaleNames).map(l=>{let f=s(t.stageSeedingScaleNames[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else if(u){let m=u.map(d=>a[d]);i.seedValue=m.pop()}}else if(!e&&typeof r=="object"){let m=Object.keys(r).map(l=>{let f=s(r[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else{let{categoryName:m,ageCategoryCode:d}=o.category||{},l=[d,o.eventId,m].filter(Boolean),f;for(let g of l){let I={eventType:o.eventType,scaleType:Ao,scaleName:g},h=Po({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 SO({convertExtensions:t,seedAssignments:e,participant:r,withSeeding:n,seedValue:o,eventId:i,ranking:s,entry:a}){let{entryStatus:c,entryStage:u,entryPosition:p,extensions:m}=a,d=m?.length&&t?Object.assign({},...Cf(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=nt(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function Ru(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let{tournamentRecord:r,status:n=Cr}=t,o=`${Ho}.${Wo}`;return J(cd({tournamentRecord:r,itemType:o})?.timeItem?.itemValue?.[n],!1,!0)}function TO(t){let{tournamentId:e}=t??{};return!!e}function Jr({event:t,status:e=Cr}){let r=`${Ho}.${Wo}`;return Au({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function Ud({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function As(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!TO(e))return{error:B};if(o&&!a)return{error:qr};if(Array.isArray(n)&&n?.length){let m={};for(let d of n){if(!kt(d))return{error:B};let l=ze({tournamentRecord:e,eventId:d})?.event;if(!l)return{error:qr};let f=mP({event:l});m[d]=f}return{...C,publishState:m}}if(a){let m=mP({event:a}),d={};if(s)return r?{publishState:{status:{published:!!m.status.publishedDrawIds?.includes(s),drawDetail:m.status.drawDetails?.[s]},...C}}:{error:br};if(Array.isArray(i)&&i?.length){let l=a.drawDefinitions?.map(gu)??[];for(let f of i){if(!kt(f))return{error:B};if(!l.includes(f))return{error:br};d[f]={status:{published:!!m.status.publishedDrawIds.includes(f),drawDetail:m.status.drawDetails?.[f]}}}}else d=m;return{...C,publishState:d}}let c=[],u=!1,p={};for(let m of e?.events??[]){let d=mP({event:m});p[m.eventId]=d,d.status.published&&(c.push(m.eventId),u=!0);for(let{drawId:l}of m.drawDefinitions??[]){let f=d.status?.publishedDrawIds?.includes(l);f&&(p[l]={status:{published:f}})}}if(e){let m=Ru({tournamentRecord:e});p.tournament=m??{},(m?.orderOfPlay?.published||m?.participants?.published)&&(u=!0),p.tournament.status={published:u,publishedEventIds:c}}return{...C,publishState:p}}function mP({event:t}){let e=Jr({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(gu)||[])n[a]||(n[a]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(a=>Ud({drawDetails:n,drawId:a})),i=o?.length?o:e.drawIds??[];if(i?.length&&!o?.length)for(let a of i)n[a]={publishingDetail:{published:!0}};let s=i?.length>0;return{status:{publishedDrawIds:i,publishedSeeding:r,drawDetails:n,published:s}}}function bS(t){let{participantMap:e,participantId:r,matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,schedule:p,drawId:m,score:d}=t;if(!p||!Object.keys(p).length)return;n==="BYE"||e[r].scheduleItems.push({...p,scheduledDate:Ut(p?.scheduledDate),scheduledTime:zt(p?.scheduledTime),checkScoreHasValue:he({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function yO({finishingPositionRange:t={},participantMap:e,finishingRound:r,participantWon:n,matchUpStatus:o,participantId:i,stageSequence:s,roundNumber:a,structureId:c,matchUpId:u,drawId:p,stage:m}){let d=e[i],l=S=>Math.abs(S[0]-S[1]);d.structureParticipation[c]||(d.structureParticipation[c]={rankingStage:m,walkoverWinCount:0,defaultWinCount:0,stageSequence:s,winCount:0,structureId:c,drawId:p});let f=d.structureParticipation[c],{winner:g,loser:I}=t,h=n?g:I;n&&(f.winCount+=1,o===Bt&&(f.walkoverWinCount+=1),o===Gt&&(f.defaultWinCount+=1)),h&&(!f.finishingPositionRange||l(h)<l(f.finishingPositionRange))&&(f.finishingPositionRange=h),r&&((!f.finishingRound||r<f.finishingRound)&&(f.finishingMatchUpId=u,f.finishingRound=r,f.roundNumber=a),r===1&&(f.participantWon=n))}function dP(t){let{withScheduleItems:e,scheduleAnalysis:r,withTeamMatchUps:n,participantMap:o,withOpponents:i,withMatchUps:s,withEvents:a,withDraws:c,finishingPositionRange:u,finishingRound:p,matchUpStatus:m,stageSequence:d,roundNumber:l,structureId:f,score:g,stage:I,withRankingProfile:h,tieWinningSide:S,roundPosition:T,matchUpTieId:y,matchUpSides:E,collectionId:P,matchUpType:A,winningSide:U,matchUpId:N,schedule:D,eventId:M,drawId:R,sides:b}=t,O=i&&b?.length===2&&Object.assign({},...b.map(({sideNumber:v},x)=>{let F=b[1-x].participantId;return v&&{[v]:F}}).filter(Boolean));for(let v of b){let{participantId:x,sideNumber:F,bye:w}=v;if(w)continue;let L=U===F,k=K=>{let Y=o[K]?.participant,j=Y?.participantType,V=[{participantId:K,participantType:j}];if(j!==Ar)for(let $ of Y?.individualParticipantIds||[]){let X=o[$]?.participant;V.push({participantType:X?.participantType,participantId:$})}return V},G=(K,Y)=>{if(s){if(o[K].matchUps[N]={participantWon:L,matchUpType:A,structureId:f,sideNumber:F,matchUpId:N,eventId:M,drawId:R,stage:I},i){let j=k(Y);o[K].matchUps[N].opponentParticipantInfo=j}P&&(o[K].matchUps[N].collectionId=P)}i&&Y&&(o[K].opponents[Y]={participantId:Y,matchUpId:N,eventId:M,drawId:R}),h&&yO({finishingPositionRange:u,participantMap:o,participantWon:L,finishingRound:p,matchUpStatus:m,participantId:K,stageSequence:d,roundNumber:l,structureId:f,matchUpId:N,drawId:R,stage:I}),(r||e)&&bS({participantMap:o,participantId:K,matchUpStatus:m,roundPosition:T,matchUpType:A,roundNumber:l,structureId:f,matchUpId:N,schedule:D,drawId:R,score:g})},H=({participant:K,partnerParticipantId:Y})=>{let j=(V,$)=>{V&&(V.partnerParticipantIds||(V.partnerParticipantIds=[]),V.partnerParticipantIds.includes($)||V.partnerParticipantIds.push($))};c&&j(K?.draws?.[R],Y),a&&j(K?.events?.[M],Y),s&&j(K?.matchUps?.[N],Y)};if(x&&o[x]){let K=O?.[F];G(x,K);let Y=o[x]?.participant.participantType===ft,j=o[x]?.participant.individualParticipantIds||[];if(y){if(n){let V=$=>o[$].matchUps[y]={participantWon:S===F,matchUpId:y,matchUpType:Wt,sideNumber:F};V(x),j.forEach(V)}if(c&&!o[x].draws[R]){let V=E.find(W=>W.sideNumber===F)?.participant?.participantId,$=o[V]?.draws?.[R]?.entryStatus,X=W=>o[W].draws[R]={entryStatus:$,eventId:M,drawId:R};X(x),j.forEach(X)}}if(Y&&(j.forEach(V=>o[V]&&G(V,K)),j.forEach((V,$)=>{let X=j[1-$],W=o[V];W&&H({participant:W,partnerParticipantId:X})}),a&&E)){let V=E.find($=>$.sideNumber===F)?.participant?.participantId;if(V){let $=o[V]?.events[M];$?(o[x].events[M]={...$},j.forEach(X=>o[X].events[M]={...$})):console.log("Missing teamEntry",{eventId:M,teamParticipantId:V})}}if(U){let V=$=>{L?(o[$].counters[A].wins+=1,o[$].counters.wins+=1,m===Bt&&(o[$].counters[A].walkoverWins+=1,o[$].counters.walkoverWins+=1),m===Gt&&(o[$].counters[A].defaultWins+=1,o[$].counters.defaultWins+=1)):(o[$].counters[A].losses+=1,o[$].counters.losses+=1,m===Bt&&(o[$].counters[A].walkovers+=1,o[$].counters.walkovers+=1),m===Gt&&(o[$].counters[A].defaults+=1,o[$].counters.defaults+=1))};V(x),j.forEach(V)}}}}function Cu(t,e){return(t||"").localeCompare(e||"")}function EO(t){let{participantFilters:e,convertExtensions:r,policyDefinitions:n,tournamentRecord:o,usePublishState:i,contextFilters:s,matchUpFilters:a,participantMap:c,contextProfile:u,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,withOpponents:I,withMatchUps:h,withSeeding:S,withEvents:T,withDraws:y}=t,E=e?.participantIds,P=v=>{let x=[v];return c[v]?.participant.individualParticipantIds?.forEach(F=>x.push(F)),x.some(F=>!E?.length||E.includes(F))?x:[]},A={withMatchUps:h||m,withEvents:T||m,withDraws:y||m,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,participantMap:c,withOpponents:I,withSeeding:S},U=[],N={},D=[],M={},R={},b={},O=({eventType:v,scaleNames:x,participantId:F})=>c[F]?.participant?.rankings?.[v]?.find(w=>x.includes(w.scaleName))?.scaleValue;for(let v of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(v.eventId))continue;let{drawDefinitions:x=[],extensions:F=[],eventType:w,eventName:L,category:k,entries:G,eventId:H,gender:K}=v,{flightProfile:Y}=Ht({event:v}),j=Y?.flights??[],V=As({event:v}).publishState;V&&(M[H]=V);let $=V?.status?.publishedSeeding;if(T||S||m){let W=r?Object.assign({},...Cf(F??[])):{};R[H]={...W,eventName:L,eventType:w,category:k,eventId:H,gender:K};let it=[k?.categoryName,k?.ageCategoryCode].filter(Boolean);for(let z of G){let{participantId:Q}=z;if(!Q||!c[Q])continue;let ut=O({eventType:w,scaleNames:it,participantId:Q}),ot,Dt;if(S){let qt=c[Q].participant;({seedAssignments:ot,seedValue:Dt}=hO({publishedSeeding:$,usePublishState:i,withSeeding:S,participant:qt,event:v}))}let Rt=qt=>{if(c[qt]?.events?.[H])return;let Se=c[qt];SO({convertExtensions:r,seedAssignments:ot,participant:Se,withSeeding:S,seedValue:Dt,eventId:H,ranking:ut,entry:z})};Rt(Q),(c[Q].participant.individualParticipantIds||[]).forEach(Rt)}}let X=M?.[H]?.publishedSeeding;if(y||m||S){let W=z=>z?Object.assign({},...z.map(({participantId:Q,seedValue:ut,seedNumber:ot})=>({[Q]:{seedValue:ut,seedNumber:ot}}))):void 0,it=pt([...x.map(gu),...j.map(gu)]);for(let z of it){let Q=x.find(pe=>pe.drawId===z),ut=[k?.categoryName,k?.ageCategoryCode].filter(Boolean),{structures:ot=[],drawOrder:Dt,drawName:Rt,drawType:De}=Q??{},qt=j?.find(pe=>pe.drawId===z),Se=Q?.entries||qt?.drawEntries,_r=qt?.flightNumber,dn=(Q?.structures||[]).sort((pe,me)=>Ni(pe,me)).map(({structureId:pe,structures:me})=>[pe,...(me||[]).map(({structureId:Sr})=>Sr)]).flat(1/0),hr,Xe,Zt,Pt,ce=0,ue=ot.filter(({stage:pe,stageSequence:me})=>pe===rt&&me===1||pe===ct).flatMap(pe=>{let{positionAssignments:me}=Ct({structure:pe}),{seedAssignments:Sr,stageSequence:jr,stage:Kt}=pe;return Kt===rt?(ce=me?.length??0,Zt=me,Pt=Sr):jr===1&&(hr=me,Xe=Sr),me}).map(({participantId:pe})=>pe).filter(Boolean),Fe=W(Pt),te=W(Xe),Je=Q?Se.filter(({participantId:pe})=>ue.includes(pe)):Se,$t=!i||X?.published&&(X?.drawIds?.length===0||X?.drawIds?.includes(z));for(let pe of Je){if(!c[pe.participantId])continue;let{entryStatus:me,entryStage:Sr,entryPosition:jr,participantId:Kt}=pe,Te=O({participantId:Kt,scaleNames:ut,eventType:w}),gr=Ee=>{if(!c[Ee]||c[Ee].draws?.[z])return;let Rn=S&&$t,ee=Rn?{}:void 0,Ur=Rn?Fe?.[Kt]?.seedValue||Fe?.[Kt]?.seedNumber:void 0,Cn=Ur?Fe?.[Kt]:void 0,An=Rn?te?.[Kt]?.seedValue||te?.[Kt]?.seedNumber:void 0,hi=An?te?.[Kt]:void 0;ee&&Ur&&(ee[rt]=Cn),ee&&An&&(ee[ct]=hi);let ga=Ur||An;ga&&(c[Ee].participant.seedings[w]||(c[Ee].participant.seedings[w]=[]),Cn&&c[Ee].participant.seedings[w].push({...Cn,scaleName:z}),hi&&c[Ee].participant.seedings[w].push({...hi,scaleName:z}),ee&&(c[Ee].events[H].seedAssignments||(c[Ee].events[H].seedAssignments={}),Object.keys(ee).forEach(ep=>c[Ee].events[H].seedAssignments[ep]=ee[ep]))),(y||m)&&(c[Ee].draws[z]=nt({seedAssignments:ee,entryPosition:jr,entryStatus:me,entryStage:Sr,seedValue:ga,eventId:H,ranking:Te,drawId:z},!1,!1,!0))};[Vr,Ci].includes(me)||(gr(Kt),(c[Kt].participant.individualParticipantIds||[])?.forEach(gr))}let ir=(Q?.structures??[]).reduce((pe,me)=>(pe.includes(me.stage)||pe.push(me.stage),pe),[]),fr=(Q?.links??[]).length;b[z]={qualifyingPositionAssignments:hr,qualifyingSeedAssignments:Xe,mainPositionAssignments:Zt,qualifyingSeedingMap:te,mainSeedAssignments:Pt,orderedStructureIds:dn,mainSeedingMap:Fe,flightNumber:_r,linksCount:fr,drawOrder:Dt,drawName:Rt,drawType:De,drawSize:ce,drawId:z,stages:ir}}}if(m||l||f||g||I||h||y){let W=!!l||p,it=to({afterRecoveryTimes:!!l,policyDefinitions:n,tournamentRecord:o,inContext:!0,participantMap:c,contextFilters:s,matchUpFilters:a,contextProfile:u,nextMatchUps:W,event:v})?.matchUps??[];for(let z of it){let{finishingPositionRange:Q,potentialParticipants:ut,tieMatchUps:ot=[],sides:Dt=[],winningSide:Rt,matchUpType:De,matchUpId:qt,eventId:Se,drawId:_r,collectionId:dn,stageSequence:hr,finishingRound:Xe,matchUpStatus:Zt,roundPosition:Pt,roundNumber:ce,structureId:ue,schedule:Fe,score:te,stage:Je}=z;N[qt]=z;let $t={finishingPositionRange:Q,finishingRound:Xe,stageSequence:hr,roundPosition:Pt,collectionId:dn,roundNumber:ce,structureId:ue,schedule:Fe,eventId:Se,drawId:_r,score:te,stage:Je};dP({...$t,...A,matchUpStatus:Zt,winningSide:Rt,matchUpType:De,matchUpId:qt,sides:Dt});for(let ir of ot){let{winningSide:fr,sides:pe=[],matchUpId:me,matchUpStatus:Sr,matchUpType:jr}=ir;dP({...$t,...A,winningSide:fr,tieWinningSide:Rt,matchUpTieId:qt,matchUpId:me,sides:pe,matchUpSides:Dt,matchUpStatus:Sr,matchUpType:jr})}Array.isArray(ut)&&(W||l||d)&&ut.flat().map(St).filter(Boolean)?.forEach(fr=>{P(fr)?.forEach(me=>{c[me]&&(c[me].potentialMatchUps[qt]=nt({tournamentId:o?.tournamentId,matchUpId:qt,eventId:Se,drawId:_r}))}),(l||d)&&bS({potential:!0,participantMap:c,participantId:fr,matchUpStatus:Zt,roundPosition:Pt,structureId:ue,matchUpType:De,roundNumber:ce,matchUpId:qt,schedule:Fe,drawId:_r,score:te})})}D.push(...it)}}if(g||m||l){let v=Object.values(c);for(let x of v){let{wins:F,losses:w,[Lt]:{wins:L,losses:k},[vt]:{wins:G,losses:H}}=x.counters,K=(Y,j,V)=>{let $=j+V,X=j,W=$&&X/$;x.statistics[Y]={denominator:$,numerator:X,statValue:W,statCode:Y}};if(g&&(K(pd,F,w),K(`${pd}.${Lt}`,L,k),K(`${pd}.${vt}`,G,H)),m){let Y=(j=[])=>Math.abs(j[0]-j[1]);for(let j of Object.keys(x.draws)){let{orderedStructureIds:V=[],flightNumber:$}=b[j]||{};if(x.structureParticipation&&V.length){let X,W=0,it=V.map(z=>{let Q=x.structureParticipation[z];if(!Q)return;X||(X=Q?.finishingPositionRange),Y(X)>Y(Q?.finishingPositionRange)&&(X=Q?.finishingPositionRange);let ut=Q.stage!==ct;return ut&&(W+=1),nt({...Q,participationOrder:ut?W:void 0,flightNumber:$})}).filter(Boolean);x.draws[j]&&(x.draws[j].finishingPositionRange=X,x.draws[j].structureParticipation=it)}}}if(l){let Y=ht(l)?l.scheduledMinutesDifference:0,j=x.scheduleItems||[],V=x.potentialMatchUps||{},$=j.reduce((W,it)=>{let{scheduledDate:z,scheduledTime:Q}=it;return W[z]||(W[z]=[]),Q&&W[z].push(it),W},{});Object.values($).forEach(W=>W.sort(ah));for(let W of j){let{typeChangeTimeAfterRecovery:it,timeAfterRecovery:z,scheduledDate:Q,scheduledTime:ut}=W,ot=$[Q],Dt=Yt(ut);for(let Rt of ot){if(Rt.matchUpId===W.matchUpId||pr(Rt.matchUpStatus)&&!Rt.checkScoreHasValue)continue;let Se=W.matchUpType!==Rt.matchUpType&&it||z,_r=W.drawId===Rt.drawId,dn=V[W.matchUpId]&&V[Rt.matchUpId],hr=Yt(Rt.scheduledTime),Xe=Math.abs(hr-Dt),Zt=hr>=Dt;if((Y&&!isNaN(Y)?Xe<=Y:Zt&&Yt(Rt.scheduledTime)<Yt(Se))&&!(dn&&_r)&&Zt){let ce=[W.matchUpId,Rt.matchUpId].sort(Cu).join("|");x.scheduleConflicts[ce]={priorScheduledMatchUpId:W.matchUpId,matchUpIdWithConflict:Rt.matchUpId}}}}let X=x.participant.participantId;Object.keys(x.scheduleConflicts).length&&U.push(X),c[X].scheduleConflicts=x.scheduleConflicts}}}return{participantIdsWithConflicts:U,eventsPublishStatuses:M,derivedEventInfo:R,derivedDrawInfo:b,mappedMatchUps:N,participantMap:c,matchUps:D}}function bu({participantFilters:t={},tournamentRecord:e,participants:r=[]}){if(!Object.keys(t).length)return r;let{accessorValues:n,drawEntryStatuses:o,positionedParticipants:i,eventEntryStatuses:s,participantRoles:a,participantRoleResponsibilities:c,participantTypes:u,participantIds:p,signInStatus:m,enableOrFiltering:d,eventIds:l,genders:f}=t,g=ea(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&nG({drawEntryStatuses:o,tournamentEvents:g}),h=s&&oG({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,E)=>y.concat(...(E.drawDefinitions||[]).map(P=>Xh({drawDefinition:P}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((E,P)=>{let{accessor:A,value:U}=P,{values:N}=ys({element:y,accessor:A});return E&&N?.includes(U)},!0);if(r=r?.filter(y=>{let E=nn({element:y,itemType:Ic})?.timeItem?.itemValue,{participantRoleResponsibilities:P,participantType:A,participantRole:U,participantId:N,person:D}=y,M=Array.isArray(f)&&f?.length&&D?.sex&&f.includes(D.sex);return d?f&&M||i&&S.includes(N)||i===!1&&!S.includes(N)||I?.includes(N)||h?.includes(N)||p?.includes(N)||m&&E===m||u&&A&&ea(u)&&u.includes(A)||a&&U&&ea(a)&&a.includes(U)||c&&ea(P)&&ea(c)&&c.find(R=>P?.includes(R))||n?.length&&ea(n)&&T(y):(!f||M)&&(i===void 0||i&&S.includes(N)||i===!1&&!S.includes(N))&&(!I||I.includes(N))&&(!h||h.includes(N))&&(!p||p.includes(N))&&(!m||E===m)&&(!u||A&&ea(u)&&u.includes(A))&&(!a||U&&ea(a)&&a.includes(U))&&(!c||ea(P)&&ea(c)&&c.find(R=>P?.includes(R)))&&(!n?.length||ea(n)&&T(y))}),g.length&&l){let y=g.filter(E=>l.includes(E.eventId)).map(E=>{let P=(E.entries||[]).map(U=>U.participantId);if(de(Qn)(E.eventType))return P;let A=(e?.participants??[]).filter(U=>P.includes(U.participantId)).map(U=>U.individualParticipantIds).flat(1);return P.concat(...A)}).flat(1);r=r?.filter(E=>y.includes(E.participantId))}return r}function ea(t){return t&&Array.isArray(t)&&t.length}function nG({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return pt(e.reduce((n,o)=>{let{flightProfile:i}=Ht({event:o}),s=i?.flights?.map(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(St):[]).flat()||[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(St):[])||[];return n.concat(...s,...a)},[]))}function oG({eventEntryStatuses:t,tournamentEvents:e}){return pt(e.reduce((r,n)=>{let o=(n.entries||[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(St);return r.concat(...o)},[]))}function Ft(t){let{withIndividualParticipants:e,participantFilters:r={},withPotentialMatchUps:n,withRankingProfile:o,convertExtensions:i,policyDefinitions:s,withScheduleItems:a,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:p,withTeamMatchUps:m,withScaleValues:d,usePublishState:l,withStatistics:f,contextFilters:g,matchUpFilters:I,contextProfile:h,withOpponents:S,withMatchUps:T,internalUse:y,withSeeding:E,withEvents:P,withDraws:A,withISO2:U,withIOC:N}=t;if(!c)return{error:q};(T||o)&&an({tournamentRecord:c});let D=aS({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:y,withISO2:U,withIOC:N}),{participantMap:M}=D,R=EO({withMatchUps:T??o,withEvents:P??o,withDraws:A??o,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:o,convertExtensions:i,withScheduleItems:a,policyDefinitions:s,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:m,usePublishState:l,withStatistics:f,contextFilters:g,matchUpFilters:I,participantMap:M,withOpponents:S,contextProfile:h,withSeeding:E}),{participantIdsWithConflicts:b,eventsPublishStatuses:O,derivedEventInfo:v,derivedDrawInfo:x,mappedMatchUps:F}=R,w=R.matchUps;M=R.participantMap;let L=u??n,k=({potentialMatchUps:$,scheduleConflicts:X,scheduleItems:W,participant:it,statistics:z,opponents:Q,matchUps:ut,events:ot,draws:Dt})=>{let Rt=Object.values(Dt),De=Object.values(Q);return S&&Rt?.forEach(qt=>{qt.opponents=De.filter(Se=>Se.drawId===qt.drawId)}),nt({...it,scheduleConflicts:u?Object.values(X):void 0,draws:A||o?Rt:void 0,events:P||o?Object.values(ot):void 0,matchUps:T||o?Object.values(ut):void 0,opponents:S?De:void 0,potentialMatchUps:L?Object.values($):void 0,statistics:f?Object.values(z):void 0,scheduleItems:a?W:void 0},!1,!1,!0)},G=new Map;for(let $ of Object.keys(M))G.set($,k(M[$]));let H=[...G.values()],Y=s?.[zs]?.participant,j=bu({participants:H,participantFilters:r,tournamentRecord:c});if(e){let $=ht(e)?e:void 0;for(let X of j)for(let W of X.individualParticipantIds??[]){X.individualParticipants||(X.individualParticipants=[]);let it=G.get(W),z=$?Qi({template:$,source:it}):it;X.individualParticipants.push(z)}}let V=Y?j.map($=>Qi({source:$,template:Y})):j;return{participantMap:t.returnParticipantMap!==!1?M:void 0,mappedMatchUps:t.returnMatchUps!==!1?F:void 0,matchUps:t.returnMatchUps!==!1?w:void 0,missingParticipantIds:D.missingParticipantIds,participantIdsWithConflicts:b,eventsPublishStatuses:O,derivedEventInfo:v,derivedDrawInfo:x,participants:V,...C}}function Pc({participantId:t,drawDefinition:e,entryStatus:r,entryStage:n}){if(!e)return{error:Z};let o=e.entries?.find(i=>i.participantId===t&&(!r||r===i.entryStatus)&&(!n||n===i.entryStage));return t&&o}function Us(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:Z};let{entryProfile:s}=Uu({drawDefinition:r}),a=i&&n&&s?.[i]?.stageSequence?.[n]?.qualifiersCount||i&&s?.[i]?.qualifiersCount||0,c={};if(!o)return{qualifiersCount:a,roundQualifiersCounts:c};let{structure:u}=at({drawDefinition:r,structureId:o}),p=r.links?.filter(l=>l?.target?.structureId===u?.structureId),m=0;if(p?.length)for(let l of p){let f=at({structureId:l.source.structureId,drawDefinition:r})?.structure;if(f?.stage===ct){let g=l.source.roundNumber,I=l.target.roundNumber,h=0;if(f.structureType===Ve){let S=f.structures?.length??0,T=l.source.finishingPositions?.length??0;h=S*T}else h=yt({matchUpFilters:{roundNumbers:[g]},structure:f,afterRecoveryTimes:!1,provisionalPositioning:e,inContext:!1}).matchUps?.length||0;c[I]||(c[I]=0),c[I]+=h,m+=h}}let d=Object.keys(c);if(d.length<=1){let l=d[0]||1;c[l]=Math.max(c[l]||0,a)}return m=Math.max(m,a),{qualifiersCount:m,roundQualifiersCounts:c}}function Fp({stage:t,drawDefinition:e}){let{entryProfile:r}=Uu({drawDefinition:e});return r?.[t]?.drawSize||0}function AO(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=Fp({stage:o,drawDefinition:r}),{qualifiersCount:s}=Us({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function lP({stage:t,drawDefinition:e}){return!!(t===$e||ug({stage:t,drawDefinition:e})&&Fp({stage:t,drawDefinition:e}))}function fP({entryStatus:t=Gr,drawDefinition:e,stageSequence:r,stage:n}){if(t===on)return wb({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...C}:{error:NA};let o=AO({drawDefinition:e,stageSequence:r,stage:n}),i=Lb({drawDefinition:e,stage:n}),s=uS({entryStatus:Pu,drawDefinition:e,stage:n}),a=uS({entryStatus:Gr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==$e&&u?{error:XI}:t===Pu?s<i?{...C}:{error:XI}:{positionsAvailable:p,...C}}function Pd(t){let e=et(t,[{[Ce]:!0,[Lh]:!0}]);if(e.error)return e;let{suppressDuplicateEntries:r=!0,entryStatus:n=Gr,entryStageSequence:o,entryStage:i=rt,ignoreStageSpace:s,drawDefinition:a,entryPosition:c,participant:u,roundTarget:p,extensions:m,extension:d,drawType:l,event:f}=t,g="addDrawEntry";if(l!==Fr&&!lP({stage:i,drawDefinition:a}))return _({result:{error:Vi},stack:g});let I=fP({stageSequence:o,stage:i,drawDefinition:a,entryStatus:n});if(!s&&!I.success&&(!l||l!==Fr))return{error:I.error};if(d&&!Bn({extension:d}))return _({result:{error:B},info:"Invalid extension",context:{extension:d},stack:g});let h=t.participantId||u?.participantId;if(!h)return _({result:{error:se},stack:g});let S=n===gs&&Pc({participantId:h,drawDefinition:a,entryStatus:n}),T=i===$e&&Pc({participantId:h,drawDefinition:a,entryStage:i}),y=Pc({participantId:h,drawDefinition:a}),E=n!==gs&&i!==$e&&y;if(E)return r?(lt({payload:{drawId:a.drawId,eventId:f?.eventId,error:bm,participantId:h},topic:Zh}),{...C}):_({result:{error:bm},context:{participantId:h},stack:g});if(S||T)return _({context:{invalidEntry:E,invalidLuckyLoser:S,invalidVoluntaryConsolation:T},result:{error:sp},stack:g});let P=nt({entryStageSequence:o,participantId:h,entryPosition:c,entryStatus:n,entryStage:i,extensions:m});return d&&At({element:P,extension:d}),p&&At({extension:{name:"roundEntry",value:p},element:P}),a.entries||(a.entries=[]),a.entries.push(P),bt({drawDefinition:a}),{...C}}function UO(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=Gr,autoEntryPositions:o=!0,ignoreStageSpace:i,participantIds:s,drawDefinition:a,stageSequence:c,stage:u=rt,roundTarget:p,extension:m,event:d}=t,l=a.drawType===Fr;if(!u)return{error:oA};if(!a)return{error:Z};if(!Array.isArray(s))return{error:wr};if(!l&&!lP({stage:u,drawDefinition:a}))return{error:Vi};if(m&&!Bn({extension:m}))return _({result:{error:B},info:"Invalid extension",context:{extension:m},stack:e});let f=fP({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!==$e&&g<s.length)return{error:of};let I=[],h=a.drawId,S=d?.eventId,T=s.reduce((y,E)=>{let P=n===gs&&Pc({participantId:E,drawDefinition:a,entryStatus:n}),A=u===$e&&Pc({entryStage:u,drawDefinition:a,participantId:E}),U=Pc({participantId:E,drawDefinition:a});return n!==gs&&u!==$e&&U&&(I.push(E),r&<({payload:{error:bm,participantId:E,eventId:S,drawId:h},topic:Zh})),P||A?y.concat(E):y},[]);return I.length&&!r?_({context:{eventId:S,drawId:h,duplicateEntries:I},result:{error:bm},stack:e}):(s.filter(y=>y&&!T.includes(y)).forEach(y=>{let E={entryStageSequence:c,entryStage:u,participantId:y,entryStatus:n};m&&At({element:E,extension:m}),p&&At({extension:{name:vn,value:p},element:E}),a.entries||(a.entries=[]),a.entries.push(E)}),o&&(a.entries=eo({entries:a.entries})),bt({drawDefinition:a}),T?.length||I?.length?{info:"some participantIds could not be added",participantIdsNotAdded:T,duplicateEntries:I,...C}:{...C})}function hg({suppressDuplicateEntries:t=!0,autoEntryPositions:e=!0,entryStageSequence:r,ignoreStageSpace:n,participantIds:o,drawDefinition:i,entryStatus:s,roundTarget:a,entryStage:c,extension:u,drawId:p,event:m}){if(!o?.length)return{error:bo};if(!m)return{error:qr};if(!p)return{error:cn};let d=(m.entries||[]).map(St);if(o.filter(I=>!d.includes(I)).length)return{error:rA};if(i){let I=UO({stageSequence:r,suppressDuplicateEntries:t,autoEntryPositions:e,stage:c,ignoreStageSpace:n,participantIds:o,drawDefinition:i,entryStatus:s,roundTarget:a,extension:u});if(I.error)return I}let{flightProfile:f}=Ht({event:m}),g=f?.flights.find(I=>I.drawId===p);return g?.drawEntries&&(o.forEach(I=>{let h=s===gs&&gP({participantId:I,entryStatus:s,flight:g}),S=c===$e&&gP({participantId:I,entryStage:c,flight:g});!(s!==gs&&c!==$e&&gP({flight:g,participantId:I}))&&!h&&!S&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=eo({entries:g.drawEntries}))),{...C}}function gP({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 Dc({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:Ot};if(!Array.isArray(e)||e.some(m=>!kt(m)))return _({result:{error:ln},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>wi({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(St).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(St).filter(m=>!s.includes(m));if(e.length?e=e.filter(m=>(!r?.length||a.includes(m))&&(!n||c.includes(m))):a.length&&c.length?e=jt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return _({result:{error:Gs},stack:i});if(!e?.length)return{...C,participantIdsRemoved:[]};let u=[];o.entries=(o.entries??[]).filter(m=>{let d=!e.includes(m?.participantId);return d||u.push(m.participantId),d}),t&&(o.entries=eo({entries:o.entries}));let{flightProfile:p}=Ht({event:o});return p?.flights?.forEach(m=>{m.drawEntries=(m.drawEntries||[]).filter(d=>!e.includes(d.participantId))}),o.drawDefinitions?.forEach(m=>{m.entries=(m.entries??[]).filter(d=>!e.includes(d.participantId))}),{...C,participantIdsRemoved:u}}var IP={[er]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},Ps=IP;function Wn(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=Gr,autoEntryPositions:n=!0,enforceGender:o=!0,entryStageSequence:i,policyDefinitions:s,entryStage:a=rt,tournamentRecord:c,ignoreStageSpace:u,drawDefinition:p,roundTarget:m,extensions:d,extension:l,drawId:f,event:g}=t,I="addEventEntries";if(!Array.isArray(t.participantIds))return _({result:{error:wr},stack:I});let h=pt(t.participantIds??[]);if(!g)return{error:Ot};if(!h?.length)return _({result:{error:bo},stack:I});if(!g?.eventId)return{error:qr};let S=Tt({tournamentRecord:c,event:g}).appliedPolicies??{},T=s?.[er]??S?.[er]??Ps[er],y=(o??T?.participants?.enforceGender)!==!1,E=[],P=[];if(d&&(!Array.isArray(d)||!d.every(x=>Bn({extension:x})))||l&&!Bn({extension:l}))return _({context:nt({extension:l,extensions:d}),result:{error:B},info:"Invalid extension(s)",stack:I});let A=!!c,U=[],N,D=c?.participants?.filter(x=>{if(!h.includes(x.participantId))return!1;let F=de(Lt)(g.eventType)&&x.participantType===Et&&!ta(r),w=g.eventType===vt&&x.participantType===ft;return F&&(!g.gender||!y||en(g.gender)||To(g.gender)||yr(g.gender)===yr(x.person?.sex))||w&&!ta(r)?!0:g.eventType===vt&&x.participantType===Et&&ta(r)?g.gender&&y&&!(en(g.gender)||To(g.gender))&&yr(g.gender)!==yr(x.person?.sex)?(U.push({participantId:x.participantId,sex:x.person?.sex}),!1):!0:F&&g.gender&&y&&!(en(g.gender)||To(g.gender))&&yr(g.gender)!==yr(x.person?.sex)?(U.push({participantId:x.participantId,sex:x.person?.sex}),!1):g.eventType===wt&&(x.participantType===wt||ta(r)&&x.participantType===Et)}).map(x=>x.participantId)??[],M=h.filter(x=>!A||D.includes(x));g.entries||(g.entries=[]);let R=g.entries.map(x=>x.participantId||x.participant?.participantId);if(M.forEach(x=>{if(!R.includes(x)){let F=nt({participantId:x,entryStatus:r,entryStage:a,extensions:d});l&&At({element:F,extension:l}),m&&At({extension:{name:vn,value:m},element:F}),i&&(F.entryStageSequence=i),E.push(F.participantId),g.entries?.push(F)}}),f&&!ta(a)){let x=hg({participantIds:M,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:i,ignoreStageSpace:u,drawDefinition:p,entryStatus:r,roundTarget:m,entryStage:a,extension:l,drawId:f,event:g});x.error&&(N=x.error)}if(g.eventType&&[Ko,Or].includes(g.eventType)){let x=(g.entries||[]).map(G=>G.participantId),F=(g.entries||[]).filter(G=>ta(G.entryStatus)).map(G=>G.participantId),L=(c?.participants??[]).filter(G=>x.includes(G.participantId)&&G.participantType&&[ft,wt].includes(G.participantType)).map(G=>G.individualParticipantIds).flat(1/0),k=F.filter(G=>L.includes(G));k.length&&(P.push(...k),Dc({participantIds:k,autoEntryPositions:!1,event:g}))}if(M.length!==h.length)return _({context:{mismatchedGender:U,gender:g.gender},result:{error:wr},stack:I});n&&(g.entries=eo({entries:g.entries||[]}));let O=E.length,v=P.length;return _({result:{...C,addedEntriesCount:O,removedEntriesCount:v},stack:I,info:N})}var hP="ADMINISTRATION",iG="CAPTAIN",sG="COACH",xe="COMPETITOR",SP="MEDIA",TP="MEDICAL",Sg="OFFICIAL",yP="OTHER",EP="SECURITY",Dd={ADMINISTRATION:hP,CAPTAIN:iG,COACH:sG,COMPETITOR:xe,MEDIA:SP,MEDICAL:TP,OFFICIAL:Sg,OTHER:yP,SECURITY:EP};function Tg({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return _({result:{error:q},stack:i});if(!r||!e)return _({result:{error:st},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return _({result:{error:re},stack:i});if(![wt,Qr].includes(a.participantType))return _({result:{participantType:a.participantType,error:Pn},stack:i});let c=PO({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:n,suppressErrors:o}),{removed:u,error:p}=c;if(p)return _({result:c,stack:i});if(t)for(let m of n.events??[]){let d=(m.entries??[]).map(({participantId:l})=>l).filter(Boolean);if(d.includes(r)){let l=u?.filter(f=>!d.includes(f));Wn({participantIds:l,entryStatus:Vr,tournamentRecord:n,event:m})}}return u&<({topic:rr,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...C,...c}}function PO({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}=Ft({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));let p=i?.find(({participantId:l})=>l===e.participantId)?.events?.map(({eventId:l})=>l),m=(e.individualParticipantIds??[]).filter(l=>{let f=t?.includes(l),g=f&&i?.find(h=>h.participantId===l)?.matchUps.filter(({eventId:h})=>p.includes(h)).map(({matchUpId:h})=>o?.[h]).filter(({winningSide:h,score:S})=>h||he({score:S})),I=f&&!g?.length;if(f&&!I&&c.push(l),I){s.push(l);for(let h of r.events??[])for(let S of h.drawDefinitions??[]){let{extension:T}=mt({element:S,name:wo}),y=T?.value[e.participantId];T&&y&&(T.value[e.participantId]=y.filter(P=>P.participantId!==l),At({element:S,extension:T}),Ma({drawDefinition:S}));let E=nr({drawDefinition:S,inContext:!1}).matchUps??[];for(let P of E){let A=P.sides??[];for(let U of A){let N=U.lineUp??[];N.find(M=>M.participantId===l)&&(U.lineUp=N.filter(M=>M.participantId!==l),gt({tournamentId:r?.tournamentId,drawDefinition:S,matchUp:P}))}}}}else a.push(l);return!I});e.individualParticipantIds=m;let d={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:a,removed:s};return c.length&&!n&&{...d,cannotRemove:c,error:ip}||d}function kp({participantRole:t=xe,individualParticipantIds:e=[],groupingTypes:r=[Ar,Qr],tournamentRecord:n}){if(!n)return{error:q};let o=n.participants??[],{participants:i,mappedMatchUps:s}=Ft({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}=PO({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?C:{error:AA}}function ns(t){let e=et(t,[{[ne]:!0},{participantIds:!0,[He]:Be,[In]:bo}]);if(e.error)return e;let{addIndividualParticipantsToEvents:r,tournamentRecord:n,participantIds:o}=t,i=n.participants?.length||0;if(!i)return{...C};let s=(n.events||[])?.filter(({eventType:f})=>f===_e).map(f=>f?.drawDefinitions?.map(({drawId:g})=>g)).flat(1/0),a=Ft({participantFilters:{participantIds:o},tournamentRecord:n,withDraws:!0}).participants??[],c=f=>{let I=(ye({matchUpFilters:{drawIds:f,matchUpTypes:[vt]},tournamentRecord:n}).matchUps??[]).flatMap(({sides:h})=>h?.map(({participantId:S})=>S||[])).filter(Boolean);return jt(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:Gs};let m={},d={};for(let f of n.events||[]){let g=Dc({participantIds:o,event:f});if(g.error)return g;m[f.eventId]=g.participantIdsRemoved}n.participants=(n.participants??[]).filter(f=>{let g=o.includes(f.participantId)||f.participantType===ft&&f.individualParticipantIds?.some(I=>o.includes(I));if(!g&&f.participantType===_e&&f.individualParticipantIds?.some(I=>o.includes(I))&&(f.individualParticipantIds=f.individualParticipantIds.filter(I=>!o.includes(I))),g&&r&&f.participantType&&[ft,wt].includes(f.participantType))for(let I of f.individualParticipantIds||[])o.includes(I)||(d[f.participantId]||(d[f.participantId]=[]),d[f.participantId].push(I));return!g});let l=i-n.participants.length;if(kp({individualParticipantIds:o,tournamentRecord:n}),r)for(let f of n.events||[]){let I=m[f.eventId].map(h=>d[h]||[]).flat();Wn({participantIds:I,entryStatus:Vr,tournamentRecord:n,event:f})}return l&<({payload:{participantIds:o,tournamentId:n.tournamentId},topic:qf}),l?{...C,participantsRemovedCount:l}:{error:ip}}function OS({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Ht({event:o}),u=c?.flights?.find(p=>p.drawId===n);u?s=u.drawEntries:e.entries&&(s=e?.entries)}let a=s.filter(c=>(!r?.length||!c.entryStatus||r.includes(c.entryStatus))&&(!i||!c.entryStage||c.entryStage===i)&&(!t||c.entryStatus&&Xr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function AP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry";if(!e)return{error:q};if(!n)return _({result:{error:se},stack:a});if(!s)return{error:Ot};if(!s.eventType||![Ko,Or].includes(s.eventType))return _({result:{error:$n},stack:a});let c=e.participants??[],u=c.find(S=>S.participantId===n);if(!u)return _({result:{error:re},stack:a});if(!u.participantType||![ft,Ar].includes(u.participantType)||u.participantType===Ar&&s.eventType!==Or||u.participantType===ft&&s.eventType!==Ko)return{error:Pn};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:QI};let{stageEntries:d}=OS({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),l=d.map(St),f=c.filter(({participantId:S})=>l.includes(S)).map(({individualParticipantIds:S})=>S).flat().filter(Boolean),g=u.individualParticipantIds?.filter(S=>ho(S,f).length===1),I=Dc({participantIds:[n],event:s});if(I.error||g?.length&&(I=Wn({participantIds:g,entryStatus:Vr,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&ns({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...C,participantRemoved:h}}function yg({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return AP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function UP(t){if(!t.tournamentRecord)return{error:q};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=AP({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...C}:{error:o}}function Ou(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=Uc(t);if(u.error)return _({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t,f=Tt({tournamentRecord:e,drawDefinition:n,event:d}).appliedPolicies??{};if([on,mo].includes(i)&&p){let{tournamentRecord:h}=t,{participant:S}=Uo({tournamentRecord:h,participantId:p}),{participantType:T,individualParticipantIds:y}=S??{};if(o&&T===ft){let E=yg({tournamentRecord:h,drawDefinition:n,participantId:p,event:d});if(E.error)return _({result:E,stack:c});y&&Ad({participantIds:y,tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else Ad({participantIds:[p],tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let h=Wr({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(h.error)return _({result:h,stack:c})}let{structure:g}=at({drawDefinition:n,structureId:l});return ad({structure:g,drawPositions:[m]}),hu({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function PP(t){return Object.assign(t,{entryStatus:mo}),Ou(t)}var Ds=({finishingPosition:t=zi,hasExistingDrawDefinition:e,qualifyingRoundNumber:r,structureAbbreviation:n,seedAssignments:o=[],stageSequence:i=1,qualifyingOnly:s,structureOrder:a,seedingProfile:c,matchUpFormat:u,structureType:p,structureName:m,matchUps:d=[],matchUpType:l,structureId:f,roundOffset:g,roundLimit:I,stageOrder:h,structures:S,tieFormat:T,stage:y})=>{let E={structureId:f??Nt(),structureAbbreviation:n,finishingPosition:t,seedAssignments:o,matchUpFormat:u,stageSequence:i,structureName:m};(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 P=d.flatMap(({drawPositions:A})=>A).filter(Boolean);return S?E.structures=S:(E.matchUps=d,E.positionAssignments=pt(P).sort((A,U)=>A-U).map(A=>({drawPosition:A}))),E},yn=Ds;function vS(t){return kt(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function Qe(t){return kt(t)?vS(t.replace(/_/g," ")):""}function Eg({structureName:t=Qe($e),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:Z};let i=yn({stage:$e,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(i),bt({drawDefinition:r,structureIds:[i.structureId]}),{...C}}function Ag({drawPositions:t}){if(!t?.length)return{error:Ja};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=pt(r.map(Ug)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function Ug(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(le).join("|")}function DP({groupSize:t,drawPositionOffset:e}){if(!t)return[];let r=m=>[...Array(m)].map((d,l)=>l),n=r(2*Math.round(t/2)+1).slice(1),o=r(n.length-1).map(()=>[]),i=n.slice(0,n.length/2),s=n.slice(n.length/2);n.slice(1).forEach((m,d)=>{i.forEach((I,h)=>{o[d].push([i[h],s[h]])});let l=i.shift(),f=i.pop(),g=s.shift();i=[l,g,...i].filter(Boolean),s=[...s,f].filter(Boolean)});let a=i.shift(),c=i.pop(),u=s.shift();i=[a,u,...i].filter(Boolean),s=[...s,c].filter(Boolean);let p=m=>m[0].reduce((d,l)=>d+l);return[...o].reverse().sort((m,d)=>p(m)-p(d)).map(m=>m.filter(d=>d.every(l=>l<=t)).map(d=>{let l=d.map(f=>f+e);return Ug(l)}))}function aG({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:st}}var DO={getRoundRobinGroupMatchUps:Ag,determineRoundNumber:aG,drawPositionsHash:Ug,groupRounds:DP};function xa(t){let{hasExistingDrawDefinition:e,groupNameBase:r="Group",playoffAttributes:n,stageSequence:o=1,structureOptions:i,appliedPolicies:s,qualifyingOnly:a,seedingProfile:c,stage:u=rt,matchUpType:p,roundTarget:m,structureId:d,groupNames:l,tieFormat:f,drawSize:g,idPrefix:I,isMock:h,uuids:S}=t,T=t.structureName??n?.["0"]?.name??Qe(rt),{groupCount:y,groupSize:E}=cG({structureOptions:i,appliedPolicies:s,drawSize:g}),P=Ei,A,U=tt(1,y+1).map(D=>{let M=uG({groupSize:E,structureOrder:D,matchUpType:p,drawSize:g,idPrefix:I,isMock:h});A=Array.isArray(M)?Math.max(...M.map(({roundNumber:b})=>b??0)):0;let R=l?.[D-1]??`${r} ${D}`;return Ds({structureId:S?.pop(),hasExistingDrawDefinition:e,structureType:hp,finishingPosition:P,qualifyingOnly:a,structureOrder:D,structureName:R,tieFormat:f,matchUps:M})}),N=Ds({structureId:d??S?.pop(),hasExistingDrawDefinition:e,structureType:Ve,finishingPosition:P,seedingProfile:c,structureName:T,stageSequence:o,structures:U,tieFormat:f,stage:u});return m&&At({extension:{name:vn,value:m},element:N}),{structures:[N],maxRoundNumber:A,groupCount:y,links:[],groupSize:E,...C}}function cG({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=Gp({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 Gp(t){let{groupSizeLimit:e=10,drawSize:r=0}=t??{},n=tt(3,e+1).filter(o=>{let i=Math.ceil(r/o),s=i*o-r,a=Math.ceil(r/i),c=Math.ceil(s/i);return(!s||s<o)&&a===o&&a>=3&&c<2});return{...C,validGroupSizes:n}}function uG({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=tt(1+a,r+1+a),u=Ag({drawPositions:c}).uniqueMatchUpGroupings??[],p=DP({groupSize:r,drawPositionOffset:a});return u.map(l).sort((f,g)=>(f.roundNumber??1/0)-(g.roundNumber??1/0));function d(f){return p.reduce((g,I,h)=>I.includes(f)?h+1:g,void 0)}function l(f){let g=Ug(f),I=d(g),h=[1,n],S=pG({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?Qt:"BYE",matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function pG({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Nt()}function Pg(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!It(r))return{seedBlocks:void 0,..._({result:{error:B},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=us(r);if(e){let l=Math.min(e,o),f=[],g=1;for(tt(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=tt(g,g+l);g+=l,f.push(I)}return{...C,seedBlocks:f}}let i=tt(1,o+1),s=[],a=o/2;for(;a>1;){let l=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,ke(g,s)||s.push(h)}),a=a/2}let c=i.filter(l=>!s.includes(l));for(;c.length;)c.length%2===0?s.push(c.pop()):s.push(c.shift());let u=tt(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),m=0,d=[];return tt(0,p).forEach(l=>{d.push(s.slice(m,m+u[l])),m+=u[l]}),{...C,seedBlocks:d}}function Dg({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!It(e))return{seedGroups:void 0,..._({result:{error:B},context:{drawSize:e},stack:r})};if(t){if(!It(t))return{seedGroups:void 0,..._({context:{roundRobinGroupsCount:t},result:{error:B},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:tt(0,o).map(()=>{let s=tt(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=Pg({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function _S({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=Gp({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return _({context:{roundRobinGroupsCount:t},result:{error:B}})}let{seedGroups:r}=Dg({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...C,seedingThresholds:n}}function Nc(t){if(!t)return 1/0;if(It(t))return dt(t);let e=t.split("-")[0];return It(e)?dt(e):1/0}function mG({size:t}){let e=[t],r=t;for(;r/2===Math.floor(r/2);)r=r/2,e.push(r);return e.includes(1)||e.push(1),e.sort(le),e.reverse(),e}function NO({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 MO({positioning:t,size:e}){let r=mG({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[nu,Ti].includes(t)&&l%2?s(d):i(d))||i(d),c=(d,l)=>{if(d.every(f=>!o.includes(f))){let f=a(d,l);return o.push(f),f}},u=d=>{let l=d.filter(f=>!o.includes(f));if(l.length)return o.push(...l),l},p=(d,l)=>{let f=a(d,l);if(!o.includes(f))return o.push(f),f},m=tt(1,e+1);for(let d of r)if(d===1){let l=Ae(m,2),f=l.map(c).filter(Boolean);f.length&&n.push(f);let g=l.flatMap(u).filter(Boolean);g.length&&n.push(g)}else{let f=Ae(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function Ns({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:Si};let{matchUps:c,roundMatchUps:u}=yt({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=sn({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:m}=Ie({structure:s}),d=m?.length,l=p?.length??0,f=[],I=Object.keys(u).map(w=>parseInt(w)).sort((w,L)=>w-L).map(w=>{let L=u[w].map(G=>G.drawPositions).flat(1/0).filter(Boolean),k=L.filter(G=>!f.includes(G));return f=f.concat(...L),k}).filter(w=>w.length).reverse(),h=I.pop()??[],S=h&&Math.min(...h)-1||0;n=n??r?.seeding?.seedingProfile;let T=h?.length||0,y=I.filter(w=>w.filter(L=>L<=l).length),{stage:E,structureType:P,roundLimit:A}=s,U=P===Ve,N=!U&&I?.length,D=!U&&E===ct&&A,M=y.flat(1/0),R=N?M?.length:0,b=i?d:l,O=gd({drawDefinition:o,structure:s,matchUps:c}),v=O?0:!N&&b||b&&M.length<b&&b-M.length||0;if(D){let w=s?.matchUps?s.matchUps.filter(({roundNumber:k})=>k===s.roundLimit).length:0,L=h.length/w;if(!N){let k=Bp(n),G=Ae(h,L),H=1,K=tt(0,G[0].length).map(()=>{let Y=tt(H,H+G.length);return H+=G.length,Y});({validSeedBlocks:a}=RO({drawPositionBlocks:G,nonRandom:n?.nonRandom,positioning:k,seedGroups:K}))}}else U?{validSeedBlocks:a}=dG({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):N?a=y.map(w=>({seedNumbers:w,drawPositions:w})):O&&Ae(h,2).map((L,k)=>({drawPositions:[L[0]],seedNumbers:[k+1]})).forEach(L=>a.push(L));if(!U&&!O&&!D){let{blocks:w}=lG({drawPositionOffset:S,seedNumberOffset:R,seedCountGoal:v,seedingProfile:n,baseDrawSize:T});w.forEach(L=>a.push(L))}let F=a.flatMap(w=>w.drawPositions).reduce((w,L)=>h?.includes(L)&&w,!0);return!O&&!N&&!U&&!F?{error:JE,validSeedBlocks:[],isContainer:U,isFeedIn:N}:{isLuckyStructure:O,validSeedBlocks:a,isContainer:U,isFeedIn:N}}function dG({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=Ct({structure:e})?.positionAssignments,s=Bp(t),a=i?.length??0,{seedGroups:c}=Dg({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>Ct({structure:p}).positionAssignments?.map(m=>m.drawPosition));return RO({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function RO({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=MO({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=NO({blockPattern:i,index:c});a.forEach((p,m)=>{let d=c%2?t.length-m-1:m,f=t[d].slice().filter((I,h)=>u.includes(h+1)&&I);e!==Ti?f=n?f:Tr(f):c%2&&f.reverse();let g=f.find(I=>!s.includes(I));g&&(s.push(g),o.push({drawPositions:[g],seedNumbers:[p]}))})}),{validSeedBlocks:o}}function lG(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=Pg({cluster:Bp(o)===nu,participantsCount:s,roundRobinGroupsCount:r});a=0;for(let m of u){if(a+1>i)break;let d=m.map(f=>f+e),l=p(a+1,m.length).map(f=>+f+n);a+=m.length,c.push({drawPositions:d,seedNumbers:l})}return{blocks:c};function p(m,d){return Array.from(new Array(d),(l,f)=>f+m)}}function Vp({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=at({drawDefinition:e,structureId:o});t||(t=Tt({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=Ns({appliedPolicies:t,drawDefinition:e,structure:s})?.validSeedBlocks),t?.seeding?.validSeedPositions?.ignore?!0:t?.seeding?.validSeedPositions?.strict?(a.find(m=>m.seedNumbers.includes(i))?.drawPositions||[]).includes(n):[].concat(...a.map(u=>u.drawPositions)).includes(n)}function xS(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=at({drawDefinition:r,structureId:i}),{seedAssignments:c}=sn({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:a}),{positionAssignments:u}=Ie({structure:a}),m=u?.filter(L=>L.participantId??L.bye??L.qualifier)?.map(L=>L.drawPosition).filter(Boolean),{appliedPolicies:d}=Tt({drawDefinition:r}),g=(o?.validSeedBlocks||a&&Ns({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(L=>L.drawPositions.filter(G=>!m?.includes(G)).length)[0],I=c?.map(L=>L.participantId).filter(Boolean),h=u?.map(L=>L.participantId).filter(Boolean),S=I?.filter(L=>h?.includes(L)),T=I?.filter(L=>!h?.includes(L)),y=c?.filter(L=>T?.includes(L.participantId)),E=c?.filter(L=>!L.participantId),A=(y?.length&&y.length>0?y.length:E?.length??0)&&g?.drawPositions.filter(L=>!m?.includes(L))||[],U=s?Tr(A):A,N=[],D=U.map(()=>{let k=w(y,N)?.participantId;return k&&N.push(k),k}).filter(Boolean),M=c?.filter(L=>S?.includes(L.participantId)).map(L=>L.seedNumber),b=(g?.seedNumbers||[]).filter(L=>!M?.includes(L)),O=c?.filter(L=>b.includes(L.seedNumber)).map(L=>L.participantId),v=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(v!==void 0?v:!0)?D:O,unplacedSeedNumbers:b,unfilledPositions:U,unplacedSeedAssignments:y};function w(L,k){let G=L.filter(j=>!k.includes(j.participantId)),H=Math.min(...G.map(j=>Nc(j.seedValue))),K=G.filter(j=>Nc(j.seedValue)===H);return Tr(K).pop()}}function Bp(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function ra({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,seedBlockInfo:i,structureId:s,seedNumber:a,seedValue:c,eventId:u,event:p}){let m="assignSeed",{structure:d}=at({drawDefinition:r,structureId:s}),{positionAssignments:l}=Ie({structure:d}),f=sn({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(P=>P.seedNumber),I=Pc({drawDefinition:r,participantId:o});if(o&&!I)return _({result:{error:ln},context:{participantId:o},stack:m});let h=p?Ht({event:p}).flightProfile?.flights?.length:0,S=h&&h>1,y=l?.find(P=>P.participantId===o)?.drawPosition;if(y&&!Vp({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return _({result:{error:Yl},context:{assignedDrawPosition:y},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let E;return f.forEach(P=>{P.participantId===o&&P.seedNumber!==a&&(P.participantId=void 0),P.seedNumber===a&&(P.participantId=o,!n?.groupSeedingThreshold&&!S&&(P.seedValue=c??a),E=!0)}),E?(rS({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...C}):_({result:{error:XE},stack:m})}function Nd({inContextTargetMatchUp:t,drawPositionSideIndex:e,teamParticipantId:r,tournamentRecord:n,drawDefinition:o,matchUp:i,event:s}){let a=t?.sides?.[e]?.sideNumber,c=a&&i.sides?.find(d=>d.sideNumber===a),{extension:u}=mt({element:o,name:wo}),p=u?.value||{},m=J(p[r],!1,!0);if(c)i?.sides?.forEach(d=>{d.sideNumber===a&&(d.lineUp=m)});else{i.sides=[1,2].map(l=>({...i.sides?.find(g=>g.sideNumber===l)??{},sideNumber:l}));let d=i.sides.find(l=>l.sideNumber===a);d&&(d.lineUp=m)}gt({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function wS(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=Vo({structureId:n.structureId,matchUpsMap:o});!e&&i&&(e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)));let c=e?.roundPosition,u=c%2?1:-1,p=c+u,m=s&&a.find(({roundNumber:f,roundPosition:g})=>f===s&&g===p),d=m?.matchUpStatus,l=[oe,be].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function CO({drawPosition:t,drawPositions:e}){let r=!1,n=!!e?.includes(t);return{updatedDrawPositions:n?e||[]:[...e,void 0,void 0].slice(0,2).map(s=>!s&&!n?(n=!0,r=!0,t):s).sort(le).filter(Boolean),positionAdded:r,positionAssigned:n}}function LS({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:Vo({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function FS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=LS({structureId:i?.structureId,matchUp:i,matchUpsMap:n});if(i&&s){let a=s?.matchUpId,c=t.find(p=>p.matchUpId===a),u=i?.structureId===c?.structureId?i?.roundPosition<c?.roundPosition&&1||2:i.structureId===c?.structureId&&2||1;o.matchUpStatusCodes=(o.matchUpStatusCodes??[]).map(p=>{let m=kt(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function Md({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 wa({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:r,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,event:u}){let p="assignMatchUpDrawPosition";a||(a=Pe({drawDefinition:o})),t||(t=ie({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[]);let m=t.find(O=>O.matchUpId===c),d=m?.structureId,l=o?.structures?.find(O=>O.structureId===d);if(!l)return{error:_t};let f=a?.drawMatchUps?.find(O=>O.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=CO({drawPositions:g,drawPosition:s}),{positionAssignments:T}=Ct({drawDefinition:o,structure:l}),E=T?.filter(O=>S.includes(O.drawPosition))?.find(({bye:O})=>O),P=f?.matchUpStatus&&pr(f.matchUpStatus)&&S.filter(Boolean).length<2;i=E&&"BYE"||i||P&&f.matchUpStatus||f?.matchUpStatus&&[oe,be].includes(f.matchUpStatus)&&f.matchUpStatus||Qt;let A=!!(pr(f?.matchUpStatus)&&f?.winningSide);if(f&&I){t=ie({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let O=P&&Md({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||A&&f.winningSide||void 0;f?.matchUpStatusCodes&&FS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:a,matchUp:f}),Object.assign(f,{drawPositions:S,winningSide:O,matchUpStatus:A?f?.matchUpStatus:i}),gt({tournamentId:r?.tournamentId,eventId:m?.eventId,context:p,drawDefinition:o,matchUp:f})}let U=ur({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:N,loserMatchUp:D,loserTargetDrawPosition:M},targetLinks:{loserTargetLink:R}}=U,b=Vo({structureId:l.structureId,matchUpsMap:a});if(h&&E){if(N)if(["BYE",oe,be].includes(i)){let O=wa({matchUpId:N.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(O.error)return O}else{let{structureId:O}=N;O!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(h&&A){if(N){let O=wa({matchUpId:N.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(O.error)return O}}else if(N&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:O}=wS({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(O){let v=wa({matchUpId:N.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(v.error)return v}}if(f?.matchUpType===Wt){let O=t?.find(({matchUpId:w})=>w===f.matchUpId),x=(O?.sides??[]).reduce((w,L,k)=>L.drawPosition===s?k:w,void 0),F=T?.find(w=>w.drawPosition===s)?.participantId;F&&x!==void 0&&Nd({inContextTargetMatchUp:O,drawPositionSideIndex:x,teamParticipantId:F,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(R?.linkCondition===kn&&S.filter(Boolean).length===2&&!E&&b.filter(({drawPositions:x,roundNumber:F})=>F===1&&ke(x,S)).every(({matchUpStatus:x})=>[ge,Me].includes(x))&&D){let{structureId:x}=D,F=Wr({drawPosition:M,tournamentRecord:r,drawDefinition:o,structureId:x,matchUpsMap:a,event:u});if(F.error)return F}return h?{...C}:_({result:{error:Xa},context:{drawPosition:s},stack:p})}function kS({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=fs({drawDefinition:e})?.containedStructures?.[o.structureId]?.map(({structureId:m})=>m)||[];s.push(o?.structureId);let a=r?.map(({drawPosition:m})=>m)||[],c=t?.filter(m=>s.includes(m.structureId)&&jt(m.drawPositions??[],a).length)??[],u=c.map(({matchUpId:m})=>m),p=n?.drawMatchUps?.filter(m=>u.includes(m.matchUpId))??[];return{drawPositions:a,matchUps:p,targetMatchUps:c}}function Rd({lineUp:t}){if(!Array.isArray(t))return;let e={};return pt(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}=Lp({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 li(t){return`${t} must be an array`}function Cd({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(li("lineUp")),{valid:!1,errors:r,error:B};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(li("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=pt(t.map(St)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?B:void 0}}function os({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:se};let o=Cd({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=mt({element:t,name:wo}),s=i?.value||{};return s[e]=Rd({lineUp:n}),At({element:t,extension:{name:wo,value:s}}),Ma({drawDefinition:t}),{...C}}function Ng({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,assignments:i,structure:s,event:a}){if(!n)return{error:Z};let{drawPositions:c,matchUps:u,targetMatchUps:p}=kS({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===xr&&(m.sides??[]).forEach((d,l)=>{if(d?.drawPosition&&c?.includes(d.drawPosition)){let f=u.find(({matchUpId:g})=>g===m.matchUpId);if(f?.sides?.[l]){if(delete f.sides[l].lineUp,e===!1){let g=m.tieFormat,I=d.participantId;g&&I&&os({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}gt({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...C}}function jn({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:r,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,seedBlockInfo:c,drawPosition:u,matchUpsMap:p,structureId:m,event:d}){let l="assignDrawPosition";if(!a&&!r)return _({result:{error:se},stack:l});p=p??Pe({drawDefinition:i}),e||({matchUps:e}=ie({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=at({drawDefinition:i,structureId:m});if(f.error)return _({result:f,stack:l});let{structure:g}=f;if(!g)return{error:_t};if(cr({structure:g}))return _({result:{error:dr},stack:l});let{seedAssignments:I}=sn({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(O=>O.participantId===a)?.seedNumber,{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!Vp({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return _({result:{error:Yl},context:{drawPosition:u},stack:l});let E=Ie({structure:g}).positionAssignments||[],P=E?.find(O=>O.drawPosition===u);if(!P)return _({result:{error:Ls},context:{drawPosition:u},stack:l});if(E?.map(St).includes(a))return _({result:{error:Gs},context:{drawPosition:u},stack:l});let{containsParticipant:U,containsBye:N}=b(P);if(N){let O=Uc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(O.error)return _({result:O,stack:l})}if(U&&P.participantId!==a){let{activeDrawPositions:O}=va({drawDefinition:i,structureId:m});if(O.includes(u))return _({result:{error:rp},stack:l});Ng({assignments:[P],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}if(P.participantId=a,r&&(P.qualifier=!0),g.stage===rt&&(!g.stageSequence||g.stageSequence>1)||g.stage&&[qe,fe].includes(g.stage)){let O=g.stage===ct?ct:rt,F=(i.structures?.find(w=>w?.stage===O&&w?.stageSequence===1)?.seedAssignments??[]).find(w=>w.participantId===a);if(F?.participantId){let{participantId:w,seedNumber:L,seedValue:k}=F;ra({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:w,seedNumber:L,seedValue:k,structureId:m,event:d})}}if(g.structureType!==Ve)fG({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{CS({positionAssignments:E,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:O,matchUps:v,targetMatchUps:x}=kS({assignments:[P],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(O&&v?.length===1&&v[0].matchUpType===Wt){let w=(x?.[0].sides??[]).reduce((L,k,G)=>O?.includes(k.drawPosition)?G:L,void 0);Nd({inContextTargetMatchUp:x[0],teamParticipantId:a,matchUp:v[0],drawPositionSideIndex:w,tournamentRecord:o,drawDefinition:i})}}let M=i.entries?.find(O=>O.participantId===a),R=d?.entries?.find(O=>O.participantId===a);return!M&&R&&Pd({entryStatus:R.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:i,participantId:a,event:d}),ko({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:E,...C};function b(O){let v=O.bye,x=O.qualifier,F=O.participantId;return{containsBye:v,containsQualifier:x,containsParticipant:F,filled:v||x||F}}}function fG({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=yt({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=Ke({matchUps:p}),{initialRoundNumber:d}=Es({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=wa({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return _({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...C}}function bd(t){let{participantIdAttributeName:e="participantId",isQualifierPosition:r,positionActionName:n,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,event:u}=t,p="positionParticipantAction";if(!i)return{error:Z};let m=Tt({tournamentRecord:o,drawDefinition:i,event:u}).appliedPolicies??{},{inContextDrawMatchUps:d,matchUpsMap:l}=t;l||(l=Pe({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),d||({matchUps:d}=ie({inContext:!0,drawDefinition:i,matchUpsMap:l}),Object.assign(t,{inContextDrawMatchUps:d}));let{positionAssignments:f}=Ct({drawDefinition:i,structureId:c}),g=f?.find(y=>y.drawPosition===a);if(g?.participantId){let y=g.participantId,E=jn({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return E.success?T({appliedPolicies:m,removedParticipantId:y}):_({result:E,stack:p})}let I=Uc({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(I.error)return _({result:I,stack:p});let h=I.participantId,S=jn({inContextDrawMatchUps:d,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(!S.success)return _({result:S,stack:p});return T({appliedPolicies:m,removedParticipantId:h});function T({appliedPolicies:y,removedParticipantId:E}){let{structure:P}=at({drawDefinition:i,structureId:c});ad({drawPositions:[a],structure:P});let A={[e]:s,name:n,drawPosition:a,structureId:c};return hu({appliedPolicies:y,drawDefinition:i,positionAction:A}),_({context:{removedParticipantId:E},result:{...C},stack:p})}}function bO({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return bd({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function NP(t){return bO(t)}function GS({params:t,modMap:e,structure:r}){let{tournamentRecord:n,drawDefinition:o,event:i}=t;for(let s of r.matchUps)e[s.matchUpId]&&(s.roundNumber=e[s.matchUpId],gt({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:o,matchUp:s}))}function VS(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=et(t,r);if(n.error)return n;let o=at(t);if(o.error)return o;let i=o.structure;if(!cr({structure:i}))return _({result:{error:si,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=Ke({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:no}}function MP(t){let e=VS(t,[{targetRoundNumber:!0,roundNumber:!0,[He]:Tb}]);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 _({result:{error:B},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?tt(s+1,i+1):tt(i,s),u={};return c.forEach(p=>(n?.[p]??[]).forEach(({matchUpId:m})=>{u[m]=p-(a?1:-1)})),n?.[s]?.forEach(({matchUpId:p})=>u[p]=i),GS({params:t,modMap:u,structure:r}),{...C}}function RP({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:Z};if(!Array.isArray(t))return{error:B};let i="setPositionAssignments";for(let a of t){let{structureId:c,positionAssignments:u}=a;if(!u)continue;let p=at({drawDefinition:n,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:_t};let d=Ct({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(jt(d,l).length!==d?.length)return _({result:{error:B},info:"drawPositions do not match",stack:i});let f=Pe({drawDefinition:n}),{matchUps:g}=ie({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=Wr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:m,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=jn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(E?.error)return E}}ko({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return bt({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...C}}function CP(t){let e=VS(t,[{roundNumbers:!0,[He]:Be,[tr]:s=>s.length===2&&s.every(Jt)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return _({result:{error:B,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]})),GS({params:t,modMap:i,structure:r}),{...C}}function bP({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i}){return bd({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i})}function BS({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{structure:r}=at({drawDefinition:t,structureId:e}),n=(t?.links||[]).filter(i=>i.source?.structureId===e).map(i=>i.target?.structureId);return{playoffStructures:(t?.structures||[]).filter(i=>n.includes(i.structureId)),structure:r}}function Mg({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:Ot};let a={},c=[];for(let u of i.drawDefinitions||[]){let{structures:p,stageStructures:m}=hn({withStageGrouping:t,stageSequences:e,drawDefinition:u,stageSequence:r,roundTarget:n,stages:o,stage:s});if(c.push(...p),m)for(let d of Object.keys(m))a[d]||(a[d]=[]),a[d].push(...m[d])}return{structures:c,stageStructures:a}}function HS({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:q};let a={},c=[];for(let u of e.events||[]){let{structures:p,stageStructures:m}=Mg({withStageGrouping:t,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,event:u,stage:s});if(p&&c.push(...p),m)for(let d of Object.keys(m))a[d]||(a[d]=[]),a[d].push(...m[d])}return{structures:c,stageStructures:a}}function Do(t){if(!t?.drawDefinition)return!1;let e=Mu(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e||{};return r&&(n=n?.filter(({matchUpType:a})=>a===Wt),o=o?.filter(({matchUpType:a})=>a===Wt),i=i?.filter(({matchUpType:a})=>a===Wt)),!!(n?.length&&!o?.length&&!i?.length)}function WS(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:Z};let{playoffStructures:n}=BS({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&Xr.includes(c.entryStatus))?.length??0,i=0;return(n||[]).reduce((c,u)=>!!((Ct({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}function jS({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=jS({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=jS({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 OO({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:qI};if(!Array.isArray(n))return{error:ec};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=OP({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 OP({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:qI};if(!n)return{error:Wi};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(...jS({significantCharacters:p,value:n,accessors:m}))}else if(a){let m=s?.includeIds,d=(e?.[a]||[]).filter(l=>!m||m.includes(l));d?.length&&r?.length&&d.forEach(l=>{let f=r.find(g=>g.participantId===l);if(f?.individualParticipantIds?.includes(n.participantId)){let g=f?.participantId;o.push(g)}})}else c&&Object.keys(c).forEach(m=>{c[m].includes(n.participantId)&&o.push(m)})}),{values:pt(o)}}function vP({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}=OP({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function _O({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 xO(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=_O(t);return r.map(s=>{let a=e.filter(m=>s.includes(m)),c=i(a),p=a.filter(m=>!c.includes(m)).filter(m=>{let d=vO(m);return!n[d]?.includesGroupsToAvoid});return{unassigned:a,unpaired:c,pairedNoConflict:p}});function i(s){return s.filter(c=>!a(c));function a(c){let u=vO(c);return!s.includes(u)}}}function wO(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=_O(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 vO(t){return Number(t%2?t+1:t-1)}function LO({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function FO({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?wO({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):xO({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}));if(i){let a=s.map(p=>p.map(m=>m.unassigned).filter(m=>m?.length)).filter(p=>p?.length).sort((p,m)=>(m.length||0)-(p.length||0)),c=s.map(p=>p.map(m=>m.unpaired).filter(m=>m?.length)).filter(p=>p?.length),u=s.map(p=>p.map(m=>m.pairedNoConflict).filter(m=>m?.length)).filter(p=>p?.length).sort((p,m)=>(m.length||0)-(p.length||0));return{unassigned:a,unpaired:c,pairedNoConflict:u}}else{let a=s.map(p=>p.map(m=>m.unassigned).filter(m=>m?.length)).filter(p=>p?.length),c=s.map(p=>p.map(m=>m.unpaired).filter(m=>m?.length)).filter(p=>p?.length),u=s.map(p=>p.map(m=>m.pairedNoConflict).filter(m=>m?.length)).filter(p=>p?.length);return{unassigned:a,unpaired:c,pairedNoConflict:u}}}function YS({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function kO({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:r=!0,allGroups:n,groupKey:o}){let i=Object.assign({},...Object.keys(n).map(p=>[p,n[p].filter(m=>e.includes(m))]).filter(p=>p[1].length).map(([p,m])=>({[p]:m}))),s=Object.keys(i).reduce((p,m)=>i[m].length>p?i[m].length:p,0),a=Object.keys(i).filter(p=>i[p].length===s),c=r?Un(a):Un(Object.keys(i));return o=t&&i[o]?.length?o:c,{participantId:o&&i[o]?Un(i[o]):Un(e),groupKey:o}}function GO({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 VO({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a}){let u=o.reduce((N,D)=>D.length>N?D.length:N,0)<=2,p=YS({positionAssignments:t,participantIds:e}),m=GO({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=kO({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=LO({participantId:d,allGroups:s}),g=FO({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:f,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:m}),{unassigned:I,unpaired:h,pairedNoConflict:S}=g,T=S?.length&&S[0],y=h?.length&&h[0],E=i&&T?T:y,P=i?y:T,A=E?.length&&E||P?.length&&P,U;if(A?.length){let N=tn(A);U=tn(N)}else{let N=tn(I[0]);U=tn(N)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:U}}function Od({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=Ag({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{ke(s[a[0]].values||[],s[a[1]].values||[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{ke(n[0]?.values||[],n[1]?.values||[])&&(r.push(n),n.conflict=!0)}),r}function BO({positionedParticipants:t,potentialDrawPositions:e,drawPositionGroups:r,avoidanceConflicts:n,isRoundRobin:o}){return n.map(i=>{let s=i.map(c=>c.drawPosition);return i.filter(c=>e.includes(c.drawPosition)).map(c=>{let p=e.filter(m=>!s?.includes(m)).filter(m=>{let d=r.find(T=>T.includes(m)).find(T=>T!==m),l=t.find(T=>T.drawPosition===d),g=Od({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=Od({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function _P(t){let{initialPositionAssignments:e,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:o,drawPositionGroups:i,policyAttributes:s,idCollections:a,allGroups:c}=t,u=[],p,m=Math.min(...(i||[]).map(T=>T?.length).filter(Boolean)),d=m>2,l=J(e,!1,!0).filter(T=>!T.qualifier),f=e.filter(T=>!T.participantId&&(!T.bye||o?.includes(T.drawPosition))).map(T=>T.drawPosition);tt(0,n).forEach(()=>{let{newGroupKey:T,selectedParticipantId:y,targetDrawPosition:E}=VO({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(P=>{P.drawPosition===E&&(P.participantId=y)})});let g=vP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ae(g,m),h=Od({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=BO({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let y=gG({candidatePositionAssignments:l,swapOptions:T});y.error&&console.log({result:y}),g=vP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=Ae(g,m),h=Od({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let y=WI;u.push(y)}if(T.qualifier&&T.participantId){let y=WI;u.push(y)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function gG({candidatePositionAssignments:t,swapOptions:e}){let r=tn(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=tn(r.possibleDrawPositions),i=t.find(u=>u.drawPosition===n),s=t.find(u=>u.drawPosition===o)??{},a={participantId:s?.participantId,qualifier:s?.qualifier,bye:s?.bye},c={participantId:i.participantId,qualifier:i.qualifier,bye:i.bye};return Object.assign(i,a),Object.assign(s,c),{...C}}function HO({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unseededByePositions:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:p,drawSize:m,event:d}){if(!p)return{error:uA};let{candidatesCount:l=1,policyAttributes:f,targetDivisions:g}=p,{roundsToSeparate:I}=p,h="randomUnseededSeparation",{structure:S}=at({drawDefinition:i,structureId:u}),{matchUps:T}=yt({provisionalPositioning:t,matchUpsMap:c,structure:S,event:d});if(g&&Ln(g)&&!I){let G=hC(g)||0,H=T.reduce((K,Y)=>Y.roundNumber>K?Y.roundNumber:K,0);I=H<G?1:H-G+1}let{positionAssignments:y}=Ie({structure:S}),E=Eu({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,P=y?.filter(G=>!G.participantId),A=y?.map(G=>G.drawPosition),U=S?.structureType===Ve,N=U?{structure:S,matchUps:T,allDrawPositions:A,roundsToSeparate:I}:{matchUps:T,allDrawPositions:A,roundsToSeparate:I},{drawPositionGroups:D,drawPositionChunks:M}=U?IG(N):hG(N),R={groupParticipants:a.filter(G=>G.participantType===Qr).map(G=>G.participantId),teamParticipants:a.filter(G=>G.participantType===wt).map(G=>G.participantId),pairParticipants:a.filter(G=>G.participantType===ft).map(G=>G.participantId)},b=OO({targetParticipantIds:e,policyAttributes:f,idCollections:R,participants:a});if(b.error)return _({result:b,stack:h});let O=Object.assign({},...e.map(G=>{let H=Object.keys(b).filter(K=>(b[K]??[]).includes(G));return{[G]:H}})),v=YS({participantIds:e,positionAssignments:y});if(v.length>(P?.length||0))return{error:cf};let x,F=v.length,w=tt(0,l).map(()=>_P({initialPositionAssignments:y,participantsWithGroupings:E,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:O,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));if(x=w.reduce((G,H)=>!G||(H.conflicts||0)<(G.conflicts||0)?H:G,void 0),!x||x.conflicts){let G=tt(0,l).map(()=>_P({initialPositionAssignments:y,participantsWithGroupings:E,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:O,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));x=w.concat(...G).filter(K=>!K.errors?.length).reduce((K,Y)=>!K||(Y.conflicts||0)<(K.conflicts||0)?Y:K,void 0)}if(!x)return{error:ap};let L=(Ct({structure:S})?.positionAssignments??[]).filter(G=>G.participantId).map(G=>G.participantId),k=x.positionAssignments.filter(G=>!L.includes(G.participantId));for(let G of k)if(G.bye){let H=Wr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...G});if(H.error)return _({result:H,stack:h})}else if(G.participantId){let H=jn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...G});if(H.error)return _({result:H,stack:h,context:{assignment:G}})}return{...C}}function IG(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function hG({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(le),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=tt(a===2?1:2,a).filter(d=>d===Cm(d)),m=u.slice(0,e||u.length).reverse().map(d=>Ae(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function WO({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:r,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,structure:p,drawSize:m,event:d}){let l="positionUnseededParticipants";p||({structure:p}=at({drawDefinition:i,structureId:u})),u||({structureId:u}=p);let{positionAssignments:f}=Ie({structure:p}),{seedAssignments:g}=sn({provisionalPositioning:t,drawDefinition:i,structure:p}),I=g?.map(M=>M.participantId).filter(Boolean),{stage:h,stageSequence:S}=p,T=h===ct?mt({element:p,name:vn})?.extension?.value:void 0,E=bi({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:mi,structureId:u,roundTarget:T,stage:h}),A=E.filter(M=>!I?.includes(M.participantId)).map(M=>M.participantId),U=f?.filter(M=>!M.participantId&&!M.bye&&!M.qualifier).map(M=>M.drawPosition);if(!n&&A.length>(U?.length||0))return _({result:{error:cf},context:{unseededParticipantsCount:A.length,unfilledDrawPositionsCount:U?.length},stack:l});let{appliedPolicies:N}=Tt({tournamentRecord:o,drawDefinition:i,event:d}),D=N?.[mu];if(p.stage===fe){let M=E.reduce((R,b)=>(R[b.groupingValue]||(R[b.groupingValue]=[]),R[b.groupingValue].push(b.participantId),R),{});Object.keys(M).length&&(D||(D={policyName:"Playoff Avoidance"}),D.policyAttributes||(D.policyAttributes=[]),D.policyAttributes.push({groupings:M}))}return D&&a?HO({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:D,drawSize:m,entries:E}):SG({provisionalPositioning:t,unseededParticipantIds:A,inContextDrawMatchUps:e,unfilledDrawPositions:U,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d})}function SG({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unfilledDrawPositions:n,multipleStructures:o,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,matchUpsMap:c,structureId:u,drawSize:p,event:m}){let d=p>2?Tr(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=jn({provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,participantId:l,drawPosition:f,matchUpsMap:c,structureId:u,event:m});if(g?.error&&console.log("!!!!!",{result:g}),g?.error)return _({result:g,stack:"randomUnseededDistribution"})}}return{...C}}function jO(t){let e=t.structure??at(t).structure,r="positionQualifiers",n=[];if(e.stage===qe)return _({result:{error:Vi},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=TG(t);for(let a of Object.keys(o)){let c=i?.filter(u=>s[a].includes(u.drawPosition)&&!u.participantId&&!u.qualifier&&!u.bye).map(u=>u.drawPosition);if(o[a]>(c||0))return _({result:{error:af},context:{unfilledDrawPositions:c},stack:r});tt(0,o[a]).forEach(()=>{let u=tn(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...C,qualifierDrawPositions:n}}function TG({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=at({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:n}=Ie({structure:e}),{stage:o,stageSequence:i}=e,{qualifiersCount:s,roundQualifiersCounts:a}=Us({drawDefinition:t,stageSequence:i,structureId:r,stage:o}),u=(a?Object.keys(a):[]).map(h=>dt(h)),{matchUps:p}=yt({structure:e}),{roundProfile:m}=Ke({matchUps:p}),d=Object.assign({},...u.filter(h=>m?.[h]).map(h=>({[h]:m?.[h]?.drawPositions?.filter(Boolean)??[]}))),l=n?.filter(h=>h.qualifier).map(h=>h.drawPosition),f=s-(l?.length??0),g=l?.length;return{unplacedRoundQualifierCounts:Object.assign({},...u.map(h=>{let S=n?.filter(T=>T.qualifier&&d[h]?.drawPositions?.includes(T.drawPosition)).map(T=>T.drawPosition);return{[h]:(a?.[h]??0)-(S?.length??0)}})),unplacedQualifiersCount:f,placedQualifiersCount:g,roundQualifiersCounts:a,positionAssignments:n,roundDrawPositions:d,qualifiersCount:s}}function xP({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,groupsCount:u,structureId:p,matchUpsMap:m,structure:d,event:l}){let f=[],g=[],I=0;if(d||({structure:d}=at({drawDefinition:i,structureId:p})),p||(p=d?.structureId),n||(n=Tt({drawDefinition:i}).appliedPolicies),!o){let h=d&&Ns({provisionalPositioning:t,appliedPolicies:n,drawDefinition:i,seedingProfile:s,structure:d});h?.error&&g.push(h.error),o=h?.validSeedBlocks}return u=u??o?.length??0,tt(0,u).forEach(()=>{if(I<(u||0)){let h=yG({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,structureId:p,matchUpsMap:m,event:l});h?.success&&(I++,f.push(...h.seedPositions??[])),h.error&&g.push({seedPositionError:h.error})}}),g.length?{error:g}:{...C,seedPositions:f}}function yG({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,participants:s,structureId:a,matchUpsMap:c,event:u}){let{unplacedSeedParticipantIds:p,unfilledPositions:m}=xS({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,event:u}),{appliedPolicies:d}=Tt({drawDefinition:n}),{avoidance:l}=d??{};l&&s&&p?.length>2;let f=[];for(let g of p){let I=m.pop();if(!I)return{error:Fs};f.push(I);let h=jn({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,participantId:g,seedBlockInfo:i,drawPosition:I,matchUpsMap:c,structureId:a,event:u});if(!h.success)return h}return{...C,seedPositions:f}}function YO({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=Ie({structure:r}),{seedAssignments:o}=sn({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 qO({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:r}){let n=[];e.forEach(i=>EG(i,r,n,t));let o=n.map(i=>Array.isArray(i)?Tr(i):i).flat(1/0);return _I(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function EG(t,e,r,n){if(e-r.length>t.drawPositions.length)r.push(...t.drawPositions);else{let i=wP(Ae(t.drawPositions,2));AG(i,r,n)}}function AG(t,e,r){let n,o=r[e.length];for(;n=Rg(t,o);)e.push(n),o=r[e.length]}function Rg(t,e){return Array.isArray(t)&&t.length!==2?t.pop():Array.isArray(t[0])?PG(t,e):UG(t,e)}function UG(t,e){return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(Math.random())?t.pop():t.shift()}function PG(t,e){let r=t[0].flat(1/0).length,n=t[1].flat(1/0).length;if(r===n){let o=t[0].flat(1/0).includes(e)?t[0]:t[1];return Rg(e?o:t[Math.round(Math.random())],e)}return r<n?Rg(t[1],e):Rg(t[0],e)}function wP(t){let e=Math.floor(t.length/2);return t.length>2?[wP(t.slice(0,e)),wP(t.slice(e))]:t}function KO({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=Ns({provisionalPositioning:t,appliedPolicies:r,drawDefinition:n,seedingProfile:o,structure:a}));let{isFeedIn:c,isLuckyStructure:u,isContainer:p}=i,{validSeedBlocks:m}=i;r?.seeding?.containerByesIgnoreSeeding&&(m=[]);let d=YO({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=pt([].concat(...e.map(E=>E.drawPositions))),f=d.filter(E=>l.includes(E.drawPosition)),g=(E,P)=>Nc(E.seedValue)-Nc(P.seedValue),h=m.reduce((E,P)=>{let A=f.filter(U=>P.drawPositions?.includes(U.drawPosition)).sort(g);return E.concat(...A)},[]).map(E=>E.drawPosition),S=qO({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=$O({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),y=$O({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function $O({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 zO({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:r,appliedPolicies:n,drawDefinition:o,seedLimit:i,structure:s,isFeedIn:a}){let c=n?.seeding?.seedingProfile,u=s.stage===ct,{positionAssignments:p}=Ie({structure:s}),m=p?.filter(v=>v.participantId).map(v=>v.drawPosition),d={isCollectionMatchUp:!1},{matchUps:l,roundMatchUps:f}=yt({provisionalPositioning:t,matchUpFilters:d,structure:s}),g=f?.[1]||[],I=s.structureType===Ve?l:g,h=pt([].concat(...I.map(v=>v.drawPositions))),S=Math.min(...h)-1,T=m?.filter(v=>h.includes(v)),y=v=>{let x=Math.ceil(v.length/2),F=[v.slice(0,x),v.slice(x)],w=F.map(V=>[].concat(...V.flat(1/0)).length),L=Math.min(...w.flat(1/0)),k=Math.max(...w.flat(1/0)),G=w.indexOf(k),H=L!==k,K=Tr(F),[Y,j]=!L||H?[F[G],F[1-G]]:[K[0],K[1]];return{greaterHalf:Y,lesserHalf:j}},E=v=>{let{greaterHalf:x,lesserHalf:F}=y(v),{greaterHalf:w,lesserHalf:L}=y(x),G=Tr(w.flat(1/0)).pop(),H=w.flat().filter(Y=>Y!==G);return{newlyFilteredChunks:[...F,...L,H],drawPosition:G}},P=v=>!e.includes(v),A=v=>!T?.includes(v),U=v=>{let F=Ae(v.sort(le),Math.ceil(v.length/4)).map(k=>k.filter(A)),w=[].concat(...F.flat(1/0)).length,L=[];for(let k=0;k<w;k++){let{newlyFilteredChunks:G,drawPosition:H}=E(F);L.push(H),F=G}return L},{validSeedBlocks:N}=Ns({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),D=N?.map(v=>v.drawPositions?.map(x=>x+S)),M;if(a){let v=h.length,{seedBlocks:x}=Pg({cluster:Bp(c)===nu,participantsCount:v});M=x.map(w=>w.map(L=>L+S)).map(U).filter(w=>w.length)}else u?M=D?.map(v=>v.filter(A)):M=D?.map(U).filter(v=>v.length);let R=I.map(v=>v.drawPositions).map(v=>v?.sort((x,F)=>x-F)).filter(v=>v?.[0]+1===v?.[1]),b=v=>R.reduce((x,F)=>F.includes(v)?F.reduce((w,L)=>L!==v?L:w,void 0):x,void 0),O=M.map(v=>v.map(b)).flat(1/0).filter(A).filter(P).filter(Boolean);if(u&&!s.structures){let v=i%4,x=O.slice(0,v),F=f[s.roundLimit]?.length,w=Ae(O.slice(v),F).map(Tr).flat();O=x.concat(w)}return{unseededByePositions:O}}function QO({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=yt({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]||[],u=n?.structureType===Ve,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=bi({entryStatuses:Xr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=Us({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=Ie({structure:n}),y=T?.map(D=>D.drawPosition),E=S?.filter(D=>D.bye).length,P=S?.filter(D=>D.bye).map(D=>D.drawPosition),A=p.map(D=>D.drawPositions).filter(D=>D?.reduce((M,R)=>!P?.includes(R)&&M,!0)).flat(1/0).filter(D=>y?.includes(D)),U=S?.length,N=U?U-h:0;return N>m&&n.stageSequence===1&&n.stage!==qe&&(N=m),{placedByes:E,byesCount:N,relevantMatchUps:p,placedByePositions:P,roundMatchUps:a,positionsToAvoidDoubleBye:A}}function LP({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,seedBlockInfo:o,seedingProfile:i,matchUpsMap:s,structureId:a,structure:c,seedLimit:u,seedsOnly:p,event:m}){c||({structure:c}=at({drawDefinition:n,structureId:a})),a||(a=c?.structureId);let d=!(c?.structures??c?.stage===ct),{byesCount:l,placedByes:f,relevantMatchUps:g}=QO({provisionalPositioning:t,drawDefinition:n,matchUpsMap:s,structure:c,event:m}),I=l-(f||0);if(I<=0)return{...C};let{strictSeedOrderByePositions:h,blockSeedOrderByePositions:S,isLuckyStructure:T,isFeedIn:y}=KO({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),E=c?.structureType&&[Ve,hp].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,P=d&&S?.length?S:h,{unseededByePositions:A}=zO({provisionalPositioning:t,seedOrderByePositions:P,isLuckyStructure:T,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:y}),U=R=>R%2,N=(R,b)=>(R||[]).every(O=>U(O)?b!==O+1:b!==O-1),D=[].concat(...P);if(!p)for(;A.length;){let R=A.find(b=>N(D,b));R?(D.push(R),A=A.filter(b=>b!==R)):(D.push(...A),A=[])}E&&(D=Tr(D),Dr({ignoreSeededByes:E})&&console.log({byePositions:D}));let M=D.slice(0,I);for(let R of M){let b=Wr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:R,matchUpsMap:s,structureId:a,structure:c,event:m});if(b?.error)return b}return{...C,unseededByePositions:A,byeDrawPositions:M}}function Mc(t){let{drawDefinition:e}=t,{applyPositioning:r=!0,provisionalPositioning:n,multipleStructures:o,placeByes:i=!0,tournamentRecord:s,placementGroup:a,seedingProfile:c,structureId:u,seedLimit:p,seedsOnly:m,drawType:d,drawSize:l,event:f}=t,g=[];r||(zA(),e=J(e,!1,!0));let I=x=>(r||hf(),_({result:x,stack:"automatedPositioning"})),h=x=>(r||hf(),x),S=at({drawDefinition:e,structureId:u});if(S.error)return I(S);let T=S.structure;if(!T)return{error:_t};let y=t.appliedPolicies||Tt({drawDefinition:e,structure:T,event:f})?.appliedPolicies,{qualifiersCount:E}=Us({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,drawDefinition:e,structureId:u}),P=mi;if(!bi({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,placementGroup:a,drawDefinition:e,entryStatuses:P,structureId:u})?.length&&!E)return h({...C});let U=t.matchUpsMap??Pe({drawDefinition:e}),N=t.inContextDrawMatchUps??ie({inContext:!0,drawDefinition:e,matchUpsMap:U})?.matchUps,D=[],M=Ns({provisionalPositioning:n,appliedPolicies:y,drawDefinition:e,seedingProfile:c,structure:T});if(M.error)return M;let{validSeedBlocks:R}=M;g.push({validSeedBlocks:R});let b=t.participants||(s?Ft({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]);if(Bp(T.seedingProfile||c)===Ti){let x=i?LP({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:M,matchUpsMap:U,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(x?.error)return I(x);D=x.unseededByePositions,g.push({action:"positionByes",unseededByePositions:D});let F=T.seedingProfile?{positioning:T.seedingProfile}:c;if(x=xP({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:U,structure:T,event:f}),x.error)return I(x);g.push({seedPositions:x.seedPositions,action:"positionSeedBlocks"})}else{if(d!==Ki){let F=T.seedingProfile?{positioning:T.seedingProfile}:c,w=xP({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:U,structure:T,event:f});if(w.error)return I(w);g.push({action:"positionSeedBlocks",seedPositions:w.seedPositions})}let x=i?LP({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:M,matchUpsMap:U,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(x?.error)return I(x);D=x?.unseededByePositions,g.push({action:"positionByes",byeDrawPositions:x?.byeDrawPositions,unseededByePositions:D})}let O={};if(!m){let x=jO({inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:U,structure:T});if(x.error||(x.conflicts&&(O.qualifierConflicts=x.conflicts),g.push({action:"positionQualifiers",qualifierDrawPositions:x.qualifierDrawPositions}),x=WO({provisionalPositioning:n,inContextDrawMatchUps:N,unseededByePositions:D,multipleStructures:o,tournamentRecord:s,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:U,structureId:u,structure:T,drawSize:l,event:f}),x.error))return I(x);x.conflicts&&(O.unseededConflicts=x.conflicts),g.push({action:"positionUnseededParticipants"})}let{positionAssignments:v}=Ct({drawDefinition:e,structure:T});return bt({drawDefinition:e,structureIds:[u]}),r||hf(),{positionAssignments:v,conflicts:O,...C,positioningReport:g}}function na(t){let{applyPositioning:e=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,placeByes:a,seedsOnly:c}=t;if(!o)return{error:br};if(!Do({drawDefinition:o,structureId:s})&&!r)return{error:jl};let p=BS({drawDefinition:o,structureId:s}).playoffStructures?.sort((l,f)=>Wf(l)-Wf(f)),m=[],d=[];if(p)for(let l of p){let{structureId:f}=l,g=Mc({structureId:f,provisionalPositioning:r,applyPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,placeByes:a,seedsOnly:c});if(g.error)return g;g.positionAssignments&&m.push({positionAssignments:g.positionAssignments,structureId:f}),g.positioningReport&&d.push(g.positioningReport)}return{...C,structurePositionAssignments:m,positioningReports:d}}function FP({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:Z};if(!o)return{error:Pr};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:ln};let{structure:c}=at({drawDefinition:r,structureId:o});if(!c)return{error:_t};if(!(!t||Jt(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>Jt(l)&&dt(l)>0)))return{error:B};let{seedAssignments:p}=sn({drawDefinition:r,structure:c}),m=p?.map(l=>l.seedNumber),d=p?.find(l=>l.participantId===n);if(d){let l=typeof i=="string"?i.includes("-")&&i.split("-").map(f=>parseInt(f)).join("-")||parseInt(i)>0&&parseInt(i)||"":i&&i>0&&i||"";d.seedValue=l}else{let f={seedNumber:Math.max(0,...m||[])+1,participantId:n};i&&(f.seedValue=i),c.seedAssignments||(c.seedAssignments=[]),c.seedAssignments.push(f)}return rS({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...C}}function Cg({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return bd({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function vu({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=Js({drawDefinition:r,structureId:n})||{},a=(i?.target||[]).filter(({linkType:u})=>u===o).filter(({target:u})=>!t||t===u.roundNumber).map(u=>{let p=u.source.structureId,{structure:m}=at({structureId:p,drawDefinition:r});if(!(e&&m?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}var XO=(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((m,d)=>!o.has(d));for(;o.has(p)&&p===-1&&o.size<t.length;)p=t.findIndex((m,d)=>!o.has(d)&&d>p);i.push(u),o.add(u)}});let s=t.filter((a,c)=>!o.has(c));return[...i,...s]};function kP({targetRoundNumber:t=1,tournamentRecord:e,drawDefinition:r,event:n,randomList:o}){let i=et({drawDefinition:r,event:n,tournamentRecord:e},[{[Ce]:!0,[co]:!0,[ne]:!0}]);if(i.error)return i;let s=[],a=[],c=r.structures?.find(S=>S.stage===rt&&S.stageSequence===1);if(!c)return _({result:{error:zl}});let m=(Tt({tournamentRecord:e,drawDefinition:r,structure:c,event:n}).appliedPolicies??{})[Jn]?.requireCompletedStructures,{qualifierPositions:d,positionAssignments:l}=Ie({structure:c});if(!d.length)return _({result:{error:af}});let f=tt(0,d.length);o&&(f=XO(f,o));let g=l.map(S=>S.participantId).filter(Boolean),{relevantLinks:I}=vu({structureId:c.structureId,targetRoundNumber:t,linkType:Xn,drawDefinition:r})||{},{relevantLinks:h}=vu({structureId:c.structureId,targetRoundNumber:t,linkType:Fn,drawDefinition:r})||{};for(let S of I){let T=r.structures?.find(E=>E.structureId===S.source.structureId);if(T?.stage!==ct)continue;let y=Do({structureId:S.source.structureId,drawDefinition:r});if(!m||y){let E=T.qualifyingRoundNumber,{matchUps:P}=yt({matchUpFilters:{...E&&{roundNumbers:[E]},isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,inContext:!0,structure:T});for(let A of P){let U=A.matchUpStatus==="BYE"&&A.sides?.find(({participantId:D})=>D),N=A.sides.find(D=>D?.sideNumber===A.winningSide);if(N||U){let{participantId:D}=N||U||{};D&&!g.includes(D)&&a.push(D)}}}}for(let S of h){let T=r?.structures?.find(E=>E.structureId===S.source.structureId);if(T?.stage!==ct)continue;if(Do({structureId:S.source.structureId,drawDefinition:r})){let{positionAssignments:E}=Ct({structure:T}),P=E?.map(A=>{let U=A.participantId,N=mt({element:A,name:Lo}).extension?.value;return N?{participantId:U,groupOrder:N?.groupOrder}:{}}).filter(({groupOrder:A,participantId:U})=>A===1&&!g.includes(U)).map(({participantId:A})=>A)??[];P&&a.push(...P)}}return a.length?(f.forEach((S,T)=>{let y=a[T],E=d[S].drawPosition;y&&Cg({qualifyingParticipantId:y,structureId:c.structureId,drawPosition:E,tournamentRecord:e,drawDefinition:r})?.success&&s.push({participantId:y,drawPosition:E})}),_({result:nt({...C,assignedParticipants:s})})):_({result:{error:yA}})}function GP({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>It(r)))&&_({result:{error:B},context:{orderMap:e}}),t.structures||(t.structures=[]),t.structures.forEach(r=>{let n=e[r.structureId];n&&(r.structureOrder=n)}),t.structures.sort((r,n)=>za(r.structureOrder)-za(n.structureOrder)),{...C}):{error:Z}}function _u({drawDefinition:t}){let e=t.structures??[],r=t.links??[],n=new Map,o=I=>{let h=n.get(I)||n.set(I,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&n.get(I);if(h&&!h?.stage){let S=e.find(T=>T.structureId===I);h.stage=S?.stage}return h},i={},s={},a=r.map(I=>{let h=I.source.structureId,S=I.target.structureId,T=o(h),y=o(S);return[yi,Nn,Sp,Ti].includes(I.target.feedProfile)?(T?.targets.push(S),y?.sources.push(h)):I.target.feedProfile===fn&&(y?.drawSources.push(h),T?.drawTargets.push(S)),s[S]=s[S]||I.target.feedProfile===fn,i[S]=pt([...i[S]||[],h]).filter(Boolean),[I.source.structureId,I.target.structureId]});for(let I of n.keys()){let h=n.get(I);if(h){let S=h.targets??[];for(;S.length;){let T=S.pop(),y=T&&n[T];y?.targets?.length?S.push(...y.targets):y&&(h.rootStage=y.stage)}if(h.rootStage||(h.rootStage=h.stage),!h.targets?.length){let T=h.sources??[];for(;T.length;){let y=T.pop(),E=y&&n[y];if(E?.sources?.length){for(let P of E.sources)h.progeny?.includes(P)||h.progeny?.push(P);T.push(...E.sources)}}}}}let c=0;for(let I of n.keys()){let h=n.get(I);if(h&&h.rootStage===ct){let S=[h.drawTargets?.[0]],T=0;for(;S.length;){T+=1;let y=S.pop(),E=y?n.get(y):void 0;E?.drawTargets?.length&&S.push(E.drawTargets[0])}h.distanceFromMain=T,T>c&&(c=T)}}let u=a.length;tt(0,Math.ceil(u/2)).forEach(()=>{a=tt(0,u).map(I=>{let h=a[I],S=a.reduce((T,y)=>ke(h,y)?T.concat(...y):T,[])||[];return pt(h.concat(...S))})});let p=a[0],m=(I,h)=>jt(I,h).length===I.length,d=a.slice(1).reduce((I,h)=>I&&m(h,p),!0),l=[p].filter(Boolean),f=[p].filter(Boolean);e.forEach(I=>{let{structureId:h,stage:S}=I;l.find(y=>y.includes(h))||(l.push([h]),S!==$e&&f.push([h]))});let g=d&&f.length===1;return!r?.length&&e.length===1&&o(e[0].structureId),{structureProfiles:Object.fromEntries(n),allStructuresLinked:g,maxQualifyingDepth:c,sourceStructureIds:i,hasDrawFeedProfile:s,structureGroups:l}}function qS({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=_u({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...C}}function bg(t){let e=et(t,[{[ne]:!0,[Ce]:!0}]);if(e.error)return e;let{tournamentRecord:r,drawDefinition:n,structure:o,link:i}=t;return DG({tournamentId:r.tournamentId,drawDefinition:n,structure:o,link:i})}function DG(t){let e=et(t,[{[Ce]:!0,[Ep]:!0},{link:!0,[He]:zr,[VE]:$l}]);if(e.error)return e;let{drawDefinition:r,tournamentId:n,structure:o,eventId:i,link:s}=t,a=s.target.structureId,c=at({drawDefinition:r,structureId:a});if(c.error)return _({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:c});r.structures||(r.structures=[]),r.links||(r.links=[]),r.structures.push(o),r.links.push(s),qS({drawDefinition:r});let u=yt({structure:o})?.matchUps||[];return Fo({drawDefinition:r,tournamentId:n,matchUps:u,eventId:i}),bt({drawDefinition:r,structureIds:[o.structureId]}),{...C}}function VP({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:B};if(!t)return{error:Z};let r=Object.assign({},...e.map(n=>{if(!ht(n))return;let{structureId:o,structureName:i}=n||{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:st};for(let n of t.structures||[]){let o=r[n.structureId];if(o&&(n.structureName=o),n.structures)for(let i of n.structures){let s=r[i.structureId];s&&(i.structureName=s)}}return{...C}}function Og({drawDefinition:t,timeItem:e}){if(!t)return{error:br};if(!e)return{error:mf};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:pf};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Ma({drawDefinition:t}),{...C}}function BP(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=et(t,[{drawDefinition:!0,structureId:!0}]);if(i.error)return i;let s=r.structures??[],a=s.find(h=>h.structureId===n);if(!a)return{error:_t};let c=s.find(({stage:h,stageSequence:S})=>h===rt&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===ct).map(Hr("structureId"));if(u&&!p.length)return{error:BE};let m=p.includes(n),d=NG({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=RG({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=CG({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(MG({removedMatchUpIds:g,drawDefinition:r}),u){let h=(c.matchUps??[])?.map(Hr("matchUpId"));g.push(...h),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&qS({drawDefinition:r}),_n({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),bt({drawDefinition:r,eventId:o?.eventId}),{...C,removedMatchUpIds:g,removedStructureIds:I}}function NG({isQualifyingStructure:t,tournamentRecord:e,drawDefinition:r,structureId:n,structure:o,event:i,force:s}){let a=[n];if(t){let p=d=>r.links?.find(l=>l.target.structureId===d),m=p(n)?.source.structureId;for(;m;)a.push(m),m=p(m)?.source.structureId}if(ie({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>he({score:p}))){let p=Tt({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[rn]?.allowDeletionWithScoresPresent?.structures))return{error:oc}}return{...C}}function MG({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=ie({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function RG({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Hr("structureId")),c=d=>o.links?.map(l=>l.source.structureId===d&&l.target.structureId!==n?.structureId&&l.target.structureId).filter(Boolean)??[],u=d=>o.links?.map(l=>t.includes(l.source.structureId)&&l.target.structureId===d&&l.source.structureId).filter(Boolean)??[],p=new Map;return a.forEach(d=>p.set(d,e?u(d):c(d))),{structureIdsToRemove:r?p.get(i):[i],relatedStructureIdsMap:p}}function CG({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(...vG({idBeingRemoved:u,drawDefinition:o}));let p=OG({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=bG({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function bG({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function OG({qualifyingStructureIds:t,isMainStageSequence1:e,idBeingRemoved:r,drawDefinition:n,structureId:o}){let i=[];return n.links=n.links?.filter(s=>s.source.structureId!==r&&s.target.structureId!==r)??[],(!e||e&&t.length||r!==o)&&(n.structures=(n.structures??[]).filter(s=>(r&&r===s.structureId&&i.push(r),s.structureId!==r))),{removedStructureIds:i}}function vG({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=at({structureId:t,drawDefinition:e}),n=yt({structure:r}).matchUps;return od(n)}function Hp({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:Z};if(!ug({drawDefinition:e,stage:n}))return{error:Vi};let o=Fb({drawDefinition:e,stage:n}),{qualifiersCount:i}=Us({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:HI};let{entryProfile:a}=ng({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return bt({drawDefinition:e}),{...C,entryProfile:a}}function $S({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?ug({drawDefinition:e,stage:r})?r!==rt?{error:HI,info:"qualifiersCount can only be set for main stage"}:(ng({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),bt({drawDefinition:e}),{...C}):{error:Vi}:{error:Z}}function JO({drawDefinition:t,drawSize:e}){if(!t)return{error:Z};let r=Hp({stage:$e,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(bt({drawDefinition:t}),{...C})}function HP(t){return JO(t)}function WP({tournamentRecord:t,drawDefinition:e,event:r,structureId:n}){if(!e)return{error:Z};let o=e.structures?.find(a=>a.stage===ct&&a.structureId===n);if(!o)return{error:_t};if(o.matchUps?.some(({matchUpStatus:a,score:c})=>he({score:c})??ae.includes(a)))return{error:oc};let s=o.matchUps?.map(({matchUpId:a})=>a)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],_n({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:s,drawDefinition:e}),bt({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}var ZO="qualifierDrawPositionAssignment",tv="withdrawParticipantAtDrawPosition",ev="alternateDrawPositionAssignment",rv="luckyLoserDrawPositionAssignment",jP="removeDrawPositionAssignment",KS="swapDrawPositionAssignments",nv="modifyPairAssignment",ov="adHocPositionSwap",iv="modifyParticipantOtherName",YP="assignDrawPosition",sv="removeSeededParticipant",av="assignDrawPositionBye",cv="modifySeedAssignment",zS="addPenalty",vg="MODIFY_PAIR",Wp="QUALIFIER",_g="ALTERNATE",xg="WITHDRAW",Ms="ASSIGN",QS="REMOVE",wg="LUCKY",jp="REMOVE_SEED",Yp="SWAP",xu="NICKNAME",oa="SEED_VALUE",ia="PENALTY";var uv={MODIFY_PAIR_ASSIGNMENT:vg,QUALIFYING_PARTICIPANT:Wp,ALTERNATE_PARTICIPANT:_g,WITHDRAW_PARTICIPANT:xg,ASSIGN_PARTICIPANT:Ms,LUCKY_PARTICIPANT:wg,REMOVE_ASSIGNMENT:QS,SWAP_PARTICIPANTS:Yp,ADD_NICKNAME:xu,REMOVE_SEED:jp,ADD_PENALTY:ia,ASSIGN_BYE:"BYE",SEED_VALUE:oa};function qP({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:Z};if(!n)return{error:Pr};if(r?.length!==2)return{error:B,drawPositions:r};let i=Pe({drawDefinition:e}),{matchUps:s}=ie({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=at({drawDefinition:e,structureId:n});if(!a)return{error:_t};let c=Tt({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===Ve?u=wG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=_G({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(ad({structure:a,drawPositions:r}),hu({appliedPolicies:c,drawDefinition:e,positionAction:{name:KS,drawPositions:r,structureId:n}}),ko({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===Or){let m=yt({matchUpFilters:{matchUpTypes:[xr]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),d=yt({matchUpFilters:{matchUpTypes:[xr]},structure:a}).matchUps;m.forEach(l=>{(l.sides||[]).forEach(f=>{let g=f?.drawPosition;if(r.includes(g)){let I=f.participantId,h=d.find(({matchUpId:T})=>T===l.matchUpId),S=l?.sides?.reduce((T,y,E)=>y.drawPosition===g?E:T,void 0);Nd({inContextTargetMatchUp:l,drawPositionSideIndex:S,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:h,event:o})}})})}return bt({drawDefinition:e,structureIds:[n]}),{...C}}function _G({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:B,structure:i,info:"Missing positionAssignments"};if(a.filter(({bye:p})=>p).length===2)return{...C};if(a.filter(({qualifier:p})=>p).length===2)return{...C};let c=a.some(({qualifier:p})=>p);return a.some(({bye:p})=>p)&&!c?pv({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):xG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function pv({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:n,matchUpsMap:o,structure:i,event:s}){let a=n.find(({bye:f})=>f),c=n.find(({participantId:f})=>f),u=a.drawPosition,{participantId:p,drawPosition:m}=c,{structureId:d}=i,l=Ou({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=Ou({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Wr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=jn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...C}}function xG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:n,matchUpsMap:o,structure:i,event:s}){let a=Object.assign({},...n.map((c,u)=>{let{drawPosition:p}=c,m={...n[1-u],drawPosition:p};return{[p]:m}}));return i.positionAssignments=i.positionAssignments.map(c=>a[c.drawPosition]||c),Ng({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...C}}function wG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i.structures?.reduce((p,m)=>{let d=m?.positionAssignments.filter(l=>n?.includes(l.drawPosition));return d&&p.push(...d),p},[]);if(a.filter(({bye:p})=>p).length===2)return{...C};if(a.filter(({qualifier:p})=>p).length===2)return{...C};Ng({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)pv({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s});else{let p=J(a,!1,!0);a.forEach((m,d)=>{let l=p[1-d].participantId;m.qualifier=p[1-d].qualifier,m.participantId=l})}return{...C}}function $P({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:q};if(!e)return{error:Z};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![rt,ct].includes(i.stage)||i.stage===rt&&i.stageSequence!==1?_({result:{error:si},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...C}:_({info:"participant not seeded",result:{error:Oe},context:{participantId:r}}):_({result:{error:_t},stack:o})}function La({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=Xn}){return!n||!o?{error:Pr}:{link:nt({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:fn,roundNumber:t,structureId:o}})}}function Li({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>wu({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function wu({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:r,matchUp:n,isMock:o,uuids:i}){let{matchUpCount:s,matchUpType:a,collectionId:c,processCodes:u}=e||{},p=r??s??0,m=d=>{if(!o&&!n?.isMock)return i?.pop()??Nt();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return tt(0,p).map(d=>{let l=t+d+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:m(d),matchUpStatus:Qt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function vd({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Nt()}function qp({includeMatchUpType:t,matchUpType:e,roundNumber:r,matchUps:n,idPrefix:o,isMock:i,uuids:s,nodes:a}){let c=0,u=[],p=1,m=r-1,d=a?.length;for(;c<(d||0);){let l=a?.[c],f=a?.[c+1];m&&(l.roundNumber=m),f&&m&&(f.roundNumber=m);let g=vd({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:Qt,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 xn({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&&(!Ln(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(!Ln(a)&&!p)return{matchUps:[],roundsCount:0};let m=tt(1,a+1).map(I=>({drawPosition:I})),d,l=[],f=1;for({roundNodes:d,matchUps:l}=qp({matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,nodes:m,uuids:u}),f++,i=i??r;d.length>1;)n&&d.length===n&&(i=f-1),{roundNodes:d,matchUps:l}=qp({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=ba({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 _d(t){let e="generateQualifyingStructure";if(!t.drawDefinition)return _({result:{error:Z},stack:e});if(t.drawSize&&!It(t.drawSize)||t.participantsCount&&!It(t.participantsCount)||t.qualifyingPositions&&!It(t.qualifyingPositions))return _({result:{error:B},stack:e});let r=t.drawSize??Rm(t.participantsCount),{hasExistingDrawDefinition:n,qualifyingRoundNumber:o,qualifyingPositions:i,targetStructureId:s,structureOptions:a,appliedPolicies:c,qualifyingOnly:u,drawDefinition:p,matchUpFormat:m,structureName:d,structureId:l,roundTarget:f,tieFormat:g,drawType:I,idPrefix:h,isMock:S,uuids:T}=t;if(!t.drawSize)return _({result:{error:Za},context:{drawSize:r},stack:e});if(i&&i>=t.drawSize)return _({result:{error:B},context:{drawSize:r,qualifyingPositions:i},stack:e});let y,E,P,A,U=0,N,D=1,{structureProfiles:M}=_u({drawDefinition:p}),R=M[s];if(!R)return _({result:{error:_t},context:{targetStructureId:s},stack:e});let b=p.matchUpType,O=f?`${f}-`:"",v=R.stage===ct,x=c?.[vo]?.namingConventions?.pre??Bb[vo]?.namingConventions?.pre,F=v&&x?`${x}-`:"",w=d??(O?`${F}${Qe(ct)} ${O}`:`${F}${Qe(ct)}`);if(I===On){let{maxRoundNumber:G,structures:H,groupCount:K}=xa({structureName:d??w,structureId:l??T?.pop(),hasExistingDrawDefinition:n,stage:ct,structureOptions:a,appliedPolicies:c,qualifyingOnly:u,stageSequence:D,matchUpType:b,roundTarget:f,tieFormat:g,idPrefix:h,drawSize:r,isMock:S,uuids:T});U=K,y=G,P=H[0],N=[1]}else({drawSize:r,matchUps:A,roundLimit:y,roundsCount:E}=xn({qualifyingRoundNumber:o,qualifyingPositions:i,matchUpType:b,idPrefix:h,drawSize:r,isMock:S,uuids:T})),y||(y=E),P=yn({structureName:d??w,structureId:l??T?.pop(),qualifyingRoundNumber:y,stage:ct,matchUpFormat:m,stageSequence:D,matchUpType:b,roundLimit:y,matchUps:A}),f&&At({extension:{name:vn,value:f},element:P}),U=A?.filter(G=>G.roundNumber===y)?.length;let L=I===On?Fn:Xn,k=P&&y&&La({sourceStructureId:P.structureId,sourceRoundNumber:y,targetStructureId:s,finishingPositions:N,linkType:L})?.link;return g&&(A=yt({structure:P})?.matchUps||[],A?.forEach(G=>{let{tieMatchUps:H}=Li({tieFormat:g,matchUp:G,isMock:S});Object.assign(G,{tieMatchUps:H,matchUpType:b})})),{qualifyingDrawPositionsCount:r,qualifiersCount:U,...C,structure:P,link:k}}function KP(t){if(!t.tournamentRecord)return{error:q};let r=LG(t);return r.error,r}function LG(t){if(!t.drawDefinition)return{error:Z};if(!t.targetStructureId)return{error:Pr};let e=_d(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:B}:bg({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function zP(t){let e=et(t,[{[Ce]:!0,[cu]:!0,[gn]:!0},{[lb]:!0,[tr]:m=>Number.isInteger(m)&&m>0},{[tr]:m=>Array.isArray(m)&&m.length===2&&m.every(kt),[kr]:wr,participantIds:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n,tournamentRecord:o,event:i}=t,{structure:s}=at({drawDefinition:r,structureId:n});if(!s)return{error:_t};if(!cr({structure:s}))return{error:si};let a=m=>m.sides?.map(d=>d.participantId).some(d=>t.participantIds.includes(d)),c=m=>m.roundNumber===t.roundNumber,u=m=>!he(m),p=(s?.matchUps??[]).filter(c).filter(u).filter(a);if(p.length!==2)return{error:wr};for(let m of p){let d=m?.sides?.find(l=>t.participantIds.includes(l?.participantId));if(d){let l=t.participantIds.find(f=>f!==d?.participantId);d.participantId=l,gt({tournamentId:o?.tournamentId,eventId:i?.eventId,drawDefinition:r,matchUp:m})}}return bt({drawDefinition:r,structureIds:[n]}),{...C}}function mv({includeMatchUpType:t,drawPosition:e,roundNumber:r,matchUpType:n,idPrefix:o,matchUps:i,isMock:s,uuids:a,nodes:c,fed:u}){let p=c.length,m=e?e-p:void 0,d=tt(0,p).map(g=>m?m+g:void 0),l=[];for(let g=0;g<p;g++){let I=d.shift(),h={drawPosition:I,fed:u+1,feed:!0},S=c[g];S.roundNumber=r-1;let T=vd({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:Qt,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 fi(t){let e=t.drawSize,{feedRoundsProfile:r,feedRounds:n=0,skipRounds:o=0,baseDrawSize:i}=t,{linkFedFinishingRoundNumbers:s,finishingPositionOffset:a,linkFedRoundNumbers:c,feedsFromFinal:u,isConsolation:p,matchUpType:m,idPrefix:d,isMock:l,uuids:f,fmlc:g}=t;i=i??F(e);let I=FG({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((w,L)=>w+L,0);else if(e){let w=e-i;r=I.filter(L=>L<=w?(w-=L,!0):!1),S=r.reduce((L,k)=>L+k,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((w,L)=>u&&!n||n&&L>=o+n||L<o?0:w),S=r.reduce((w,L)=>w+L,0),n=r.length;let T=[...I,...r].sort((w,L)=>L-w),y=T.length,P=[...(c??[]).map(w=>w-1),...(s??[]).map(w=>y-w)].map(w=>T[w]).reduce((w,L)=>w+L,0);S=S-P;let A=0,U=[],N,D=1,R=tt(0,i).map((w,L)=>({drawPosition:L+1+S})),b=S+1;for(let w of I){if({roundNodes:N,matchUps:U}=qp({matchUpType:m,roundNumber:D,idPrefix:d,matchUps:U,isMock:l,nodes:R,uuids:f}),D++,r.includes(w)){let L=Er(r)[w],k=tt(0,L),G=y+1-D,H=s?.includes(G)??c?.includes(D);k.forEach(()=>{({roundNodes:N,matchUps:U,drawPosition:b}=mv({drawPosition:!H&&b||void 0,nodes:N,matchUpType:m,roundNumber:D,idPrefix:d,matchUps:U,isMock:l,uuids:f,fed:A})),D++,A+=1})}R=N}y!==D-1&&console.log("ERROR");let O=i-S;U=ba({finishingPositionOffset:p?O:a,positionsFed:S,roundsCount:y,matchUps:U,fmlc:g});let x=N?.length?N[0]:N;return x&&(x.roundNumber=D-1,x.matchUps=U),{draw:x,matchUps:U,roundsCount:y};function F(w){let L=Cm(w);return L>w?L/2:L}}function FG({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return tt(0,e).reverse().map(n=>Math.pow(2,n))}function Rc(t){let{finishingPositionOffset:e=0,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,stageSequence:a=1,exitProfile:c="0",exitProfileLimit:u,roundOffsetLimit:p,roundOffset:m=0,drawDefinition:d,staggeredEntry:l,sequenceLimit:f,stage:g=rt,drawSize:I,idPrefix:h,isMock:S,uuids:T}=t;if(!(!s||!u||s?.[c])||I<2||f&&a>f)return{};let E=[],P=[],A=[],U=t.matchUpType??d?.matchUpType,N=e+1,D=e+I,M=`${N}-${D}`,R=s?.[c],b=n&&`${n} `||"",O=s?.[M]??o?.[M],v=t.structureName||O?.name||R?.name&&(r?`${b}${R?.name}`:R.name)||`${b}${M}`,x=O?.abbreviation??R?.abbreviation,F=t.structureId??R?.structureId??T?.pop(),w={idPrefix:h&&`${h}-${v}-RP`,finishingPositionOffset:e,matchUpType:U,drawSize:I,isMock:S,uuids:T},{matchUps:L}=l?fi(w):xn(w),k=yn({structureAbbreviation:x,stageSequence:a,structureName:v,matchUpType:U,roundOffset:m,structureId:F,matchUps:L,stage:g});E.push(...L),P.push(k);let G=Math.ceil(Math.log(I)/Math.log(2)),H=p?Math.min(p-m,G):(!i||N<i)&&G||0;return I>2&&tt(1,H+1).forEach(Y=>K(Y)),{structureId:k.structureId,matchUps:E,structureName:v,structures:P,links:A,...C};function K(Y){let j=I/Math.pow(2,Y);if(j<2)return;let V=I/Math.pow(2,Y)+e;if(i&&V+1>i)return;let{structures:$,structureId:X,matchUps:W,links:it}=Rc({finishingPositionOffset:V,exitProfile:`${c}-${Y}`,roundOffset:m+Y,stageSequence:a+1,drawSize:j,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:d,sequenceLimit:f,matchUpType:U,idPrefix:h,uuids:T,stage:g});if(k.structureId&&X){let z={linkType:so,source:{roundNumber:Y,structureId:k.structureId},target:{roundNumber:1,feedProfile:Nn,structureId:X}};it&&k&&it.push(z),it?.length&&A.push(...it)}return $?.length&&P.push(...$),W?.length&&E.push(...W),{structureId:X,childLinks:it,structures:P}}}function xd({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=at({drawDefinition:t,structureId:r});if(n.error)return _({result:n});let{matchUps:o}=yt({structure:n.structure,matchUpsMap:e});return{...Ke({matchUps:o}),matchUps:o,matchUpsMap:e}}function QP({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=xd({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(dv(n?.[s]).forEach(c=>{t.forEach(u=>{kG({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function kG({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return tt(r,(n||r)+1).includes(t)}function dv(t){return[pt(t?.finishingPositionRange?.loser||[]),pt(t?.finishingPositionRange?.winner||[])]}function lv(t){return dv(t).map(e=>tt(e[0],e[1]&&e[1]+1||e[0]+1))}function Cc({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:B,context:{structureIds:e}};if(!t)return{error:Z};e=e??(t.structures??[]).filter(a=>a.stage!==ct).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=xd({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(lv).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(le).flat();return{positionsNotPlayedOff:pt(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function XS({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){if(!r)return{error:Z};if(!n)return{error:Pr};if(!e)return{error:st,info:"missing playoffPositions"};let o=Cc({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=QP({finishingPositions:s,drawDefinition:r,structureId:n}),u=Object.values(a).reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>dt(S)).filter(S=>!t.includes(S)),p=QP({finishingPositions:i,drawDefinition:r,structureId:n}),m=p?Object.values(p):[],d=p?m.reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>dt(S)):[],l=u.filter(S=>!d.includes(S)).sort(le),{roundProfile:f}=xd({drawDefinition:r,structureId:n}),g=l.map(S=>{let T=f?.[S].finishingPositionRange.loser,[y,E]=T??[0,0];return tt(y,(E||y)+1)}).flat().sort(le),{playoffRoundsRanges:I}=GG({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function GG({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=tt(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function Lu({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{matchUps:r,matchUpsMap:n}=nr({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=Cc({drawDefinition:t,matchUpsMap:n}),{structures:s}=hn({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==$e||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=VG({playoffPositions:o,drawDefinition:t,structure:u,matchUps:r}),{error:d,...l}=m;if(d)return m;c[p]={structureId:p,...l}}return e?{positionsPlayedOff:i,...c[e]}:{availablePlayoffProfiles:Object.values(c),availablePlayoffRounds:Object.values(c),positionsPlayedOff:i}}function VG({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=Js({drawDefinition:e,structureId:o});if(r.structureType===Ve||r.structures){let l=Ct({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:D})=>D?.finishingPositions||[])||[],h=tt(1,g+1).filter(D=>!I.includes(D)),S=n.find(D=>D.containerStructureId===o&&D.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:D})=>D.structureId),{positionsPlayedOff:y=[],positionsNotPlayedOff:E=[]}=Cc({structureIds:T,drawDefinition:e}),P=[...y,...E],A=tt(S[0],S[1]+1).filter(D=>!P.includes(D)),U=Ae(A,A.length/h.length),N=h.map((D,M)=>{let R=U[M],b=[Math.min(...R||[]),Math.max(...R||[])].join("-");return{finishingPosition:D,finishingPositions:R,finishingPositionRange:b}});return{positionsNotPlayedOff:A,playoffFinishingPositionRanges:N,finishingPositionsAvailable:h,finishingPositionsPlayedOff:I,positionsPlayedOff:y,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==kn).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===kn).map(l=>l.source?.roundNumber)||[],c=XS({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:e,structureId:o}),u=c?.playoffSourceRounds?[...c?.playoffSourceRounds||[]]:void 0,p=[...c?.playoffRoundsRanges||[]],{roundProfile:m,error:d}=c;for(let l of a){let f=i?.source.find(T=>T.source.roundNumber===l),g=f?.target.roundNumber,I=f?.target.structureId,h=n.filter(({roundNumber:T,structureId:y})=>y===I&&T===g),S=h.filter(({sides:T})=>T.find(y=>y.participantFed&&!y.participantId)).length;if(u&&S===h.length){u.push(l);let T=m?.[l]?.finishingPositionRange?.loser;if(T){let y=Math.min(...T),E=y+S,P=tt(y,E),A={finishingPositionRange:[y,E-1].join("-"),finishingPositions:P,roundNumber:l};p.push(A)}}}return u&&u.sort(le),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function fv({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:Z};if(!kt(r)||!Array.isArray(t))return{error:B};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Lu({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function JS(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=rt,matchUpType:a,structureId:c,idPrefix:u,drawSize:p,isMock:m,uuids:d}=t,l={finishingPositionOffset:e,matchUpType:a,drawSize:p,idPrefix:u,isMock:m,uuids:d},{matchUps:f}=o?fi(l):xn(l),g=yn({structureName:i||r?.["0"]?.name||Qe(rt),structureId:c||d?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],h=[];if(p>2){let S=p/2,{matchUps:T}=xn({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:m}),y=Qe(qe),E=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),P=yn({structureName:E,matchUps:T,structureId:d?.pop(),stage:qe,stageSequence:1,matchUpType:a});I.push(P);let A={linkType:so,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:Nn,structureId:P.structureId}};h.push(A)}return{...C,structures:I,links:h}}function ZS({consolationStructure:t,roundOffset:e=0,mainStructure:r,roundsCount:n,feedPolicy:o,fmlc:i}){let a=t.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),c=o?.roundGroupedOrder||[],u=o?.roundFeedProfiles;return tt(1+e,n+1+e).map(p=>{let m=u?.[p-1]?u[p-1]:p%2&&Nn||yi,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:so,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),Dr()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=kn,l.target.feedProfile=Nn),a.includes(d)?l:void 0}).filter(Boolean)}function tT(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=rt,matchUpType:c,structureId:u,drawSize:p,idPrefix:m,isMock:d,uuids:l}=t,f={finishingPositionOffset:r,matchUpType:c,drawSize:p,idPrefix:m,isMock:d,uuids:l},{matchUps:g,roundsCount:I}=s?fi(f):xn(f),h=t.structureName??o?.["0"]?.name??Qe(rt),S=Ds({structureId:u||l?.pop(),structureName:h,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[S],y=[];if(p>2){let A=[0,2].slice(0,p/16).map((U,N)=>{let D=N+1,{consolationStructure:M}=BG({idPrefix:m&&`${m}-c${N}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:D,roundOffset:U,matchUpType:c,drawSize:p,isMock:d,index:N,uuids:l});T.push(M);let R=ZS({consolationStructure:M,roundsCount:2,mainStructure:S,roundOffset:U});return{consolationStructure:M,links:R}}).map(U=>U.links).flat();if(y.push(...A),p>=4&&p<=16||p>32){let{matchUps:U}=xn({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),N=o?.["3-4"]?.name??Qe(fe),D=i?.[N]||N,M=e?`${e} ${D}`:D,R=Ds({structureId:l?.pop(),matchUps:U,stageSequence:2,stage:fe,structureName:M,matchUpType:c}),b={linkType:so,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:R.structureId,feedProfile:Nn,roundNumber:1}};T.push(R),y.push(b)}}return{structures:T,links:y,...C}}function BG({playoffStructureNameBase:t,stageSequence:e=1,playoffAttributes:r,structureNameMap:n,roundOffset:o=0,matchUpType:i,structureId:s,idPrefix:a,drawSize:c,isMock:u,index:p,uuids:m}){let d=c/(2*Math.pow(2,o)),{matchUps:l,roundsCount:f}=fi({finishingPositionOffset:d,baseDrawSize:d,isConsolation:!0,feedRounds:1,matchUpType:i,idPrefix:a,isMock:u,uuids:m}),I=p===0&&r?.["0-1"]?.name||p===1&&r?.["0-3"]?.name||`${Qe(qe)} ${p+1}`,h=n?.[I]||I,S=t?`${t} ${h}`:h;return{consolationStructure:Ds({matchUps:l,stage:qe,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function bc(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=rt,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,h=t.feedPolicy||t.policyDefinitions?.[dc]||t.appliedPolicies?.[dc],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?fi(S):xn(S),y=yn({structureName:s||n?.["0"]?.name||Qe(rt),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),E=[y],P=[],A=l/2,{matchUps:U,roundsCount:N}=fi({finishingPositionOffset:A,idPrefix:d&&`${d}-c`,isConsolation:!0,feedsFromFinal:o,baseDrawSize:A,matchUpType:u,feedRounds:m,skipRounds:p,isMock:f,uuids:g,fmlc:I});if(l>2){let D=n?.["0-1"]?.name??Qe(qe),M=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${D}`:D,R=yn({matchUps:U,structureId:g?.pop(),stage:qe,stageSequence:1,structureName:M,matchUpType:u});E.push(R);let b=ZS({consolationStructure:R,mainStructure:y,roundsCount:N,feedPolicy:h,fmlc:I});P.push(...b)}return{...C,structures:E,links:P}}function rT({requireSequential:t=!0,playoffMatchUpFormat:e,playoffAttributes:r,sourceStructureId:n,policyDefinitions:o,stageSequence:i,drawDefinition:s,playoffGroups:a,matchUpType:c,feedPolicy:u,groupCount:p,idPrefix:m,isMock:d,uuids:l}){u=u||o?.[dc];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:y}=fv({structureId:n,drawDefinition:s,playoffGroups:a});if(T)return _({result:{error:T},stack:f});if(!(!y||a?.every(P=>{let{finishingPositions:A=[]}=P;if(!A.length)return!1;let U=[...A].sort(le).map((N,D)=>(A[D+1]||N)-N).every(N=>N<2);return(!t||U)&&A.every(N=>y[N])})))return _({context:{validFinishingPositions:Object.values(y)},result:{error:B},stack:f});for(let P of a){let A=P.finishingPositions,U=y&&A.flatMap(F=>y[F]?.finishingPositions??[]),N=p*A.length,D=us(N),M=D===2&&yo||P.drawType||yo;U&&(g=Math.min(...U)-1);let R=U&&`${Math.min(...U)}-${Math.max(...U)}`,b=P.structureName||R&&P.playoffAttributes?.[R]?.name||P.playoffAttributes?.["0"]?.name,v={...{addNameBaseToAttributeName:P.addNameBaseToAttributeName,playoffStructureNameBase:P.playoffStructureNameBase,finishingPositionNaming:P.finishingPositionNaming,finishingPositionLimit:P.finishingPositionLimit,structureId:P.structureId??l?.pop(),playoffAttributes:P.playoffAttributes,structureNameMap:P.structureNameMap,sequenceLimit:P.sequenceLimit,structureName:b},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:g,stage:fe,stageSequence:i,matchUpType:c,drawSize:D,isMock:d,uuids:l},x=({playoffStructures:F,playoffLinks:w})=>{let[L]=F,k=eT({playoffStructureId:L.structureId,finishingPositions:A,sourceStructureId:n});S.push(k),S.push(...w),h.push(...F),I.push({structureId:L.structureId,finishingPositions:A}),g+=N};if(M===yo){let{matchUps:F}=xn({finishingPositionLimit:g+N,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:D,isMock:d,uuids:l}),w=yn({structureId:P.structureId??l?.pop(),matchUpFormat:e,stage:fe,structureName:b,stageSequence:i,matchUps:F});h.push(w);let L=eT({playoffStructureId:w.structureId,finishingPositions:A,sourceStructureId:n});S.push(L),g+=N,I.push({structureId:w.structureId,finishingPositions:A})}else if([ou,iu,fe].includes(M)){let F={playoffAttributes:P.playoffAttributes??r,playoffStructureNameBase:P.playoffStructureNameBase,structureId:P.structureId??l?.pop(),structureName:P.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:fe,roundOffset:0,stageSequence:i,drawSize:D,isMock:d,uuids:l};M===ou?Object.assign(F,{playoffAttributes:P?.playoffAttributes??r??Of,roundOffsetLimit:3}):M===iu&&Object.assign(F,{playoffAttributes:P?.playoffAttributes??r??vf,roundOffsetLimit:2});let w=Rc(F);if(w.error)return w;if(w.links?.length&&S.push(...w.links),w.structures?.length&&h.push(...w.structures),h.sort(Ni),w.structureId){let L=eT({playoffStructureId:w.structureId,finishingPositions:A,sourceStructureId:n});S.push(L),I.push({structureId:w.structureId,finishingPositions:A})}g+=N}else if([au,yp,Ym,jm,Wm,qm].includes(M)){let F=[l?.pop(),l?.pop()],w={playoffStructureNameBase:P.playoffStructureNameBase,structureId:P.structureId??l?.pop(),playoffAttributes:P.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,uuids:F,stage:fe,structureName:b,matchUpType:c,feedPolicy:u,drawSize:D,isMock:d},L={[au]:{fmlc:!0,feedRounds:1},[qm]:{feedRounds:1},[Ym]:{feedsFromFinal:3},[jm]:{feedsFromFinal:2},[Wm]:{feedsFromFinal:1}};Object.assign(w,L[M]||{});let{structures:k,links:G}=bc(w),[H]=k,K=eT({playoffStructureId:H.structureId,finishingPositions:A,sourceStructureId:n});S.push(K),S.push(...G),h.push(...k),I.push({structureId:H.structureId,finishingPositions:A}),g+=N}else if([On].includes(M)){let{structures:F,links:w}=xa({...v,structureOptions:P.structureOptions||{groupSize:4}});x({playoffStructures:F,playoffLinks:w})}else if([Tp].includes(M)){let{structures:F,links:w}=JS(v);x({playoffStructures:F,playoffLinks:w})}else if([cb].includes(M)){let{structures:F,links:w}=tT(v);x({playoffStructures:F,playoffLinks:w})}else if([Fr].includes(M)){let F=yn({structureId:P.structureId??l?.pop(),structureName:P.structureName,finishingPosition:pd,stage:fe,stageSequence:i,matchUps:[]});x({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:h,links:S}}function eT({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:Fn,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:fn,roundNumber:1}}}function gv(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return _({result:{error:st},info:"playoffGroups required",stack:e});let{sourceStructureId:r,requireSequential:n,tournamentRecord:o,drawDefinition:i,playoffGroups:s,groupCount:a,groupSize:c,event:u}=t,p=rT({requireSequential:n,sourceStructureId:r,playoffGroups:s,groupCount:a,groupSize:c,...t});if(p.error)return _({result:p,stack:e});let{structures:m=[],links:d=[],finishingPositionTargets:l,positionRangeMap:f}=p,g=l?.map(({finishingPositions:U})=>U).flat().map(U=>f[U].finishingPositions).flat();i.structures.push(...m),i.links.push(...d);let{matchUps:I,matchUpsMap:h}=ie({inContext:!0,drawDefinition:i}),S=m.map(({structureId:U})=>U),T=I?.filter(({structureId:U})=>S.includes(U)).map(Ue),y=h?.drawMatchUps?.filter(({matchUpId:U})=>T?.includes(U));if(y?.length){let U=We({drawDefinition:i,event:u})?.tieFormat;U&&y.forEach(N=>{let{tieMatchUps:D}=Li({isMock:t.isMock,tieFormat:U,matchUp:N});Object.assign(N,{tieMatchUps:D,matchUpType:xr})})}let{positionAssignments:E}=Ct({structureId:r,drawDefinition:i}),P={};E?.forEach(U=>{let M=mt({element:U,name:Lo})?.extension?.value?.groupOrder;M&&(P[M]||(P[M]=[]),P[M].push(U.participantId))});let A=na({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return A.error&&A.error?.code!==jl.code?_({result:A,stack:e}):{structures:m,links:d,positionsPlayedOff:g,drawDefinition:i,...C}}function Fu({value:t,sourceRange:e,targetRange:r}){let n=Math.min(...e),o=Math.max(...e),i=Math.min(...r),s=Math.max(...r);return(t-n)*(s-i)/(o-n)+i}var XP="NTRP";var Iv={ELO:"ELO",NTRP:XP,TRN:"TRN",UTR:"UTR",WTN:"WTN"};var WG={ELO:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[XP]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},WTN:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},je=WG;function hv({sourceRatingType:t,sourceRating:e}){let r=je[t].range,n=r[0]>r[1],o=je["ELO"].range;return Fu({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function Sv({targetRatingType:t,sourceRating:e}){let r=je[t].decimalsCount||0,n=je[t].range,o=n[0]>n[1],i=Math.max(...n),s=je["ELO"].range,a=Fu({targetRange:n,sourceRange:s,value:e}),c=parseFloat(a.toFixed(r));return o?i-c:c}function ZP(t){let e=et(t,[{ratings:!0,[He]:zr}]);if(e.error)return e;let r=t.matchUpType&&[Lt,vt].includes(t.matchUpType)?t.matchUpType:Lt,n=Object.keys(je),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:"ELO",i=t.ratings[r]?t.ratings[r].reduce((d,l)=>d.includes(l.scaleName)?d:d.concat(l.scaleName),[]):[];if(!i)return{error:Oe};let s=t.ratings[r]?.find(d=>d.scaleName===o)??t.ratings[r][0];if(i[0]===o)return s;let a=s.scaleName,c=je[s.scaleName].accessor,u=c?s.scaleValue[c]:s.scaleValue,p=hv({sourceRatingType:a,sourceRating:u});return{convertedRating:Sv({targetRatingType:o,sourceRating:p}),sourceRating:u}}function Tv({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?.[Lt]&&s?.[Lt]){let a="ELO",{convertedRating:c}=ZP({ratings:i,targetRatingType:a}),{convertedRating:u}=ZP({ratings:s,targetRatingType:a}),{side1pressure:p,side2pressure:m}=jG({side1ConvertedRating:c,side2ConvertedRating:u,score:r});p&&t[n?.participantId].pressureScores.push(p),m&&t[o?.participantId].pressureScores.push(m);let d=Math.max(...je["ELO"].range),l=Hl((u-c)/d),f=Hl((c-u)/d);t[n?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(f)}}function jG({side1ConvertedRating:t,side2ConvertedRating:e,score:r}){let n=t>e?t:e,o=t>e?e:t,i=Math.abs(t-e),s=je["ELO"].range,a=Math.max(...s),c=(a-n)*0,p=(n+c)/a*i,m=r?.sets?.reduce((T,y)=>T+(y?.side1Score??0),0),d=r?.sets?.reduce((T,y)=>T+(y.side2Score??0),0),l=t>e?2:1,f=(m||0)*(o+(l===1?p:0)),g=(d||0)*(o+(l===2?p:0)),I=f+g,h=I?Hl(f/I):0,S=I?Hl(g/I):0;return{side1pressure:h,side2pressure:S}}function Lg({winningSide:t,matchUpFormat:e=bn,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=Ne(e),u=tD(c?.bestOf??1);if(typeof a=="number"&&(r===Gt&&n?.setsCreditForDefaults||r===Bt&&n?.setsCreditForWalkovers))i[a]=u;else for(let p of s||[]){let{winningSide:m}=p;m&&(i[m-1]+=1)}return typeof a=="number"&&r===Me&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function nT({matchUpFormat:t=bn,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=tD(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===Gt&&n?.gamesCreditForDefaults||r===Bt&&n?.gamesCreditForWalkovers)){let d=a?.setFormat?.setTo||0,l=u*d;m[s].push(l)}else i.forEach((d,l)=>{let g=(d.setNumber||l+1)>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",I=a?.[g]?.based,h=a?.[g].tiebreakSet,{side1Score:S,side2Score:T}=d;yv(I)&&!h&&(m[0].push(dt(S||0)),m[1].push(dt(T||0))),h&&d.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&m[d.winningSide-1].push(1)});if(r===Me&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(yv(l.based)){let f=l?.setTo||0,g=S=>{if(!(!a||S===""))return+S===p-1||+S===p?dt(p||0)+1:+S<p?f:p},I=Lg({winningSide:e,score:{sets:i},matchUpStatus:r,matchUpFormat:t,tallyPolicy:n});if(m.map(S=>S[s]<=S[1-s]).reduce((S,T)=>S+(T?1:0),0)>I[1-s]){let S=m[s].length,T=g(m[1-s][S-1]);T&&(m[s][S-1]=T)}u>m[s].length&&n?.gamesCreditForRetirements&&m[s].push(f)}}return[m[0].reduce((d,l)=>d+l,0),m[1].reduce((d,l)=>d+l,0)]}function oT({matchUpFormat:t,score:e}){let r=t?Ne(t):void 0,n=r?.bestOf??1,o=tD(n),i=[0,0],s=[0,0];return e?.sets?.forEach((a,c)=>{let p=(a.setNumber||c+1)>o&&r?.finalSetFormat?"finalSetFormat":"setFormat",m=r?.[p]?.based;if(Ev(m)){let{side1Score:d,side2Score:l}=a;d&&(s[0]+=dt(d||0)),l&&(s[1]+=dt(l||0))}else a.side1TiebreakScore&&(s[0]+=dt(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=dt(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function tD(t){return t&&Math.ceil(t/2)||1}function Ev(t){return t==="P"}function yv(t){return!Ev(t)}function Av({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,m=Math.pow(10,n?.precision||3);Object.keys(t).forEach(d=>{let l=t[d].setsWon,f=t[d].setsLost,g=n?.groupTotalSetsPlayed||e==="setsPct"?s:i*(u||0)||l+f,I=Math.round(l/g*m)/m;(I===1/0||isNaN(I))&&(I=g);let h=t[d].tieMatchUpsWon,S=t[d].tieMatchUpsLost,T=h+S,y=Math.round(h/T*m)/m;(y===1/0||isNaN(y))&&(y=h);let E=t[d].matchUpsWon,P=t[d].matchUpsLost,A=E+P,U=Math.round(E/A*m)/m;(U===1/0||isNaN(U))&&(U=E);let N=t[d].gamesWon||0,D=t[d].gamesLost||0,M=(i||0)*(u||0)*(p||0),R=n?.groupTotalGamesPlayed||e==="gamesPct"?o:Math.max(M,N+D),b=Math.round(N/R*m)/m;(b===1/0||isNaN(b))&&(b=0);let O=t[d].pointsWon+t[d].pointsLost,v=Math.round(t[d].pointsWon/O*m)/m;(v===1/0||isNaN(v))&&(v=0),t[d].setsWon=l,t[d].setsLost=f,t[d].setsPct=I,t[d].tieMatchUpsWon=h,t[d].tieMatchUpsPct=y,t[d].matchUpsPct=U,t[d].gamesWon=N,t[d].gamesLost=D,t[d].gamesPct=b,t[d].pointsPct=v,t[d].result=`${t[d].matchUpsWon}/${t[d].matchUpsLost}`})}function ku({participantIds:t,pressureRating:e,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,perPlayer:i,matchUps:s}){let a={},c=o?.excludeMatchUpStatuses||[],u=s?.filter(g=>(g.tieMatchUps||!c.includes(g.matchUpStatus))&&(!t?.length||jt(t,[wd(g,0),wd(g,1)]).length===2)),m=u?.flatMap(({score:g,tieMatchUps:I})=>I?I.filter(({matchUpStatus:h})=>!c.includes(h)).flatMap(({score:h})=>h?.sets?.length??0):g?.sets?.length??0)?.reduce((g,I)=>g+I,0),d=g=>g?.sets?.reduce((I,h)=>I+(h?.side1Score??0)+(h?.side2Score??0),0)??0,f=u?.flatMap(({score:g,tieMatchUps:I})=>I?I.filter(({matchUpStatus:h})=>!c.includes(h)).flatMap(({score:h})=>d(h)):d(g))?.reduce((g,I)=>g+I,0);for(let g of u??[]){let{matchUpStatus:I,tieMatchUps:h,tieFormat:S,score:T,winningSide:y,sides:E}=g,P=S&&g._disableAutoCalc&&S.collectionDefinitions.every(({scoreValue:N})=>N),A=y&&YG(g),U=y&&qG(g);if(!A&&!U)if(I&&ae.includes(I)){let N=wd(g,0),D=wd(g,1);N&&(Oc(a,N),a[N].matchUpsCancelled+=1),D&&(Oc(a,D),a[D].matchUpsCancelled+=1)}else if(h?.length){i=0;for(let N of h){if(N.winningSide){let D=E?.find(({sideNumber:R})=>R===N.winningSide)?.participantId,M=E?.find(({sideNumber:R})=>R===N.winningSide)?.participantId;D&&M&&(Oc(a,D),Oc(a,M),a[D].tieMatchUpsWon+=1,a[M].tieMatchUpsLost+=1,de(Lt)(N.matchUpType)?(a[D].tieSinglesWon+=1,a[M].tieSinglesLost+=1):de(vt)(N.matchUpType)&&(a[D].tieDoublesWon+=1,a[M].tieDoublesLost+=1))}Uv({score:N.score,manualGamesOverride:P,participantResults:a,sides:E})}}else Uv({manualGamesOverride:P,participantResults:a,score:T,sides:E});else if(Oc(a,A),Oc(a,U),h?.length){i=0;for(let N of h){let{matchUpType:D}=N,M=de(vt)(D),R=de(Lt)(D);N.winningSide&&(N.winningSide===y?(A&&(a[A].tieMatchUpsWon+=1,R&&(a[A].tieSinglesWon+=1),M&&(a[A].tieDoublesWon+=1)),U&&(a[U].tieMatchUpsLost+=1,R&&(a[U].tieSinglesLost+=1),M&&(a[U].tieDoublesLost+=1))):N.winningSide!==y&&(U&&(a[U].tieMatchUpsWon+=1,R&&(a[U].tieSinglesWon+=1),M&&(a[U].tieDoublesWon+=1)),A&&(a[A].tieMatchUpsLost+=1,R&&(a[A].tieSinglesLost+=1),M&&(a[A].tieDoublesLost+=1)))),Pv({matchUpFormat:N.matchUpFormat,matchUpStatus:N.matchUpStatus,matchUpType:N.matchUpType,score:N.score,sides:N.sides,winningParticipantId:A,losingParticipantId:U,manualGamesOverride:P,participantResults:a,isTieMatchUp:!0,pressureRating:e,tallyPolicy:o,winningSide:y})}Dv({winningParticipantId:A,losingParticipantId:U,participantResults:a,matchUpStatus:I})}else Pv({matchUpFormat:g.matchUpFormat??n,matchUpType:g.matchUpType,isTieMatchUp:void 0,winningParticipantId:A,manualGamesOverride:P,losingParticipantId:U,participantResults:a,pressureRating:e,matchUpStatus:I,tallyPolicy:o,winningSide:y,score:T,sides:E});if(P){let N=T?.sets?.reduce((b,O)=>b+(O?.side1Score??0),0),D=T?.sets?.reduce((b,O)=>b+(O.side2Score??0),0),M=E?.find(({sideNumber:b})=>b===1)?.participantId,R=E?.find(({sideNumber:b})=>b===2)?.participantId;Oc(a,M),Oc(a,R),M&&(a[M].gamesWon+=N,a[M].gamesLost+=D),R&&(a[R].gamesWon+=D,a[R].gamesLost+=N)}}return Av({participantResults:a,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,totalGames:f,perPlayer:i,totalSets:m}),{participantResults:a}}function YG(t){let e=t.winningSide-1;return wd(t,e)}function qG(t){let e=1-(t.winningSide-1);return wd(t,e)}function wd(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 Oc(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 Uv({manualGamesOverride:t,participantResults:e,score:r,sides:n}){let{sets:o}=r||{},i=[[],[]],s=[0,0];for(let c of o||[]){let{winningSide:u,side1Score:p,side2Score:m}=c;u&&(s[u-1]+=1),i[0].push(dt(p||0)),i[1].push(dt(m||0))}let a=[i[0].reduce((c,u)=>c+u,0),i[1].reduce((c,u)=>c+u,0)];n.forEach((c,u)=>{let{participantId:p}=c;p&&(Oc(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 Pv({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,isTieMatchUp:a,matchUpType:c,tallyPolicy:u,winningSide:p,score:m,sides:d}){let l=p&&p-1,f=1-l;o&&c===Lt&&Tv({participantResults:n,sides:d,score:m}),a||Dv({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let g=Lg({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),I=nT({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),{pointsTally:h}=oT({score:m,matchUpFormat:i});t&&(n[t].setsWon+=g[l],n[t].setsLost+=g[f],e||(n[t].gamesWon+=I[l],n[t].gamesLost+=I[f]),n[t].pointsWon+=h[l],n[t].pointsLost+=h[f]),r&&(n[r].setsWon+=g[f],n[r].setsLost+=g[l],e||(n[r].gamesWon+=I[f],n[r].gamesLost+=I[l]),n[r].pointsWon+=h[f],n[r].pointsLost+=h[l])}function Dv({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===Bt&&(r[e].walkovers+=1),n===Gt&&(r[e].defaults+=1),n===Me&&(r[e].retirements+=1),pr(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 $G(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 KG(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)}$G(t,r,n,o)}n.push("----------------------")}function Nv({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)=>{KG(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
|
-
`)}function eD({participantResults:t,participantIds:e,attribute:r}){return rD({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 rD(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var zG=[{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}],nD={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function oD(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!QG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=eD({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let p=Object.keys(a).map(S=>parseFloat(S)).sort((S,T)=>T-S).map(S=>a[S]).map(S=>{let T=Mv({participantIds:S,...t});return i.push(...T.report??[]),T.order}).map((S,T)=>S.map(y=>y.resolved?y:{...y,subGroup:[T].concat(...y.subGroup??[])})).flat(),m,d=0,l=1,f;p.forEach((S,T)=>{T&&(S.resolved||f&&!S.resolved)&&(l+=1),f=S.resolved;let y=parseInt(S.subGroup?.join("")||0);S.resolved?(S.position=T+1,l=S.position):(m&&y>m&&(l+=d,d=0),S.position=l,d+=1),m=y});let g=p.map(({position:S})=>S),I=Er(g);return p.forEach(S=>{let{participantId:T,position:y}=S||{},E=r[T];S.GEMscore=h(E);let P=I[y];S?.position!==void 0&&(P>1&&(S.ties=P,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(nD).filter(E=>o.GEMscore.includes(E)):Object.keys(nD)).map(E=>(S[E]||0)*Math.pow(10,nD[E].toFixed(3))).reduce((E,P)=>E+P,0)}}function QG({participantResults:t,participantsCount:e}){let n=rD({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function XG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,groupTotals:n,tallyPolicy:o,attribute:i,idsFilter:s,matchUps:a,reversed:c}){let{participantResults:u}=ku({participantIds:s&&e,groupingTotal:n&&i,matchUpFormat:r,tallyPolicy:o,matchUps:a}),p=eD({participantResults:u,participantIds:e,attribute:i}),m=[{attribute:i,reversed:c,groups:p,idsFilter:s,groupTotals:n}],d;return Object.keys(p).length>1&&e.length&&(d=Object.keys(p).map(g=>parseFloat(g)).sort((g,I)=>c?g-I:I-g).map(g=>p[g]).map(g=>{let I=Mv({participantResults:u,disableHeadToHead:t,participantIds:g,matchUpFormat:r,tallyPolicy:o,matchUps:a});return m.push(...I.report??[]),I.order}).map((g,I)=>g.map(h=>h.resolved?h:{...h,subGroup:[I].concat(...h.subGroup??[])})).flat()),{order:d,report:m}}function Mv({participantResults:t,disableHeadToHead:e,participantIds:r,matchUpFormat:n,tallyPolicy:o,matchUps:i}){let s=[],a=[],c;if(r?.length===1)return{order:[{resolved:!0,participantId:r[0]}]};if(r?.length===2&&(!o?.headToHead||!o.headToHead.disabled&&!e)){let m=JG({participantIds:r,participantResults:t});if(m){let d=m[0].participantId;return a.push({attribute:"head2Head",participantIds:r,headToHeadWinner:d}),{order:m,headToHeadWinner:d,report:a}}}let p=(o?.tallyDirectives||zG).filter(m=>{let d=!(Jt(m.maxParticipants)&&r?.length>m.maxParticipants);return d||s.push(m),d});return s.length&&a.push({excludedDirectives:s,participantIds:r}),p.every(({attribute:m,reversed:d,idsFilter:l,groupTotals:f,disableHeadToHead:g})=>(c=XG({disableHeadToHead:g,participantIds:r,matchUpFormat:n,groupTotals:f,tallyPolicy:o,attribute:m,idsFilter:l,matchUps:i,reversed:d}),a.push(c.report),!c.order)),c.order?{order:c.order,report:a}:{order:r?.map(m=>({participantId:m})),report:a}}function JG({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 Fa({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Br(o))return{error:no};let a=pt(o.map(({structureId:y})=>y));if(a.length!==1)return _({result:{error:B,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!=="BYE"),u=c.length&&pt(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>Ts({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:E})=>y===Wt&&E?.every(P=>Ts({matchUp:P}))),d=t?.[kf],l=o.filter(y=>Ts({matchUp:y})??y.matchUpType===Wt),{participantResults:f}=ku({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=oD({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,subOrderMap:i,tallyPolicy:d});if(r&&ZG({participantResults:f}),p&&h)g=S,I=h,h.forEach(y=>{let{participantId:E,groupOrder:P,rankOrder:A,subOrder:U,ties:N,GEMscore:D}=y,M=f[E];Object.assign(M,{groupOrder:P,rankOrder:A,GEMscore:D,subOrder:U,ties:N})});else{let{groupOrder:y,report:E}=oD({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=E,I=y,y&&y.forEach(P=>{let{participantId:A,groupOrder:U,GEMscore:N}=P,D=f[A];Object.assign(D,{provisionalOrder:U,GEMscore:N})})}let T={completedTieMatchUps:m,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||m)&&(T.order=I),e||Dr({tally:!0})){let y=Nv({matchUps:o,report:g,order:I});Dr({tally:!0})&&console.log(y),T.readableReport=y}return T}function ZG({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 iT({positionAssignments:t}){let e=(t||[]).filter(Hr(ao)).map(i=>{let{extension:s}=mt({element:i,name:fc}),a=dt(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=Er(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function Ld({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Br(o))return{error:B};if(!t)return{error:B};let{policyDefinitions:s}=Go({policyTypes:[kf],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=iT({positionAssignments:t}),c=o.length?Fa({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;if(c?.error)return c;let{participantResults:u={},bracketComplete:p,report:m}=c??{},d=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;if(d.includes(f)){let g={value:u[f],name:Lo};At({element:l,extension:g}),u[f].ties||Ir({element:l,name:fc})}else Ir({element:l,name:Lo}),Ir({element:l,name:fc})}),bt({drawDefinition:r}),{...C,participantResults:u,bracketComplete:p,report:m}}function sT({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Vt(t){let e=et(t,[{[Ce]:!0,[gn]:!0}]);if(e.error)return e;let{tournamentParticipants:r,afterRecoveryTimes:n,contextProfile:o,drawDefinition:i,matchUpsMap:s,matchUpId:a,inContext:c,context:u,event:p}=t,{structures:m=[]}=hn({drawDefinition:i}),d=t.contextContent||o&&Zn({contextProfile:o,drawDefinition:i});for(let l of m){let{matchUps:f}=yt({tournamentParticipants:r,afterRecoveryTimes:n,contextContent:d,drawDefinition:i,contextProfile:o,matchUpsMap:s,inContext:c,structure:l,context:u,event:p}),{matchUp:g}=sT({matchUps:f,matchUpId:a});if(g)return{matchUp:g,structure:l}}return{error:we}}function $p(t){return!ht(t)||!t.notes?{error:st}:ht(t.element)?!kt(t.notes)&&!t.notes?.testing?{error:B}:(Object.assign(t.element,{notes:t.notes}),{...C}):{error:B}}function Fg(t){return ht(t)?ht(t.element)?(t.element.notes&&delete t.element.notes,{...C}):{error:B}:{error:st}}var Gu={matchUpStatus:Qt,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:m,event:d,notes:l,score:f}=t,I=t.appliedPolicies&&Object.keys(t.appliedPolicies).length?t.appliedPolicies:Tt({policyTypes:[rn],tournamentRecord:s,drawDefinition:a,structure:o,event:d})?.appliedPolicies,h=n.matchUpType===Wt;if(h&&a){if(m&&n.matchUpId!==m){let U=Vt({drawDefinition:a,matchUpId:m,event:d});if(!U.matchUp)return{error:we};({matchUp:n,structure:o}=U)}}else n.matchUpId!==m&&console.log("!!!!!");c&&[Bt,oe].includes(c)||u?Object.assign(n,{...Gu}):f&&(n.score=f);let S=c&&n?.matchUpStatus===Gt&&c!==Gt;c&&(n.matchUpStatus=c),r&&(n.matchUpFormat=r),i&&(n.matchUpStatusCodes=i),p&&(n.winningSide=p),t.removeWinningSide&&(n.winningSide=void 0),!o&&a&&({structure:o}=Vt({drawDefinition:a,matchUpId:m,event:d})),c&&!n.winningSide&&he(n)&&!ae.includes(c)&&![gc,ls,mn].includes(c)&&(n.matchUpStatus=Hn);let T;if((S&&n?.processCodes?.length||c===Gt)&&(T=I?.[rn]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let U=o?.structureType===Ve,N=cr({structure:o});if(gd({drawDefinition:a,structure:o})||N||U){let D=b=>{r=h?"SET1-S:T100":r??n.matchUpFormat??b?.matchUpFormat??a?.matchUpFormat??d?.matchUpFormat;let O=h?{matchUpTypes:[Wt]}:void 0,{matchUps:v}=yt({afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,matchUpFilters:O,drawDefinition:a,structure:b,event:d});return N&&(b.positionAssignments=pt(v.flatMap(x=>(x.sides??[]).map(F=>F.participantId)).filter(Boolean)).map(x=>({participantId:x}))),Ld({positionAssignments:b.positionAssignments,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUps:v,event:d})},M=U&&o.structures.find(b=>b?.matchUps.find(O=>O.matchUpId===m)),R=D(M||o);if(R.error)return _({result:R,stack:e})}}if(l){let U=$p({element:n,notes:l});if(U.error)return _({result:U,stack:e})}let y=s?.tournamentId,E=Lr().topics.includes(Rp),P=(E||T)&&Pe({drawDefinition:a}),A=P&&ie({matchUpFilters:{matchUpIds:[m]},nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:a,matchUpsMap:P}).matchUps?.[0];if(E&&A&&Cb({tournamentId:y,inContextMatchUp:A}),Array.isArray(T)&&A&&!A.sides?.every(({participantId:U})=>U))if(c===Gt)n.processCodes=pt([...n.processCodes??[],...T]);else for(let U of T||[]){let N=U&&n?.processCodes?.lastIndexOf(U);n?.processCodes?.splice(N,1)}return gt({eventId:d?.eventId,context:e,drawDefinition:a,tournamentId:y,matchUp:n}),{...C}}function Fd(t){let{propagateExitStatus:e,matchUpStatusCodes:r,autoCalcDisabled:n,inContextMatchUp:o,matchUpStatus:i,dualMatchUp:s,structure:a,matchUp:c}=t,u=Oa({matchUpStatus:i})||[po,vr].includes(i)&&s||n,p=c?.sides?.map(h=>h.participantId).filter(Boolean).length||o?.sides?.map(h=>h.participantId).filter(Boolean).length,m="attemptToModifyScore";if(!(cr({structure:a})&&p===1||i===Gt&&p||tV({structure:a,matchUp:c,inContextMatchUp:o})||t.appliedPolicies?.[rn]?.requireParticipantsForScoring===!1||pr(i)&&p===1&&e))return _({result:{error:Ql},stack:m});let f=[Bt].includes(i),g=u?i:t.winningSide&&ge||mn,I=Yn({...t,winningSide:t.winningSide,matchUpStatusCodes:u&&r||[],matchUpStatus:g,context:m,removeScore:f});return _({result:I,stack:m})}function tV({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=Ie({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 aT({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=>dt(n));return{groupValueGroups:e,groupValueNumbers:r}}function Rv({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=>ae.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),It(d)?i.forEach(S=>{S.winningSide&&(s[S.winningSide-1]+=d)}):It(g)?i.forEach(S=>{S.score?.sets?.forEach(T=>{T.winningSide&&(s[T.winningSide-1]+=g)})}):It(f)?i.forEach(S=>{S.score?.sets?.forEach(T=>{let{side1TiebreakScore:y=0,side2TiebreakScore:E=0,side1Score:P=0,side2Score:A=0}=T;(S.matchUpStatus===ge||S.winningSide||T.winningSide)&&(P||A?(s[0]+=P,s[1]+=A):(y||E)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,y=eV({collectionDefinition:t,collectionPosition:T});It(y)&&(s[S.winningSide-1]+=y)}}),It(m)){let S;if(l?.aggregateValue)c&&(It(d||g||f)&&s[0]!==s[1]?S=s[0]>s[1]?1:2:h[0]!==h[1]&&(S=h[0]>h[1]?1:2));else if(l?.valueGoal)S=s.reduce((T,y,E)=>y>=l.valueGoal?E+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((y,E,P)=>E>=T?P+1:y,0)}S&&(I?r[p].values[S-1]+=m:a[S-1]+=m)}else I?(r[p].values[0]+=s[0]||0,r[p].values[1]+=s[1]||0):a=s;I?(r[p].sideWins[0]+=h[0]||0,r[p].sideWins[1]+=h[1]||0,r[p].allGroupMatchUpsCompleted=r[p].allGroupMatchUpsCompleted&&c,r[p].matchUpsCount+=i.length):a.forEach((S,T)=>n[T]+=S||0)}function eV({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function vc(t){let{sideAdjustments:e=[0,0],separator:r="-",drawDefinition:n,matchUpsMap:o,structure:i,matchUp:s,event:a}=t;if(!Array.isArray(e)||e.length!==2||isNaN(e.reduce((y,E)=>y+E)))return{error:B};if(!s)return{error:mr};let c=We({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:ks};let u=ar({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=aT(c);for(let y of p)Rv({collectionDefinition:y,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let y of f){let E=l[y],{allGroupMatchUpsCompleted:P,matchUpCount:A,winCriteria:U,groupValue:N,sideWins:D,values:M}=E,R;if(U?.aggregateValue)P&&M[0]!==M[1]&&(R=M[0]>M[1]?1:2);else if(U?.valueGoal)R=M.reduce((b,O,v)=>O>=U.valueGoal?v+1:b,void 0);else{let b=Math.floor(A/2)+1;R=D.reduce((O,v,x)=>v>=b?x+1:O,void 0)}R&&(d[R-1]+=N||0)}let g=d.map((y,E)=>(y||0)+e[E]),I={side1Score:g[0],side2Score:g[1],winningSide:void 0},h=g.join(r),S=g.slice().reverse().join(r),T;if(c?.winCriteria){let{valueGoal:y,aggregateValue:E,tallyDirectives:P}=c.winCriteria;if(y?T=g.map((U,N)=>({sideNumber:N+1,points:U})).find(({points:U})=>U>=y)?.sideNumber:E&&m.every(U=>U.matchUpStatus&&ae.includes(U.matchUpStatus)||U.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&P){let A=s.matchUpId,U=s.hasContext?s:o?.drawMatchUps?.[A]||n&&Vt({inContext:!0,drawDefinition:n,matchUpId:A})?.matchUp;if(U){let{completedTieMatchUps:N,order:D}=Fa({matchUps:[U]});if(N&&D?.length){let M=D[0].participantId;T=U.sides.find(({participantId:R})=>R===M)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function ka({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Vt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=mt({element:e,name:wo}),s=J(i?.value||{},!1,!0),a=({displaySideNumber:c,drawPosition:u,sideNumber:p})=>({drawPosition:u,sideNumber:p,displaySideNumber:c});n.sides=t?.sides?.map(c=>{let u=c.participantId,p=u&&s[u]||void 0,{lineUp:m,...d}=n.sides?.find(({sideNumber:f})=>f===c.sideNumber)??{},l=m?.length?m:p;return{...a(c),...d,lineUp:l}}),gt({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function or(t){if(t)return J(t,!1,!0)}function kg(t){let e=et(t,[{[Re]:!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 cT({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=kg({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function go(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&&cT({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:q};let m=Vt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:we};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:dr};ka({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=mt({name:Ua,element:d});if(f?.value)if(o)Ir({element:d,name:Ua});else return{...C,score:d.score};let g=We({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=or(g);let I=vc({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:y}=I,E=S?.side1Score||S?.side2Score;if(e&&!d.score&&!E)return{...C};let P={scoreStringSide1:T,scoreStringSide2:y,sets:S?[S]:[]},A=h&&[1,2].includes(h),U=A&&ge||Ig({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:P})&&Hn||Qt,N=!!(d.winningSide&&!A),D=d.tieMatchUps.find(({score:R,winningSide:b,matchUpStatus:O})=>R?.sets?.length&&(R.sets[0].side1Score||R.sets[0].side2Score)||O&&ae.includes(O)||b),M;if(d.tieFormat&&!A&&!D){let R=We({drawDefinition:r,structure:l,event:a})?.tieFormat;R&&JSON.stringify(g)===JSON.stringify(R)&&(d.tieFormatId=void 0,d.tieFormat=void 0,M=!0)}return Yn({appliedPolicies:t.appliedPolicies,matchUpStatus:U,score:P,removeWinningSide:N,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...C,score:P,removeWinningSide:N,tieFormatRemoved:M,winningSide:h}}function Cv({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:r,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}){let l="directWinner";if(s){let f=u.drawPositions||[],g=f[t],I=s.source.structureId,h=at({structureId:I,drawDefinition:c});if(h.error)return h;let{structure:S}=h,{positionAssignments:T}=Ie({structureId:I,drawDefinition:c}),E=T?.find(R=>R.drawPosition===o)?.participantId,P=s.target.structureId,{positionAssignments:A}=Ie({structureId:P,drawDefinition:c}),N=A?.find(R=>R.participantId===E)?.drawPosition,D=A?.filter(R=>{let b=f.includes(R.drawPosition),O=!R.participantId&&!R.bye&&!R.qualifier;return b&&O}).map(R=>R.drawPosition),M=D?.includes(g);if(E&&s.target.roundNumber===1&&M)jn({drawPosition:g,participantId:E,structureId:P,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(E&&D?.length){let R=D.pop();R&&jn({participantId:E,structureId:P,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:R,matchUpsMap:m,event:d})}else if(N){let R=wa({drawPosition:N,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(R.error)return _({result:R,stack:l})}else if(S?.stage!==ct){let R="winner target position unavaiallble";console.log(R),_({stack:l,result:{error:R}})}if(S?.seedAssignments&&S.structureId!==P){let R=S.seedAssignments.find(({participantId:O})=>O===E),b=R?.participantId;R&&b&&ra({eventId:u?.eventId,structureId:P,...R,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=wa({matchUpId:u.matchUpId,drawPosition:o,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(f.error)return f}if(p&&r){let f=p.sides?.find(g=>g.sideNumber===r);if(f?.lineUp){let g=p.roundPosition,I=u.roundPosition,h=g===I&&g!==1||Math.floor(g/2)===I?2:1,S=m?.drawMatchUps?.find(({matchUpId:E})=>E===u.matchUpId),T=[1,2].map(E=>({...S.sides?.find(A=>A.sideNumber===E)||{},sideNumber:E}));S.sides=T;let y=S.sides.find(E=>E.sideNumber===h);if(y){let E=f.lineUp?.filter(P=>P?.participantId);y.lineUp=Rd({lineUp:E}),gt({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...C}}function bv(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,propagateExitStatus:o,sourceMatchUpStatus:i,loserDrawPosition:s,tournamentRecord:a,loserTargetLink:c,drawDefinition:u,loserMatchUp:p,dualMatchUp:m,matchUpsMap:d,event:l}=t,f="directLoser",g=c.linkCondition,I=p.drawPositions||[],h=g===kn&&p.roundNumber===2&&Math.min(...I.filter(Boolean)),S=h||I[e],T=h||I[1-e],y=c.source.structureId,{structure:E}=at({structureId:y,drawDefinition:u}),{matchUps:P}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:u,structure:E,event:l}),U=P.filter(V=>V.drawPositions?.includes(s)).filter(V=>{let $=V.sides.find(W=>W.drawPosition===s),X=V.matchUpStatus===Bt||V.matchUpStatus===Gt&&!he(V);return $?.sideNumber===V.winningSide&&!X}),N=g===kn&&U.length===0,{positionAssignments:D}=Ie({structureId:y,drawDefinition:u}),R=D?.find(V=>V.drawPosition===s)?.participantId,b={loserParticipantId:R},O=c.target.structureId,{positionAssignments:v}=Ie({structureId:O,drawDefinition:u}),x=v?.filter(({drawPosition:V})=>I.includes(V)),F=x?.some(V=>V.participantId&&R&&V.participantId===R),w=o&&[Me,Bt,Gt].includes(i||"");if(F)return{...C,stack:f};let L=x?.filter(V=>{let $=I.includes(V.drawPosition),X=!V.participantId&&!V.bye&&!V.qualifier;return $&&X}).map(V=>V.drawPosition),k=L?.includes(S),G=c.target.roundNumber>1&&L?.length,H=c.target.roundNumber===1&&k;if(h){let V=K();if(V.context&&Object.assign(b,V.context),V.error)return _({result:V,stack:f})}else if(H){let V=j();if(V.context&&Object.assign(b,V.context),V.error)return _({result:V,stack:f})}else if(R&&G){L.sort(le);let V=L[0],$=jn({participantId:R,structureId:O,drawPosition:V,inContextDrawMatchUps:r,sourceMatchUpStatus:i,tournamentRecord:a,drawDefinition:u,matchUpsMap:d,event:l});if($.error)return _({result:$,stack:f});if(!$.error&&w&&o)return{stack:f,context:{progressExitStatus:!0,loserParticipantId:R}}}else return _({context:{loserDrawPosition:s,loserTargetLink:c,targetDrawPositionIsUnfilled:k},result:{error:k?Ls:CC},stack:f});if(E?.seedAssignments&&E.structureId!==O){let V=E.seedAssignments.find(({participantId:X})=>X===R),$=V?.participantId;V&&$&&ra({eventId:p?.eventId,structureId:O,...V,tournamentRecord:a,drawDefinition:u,participantId:$})}if(m&&n){let V=m.sides?.find($=>$.sideNumber===3-n);if(V?.lineUp){let{roundNumber:$,eventId:X}=p,{roundPosition:W}=m,it=$===1?2-W%2:1,z=d?.drawMatchUps?.find(({matchUpId:ot})=>ot===p.matchUpId),Q=[1,2].map(ot=>({...z.sides?.find(Rt=>Rt.sideNumber===ot)||{},sideNumber:ot}));z.sides=Q;let ut=z.sides.find(ot=>ot.sideNumber===it);ut&&(ut.lineUp=Rd({lineUp:V.lineUp}),gt({tournamentId:a?.tournamentId,matchUp:z,context:f,drawDefinition:u,eventId:X}))}}return _({result:{...C},stack:f,context:b});function K(){let V="loserLinkFedFMLC";return N?_({result:j(),stack:V}):_({result:Y(),stack:V})}function Y(){let V=Wr({drawPosition:T,structureId:O,tournamentRecord:a,drawDefinition:u,event:l});return _({result:V,stack:"assignLoserPositionBye"})}function j(){let V=R?jn({drawPosition:S,participantId:R,structureId:O,inContextDrawMatchUps:r,sourceMatchUpStatus:i,tournamentRecord:a,drawDefinition:u,matchUpsMap:d,event:l}):{error:se};return!V.error&&w&&o?{stack:f,context:{progressExitStatus:!0}}:_({result:V,stack:"assignLoserDrawPosition"})}}function uT(t){let e="directParticipants",r=Fd(t);if(r.error)return _({result:r,stack:e});let n=Oa({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:p,matchUpStatus:m,dualMatchUp:d,matchUpsMap:l,winningSide:f,targetData:g,matchUpId:I,structure:h,matchUp:S,event:T}=t,y=!!S.collectionId,E=cr({structure:h}),P=S.drawPositions,A;if(y){let{matchUpTieId:U,matchUpsMap:N}=t,D=go({appliedPolicies:t.appliedPolicies,matchUpId:U,tournamentRecord:u,drawDefinition:p,matchUpsMap:N,event:T});if(A=D&&{tieMatchUpResult:D},P=i.find(({matchUpId:R})=>R===U)?.drawPositions,!o)return _({result:{...C,...A},stack:e})}if(E)return _({result:{...C,...A},stack:e});if(P){let U=s?s-1:f-1,N=1-U,D=P[U],M=P[N],R={},{targetLinks:{loserTargetLink:b,winnerTargetLink:O,byeTargetLink:v},targetMatchUps:{winnerMatchUpDrawPositionIndex:x,loserMatchUpDrawPositionIndex:F,winnerMatchUp:w,loserMatchUp:L,byeMatchUp:k}}=g;if(w){let G=Cv({sourceMatchUpStatus:n&&m||ge,winnerMatchUpDrawPositionIndex:x,sourceMatchUpId:I,inContextDrawMatchUps:i,projectedWinningSide:s,winningDrawPosition:D,tournamentRecord:u,winnerTargetLink:O,drawDefinition:p,winnerMatchUp:w,dualMatchUp:d,matchUpsMap:l,event:T});if(G.error)return _({result:G,stack:e})}if(L){let G=bv({sourceMatchUpStatus:n&&m||ge,sourceMatchUpStatusCodes:c||[],sourceWinningSide:f,loserMatchUpDrawPositionIndex:F,sourceMatchUpId:I,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,loserDrawPosition:M,tournamentRecord:u,loserTargetLink:b,drawDefinition:p,loserMatchUp:L,winningSide:f,matchUpsMap:l,dualMatchUp:d,event:T});if(G.context?.progressExitStatus&&Object.assign(R,G.context,{sourceMatchUpStatus:n&&m||ge,sourceMatchUpStatusCodes:c||[],loserMatchUp:L,matchUpsMap:l}),G.error)return _({result:G,stack:e})}if(k){let G=k.drawPositions||[],H=Math.min(...G.filter(Boolean)),K=v.target.structureId,Y=Wr({drawPosition:H,structureId:K,tournamentRecord:u,drawDefinition:p,event:T});if(Y.error)return _({result:Y,stack:e})}return _({result:{...C,...A},stack:e,context:R})}else return _({result:{error:Ja},stack:e})}function kd(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:Z},stack:e});let r=Lu(t);if(r.error)return _({result:r,stack:e});let{structureId:n,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:m,exitProfileLimit:d,roundProfiles:l,roundNumbers:f,idPrefix:g,isMock:I,event:h,uuids:S}=t,T=J(t.drawDefinition,!1,!0),{structure:y}=at({structureId:n,drawDefinition:T});if(!y)return _({result:{error:_t},stack:e});if(y.structureType===Ve||y.structures)return gv({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:E,playoffRounds:P}=r,{playoffPositionsReturned:A,error:U,playoffSourceRounds:N,playoffRoundsRanges:D}=XS(t);if(U)return _({result:{error:U},stack:e});let M=l?.length&&Object.assign({},...l),R=f||typeof l=="object"&&l.map(W=>Object.keys(W)).flat(),b=Array.isArray(R)&&R.map(W=>!isNaN(W)&&dt(W)).filter(Boolean);if(b){if(!Array.isArray(b))return _({result:{error:B},context:{validRoundNumbers:b},stack:e});b.forEach(W=>{if(!P?.includes(W))return _({result:{error:B},context:{roundNumber:W},stack:e})})}u&&u.forEach(W=>{if(!A?.includes(W))return _({result:{error:B},context:{playoffPosition:W},stack:e})});let O=b||N,v=b?E:D,x=[],F=[];for(let W of O??[]){let it=v?.find(qt=>qt.roundNumber===W);if(!it)return _({result:{error:B},context:{roundNumber:W},stack:e});let z=it.finishingPositions.length,Q=Math.min(...it.finishingPositions)-1,ut=2,ot=W&&M?.[W]&&ut+M[W]-1,Dt=Rc({exitProfile:`0-${W}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:Q,playoffAttributes:c,exitProfileLimit:d,stage:fe,roundOffset:0,drawDefinition:T,sequenceLimit:ot,stageSequence:ut,drawSize:z,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(Dt.error)return _({result:Dt,stack:e});let{structures:Rt,links:De}=Dt;if(Rt?.length&&x.push(...Rt),De?.length&&F.push(...De),Dt.structureId&&W){let qt={linkType:so,source:{structureId:n,roundNumber:W},target:{structureId:Dt.structureId,feedProfile:Nn,roundNumber:1}};F.push(qt)}}if(!x.length)return _({result:{error:B},info:"No structures generated",stack:e});T.structures.push(...x),T.links.push(...F);let{matchUps:w,matchUpsMap:L}=ie({inContext:!0,drawDefinition:T}),k=x.map(({structureId:W})=>W),G=w?.filter(({structureId:W})=>k.includes(W)).map(Ue),H=L?.drawMatchUps?.filter(({matchUpId:W})=>G?.includes(W));if(H?.length){let W=We({drawDefinition:T,event:h})?.tieFormat;W&&H.forEach(it=>{let{tieMatchUps:z}=Li({matchUp:it,tieFormat:W,isMock:I});Object.assign(it,{tieMatchUps:z,matchUpType:Wt})})}w?.filter(W=>Ts({matchUp:W})&&W.structureId===n)?.forEach(W=>{let{matchUpId:it,score:z,winningSide:Q}=W,ut=ur({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:it}),ot=uT({inContextDrawMatchUps:w,tournamentRecord:m,drawDefinition:T,matchUpsMap:L,winningSide:Q,targetData:ut,matchUpId:it,structure:y,matchUp:W,score:z,event:h});ot.error&&console.log(ot.error)}),w?.filter(W=>W.matchUpStatus==="BYE"&&W.structureId===n)?.forEach(W=>{let{matchUpId:it}=W,z=ur({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:it}),{targetLinks:{loserTargetLink:Q},targetMatchUps:{loserMatchUpDrawPositionIndex:ut,loserMatchUp:ot}}=z;if(Q&&ot){let Dt=Q.target.structureId,Rt=ot.drawPositions[ut],De=Wr({drawPosition:Rt,structureId:Dt,tournamentRecord:m,drawDefinition:T,event:h});De.error&&console.log(De.error)}});let j=[],V=rs({inContextDrawMatchUps:w,drawDefinition:T,matchUpsMap:L}).goesToMap,{structure:$}=at({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:X}=yt({structure:$});return X.forEach(W=>{let it=V?.loserMatchUpIds[W.matchUpId];if(it&&W.loserMatchUpId!==it){W.loserMatchUpId=it;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:W};j.push(Q)}let z=V?.winnerMatchUpIds[W.matchUpId];if(z&&W.winnerMatchUpId!==z){W.winnerMatchUpId=z;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:W};j.push(Q)}}),{structures:x,matchUpModifications:j,links:F,drawDefinition:T,...C}}function pT({element:t}){if(!t)return{error:B};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:B};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function ro(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:mf};let i=oS(t);if(i.error)return i;if(!(ht(o)&&kt(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:pf};if(!i.timeItems)i.timeItems=[];else if(rV({element:i,duplicateValues:e,timeItem:o}))return{...C};if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let c=new Date().toISOString();Object.assign(o,{createdAt:c})}return n&&(i.timeItems=i.timeItems.filter(({itemType:c})=>o.itemType!==c)),n&&!o.itemValue||i.timeItems.push(o),{...C}}function rV({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&nn({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function Gg({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:q};if(!o)return{error:se};let s=Uo({tournamentRecord:r,participantId:o});return s.error?s:ro({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function _c(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:q};let s=ro({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=pT({element:r});return lt({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:Xi}),s}function is(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?ro({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:qr}}function iD(t){return Bg({...t,itemType:"attachConsolationStructures"})}function Vg(t){return Bg({...t,itemType:"attachPlayoffStructures"})}function Bg({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:Z};if(!Array.isArray(o)||!Array.isArray(i))return _({result:{error:B},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 _({result:{error:If},info:"playoff structure exists",stack:a});i.length&&n.links?.push(...i);let m=o.map(({structureId:h})=>h),d=n.structures?.map(({structureId:h})=>h);n.structures=(n.structures??[]).map(h=>m.includes(h.structureId)?o.find(({structureId:S})=>S===h.structureId):h);let l=o?.filter(({structureId:h})=>!d?.includes(h));l.length&&n.structures.push(...l),rs({drawDefinition:n});let f=o.map(h=>yt({structure:h})?.matchUps||[]).flat();Fo({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(bt({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,...P}=h[y.matchUpId].matchUp;if(Object.assign(y,P),E?.length){let A={};E.forEach(U=>h[U.matchUpId]=U),y.tieMatchUps.forEach(U=>Object.assign(U,A[U.matchUpId]))}h[y.matchUpId].matchUp=y,gt(h[y.matchUpId])}})};n.structures.forEach(T=>{if(d?.includes(T.structureId))if(T.structures)for(let y of T.structures)S(y);else S(T)})}let I=l.map(Hr("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};ro({element:r,timeItem:S})}return{...C,addedStructureIds:I}}function Kp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=kd(t);if(o)return{error:o};let i=t.drawDefinition;return Vg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function ss(t){let e=et(t,[{_anyOf:{[Re]:!1,[ne]:!1,[Ce]:!1,[co]:!1},[_f]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=Ov(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&bt({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:q};for(let i of o){let s=t.tournamentRecords[i],a=Ov(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:q};return r.length?{...C,applied:r}:{error:$I}}function Ov(t,e){let r=Tt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:op};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!ht(s))return{error:B};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!kt(a))return{error:B};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...At({element:e,extension:{name:du,value:r}}),applied:n}:{applied:n,error:$I}}function Hg({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:B},context:{drawName:n}});r||(r=Ht({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:pn,value:{...r,flights:r.flights}};xo({event:i,extension:a})}return e&&(e.drawName=n,bt({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:Z}:{...C,flight:s}}function sD({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!ht(r))return{error:B};let i=Ht({event:o}).flightProfile,s=r.drawName&&Hg({drawName:r.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:i,drawId:n,event:o});if(s?.error)return s?.error;let a=s?.flight||i?.flights?.find(c=>c.drawId===n);if(!a&&!e)return{error:Z};if(a){let c={name:pn,value:{...i,flights:i.flights}};xo({event:o,extension:c})}return e&&(r.policyDefinitions&&ss({policyDefinitions:r.policyDefinitions,drawDefinition:e}),bt({tournamentId:t?.tournamentId,drawDefinition:e})),{...C}}function aD({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:Z};let n=Pe({drawDefinition:r}),o=s=>n?.drawMatchUps?.find(a=>a.matchUpId===s);for(let s of r.structures||[]){let{positionAssignments:a,stage:c,stageSequence:u}=s;a&&(u!==1||![ct,rt].includes(c))&&(s.positionAssignments=a.map(d=>(delete d.participantId,d)),s.seedAssignments=[]);let{matchUps:p,isRoundRobin:m}=yt({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:n,structure:s});for(let d of p){let{matchUpId:l,roundNumber:f}=d,g=d.sides||[],I=o(l);if(I){if(delete I.extensions,delete I.notes,I.matchUpStatus!=="BYE"&&Object.assign(I,Gu),f&&f>1&&I.drawPositions?.length&&!m){let h=g?.map(({drawPosition:T,participantFed:y})=>!y&&T).filter(Boolean),S=I.drawPositions.map(T=>h.includes(T)?void 0:T);I.drawPositions=S}e?delete I.timeItems:I.timeItems?.length&&(I.timeItems=I.timeItems.filter(h=>h.itemType&&![lo,Jo,Ji,dg,Zi,ts].includes(h.itemType))),gt({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}r.extensions=r.extensions.filter(s=>s.name!==lc);let i=(r.structures||[]).map(({structureId:s})=>s);return bt({drawDefinition:r,structureIds:i}),{...C}}function Vu({tournamentRecord:t}){if(!t)return{error:q};let e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={};return(t.events?.map(o=>{let i=o.eventId;return r[i]=o,(o?.drawDefinitions||[]).map(s=>({drawDefinition:s,eventId:i}))}).flat().filter(Boolean)).forEach(({drawDefinition:o,eventId:i})=>{let s=0,a=0,c=0,{allStructuresLinked:u}=_u({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(E=>{let{stage:P,stageSequence:A,structureId:U}=E,N=$s[P],{inContextStructureMatchUps:D}=va({drawDefinition:o,structure:E,event:p}),M=D?.filter(({winningSide:Y})=>Y),R=M.filter(Boolean).length||0;a+=R,c+=D.length-a;let b=Math.max(M.filter(({roundNumber:Y})=>Y===1).map(({roundPosition:Y})=>Y)),{positionAssignments:O}=Ct({structure:E}),v=O?.filter(({participantId:Y})=>Y);s+=v?.length??0;let x=(O?.length??0)-(v?.length??0),{roundMatchUps:F,roundProfile:w,roundNumbers:L,maxMatchUpsCount:k}=Ke({matchUps:D}),G=w&&Object.keys(w).filter(Y=>!w[Y].inactiveRound).map(Y=>parseInt(Y)),H=w&&Object.keys(w).filter(Y=>w[Y].inactiveRound).map(Y=>parseInt(Y)),K=w&&Object.values(w).every(Y=>Y.inactiveRound);return{positionsAssignedCount:v?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:x,inactiveStructure:K,maxMatchUpsCount:k,inactiveRounds:H,roundMatchUps:F,activeRounds:G,roundNumbers:L,roundProfile:w,structureId:U,stageSequence:A,orderNumber:N,stage:P}}),l=d.find(E=>E.orderNumber===2&&E.stageSequence===1),f=d.filter(({inactiveStructure:E})=>!E).length,{links:g}=Js({structureId:l.structureId,drawDefinition:o}),I=dt(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=d?.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:d,inactiveDraw:h,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=y}),{...C,drawsAnalysis:e}}function cD({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:q};if(!r)return{error:Z};let o=[],{drawsAnalysis:i}=Vu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=hn({stageSequence:1,drawDefinition:r,stage:rt}),u=a.structuresData.find(({structureId:l})=>c.structureId===l),p=(c.matchUps??[]).sort((l,f)=>l.roundPosition-f.roundPosition);o=p.filter(({roundNumber:l})=>!u.inactiveRounds.includes(l));let m=o.map(Ue),d=p.map(Ue).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Ue),g=m.filter(T=>!f.includes(T));d.push(...g);let h=l.flatMap(T=>T.drawPositions??[]).filter(Boolean).flat(),S=Object.assign({},...h.map((T,y)=>({[T]:y+1})));if(l.forEach(T=>{t?T.drawPositions=T.drawPositions.map(y=>S[y]):delete T.drawPositions}),t){let T=c?.positionAssignments?.filter(y=>h.includes(y.drawPosition)).map(y=>(y.drawPosition=S[y.drawPosition],y));c.positionAssignments=T}else c.positionAssignments=[];c.matchUps=l,o=l}_n({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),bt({drawDefinition:r})}return{...C,matchUps:o}}function uD({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,qualifier:i,event:s,bye:a}){if(!e)return{error:Z};if(!n)return{error:Fs};if(!o)return{error:Pr};if(a){let c=Wr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:pp};{let c=jn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...C}}function mT(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:_t};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:_t};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===zi)return{error:si};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Ue);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function pD(t){let e=et(t,[{[Ce]:!0},{[Ks]:{[mc]:!1,roundNumbers:!1},[kr]:B,[He]:Be}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=mT(t);if(c.error)return c;let{structure:u,structureId:p,existingMatchUps:m,matchUpIds:d}=c,l=[],f=m?.filter(({matchUpId:h,score:S,winningSide:T})=>{if(T&&!o)return!1;if(T||he({score:S})){if(!T&&!r)return!1;l.push(h)}else if(!n)return!1;return d?.includes(h)})??[],g=f.map(Ue),I=f.map(({tieMatchUps:h})=>h?.map(Ue)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),_n({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=pt(u.matchUps.map(Hr("roundNumber"))),S=PC(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,gt({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=pt(u.matchUps.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,E=c.existingMatchUps.some(N=>N.matchUpType===xr)?{matchUpTypes:[xr]}:void 0,{matchUps:P}=yt({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:E,structure:u,event:a});cr({structure:u})&&(u.positionAssignments=pt(P.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N})));let U=Ld({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:P,event:a});U.error&&console.log(U)}bt({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:oc}:{...C,deletedMatchUpsCount:[...g,...I].length}}function mD({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:q};if(!r)return{error:Z};if(!o)return _({result:{error:st},info:"roundNumber required"});let s=at({drawDefinition:r,structureId:n});if(s.error)return s;let a=s.structure;return a?.structures?{error:si}:cr({structure:a})?nV({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...C})}function nV({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:r,roundNumber:n,structure:o,eventId:i}){let s=o?.matchUps??[],a=[],c=[],u=!1;if(s.reduce((m,d)=>{let l=d?.roundNumber;return l?m.includes(l)?m:m.concat(l):m},[]).sort(le).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!ae.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Ue))),!l});c.length&&(_n({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,gt({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...C}}function Gd(t){let{suppressNotifications:e,tournamentRecord:r,drawDefinition:n,matchUps:o,event:i}=t;if(typeof n!="object")return{error:Z};let s=t?.structureId;if(!s&&n.structures?.length===1&&(s=n.structures?.[0]?.structureId),typeof s!="string")return{error:Pr};if(!Br(o))return{error:B,info:li("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:_t};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===zi)return{error:si};let p=ye({tournamentRecord:r,inContext:!1})?.matchUps?.map(Ue)??[],m=o.map(Ue);if(ke(p,m))return{error:YA,info:"One or more matchUpIds already present in tournamentRecord"};a.matchUps.push(...o);let d=o.map(({tieMatchUps:l})=>l).filter(Boolean).flat();return e||(Fo({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),bt({drawDefinition:n,structureIds:[s]})),{...C}}function dD({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:Z};if(!n)return{error:Pr};if(!r)return{error:Fs};let{structure:s}=at({drawDefinition:e,structureId:n});if(!s)return{error:_t};let a=s;s.structures&&s.structureType===Ve&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&At({element:u,extension:{name:fc,value:o}});let d=(i?.eventType===Wt||e.matchUpType===Wt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[Wt]},{matchUps:l}=yt({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return Ld({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),bt({drawDefinition:e,structureIds:[n]}),{...C}}var PD={};Xt(PD,{addGoesTo:()=>rs,allPlayoffPositionsFilled:()=>WS,checkValidEntries:()=>Hd,findDrawDefinition:()=>gT,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getMatchUpsMap:()=>Pe,getParticipantIdFinishingPositions:()=>fT,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getRandomQualifierList:()=>RT,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getValidGroupSizes:()=>Gp,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,positionActions:()=>MT});function dT({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:r,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:m,winsLimit:d,event:l}){if(!a)return{error:Z};let f=[rt,fe];r&&f.push(ct);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?to({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:nr({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=bi({stage:$e,drawDefinition:a}).map(({participantId:L})=>L),y={},E={},P={},A={};o||(o=Go({policyTypes:[Bh],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let U=o?.[Bh];t=t.length&&t||U?.excludedMatchUpStatuses||[],e=e??U?.includeEventParticipants,m=m??U?.allEntries,n=n??U?.finishingRoundLimit,i=i??U?.roundNumberLimit,c=c??U?.matchUpsLimit,u===void 0&&(u=U?.requirePlay!==void 0?U.requirePlay:!0),p===void 0&&(p=U?.requireLoss!==void 0?U.requireLoss:!0),d=d??U?.winsLimit;for(let L of h){if(u&&L.winningSide&&![1,2].includes(L.winningSide)&&L.matchUpStatus!==oe||L.finishingRound&&n&&L.finishingRound>=n||L.finishingRound&&i&&L.finishingRound<=i)continue;let k=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===3-L.winningSide),G=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===L.winningSide);if(L.sides?.forEach(H=>{let K=H?.participant?.participantId;K&&(P[K]=H.participant,L.matchUpStatus===oe&&!u&&(E[K]=H.participant,y[K]||(y[K]=0),(!L.matchUpStatus||!t.includes(L.matchUpStatus))&&(y[K]+=1)))}),k?.participant){let H=k.participant.participantId;E[H]=k.participant,y[H]||(y[H]=0),L.matchUpStatus&&!t.includes(L.matchUpStatus)&&(y[H]+=1)}if(G?.participant){let H=G.participant.participantId;A[H]||(A[H]=0),A[H]+=1,y[H]||(y[H]=0),L.matchUpStatus&&!t.includes(L.matchUpStatus)&&(y[H]+=1)}}let N=s?.participants&&!u&&!p&&m,D=N?((e&&l?l.entries:a.entries)??[]).filter(L=>![mo,Vr].includes(L.entryStatus)).map(({participantId:L})=>L):[],M=Object.keys(E),R=N?(s?.participants??[]).filter(({participantId:L})=>D.includes(L)):p&&Object.values(E)||Object.values(P),b=L=>!p||M.includes(L),O=L=>!u||(y[L]||0)>=0,v=L=>!d||(A[L]||0)<=d,x=L=>!c||y[L]<=c,F=L=>!T.includes(L);return{eligibleParticipants:R.filter(L=>b(L.participantId)&&O(L.participantId)&&v(L.participantId)&&x(L.participantId)&&F(L.participantId)).map(L=>({...L,individualParticipants:L.individualParticipantIds?.map(k=>s?.participants?.find(G=>G.participantId===k))})),losingParticipantIds:M,...C}}function Vd(t){let e=et(t,[{drawDefinition:!0}]);if(e.error)return e;let{drawDefinition:r,roundNumber:n}=t,o=t.structureId??(r.structures?.length===1&&r.structures?.[0]?.structureId);if(typeof o!="string")return{error:Pr};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:_t};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===zi)return{error:si};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return Xr.includes(I)})??[],p=Math.floor(u?.length/2)||1,m=n??c??1,d=i.matchUps?.filter(g=>g.roundNumber===m)?.length??0,l=p-d,f=l>0?l:0;return{...C,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function lT({drawDefinition:t}){let e=mt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function vv({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:Z};let n=ie({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=J(n.matchUps,!1,!0),i=pt(o.reduce((a,c)=>a.concat(...c.sides.map(u=>u.participantId).filter(Boolean)),[])),s=Object.assign({},...i.map(a=>{let c=o.filter(u=>u.sides.map(m=>m.participantId).filter(Boolean).includes(a));return{[a]:c}}));return{participantIds:i,participantIdMatchUps:s}}function fT({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:Z};let{participantIds:n,participantIdMatchUps:o}=vv({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[ge,"BYE"].includes(d.matchUpStatus)||d.winningSide),u=c.map(d=>{let l=d.sides.find(I=>I.bye),f=d.sides.find(I=>I.participantId===s).sideNumber;return(d.winningSide||t&&l&&f)===f?d.finishingPositionRange.winner:d.finishingPositionRange.loser}),p=d=>Math.abs(d[0]-d[1]),m=u.reduce((d,l)=>d&&p(d)<p(l)?d:l,void 0);return{[s]:{relevantMatchUps:c,finishingPositionRanges:u,finishingPositionRange:m}}})||[];return Object.assign({},...i)}function jo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:q};if(!n)return{error:cn};if(!e&&t){if(typeof r!="string"&&(r=cT({tournamentRecords:t,drawId:n}),!r))return{error:ha};if(e=t[r],!e)return{error:q}}let o=e&&ze({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...C}:_({result:{error:br},stack:"findDrawDefinition"})}function gT(t){let{drawDefinition:e,error:r}=jo(t);return r?{error:r}:{drawDefinition:J(e)}}function _v({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Vr,Ci].includes(a)).map(({participantId:a})=>a)||[];if(s.length){let a=n.individualParticipantIds,c=e?t.filter(({participantId:m})=>s.includes(m)):void 0,u=e?t.filter(({participantId:m})=>a.includes(m)):void 0;return{validModifyAssignedPairAction:nt({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:nv,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:vg},!1,!1,!0)}}return{}}function Fi(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===kn&&r?.matchUp?.matchUpStatus==="BYE")return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&ur({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,m=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,d=p?.sides[m]?.participant,l=pr(s?.matchUpStatus),f=l&&!d,g=s?.sides?.reduce((E,P)=>P?.participant?++E:E,0)??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||!pr(a?.matchUpStatus))))return!0;let S=a&&ur({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),T=u&&Fi({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(S&&Fi({targetData:S,inContextDrawMatchUps:e,drawDefinition:n})||T)}var IT={[Jn]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ct,rt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[xu,ia,Wp,oa],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var Wg="positionAction",hT="matchUpAction";function ST({actionType:t=Wg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===Wg&&Jn||t===hT&&er,i=t===Wg&&IT||t===hT&&IP,s=o&&(e?.[o]||i?.[o]),c=r.links?.filter(d=>d?.target?.structureId===n?.structureId)?.map(({target:d})=>d.feedProfile)??[],{enabledStructures:u,disabledStructures:p}=s||{},m=p?.find(d=>{let{stages:l,stageSequences:f,structureTypes:g,feedProfiles:I}=d;return(!I?.length||Array.isArray(I)&&I.some(h=>c.includes(h)))&&(!l?.length||Array.isArray(l)&&l?.includes(n?.stage))&&(!g?.length||Array.isArray(g)&&g?.includes(n?.structureType))&&(!f?.length||Array.isArray(f)&&f.includes(n?.stageSequence))});return{enabledStructures:u,actionsDisabled:m,actionsPolicy:s}}function fD({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function TT({enabledStructures:t,drawDefinition:e,structure:r}){if(t===!1)return{};if(!t?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};let{stage:n,stageSequence:o,structureType:i}=r||{},a=e.links?.filter(u=>u?.target?.structureId===r?.structureId)?.map(({target:u})=>u.feedProfile)||[];return{policyActions:t.find(u=>{let{stages:p,stageSequences:m,structureTypes:d,feedProfiles:l}=u||{},f=!p?.length||Array.isArray(p)&&p.includes(n),g=!m?.length||Array.isArray(m)&&m.includes(o),I=!d?.length||Array.isArray(d)&&d.includes(i),h=!l?.length||Array.isArray(l)&&l.some(S=>a.includes(S));return g&&I&&h&&u&&f})}}function qn({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 gD="replaceTieMatchUpParticipantId",ID="assignTieMatchUpParticipantId",yT="removeTieMatchUpParticipantId",hD="assignMatchUpSideParticipant",xv="removeMatchUpSideParticipant",SD="substituteParticipant",ET="REMOVE_SUBSTITUTION",TD="REPLACE_PARTICIPANT",jg="REMOVE_PARTICIPANT",AT="setMatchUpStatus",UT="SUBSTITUTION",yD="SCHEDULE",oV="PENALTY",PT="REFEREE",ED="STATUS",DT="START",AD="SCORE";var wv={REPLACE_TEAM_POSITION_METHOD:gD,ASSIGN_TEAM_POSITION_METHOD:ID,REMOVE_TEAM_POSITION_METHOD:yT,REPLACE_PARTICIPANT:TD,SUBSTITUTION_METHOD:SD,REMOVE_SUBSTITUTION:ET,REMOVE_PARTICIPANT:jg,SCHEDULE_METHOD:AT,SUBSTITUTION:UT,SCHEDULE:yD,PENALTY:oV,REFEREE:PT,STATUS:ED,SCORE:AD,START:DT,END:"END"};function Lv({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:m,side:d}){let l=[],f=o.sides?.find(F=>F.participant),g=en(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(St),E=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),P=E?.map(St),U=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:w,person:L})=>!P?.includes(w)&&(!S||To(S)||L.sex===S||en(S)&&!g||g&&L.sex!==g))),N=c?U?.[c-1]:U?.map((F,w)=>({participants:F,sideNumber:w+1})),D=c?U?.[c-1]?.map(St):U?.map((F,w)=>({participants:F?.map(St),sideNumber:w+1})),M=c&&(de(Ia)(I)&&!P?.length||de(Gi)(I)&&(P?.length??0)<2)||!c&&(de(Ia)(I)&&(P?.length??0)<2||de(Gi)(I)&&(P?.length??0)<4),R=D?.filter(F=>!y?.includes(F)),b=N?.filter(({participantId:F})=>R.includes(F));if(M&&R?.length&&l.push({availableParticipantIds:R,method:ID,availableParticipants:b,type:Ms,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),P?.length&&(!he(p)||d?.substitutions?.length)&&l.push({method:yT,type:jg,existingParticipantIds:P,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&P?.length||c&&d?.participant)&&l.push({availableParticipantIds:R,method:gD,availableParticipants:b,type:TD,existingParticipantIds:P,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),qn({policyActions:i,action:ET})&&d?.substitutions?.length){let F=d.participant?.participantType===Et&&[d.participantId]||d.participant?.participantType===ft&&d.participant.individualParticipantIds||[],w=d.substitutions.map(L=>L.participantId).filter(L=>F.includes(L));(!a||w.includes(a))&&l.push({method:yT,type:ET,substitutedParticipantIds:w,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let O=t?.[er],v=O?.substituteWithoutScore,x=O?.substituteAfterCompleted;if(qn({policyActions:i,action:UT})&&r.length===2&&(!c&&P?.length||c&&d?.participant)&&(v||he(p))&&(x||p.matchUpStatus&&!ae.includes(p.matchUpStatus))&&E?.length&&N.length){let F=E.map(St);l.push({info:"list of team players available for substitution",method:SD,availableParticipantIds:D,existingParticipantIds:F,availableParticipants:N,existingParticipants:E,type:UT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function Fv({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:r,positionAssignments:n,returnParticipants:o,appliedPolicies:i,drawDefinition:s,drawPosition:a,validActions:c,structureId:u,structure:p,drawId:m,event:d}){if(r.includes(a))return{};let l=c.find(U=>U.type===Ms)?.availableParticipantIds,f=i?.[Jn]?.otherFlightEntries,g=i?.[Jn]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:U})=>!g||(p.stage===ct?U===ct:U!==ct)).sort((U,N)=>(U.entryPosition??1/0)-(N.entryPosition??1/0)).map(({participantId:U})=>U).filter(Boolean),{allPositionedParticipantIds:h}=Xh({drawDefinition:s}),S=n.map(U=>U.participantId).filter(Boolean),T=I.filter(U=>p.stage&&[ct,rt,fe].includes(p.stage)?!h?.includes(U):!S.includes(U)),E=(d?.entries??[]).filter(U=>U.entryStatus===on&&UD({restrictQualifyingAlternates:g,structure:p,entry:U})&&(p.stage&&[ct,rt,fe].includes(p.stage)?!h?.includes(U.participantId):!S.includes(U.participantId))).sort((U,N)=>(U.entryPosition??1/0)-(N.entryPosition??1/0)).map(U=>U.participantId),P=pt(T.concat(E));if(f){let N=(d?Ht({event:d}).flightProfile:void 0)?.flights?.filter(D=>D.drawId!==m).map(D=>D.drawEntries.filter(M=>M.participantId&&![mo,Vr,Ci].includes(M.entryStatus)&&!I.includes(M.participantId)).map(({participantId:M})=>M)).flat().filter(Boolean);N?.length&&P.push(...N)}l?.length&&(P=P.filter(U=>!l.includes(U)));let A=o?t?.filter(U=>P.includes(U.participantId)):void 0;return A?.forEach(U=>{let N=(s.entries??[]).find(D=>D.participantId===U.participantId);U.entryPosition=N?.entryPosition}),A?.sort((U,N)=>(U.entryPosition||1/0)-(N.entryPosition||1/0)),P.length?{validAlternatesAction:nt({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:ev,availableAlternatesParticipantIds:P,type:_g,availableAlternates:A})}:{}}function UD({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===ct&&!t||r.entryStage===rt&&n===qe)return!0}function kv({eventEntries:t,structure:e}){let r=o=>o.entryStatus===on&&UD({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(St)}function Gv({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:m}){let d=[],l=c?.matchUps??[],g=u.sides?.find(N=>N.sideNumber===s)?.participantId,I=l.filter(({roundNumber:N})=>N===u.roundNumber),h=o?.entries?.filter(({entryStatus:N})=>N&&mi.includes(N)).map(St)??[],S=I.map(N=>(N.sides??[]).flatMap(St)).flat().filter(Boolean),T=h.filter(N=>!r.includes(N)&&(!t||!S.includes(N))),y=e?.filter(N=>T?.includes(N.participantId)).map(N=>J(N,void 0,!0));y?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),T.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:hD,type:Ms,availableParticipantIds:T,participantsAvailable:y});let E=m?.entries??[],P=kv({eventEntries:E,structure:c}),A=pt(h.concat(P));if(n){let D=(m?Ht({event:m}):void 0)?.flights?.filter(M=>M.drawId!==p).flatMap(M=>M.drawEntries.filter(R=>R.participantId&&![mo,Vr,Ci].includes(R.entryStatus)).map(({participantId:R})=>R)).filter(Boolean);D?.length&&A.push(...D)}A=A.filter(N=>!r.includes(N)&&!T.includes(N)&&(!t||!S.includes(N)));let U=e?.filter(N=>A.includes(N.participantId)).map(N=>J(N,void 0,!0));if(U?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),U?.sort((N,D)=>(N.entryPosition||1/0)-(D.entryPosition||1/0)),A.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:A,participantsAvailable:U,method:hD,type:on}),!he(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:xv,type:jg});let N=w=>w.sides.map(St),D=({matchUpId:w})=>w!==u.matchUpId,M=w=>!he(w),R=u.sides?.find(w=>w.sideNumber!==s)?.participantId,O=l.filter(({roundNumber:w})=>w!==u.roundNumber).filter(D).map(N),v=[R,...O.filter(w=>w.includes(g)).flat()].filter(Boolean),x=w=>!v.flat().includes(w),F=I.filter(M).filter(D).map(N).flat().filter(x);if(F.length){let w=e?.filter(L=>F.includes(L.participantId)).map(L=>J(L,void 0,!0));d.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:ov,type:Yp,swappableParticipants:w})}}return d}function Bd(t){if(!t)return{error:B};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&&kt(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:q};if(!c||!kt(c))return{error:sr};if(a&&![1,2].includes(a))return _({result:{error:B},context:{sideNumber:a}});if(!e){let Q=(ye({tournamentRecord:u}).matchUps??[]).find(ot=>ot.matchUpId===c);r=(u?.events??[]).find(ot=>ot.eventId===Q?.eventId);let ut=(r?.drawDefinitions??[]).find(ot=>ot.drawId===Q?.drawId);ut&&(e=ut)}if(!e)return{error:Z};let p=Ft({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Vt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:we};let f=Tt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[Jn]?.otherFlightEntries,I=f?.[er]??Ps[er],{enabledStructures:h}=ST({actionType:hT,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=TT({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??Pe({drawDefinition:e}),y=t.inContextDrawMatchUps??ie({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,E=y?.find(z=>z.matchUpId===c),P=a&&E?.sides?.find(z=>z.sideNumber===a),A=E?.sides?.map(z=>z.participantId||z.participant?.participantid).filter(Boolean)??[],{assignedPositions:U,allPositionsAssigned:N}=Ie({structure:l}),{structureId:D}=l??{},M=[];if(!D)return{validActions:M};let R=cr({structure:l}),b=!!d.collectionId;if(R&&!b){let z=Gv({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:A,otherFlightEntries:g,drawDefinition:e,structureId:D,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r});M.push(...z)}let O=Do({drawDefinition:e,structure:l}),v=U?.filter(z=>z.participantId).map(z=>z.drawPosition),x=U?.filter(z=>z.bye).map(z=>z.drawPosition),F=d.matchUpStatus==="BYE"||!b&&d.drawPositions?.reduce((z,Q)=>x?.includes(Q)||z,!1);if(F)return{validActions:M,isByeMatchUp:F};qn({policyActions:S,action:PT})&&M.push({type:PT,payload:{matchUpId:c}});let w=!Oa({matchUpStatus:d.matchUpStatus}),L=f?.scoring?.structures,k=l?.stage&&L?.stage&&L?.stage[l.stage],G=l?.stageSequence&&k?.stageSequence&&k.stageSequence[l.stageSequence],K=!(f?.scoring?.requireAllPositionsAssigned||k?.requireAllPositionsAssigned||G?.requireAllPositionsAssigned)||N,Y=d.sides&&d.sides.filter(z=>z?.participantId).length===2,j=d.matchUpStatus&&[oe,be].includes(d.matchUpStatus),V=ur({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),$=Fi({inContextDrawMatchUps:y,drawDefinition:e,targetData:V}),W=(E?.drawPositions?.length===2&&E.drawPositions.every(z=>v?.includes(z))&&E?.sides?.length===2&&E.sides.every(({participantId:z})=>z)||Y)&&!(j&&$),it={method:zS,type:ia,payload:{drawId:m,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(w&&M.push({payload:{drawId:m,matchUpId:c,schedule:{}},method:AT,type:yD}),qn({policyActions:S,action:ia})&&(P?.participant||!a&&A?.length)&&M.push(it),w&&W&&M.push({type:ED}),K&&W){let{matchUpId:z,matchUpFormat:Q}=d,ut={drawId:m,matchUpId:z,matchUpFormat:Q,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};M.push({info:"set outcome and winningSide",method:AT,type:AD,payload:ut}),qn({policyActions:S,action:DT})&&M.push({type:DT}),qn({policyActions:S,action:"END"})&&M.push({type:"END"})}if(b&&E){let z=Lv({specifiedPolicyDefinitions:o,inContextDrawMatchUps:y,matchUpParticipantIds:A,matchUpActionsPolicy:I,inContextMatchUp:E,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:P});M.push(...z)}return{structureIsComplete:O,validActions:M,isDoubleExit:j,...C}}function Bv({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:o,positionAssignments:i,drawDefinition:s,drawPosition:a,structureId:c,structure:u,drawId:p,event:m}){if(o.includes(a)||n&&!e)return{};let{sourceStructureIds:d,targetStructureIds:l}=s.links?.reduce((h,S)=>{let T=S.source?.structureId,y=S.target?.structureId;return h.sourceStructureIds.includes(T)||h.sourceStructureIds.push(T),h.targetStructureIds.includes(y)||h.targetStructureIds.push(y),h},{sourceStructureIds:[],targetStructureIds:[]})||{},f=[],g=s.links?.filter(h=>h.target?.structureId===u.structureId)??[];for(let h of g){let S=h?.source?.structureId,{structure:T}=at({structureId:S,drawDefinition:s}),y=T?.finishingPosition===zi&&(d?.length!==1||l?.length!==1),E={};if(y){let{matchUps:N}=yt({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:D}=Es({drawPosition:a,matchUps:N}),R=s.links?.find(b=>b.target?.structureId===u?.structureId&&b.target.roundNumber===D)?.source?.roundNumber;E.roundNumbers=[R]}let{completedMatchUps:P}=Mu({structureId:S,inContext:!0,matchUpFilters:E,drawDefinition:s}),A=i.map(N=>N.participantId).filter(Boolean);P?.filter(({matchUpType:N,winningSide:D})=>D&&(m?.eventType!==_e||N===_e)).map(({winningSide:N,sides:D})=>N&&D?.[1-(N-1)]).map(St).filter(N=>N&&!A.includes(N))?.forEach(N=>{f.includes(N)||f.push(N)})}let I=t?.filter(h=>f?.includes(h.participantId));return I?.forEach(h=>{let S=(s.entries??[]).find(T=>T.participantId===h.participantId);h.entryPosition=S?.entryPosition}),f?.length?{validLuckyLosersAction:{type:wg,method:rv,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function Hv({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:o,isWinRatioFedStructure:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,seedingProfile:p,isByePosition:m,drawPosition:d,structureId:l,event:f}){let{drawId:g}=u,I=[],h,S,T=[],y=c?.[Vn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=xS({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)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:av,type:"BYE"}),i&&y){let E=s.map(D=>D.participantId).filter(Boolean),P={structureIds:t},{completedMatchUps:A}=Zs({inContext:!0,matchUpFilters:P,drawDefinition:u}),U=pt((A??[]).filter(({matchUpType:D})=>f?.eventType!==_e||D===_e)?.map(({sides:D})=>D?.map(St)).flat().filter(D=>D&&!E.includes(D))),N=a?o?.filter(D=>U?.includes(D.participantId)).map(D=>J(D,void 0,!0)):void 0;return N?.forEach(D=>{let M=(u.entries??[]).find(R=>R.participantId===D.participantId);D.entryPosition=M?.entryPosition}),N?.length&&I.push(nt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:YP,type:Ms,availableParticipantIds:U,participantsAvailable:N})),{validAssignmentActions:I}}if(T.includes(d)||m){let E;if(S?.length){let A=S.filter(U=>h?.includes(U.participantId));A.sort(iV),E=A.map(U=>U.participantId)}else E=e;let P=a?o?.filter(A=>E.includes(A.participantId)).map(A=>J(A,void 0,!0)):void 0;P?.length&&I.push(nt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:YP,type:Ms,availableParticipantIds:E,participantsAvailable:P}))}return{validAssignmentActions:I}}function iV(t,e){return t.bye||Nc(t.seedValue)<Nc(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function Wv({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:r,returnParticipants:n,appliedPolicies:o,drawDefinition:i,drawPosition:s,structureId:a,drawId:c}){let u=[],p=[],m=[],d=[],l=r.map(E=>E.participantId).filter(Boolean),f=o?.[Jn],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=vu({targetRoundNumber:g,linkType:Xn,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=vu({targetRoundNumber:g,linkType:Fn,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let E of S){let P=i.structures?.find(U=>U.structureId===E.source.structureId);if(P?.stage!==ct)continue;let A=Do({structureId:E.source.structureId,drawDefinition:i});if(!I||A){let U=P.qualifyingRoundNumber,{matchUps:N}=yt({matchUpFilters:{roundNumbers:[U],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:P});for(let D of N){let M=D.sides.find(b=>b?.sideNumber===D.winningSide),R=D.matchUpStatus==="BYE"&&D.sides?.find(({participantId:b})=>b);if(M||R){let{participantId:b,participant:O}=M||R||{};b&&!l.includes(b)&&(O&&n&&u.push(O),p.push(b))}}}}for(let E of y){let P=i.structures?.find(U=>U.structureId===E.source.structureId);if(P?.stage!==ct)continue;let A=Do({structureId:E.source.structureId,drawDefinition:i});if(!I||A){let{positionAssignments:U}=Ct({structure:P}),N=U?.map(D=>{let M=D.participantId,R=mt({element:D,name:Lo}).extension?.value;return R?{participantId:M,groupOrder:R?.groupOrder}:{}}).filter(({groupOrder:D,participantId:M})=>D===1&&!l.includes(M)).map(({participantId:D})=>D)??[];if(N&&p.push(...N),n){let D=e.filter(({participantId:M})=>N.includes(M));u.push(...D)}}}return p.length&&m.push(nt({qualifyingParticipants:n?u:void 0,method:ZO,type:Wp,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:m,sourceStructureIds:d}}function jv({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:r,inactiveDrawPositions:n,activeDrawPositions:o,positionAssignments:i,returnParticipants:s,byeDrawPositions:a,drawDefinition:c,isByePosition:u,drawPosition:p,structureId:m,structure:d,drawId:l,event:f}){if(o.includes(p))return{};let g=D=>!t||D.participantId||D.qualifier||D.bye,I=n?.filter(D=>D!==p&&!(u&&a.includes(D))),h=i?.filter(D=>g(D)&&I?.includes(D.drawPosition))??[],S=h.map(({drawPosition:D})=>D),{matchUps:T}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:D})=>ke(D,S)),E=Object.assign({},...y.map(D=>D.sides?.filter(({sourceDrawPositionRange:M})=>M).map(({drawPosition:M,sourceDrawPositionRange:R})=>({[M]:R}))).flat()),P=h.map(D=>D.participantId).filter(Boolean),A=(r??[]).filter(D=>P.includes(D.participantId)),U=Object.assign({},...A.map(D=>({[D.participantId]:D}))),N=h.map(D=>{let M=U?.[D.participantId],R=E[D.drawPosition];return nt({...D,participant:s?J(M,!1,!0):void 0,sourceDrawPositionRange:R})});return N.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:KS,type:Yp,availableAssignments:N}}:{}}function MT(t){let e=et(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return e;let{policyDefinitions:r,returnParticipants:n=!0,provisionalPositioning:o,tournamentRecord:i,drawDefinition:s,drawPosition:a,event:c}=t,u=t.tournamentParticipants??(i&&Ft({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=at({structureId:t.structureId,drawDefinition:s});if(p.error)return p;let m=p.containingStructure||p.structure;if(!m)return{error:_t};let d=m.structureId;if(p=va({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:Fs};if(p.isAdHoc)return Bd(t);if(p.error)return p;let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=Tt({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:y}=ST({actionType:Wg,appliedPolicies:h,drawDefinition:s,structure:m}),E=S?.activePositionOverrides||[],{sourceStructureIds:P}=vu({finishingPosition:Ei,targetRoundNumber:1,linkType:Fn,drawDefinition:s,structureId:d})||{},A;P?.length&&(A=P.every(W=>Do({structureId:W,drawDefinition:s})));let U=P.length,N=P.length&&!A,{policyActions:D}=TT({enabledStructures:T,drawDefinition:s,structure:m}),M=![ct,rt].includes(m.stage)||m.stageSequence!==1,{drawId:R}=s,b=[],{assignedPositions:O,positionAssignments:v}=Ie({structure:m}),x=O?.find(W=>W.drawPosition===a),F=!!x;if(!v?.map(W=>W.drawPosition)?.includes(a))return{error:Ls};let{stage:L,stageSequence:k}=m,G=[L];L===qe&&G.push(rt),L===rt&&G.push(qe);let H=bi({entryStatuses:mi,provisionalPositioning:o,drawDefinition:s,stageSequence:k,structureId:d,stages:G}),K=wi({drawDefinition:s,stages:G}).assignedParticipantIds??[],Y=H.filter(W=>!K.includes(W.participantId)).map(W=>W.participantId),j=I.includes(a),V=g.includes(a);if(y)return{info:"Actions Disabled for structure",isActiveDrawPosition:V,isDrawPosition:!0,hasPositionAssigned:F,validActions:[],isByePosition:j};if(qn({policyActions:D,action:Ms})&&!V&&v&&!N&&(!x||j)){let{validAssignmentActions:W}=Hv({positionSourceStructureIds:P,unassignedParticipantIds:Y,possiblyDisablingAction:M,isWinRatioFedStructure:U,tournamentParticipants:u,positionAssignments:v,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:j,drawPosition:a,structureId:d,event:c});W?.forEach(it=>b.push(it))}if(qn({policyActions:D,action:Wp})&&!V){let{validAssignmentActions:W}=Wv({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:v,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:R});W?.forEach(it=>b.push(it))}let{participantId:$}=x||{},X=$&&u.find(W=>W.participantId===$);if(x){qn({policyActions:D,action:QS})&&!V&&(b.push({type:QS,method:jP,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),j||b.push({type:xg,method:tv,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),qn({policyActions:D,action:"BYE"})&&!j&&b.push({type:"BYE",method:jP,payload:{drawId:R,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:M}));let W=m.stage===ct||m.stage===rt&&m.stageSequence===1;if(!j&&fD({activePositionOverrides:E,activeDrawPositions:g,action:oa})&&qn({policyActions:D,action:oa})&&Vp({drawDefinition:s,structureId:d,drawPosition:a})&&W){let{seedAssignments:it}=sn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z,seedValue:Q}=it?.find(ut=>ut.participantId===$)??{};b.push({type:oa,method:cv,participant:X,seedNumber:z,payload:{drawId:R,structureId:d,participantId:$,seedValue:Q}})}if(!j&&fD({activePositionOverrides:E,activeDrawPositions:g,action:jp})&&qn({policyActions:D,action:jp})&&Vp({drawDefinition:s,structureId:d,drawPosition:a})&&W){let{seedAssignments:it}=sn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z}=it?.find(Q=>Q.participantId===$)??{};b.push({method:sv,type:jp,participant:X,seedNumber:z,payload:{participantId:$,structureId:d,drawId:R}})}if(!j&&$){if(qn({policyActions:D,action:ia})){let it={type:ia,method:zS,participant:X,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};b.push(it)}if(qn({policyActions:D,action:xu})){let it={type:xu,method:iv,participant:X,payload:{participantId:$,otherName:void 0}};b.push(it)}}if(qn({policyActions:D,action:Yp})){let{validSwapAction:it}=jv({possiblyDisablingAction:M,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:v,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:j,drawPosition:a,structureId:d,structure:m,drawId:R});it&&b.push(it)}}if(qn({policyActions:D,action:_g})&&!N){let{validAlternatesAction:W}=Fv({possiblyDisablingAction:M,tournamentParticipants:u,positionAssignments:v,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:b,structureId:d,structure:m,drawId:R,event:c});W&&b.push(W)}if(qn({policyActions:D,action:wg})&&!N&&!V&&v){let{validLuckyLosersAction:W}=Bv({sourceStructuresComplete:A,possiblyDisablingAction:M,isWinRatioFedStructure:U,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:v,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:R});W&&b.push(W)}if(X?.participantType===ft&&qn({policyActions:D,action:vg})){let{validModifyAssignedPairAction:W}=_v({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:X,drawId:R,event:c});W&&b.push(W)}return{isActiveDrawPosition:V,isDrawPosition:!0,hasPositionAssigned:F,isByePosition:j,validActions:b,...C}}function Bu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Xm]?.drawTypeCoercion,o=e?.[Xm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}var RT=({drawDefinition:t})=>{let e=et({drawDefinition:t},[{[Ce]:!0}]);if(e.error)return e;let r=t.structures?.find(o=>o.stage===rt&&o.stageSequence===1);if(!r)return _({result:{error:zl}});let{qualifierPositions:n}=Ie({structure:r});return tt(0,n.length).sort(()=>Math.random()-.5)};function CT({structureId:t,drawDefinition:e}){if(!e)return{error:Z};if(!kt(t))return{error:B};let r=Js({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!jt([yi,Nn,Sp,Ti],n).length;return{...C,valid:o}}function zp({tournamentRecord:t,drawDefinition:e,stage:r=rt,structureId:n,structure:o}){if(!t)return{error:q};if(!o&&!e)return{error:Z};if(!o&&!n&&e?.structures?.filter(a=>a.stage===r).length===1&&(o=e.structures.find(a=>a.stage===r)),!o&&!n)return{error:Pr};let{error:i,positionAssignments:s}=Ct({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function bT({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:B};let r=us(t);return r?{drawSize:r}:_({result:{error:B},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function Hu(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=Go({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return _({result:I,stack:c});r=I.policyDefinitions}let p=It(u);if(u&&!p)return _({result:{error:B},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:UA},stack:c});if(isNaN(n))if(u)({drawSize:n}=bT({participantsCount:u}));else return _({result:{error:Za},stack:c});let m=o&&u||n;if(m&&m>n)return{error:of};let d=r?.[Vn];if(!d)return{error:pA};let l=d.seedsCountThresholds;return l?(d.drawSizeProgression!==void 0&&(e=d.drawSizeProgression),{seedsCount:l.filter(I=>e?I.drawSize<=n:n===I.drawSize).reduce((I,h)=>u&&u>=h.minimumParticipantCount?h.seedsCount:I,0)}):{error:KE}}function Hd({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=Ft({tournamentRecord:r})),!s)return{error:ec};if(!Array.isArray(s))return{error:B};if(!a)return{error:Ot};let c=e?.[er]??n?.[er]??Ps[er],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===Ko,l=p===Or&&wt||d&&ft||Et,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=sV({participant:S,participantType:l,eventType:p,entryStatusMap:f}),y=aV({genderEnforced:u,participantMap:o,eventGender:m,participant:S,isDoubles:d,mismatch:T});return T||!y});if(h.length){let S=h.map(T=>T.participantId);return{error:nA,invalidParticipantIds:S}}return{...C,valid:!0}}function sV({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[Ko,Or].includes(r)&&t.participantType===Et&&(ta(o)||o===mo);return t.participantType!==e&&!i}function aV(t){let{participant:e,participantMap:r,eventGender:n,mismatch:o,isDoubles:i,genderEnforced:s}=t,a=!o&&i&&pt(e?.individualParticipantIds?.map(m=>r?.[m]?.participant?.person?.sex).filter(Boolean)??[])||[],c=!n||!a?.length||To(n)||Dn(n)&&yr(a[0])===yr(n)||en(n)&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||en(n)||To(n)||Dn(n)&&yr(u)===yr(n);return!s||c&&p}function OT({hasExistingDrawDefinition:t,qualifyingProfiles:e,appliedPolicies:r,qualifyingOnly:n,tieFormat:o,idPrefix:i,isMock:s,uuids:a}){let c="generateQualifyingSTructures",u=[],p=[],m=[],d=(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,P,A,U;for(let N of(T||[]).sort(d)){let D=Rm(N.drawSize||N.participantsCount),{qualifyingRoundNumber:M,structureOptions:R,matchUpFormat:b,structureName:O,structureId:v,drawType:x}=N,F=N.matchUpType,w=N.qualifyingPositions||cV({drawSize:D,qualifyingRoundNumber:M}),L,k,G;if(!It(D))return _({result:{error:Za},stack:c});let H=e.length>1?`${h}-`:"",K=T.length>1||H?y:"",Y=O||(H||K?`${Qe(ct)} ${H}${K}`:Qe(ct));if(x===On){let{structures:j,groupCount:V,maxRoundNumber:$}=xa({structureName:N.structureName||Y,structureId:v||a?.pop(),hasExistingDrawDefinition:t,stage:ct,structureOptions:R,appliedPolicies:r,qualifyingOnly:n,stageSequence:y,matchUpType:F,roundTarget:h,tieFormat:o,drawSize:D,idPrefix:i,isMock:s,uuids:a});E=V,L=$,k=j[0],I=[1]}else({drawSize:D,matchUps:G,roundLimit:L}=xn({qualifyingRoundNumber:M,qualifyingPositions:w,matchUpType:F,drawSize:D,idPrefix:i,isMock:s,uuids:a})),k=yn({structureName:N.structureName||Y,structureId:v||a?.pop(),qualifyingRoundNumber:L,hasExistingDrawDefinition:t,stage:ct,qualifyingOnly:n,matchUpFormat:b,stageSequence:y,matchUpType:F,roundLimit:L,tieFormat:o,matchUps:G}),h&&At({extension:{name:vn,value:h},element:k}),E=G?.filter(j=>j.roundNumber===L)?.length||0;if(y>1){let{link:j}=La({sourceStructureId:A,sourceRoundNumber:P,targetStructureId:k.structureId,finishingPositions:U===Fn?[1]:void 0,linkType:U});m.push(j),f+=(D||0)-E}else f+=D||0;U=x===On?Fn:Xn,A=k.structureId,P=L,o&&(G=yt({structure:k})?.matchUps||[],G?.forEach(j=>{let{tieMatchUps:V}=Li({tieFormat:o,matchUp:j,isMock:s});Object.assign(j,{tieMatchUps:V,matchUpType:F})})),p.push(k),y+=1}g+=E,u.push({qualifiersCount:E,finalQualifyingRoundNumber:P,finalQualifyingStructureId:A,finishingPositions:I,roundTarget:h,linkType:U}),h+=1}return{qualifiersCount:g,qualifyingDrawPositionsCount:f,qualifyingDetails:u,structures:p,...C,links:m}}function cV({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function vT(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=dt(t.drawSize),o=e&&t.drawType!==Fr&&(typeof e=="boolean"||e<=2)&&n===2&&yo||t.drawType||yo,i=DU.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=yo;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:np},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function Yv(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Qe(rt),...t,stage:rt},{structures:i,groupCount:s,groupSize:a}=xa(o);if(s<1)return{error:GA};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Qe(fe)}],[u]=i,{structures:p,links:m}=rT({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...C,structures:i,links:m}}function qv({mainStructure:t,consolationStructure:e,deciderStructure:r}){let o=e.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),i=t.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),s=e.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),a=o.map((p,m)=>{let l=o.indexOf(p)%2?Nn:yi,f=1+m;return{linkType:so,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:Xn,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:Nn,roundNumber:i,structureId:t.structureId}},u=[{linkType:Xn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Nn,roundNumber:1,structureId:r.structureId}},{linkType:so,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Nn,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function $v({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=fi({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=Ds({structureName:t||Qe(rt),structureId:i?.pop(),stageSequence:1,stage:rt,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=fi({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=Ds({structureName:Qe(PU),matchUps:p,structureId:i?.pop(),stage:qe,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=xn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=Ds({structureName:Qe(UU),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:fe,matchUpType:e});s.push(l);let f=qv({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...C}}function Kv(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(Ln(s))return xn(t);let u=uV(s),p=u.shift(),m=tt(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=qp({roundNumber:l,matchUpType:o,idPrefix:i,matchUps:d,isMock:a,nodes:m,uuids:c})),l++;let f=t.roundLimit||e;for(let I of u){let h=I.participantsCount/2,S=tt(1,h+1);n&&h===n&&(f=l-1);let T=S.map(y=>{let E=vd({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:E}});d.push(...T),l++}let g=l-1;return d=ba({finishingPositionOffset:r,lucky:!0,roundsCount:g,roundLimit:f,matchUps:d}),f&&(d=d.filter(I=>I.roundNumber<=f)),{matchUps:d,roundsCount:g,roundLimit:f}}function uV(t){let e=dt(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 _T(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=rt,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??Tt(t),m=t.policyDefinitions?.[dc]||p?.[dc];t.skipRounds=t.skipRounds||s<=4&&(m?.feedFromMainFinal?0:1)||0;let d=t.structureName??e?.["0"]?.name??Qe(rt),l=()=>{let{matchUps:g}=xn(t);return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,tieFormat:o,matchUps:g,stage:n})],links:[],...C}};return{generators:{[Fr]:()=>({structures:[yn({finishingPosition:Ei,stageSequence:r,structureName:d,matchUps:[],matchUpType:i,structureId:u,stage:n})],links:[],...C}),[Ki]:()=>{let{matchUps:g}=Kv(t);return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,matchUps:g,stage:n})],links:[],...C}},[yo]:()=>l(),[su]:()=>$v(t),[ou]:()=>Rc({...t,roundOffsetLimit:3,playoffAttributes:e??Of}),[iu]:()=>Rc({...t,roundOffsetLimit:2,playoffAttributes:e??vf}),[fe]:()=>Rc(t),[Ea]:()=>{let{matchUps:g}=fi({drawSize:s,uuids:a,matchUpType:i});return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,stage:rt,tieFormat:o,matchUps:g})],links:[],...C}},[Tp]:()=>JS(t),[au]:()=>bc({...t,feedRounds:1,fmlc:!0}),[AU]:()=>bc({...t,feedRounds:1}),[bh]:()=>bc({...t,feedsFromFinal:1}),[Oh]:()=>bc({...t,feedsFromFinal:2}),[vh]:()=>bc({...t,feedsFromFinal:3}),[yp]:()=>bc(t),[bf]:()=>tT(t),[On]:()=>xa(t),[Eo]:()=>Yv(t)}}}function Wd(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,qualifyingOnly:o,staggeredEntry:i,drawDefinition:s,tieFormat:a,isMock:c,uuids:u}=t||{},p=dt(t.drawSize),m=t.drawTypeCoercion??Bu({appliedPolicies:n,drawType:t.drawType}),d="generateDrawStructuresAndLinks",l=vT({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:m,drawSize:p});if(l.error)return l;let f=l.drawType,g=[],I=[],h=t?.matchUpType??Lt,S=s?.structures?.filter(({stage:K})=>K===ct);S&&g.push(...S);let T=S?.map(({structureId:K})=>K),y=s?.structures?.find(({stage:K,stageSequence:Y})=>K===rt&&Y===1),E=s?.links?.filter(K=>K.target.structureId===y?.structureId&&T?.includes(K.source.structureId)),P=(K,Y)=>{if(K.linkType===Fn&&Y?.structures){let j=K.source.finishingPositions||[];return Y.structures.length*j.length}else if(K.linkType===Xn&&Y?.matchUps?.length){let j=K.source.roundNumber;return Y.matchUps.filter(({roundNumber:$})=>$===j).length}},A=S?.map(K=>{let Y=E?.find(W=>W.target.structureId===K.structureId),j=Ct({structure:K})?.positionAssignments?.length??0;if(!Y)return j;let V=Y?.source.structureId,$=s.structures?.find(W=>W.structureId===V),X=P(Y,$)||0;return j-X}).filter(Boolean).reduce((K,Y)=>K+Y,0),U=E?.map(K=>{let Y=K.source.structureId,j=S?.find(V=>V.structureId===Y);return P(K,j)}).filter(Boolean).reduce((K,Y)=>K+Y,0),N=!!(y&&!y?.matchUps?.length);if(S?.length&&!N)return{error:ZI};let D=!S?.length&&t.qualifyingProfiles,M=D?.length&&OT({idPrefix:t.idPrefix,qualifyingProfiles:D,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,isMock:c,uuids:u});if(M?.error)return M;let{qualifyingDrawPositionsCount:R,qualifyingDetails:b,qualifiersCount:O}=M||{qualifyingDrawPositionsCount:A,qualifiersCount:U};R&&(M?.structures&&g.push(...M.structures),M?.links&&I.push(...M.links)),Object.assign(t,nt({drawSize:p,matchUpType:h,tieFormat:a}));let v=f!==Fr&&(!p||p<2||!i&&![Ea,Ki].includes(f)&&([Eo,On].includes(f)&&p<3||![On,Eo].includes(f)&&!Ln(p)));if(v&&!R)return _({context:{drawSize:p,invalidDrawSize:v},result:{error:np},stack:d});let{generators:x,error:F}=_T(t);if(F)return{error:F};let w=x[f];if(!w)return{error:ql};let L=w?.();if(L.error)return L;let{structures:k,links:G}=L;if(k?.length){let K=k.find(({stage:Y,stageSequence:j})=>Y===rt&&j===1);if(y&&K){if(N){let Y=K.structureId;if(K.structureId=y.structureId,G?.length)for(let j of G)j.source.structureId===Y&&(j.source.structureId=y.structureId),j.target.structureId===Y&&(j.target.structureId=y.structureId)}else if(!r)return{error:ZI}}g.push(...k)}g.sort(Ni),G?.length&&I.push(...G);let H=L.structures.find(({stage:K,stageSequence:Y})=>K===rt&&Y===1);for(let K of b||[]){let{finalQualifyingRoundNumber:Y,finalQualifyingStructureId:j,roundTarget:V,finishingPositions:$,linkType:X}=K,W=H&&La({targetStructureId:H.structureId,sourceStructureId:j,sourceRoundNumber:Y,finishingPositions:$,targetEntryRound:V,linkType:X})?.link;if(W?.error)return W;W&&I.push(W)}return E&&I.push(...E),{...C,qualifyingResult:{qualifyingDrawPositionsCount:R,qualifiersCount:O},structures:g,links:I}}function jd(t){let{modifyOriginal:e=!0,stageSequence:r=1,isMock:n}=t||{},o="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return _({result:{error:Z},stack:o});let i=e?t.drawDefinition:J(t.drawDefinition,!1,!0),{tieFormat:s,matchUpType:a}=t;if(s){let T=ar({tieFormat:s});if(T.error)return T}s=or(s??We({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||Lt),t.tieFormat=s,t.matchUpType=a;let c=Fp({drawDefinition:i,stage:rt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&Hp({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:rt});let u=Pe({drawDefinition:i}).drawMatchUps.map(Ue),p=Wd(t);if(p.error)return _({result:p,stack:o});let{structures:m,links:d,qualifyingResult:l}=p;i.structures=m,i.links=d;let f=Math.max(t.qualifiersCount??0,l?.qualifiersCount||0);if(l?.qualifyingDrawPositionsCount&&!Fp({stage:ct,drawDefinition:i})){let y=Hp({drawSize:l.qualifyingDrawPositionsCount,stage:ct,drawDefinition:i});if(y.error)return y}if(f){let T=$S({qualifiersCount:f,drawDefinition:i,stage:rt});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,nt({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=ie({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=Li({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=rs({drawDefinition:i,matchUpsMap:h});return bt({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...C,structures:m,matchUps:I,links:d}}function xc(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!zv({scaleItem:o}))return{error:rc};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===Ar&&o?.eventType!==Or)return{error:rc};let a=Qv({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=Lr();c.includes(rr)&<({topic:rr,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...C,info:ff,existingValue:o?.scaleValue}||s&&{...C,newValue:o?.scaleValue}||{error:re}}function DD(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:q};if(!n.participants)return{error:ec};let s=0,a={},c=[];for(let m of e){let d=m?.participantId;if(Array.isArray(m?.scaleItems))for(let l of m.scaleItems)if(zv({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:rc}}for(let m of n.participants){let{participantId:d}=m||{};if(Array.isArray(a[d]))for(let l of a[d]){if(m.participantType===Ar&&l?.eventType!==Or)return _({context:{participantId:d,scaleItem:l,participantType:m.participantType},info:"Invalid participantType for eventType",result:{error:rc}});Qv({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++}}let u=s?void 0:Bs,{topics:p}=Lr();if(p.includes(rr)&&s&<({topic:rr,payload:{tournamentId:n.tournamentId,participants:c}}),i){let{eventId:m,drawId:d,...l}=i,f=l.scaleAttributes?.scaleType&&[l.scaleAttributes.scaleType];if(Object.keys(l).length){let g={itemType:Yf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=ze({tournamentRecord:n,eventId:m,drawId:d});d&&Og({drawDefinition:I,timeItem:g}),m&&is({event:h,timeItem:g})}else _c({tournamentRecord:n,timeItem:g})}}return o&&p.includes(Mi)&<({topic:Mi,payload:o}),nt({...C,modificationsApplied:s,info:u})}function zv({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function Qv({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Wi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:rc};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=Po({scaleAttributes:r,participant:e}),c=p=>[void 0,null,""].includes(p),u=!(c(a?.scaleValue)&&c(r.scaleValue))&&JSON.stringify(a?.scaleValue)!==JSON.stringify(r.scaleValue);if(u){let{scaleType:p,eventType:m,scaleName:d}=r,l=[Pi,p,m,d].join("."),f=nt({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...C,valueChanged:u,newValue:r.scaleValue}}function Yg(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=et(t,[{[ne]:!0},{modifiedScaleValues:!0,[He]:zr}]);if(o.error)return o;for(let i in r){let s=xc({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...C}}function wc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:se};let{participant:i,tournamentId:s}=Uo({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...Po({participant:i,scaleAttributes:r}),tournamentId:s}:{error:re}}var pV=(t=0)=>250/Math.pow(t+5,.4),mV=()=>1;function dV(t=3,e=2){let r=t/e;return isNaN(r)?Yd.kDefault():r}var Yd={nSpread:400,diffThreshold:.125,kCalc:pV,kMultiplier:dV,kDefault:mV};function xT(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=je,winnerCountables:o=1,loserCountables:i=0,ratingType:s="ELO",maxCountables:a,countables:c}=t||{},u=n?.[s];if(!u)return{error:st};let p=u.range||t.ratingRange;e=e||u.defaultInitialization,r=r||u.defaultInitialization;let m=p[0]>p[1],d=u.decimalsCount||0,l=m?p.slice().reverse():p,f=(x,F)=>parseFloat(F)>=Math.min(...x)&&parseFloat(F)<=Math.max(...x);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=Fu({targetRange:je["ELO"].range,sourceRange:l,value:m?p[0]-e:e}),I=Fu({targetRange:je["ELO"].range,sourceRange:l,value:m?p[0]-r:r}),h=(x,F)=>1/(1+Math.pow(10,(F-x)/Yd.nSpread)),S=h(g,I),T=h(I,g),y=Yd.kCalc(o),E=Yd.kCalc(i),P=Yd.kMultiplier(a,c),A=g+P*y*(1-S),U=I+P*E*(0-T),N=Fu({sourceRange:je["ELO"].range,value:A,targetRange:l}),D=Fu({sourceRange:je["ELO"].range,value:U,targetRange:l}),M=m?p[0]-N:N,R=parseFloat(M.toFixed(d)),b=m?p[0]-D:D,O=parseFloat(b.toFixed(d)),v=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(N>D&&v>Yd.diffThreshold||R<0||O<0)&&(R=e,O=r),{newWinnerRating:R,newLoserRating:O}}var Xv=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function wT(t){let e=et(t,[{[ne]:!0},{matchUpIds:!0,[He]:Be,[In]:ps},{ratingType:!1,[tr]:S=>je[S]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i="ELO",refreshDynamic:s,considerGames:a,drawDefinition:c,matchUpIds:u,asDynamic:p}=t,m=je[i],{accessor:d}=m,l={},f=(t.matchUps||s&&nr({drawDefinition:c,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:ae}}).matchUps||ye({matchUpFilters:{matchUpIds:u,matchUpStatuses:ae},tournamentRecord:o,inContext:!0}).matchUps)??[],g=`${i}.${Qm}`,I=p?g:i;f.sort(xi);for(let S of f){let{endDate:T,matchUpFormat:y,score:E,sides:P,winningSide:A}=S,U=S.matchUpType,N={eventType:U,scaleName:i,scaleType:Ui},D={scaleName:g,eventType:U,scaleType:Ui},M=Object.assign({},...(P??[]).map(k=>{let{sideNumber:G,participant:H}=k;return G&&{[G]:[H?.participantId,...H?.individualParticipantIds??[]].filter(Boolean).flat()}})),R=Object.assign({},...Object.values(M).flat().map(k=>{let G=l[k],K=!s||G?wc({scaleAttributes:D,tournamentRecord:o,participantId:k}).scaleItem:void 0,Y=wc({tournamentRecord:o,scaleAttributes:N,participantId:k}).scaleItem,j=d?{[d]:void 0}:void 0;return k&&{[k]:K??Y??{scaleName:I,eventType:U,scaleDate:T,scaleType:Ui,scaleValue:j}}})),b=y?Ne(y):{},O=b?.bestOf||1,v=b?.setsTo||1,x=a?O&v:O,F=E?.sets&&Xv(E.sets)||A===1&&[1,0]||[0,1],w=A?M[A]:[],L=A?M[3-A]:[];for(let k of w){let G=R[k]?.scaleValue,H=typeof G=="object"?G[d]:G;for(let K of L){let Y=R[K]?.scaleValue,j=typeof Y=="object"?Y[d]:Y,V=A?F[A]:[0,0],$=A?F[3-A]:[0,0],{newWinnerRating:X,newLoserRating:W}=xT({winnerCountables:V,loserCountables:$,maxCountables:x,winnerRating:H,loserRating:j,ratingType:i}),it=d?{...G,[d]:X}:X,z=d?{...Y,[d]:W}:W;R[k].scaleValue=it,R[K].scaleValue=z,R[k].scaleName=I,R[K].scaleName=I}}Object.assign(l,R),r&&Yg({tournamentRecord:o,modifiedScaleValues:l,removePriorValues:n})}let h=f.map(({matchUpId:S})=>S);return{...C,modifiedScaleValues:l,outputScaleName:I,processedMatchUpIds:h}}function Wu(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:Z};let{participantIdPairings:a,matchUpsCount:c}=t,u=Vd(t);if(u.error)return _({result:u});let{lastRoundNumber:p,availableMatchUpsCount:m=0,roundMatchUpsCount:d=0}=u;if(!c)o?c=d:m>0&&(c=m);else if(c>d&&t.restrictMatchUpsCount!==!1)return _({result:{error:B,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!It(c)||e&&!Array.isArray(e)||!a&&!c)return{error:B,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:B,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:B,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??tt(0,c).map(()=>({participantIds:[void 0,void 0]}));let f=I=>{if(!t.idPrefix)return;let h=r.drawId,S=t.idPrefix??"ah";return`${h}-${S}-${l}-${I}`},g=a?.map((I,h)=>{let S=I?.participantIds??[void 0,void 0];S.push(void 0,void 0);let y=S.slice(0,2).map((P,A)=>nt({sideNumber:A+1,participantId:P})),E=e[h]??f(h)??Nt();return{roundNumber:l,matchUpStatus:Qt,matchUpId:E,sides:y}});if(g?.length){let I=We({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=Li({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:Wt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...C}}function Zv({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:r,valueObjects:n,deltaObjects:o}){let i=Object.assign({},...e.map(S=>({[S.pairing]:S.value}))),s=Object.keys(r),a=[],c=Jv({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[ND(c)];a.push(c);let p=c.value,m=c,d=1,l=0,f=s.length,g;do f-=1,g=s.length*r[s[0]].length;while(g>t&&f>5);let I=[];s.forEach(S=>{r[S].slice(0,f).forEach(y=>{l+=1;let E=Ga(S,y.opponent);if(!I.includes(E)){let P=Jv({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(ND(P))){u.push(ND(P)),a.push(P);let{maxDelta:A,value:U}=P;A<m.maxDelta&&(m=P),(U<p||U===p&&Math.round(Math.random()))&&(p=U),I.push(E),d+=1}}}),a=a.filter(y=>Math.abs(y.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=tn(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function ND(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function Jv({valueSortedPairings:t,stipulated:e=[],pairingValueMap:r,deltaObjects:n,valueObjects:o,actorsCount:i}){let s=[].concat(...e),a=[],c=0;e.filter(Boolean).forEach(d=>{let[l,f]=d,g=Ga(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Ae(t,i).map(d=>Tr(d).map(l=>({...l,value:l.value+Math.random()*Math.round(Math.random())}))).flat().forEach(d=>{let l=d.pairing.split("|");if(!l.reduce((g,I)=>s.includes(I)||g,!1)){s.push(...l);let g=d.value;c+=g,a.push({participantIds:l,value:g})}}),a.sort((d,l)=>d.value-l.value);let p=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Ga(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Ga(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function Ga(t,e){return[t,e].sort(Cu).join("|")}function MD({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 t_({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(St);if(n.length===2){let[o,i]=n,s=Ga(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function e_({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 lV=0;function r_({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=je[n]?.defaultInitialization??lV;return o.split("|").map(s=>{if(r===Kr){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 n_(t){let{tournamentParticipants:e,adHocRatings:r={},possiblePairings:n,uniquePairings:o,maxIterations:i,minimizeDelta:s,deltaObjects:a,valueObjects:c,eventType:u,scaleName:p,salted:m}=t;o.forEach(T=>{let y=r_({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),E=typeof m=="number"&&m||.5,P=m&&(Math.round(Math.random())?E:E*-1)||0,A=Math.abs(y[0]-y[1])+P,U=Math.abs(y[0]-y[1]);a[T]=U,c[T]||(c[T]=0),c[T]+=A?Math.pow(A,2):0});let d=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=e_({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=Zv({valueSortedPairings:d,maxIterations:i,pairingValues:l,deltaObjects:a,valueObjects:c}),{participantIdPairings:S}=s?I:f;return{participantIdPairings:S,candidatesCount:g,deltaCandidate:I,iterations:h,candidate:f}}var fV=100,gV=100,IV=4e3;function qd(t){let{encounterValue:e=fV,sameTeamValue:r=gV,maxIterations:n=IV,updateParticipantRatings:o,generateMatchUps:i=!0,ignoreLastRoundNumber:s,iterationMatchUps:a,tournamentRecord:c,dynamicRatings:u,refreshDynamic:p,participantIds:m,drawDefinition:d,roundNumber:l,structureId:f,matchUpIds:g,eventType:I,scaleName:h,idPrefix:S,isMock:T,salted:y,event:E}=t;if(!d)return{error:Z};if(!t.structure&&!f)return{error:_t};let P=t.structure||at({drawDefinition:d,structureId:f}).structure;if(!ht(P))return{error:Si};if(!m?.length)return{error:bo};let A=[...a??[],...P?.matchUps??[]],{encounters:U}=t_({matchUps:A}),N=c?.participants??[],D={};if(u){let V=pt(P?.matchUps?P.matchUps.map(({roundNumber:X})=>X):[]),$=Math.max(...V,0);if($){let X=P?.matchUps?.filter(({roundNumber:it})=>it===$).map(({matchUpId:it})=>it),W=wT({ratingType:h??E?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,refreshDynamic:p,drawDefinition:d,matchUpIds:X});if(W.error)return W;W.modifiedScaleValues&&(D=W.modifiedScaleValues)}}let{valueObjects:M}=hV({tournamentParticipants:N,encounterValue:e,sameTeamValue:r,encounters:U}),{uniquePairings:R,possiblePairings:b,deltaObjects:O}=MD({participantIds:m}),v=Object.values(D).length?D:t.adHocRatings,x={tournamentParticipants:N,possiblePairings:b,participantIds:m,uniquePairings:R,drawDefinition:d,maxIterations:n,adHocRatings:v,deltaObjects:O,valueObjects:M,eventType:I,scaleName:h,structure:P,salted:y},{candidatesCount:F,participantIdPairings:w,deltaCandidate:L,iterations:k,candidate:G}=n_(x);if(!F)return{error:ap};let H,K;if(i){let V=Wu({structureId:P?.structureId,ignoreLastRoundNumber:s,participantIdPairings:w,newRound:!0,drawDefinition:d,roundNumber:l,matchUpIds:g,idPrefix:S,isMock:T,event:E});if(V.error)return V;H=V.roundNumber,K=V.matchUps}let{maxDelta:Y,maxDiff:j}=G;return{roundNumber:H,participantIdPairings:w,modifiedScaleValues:D,candidatesCount:F,deltaCandidate:L,...C,iterations:k,matchUps:K,maxDelta:Y,maxDiff:j}}function hV({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===wt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=MD({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function LT(t){let{drawType:e=yo,attachConsolation:r=!0,applyPositioning:n=!0,tournamentRecord:o,staggeredEntry:i,automated:s,placeByes:a,isMock:c,event:u}=t,p=t?.drawDefinition;if(!p)return{error:Z};let m=$e,d=bi({stageSequence:1,drawDefinition:p,stage:m}),l=[On,su,Eo].includes(e)?d.length:us(d.length);if(!i&&e===Ea&&d.length<2||e===On&&d.length<3)return{error:np};let{tieFormat:f,matchUpType:g}=t;if(f){let R=ar({tieFormat:f});if(R.error)return R}f=or(f??We({drawDefinition:p})?.tieFormat),g=g??p.matchUpType;let{structures:I}=hn({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:iA};if(I?.[0]?.matchUps?.length)return{error:If};let S=I?.[0]?.structureId;Object.assign(t,nt({structureName:t.structureName??Qe($e),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:m}));let T=_T(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:ql};let E=y?.();if(E.error)return E;let{structures:P,links:A}=E,U=P.map(R=>yt({structure:R}).matchUps).flat();f&&U.forEach(R=>{let{tieMatchUps:b}=Li({matchUp:R,tieFormat:f,isMock:c});Object.assign(R,{tieMatchUps:b,matchUpType:g})}),(!n||!r)&&(p=J(p,!1,!0)),p.links||(p.links=[]),A.length&&p.links.push(...A);let N=P.map(({structureId:R})=>R);p.structures||(p.structures=[]);let D=p.structures.map(({structureId:R})=>R);p.structures=p.structures.map(R=>N.includes(R.structureId)?P.find(({structureId:b})=>b===R.structureId):R);let M=P.filter(({structureId:R})=>!D.includes(R));return M.length&&p.structures.push(...M),s&&Mc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&bt({drawDefinition:p}),{links:A,structures:P,...C}}var Jg={};Xt(Jg,{addGame:()=>xD,addPoint:()=>_D,addSet:()=>LD,addShot:()=>wD,analyzeScore:()=>zg,analyzeSet:()=>qu,calculateHistoryScore:()=>bD,checkScoreHasValue:()=>he,checkSetIsComplete:()=>Jp,clearHistory:()=>vD,generate:()=>CD,generateScoreString:()=>Mo,generateTieMatchUpScore:()=>vc,getSetComplement:()=>Xg,getTiebreakComplement:()=>rm,helpers:()=>cN,isValidMatchUpFormat:()=>Nr,keyValueScore:()=>rN,mutate:()=>VD,parseMatchUpFormat:()=>Ne,parseScoreString:()=>nm,query:()=>mN,redo:()=>FD,reverseScore:()=>RD,setServingSide:()=>OD,stringifyMatchUpFormat:()=>gp,tidyScore:()=>aN,umo:()=>GD,undo:()=>kD,validateMatchUpScore:()=>uN,validateScore:()=>Qg,validateSetScore:()=>$T,validateTieFormat:()=>ar});var CD={};Xt(CD,{generateScoreString:()=>Mo,generateTieMatchUpScore:()=>vc,reverseScore:()=>RD});function Mo(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:st,info:"missing sets"};let p=s&&Ne(s),{bestOf:m,finalSetFormat:d,setFormat:l}=p??{},g=o||!(!e||!c||c===1),I=n?SV({matchUpStatus:i}):"",h=u?.sort(TV).map(S).filter(Boolean).join(" ")||"";if(!I)return h;if(c===2)return`${I} ${h}`;return`${h} ${I}`;function S(T){let E=m&&T.setNumber===m&&d?d:l,P=V=>Jt(V?.side1Score)||Jt(V?.side2Score),U=(V=>Jt(V?.side1TiebreakScore)||Jt(V?.side2TiebreakScore))(T),N=E?.tiebreakSet||!P(T)&&U,{side1Score:D,side2Score:M,side1TiebreakScore:R,side2TiebreakScore:b}=T,O=R||(Jt(R)||U&&a?0:""),v=b||(Jt(b)||U&&a?0:"");if(N){let V=P(T)&&!U,$=V?D:O,X=V?M:v;return`[${(g?[X,$]:[$,X]).join("-")}]`}let x=U?Math.min(O,v):"",F=x===O?1:2,w=Jt(x)?`(${x})`:"",L=D||(Jt(D)||a?0:""),k=M||(Jt(M)||a?0:""),G=V=>!r&&F===V?w:"",H=`${L}${G(1)}`,K=`${k}${G(2)}`,Y=r&&U?`(${x})`:"",j=g?`${[K,H].join("-")}${Y}`:`${[H,K].join("-")}${Y}`;return["-"," "].includes(j)&&(j=""),j}}function SV({matchUpStatus:t}){let e={[Me]:"RET",[Bt]:"WO",[be]:"DF/DF",[oe]:"WO/WO",[ls]:"SUS",[vr]:"ABN",[Gt]:"DEF",[Iu]:"DR"};return t&&e[t]||""}function TV(t,e){return t.setNumber-e.setNumber}function RD(t){if(!t?.score)return{error:st};let{sets:e}=t.score,r=e.map(s=>{let{side1TiebreakScore:a,side2TiebreakScore:c,winningSide:u,side1Score:p,side2Score:m,setNumber:d}=s;return nt({winningSide:u?3-u:void 0,side1TiebreakScore:c,side2TiebreakScore:a,side1Score:m,side2Score:p,setNumber:d})}),n=t?.setTBlast,o=Mo({setTBlast:n,sets:r}),i=Mo({sets:r,reversed:!0,setTBlast:n});return{reversedScore:{sets:r,scoreStringSide1:o,scoreStringSide2:i},...C}}var VD={};Xt(VD,{addGame:()=>xD,addPoint:()=>_D,addSet:()=>LD,addShot:()=>wD,calculateHistoryScore:()=>bD,clearHistory:()=>vD,redo:()=>FD,setServingSide:()=>OD,umo:()=>GD,undo:()=>kD});function ei({matchUp:t}){let{extension:e}=mt({name:rd,element:t});if(!e)return{error:Oe};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...C}}function bD(t){if(!t)return{error:st};let{matchUp:e,updateScore:r}=t;if(!e)return{error:mr};let n=ei({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:B,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Zl};if(!Nr({matchUpFormat:o}))return{error:Jl};let i=Ne(o),{bestOf:s,finalSetFormat:a,setFormat:c}=i,u=["0","15","30","40","A","G"],p={sets:[]},m=[],d,l=[0,0],f=1,g=0,I,h=0,S=D=>[1,2].includes(D),T=()=>(g+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:g,games:[]}),y=()=>({winningSide:void 0,points:[]}),E=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),P=E(),A=y(),U=T(),N=0;for(let D of n){N+=1,I=p.sets.length+1===s;let M=I&&a?a:c,{tiebreakAt:R,setTo:b,NoAD:O,tiebbreakFormat:v}=M,x=U.side1Score===R&&U.side1Score===U.side2Score,F=!!M.tiebreakSet,w=F?M.tiebreakSet:v,{tiebreakTo:L,NoAD:k}=w||{},G=()=>{d=void 0,l=[0,0],f=3-f,U.side1TiebreakScore="",U.side2TiebreakScore="",U.side1PointScore="",U.side2PointScore="",h=0},H=j=>{U.winningSide=j;let{s:V,...$}=U;p.sets.push($),P=E(),A=y(),U=T(),G()},K=j=>{A.winningSide=j;let{g:V,...$}=A;U.games.push($),P=E(),A=y(),G();let X=`side${j}Score`;U[X]+=1},Y=j=>{P.winningSide=j;let{p:V,...$}=P;A.points.push($),P=E(),h=0;let X=()=>l.reduce((Q,ut)=>Q+ut)%4/4>.5?f:3-f,W=j-1;if(x||F){l[W]+=1,d=X(),U[`side${j}TiebreakScore`]=l[W],U[`side${3-j}TiebreakScore`]=l[1-W];let it=k?1:2;if(l[W]>=L&&l[W]>=l[1-W]+it)return K(j),{gameCompleted:!0}}else if(l[1-W]===4&&l[W]===3?l[1-W]-=1:l[W]+=1,U.side1PointScore=u[l[0]],U.side2PointScore=u[l[1]],l[W]===5||l[W]===4&&l[1-W]<3||O&&l[W]===4)return K(j),{gameCompleted:!0}};if(S(D.srv)&&(f=D.srv),["p","s","g","o"].includes(D.u)&&m.push(D.u),D.shotOutcome&&(P.shots.push(D),D.shotType==="SERVE"&&["OUT","NET"].includes(D.shotOutcome)&&(h+=1),h===2)){let V=3-f;Y(V)}if(S(D.p)||It(D.pointNumber)){let j=D.winningSide||D.p;if(Y(j)?.gameCompleted)continue}if(S(D.g)||It(D.gameNumber)){let j=D.winningSide||D.g;A.winningSide=j;let V=`side${j}Score`,$=`side${3-j}Score`;if(m.length&&(m.includes("p"),m=[]),K(j),U[V]===b&&U[V]-U[$]>=(O?1:2)&&(H(j),I))break}if(S(D.s)||It(D.setNumber)){let j=D.winningSide||D.s;if(H(j),m.length&&(m.includes("p"),m.includes("g"),m=[]),I)break}}return N!==n.length&&console.log({error:"Match completed with excess history"}),(U.side1Score||U.side2Score||U.games.length||U.side1TiebreakScore||U.side2TiebreakScore)&&p.sets.push(U),p.scoreStringSide1=Mo({...p,matchUpFormat:o}),p.scoreStringSide2=Mo({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...C,servingSide:f,score:p}}function ri({undoHistory:t,history:e,matchUp:r}){return At({element:r,extension:{value:{history:e,undoHistory:t},name:rd}})}function OD({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:tf};let{history:r=[]}=ei({matchUp:t});return r.push({srv:e}),ri({matchUp:t,history:r})}function vD({matchUp:t}){return ri({matchUp:t})}function _D({matchUp:t,point:e}){if(!e||!t)return{error:st};if(typeof e!="object")return{error:B,context:{point:e}};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function xD({matchUp:t,game:e}){if(typeof e!="object")return{error:B,context:{game:e}};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function wD({matchUp:t,shot:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function LD({matchUp:t,set:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function FD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=ei({matchUp:t});return r.length&&e.push(r.pop()),ri({matchUp:t,history:e,undoHistory:r})}function kD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=ei({matchUp:t});return r.push(e.pop()),ri({matchUp:t,history:e,undoHistory:r})}var GD={};var cN={};Xt(cN,{keyValueScore:()=>rN,parseMatchUpFormat:()=>Ne,stringifyMatchUpFormat:()=>gp,tidyScore:()=>aN});var o_="COMPLETED";var yV="WO/WO";var FT=["RET","DEF","WO",yV,"ABN","SUS","INT"];var kT="DEFAULTED";var BD="WALKOVER";var GT="ABANDONED",VT="SUSPENDED",HD="RETIRED",BT="INTERRUPTED";var i_=[HD,kT,BD],EV="Enter Score",Rs="()",Cs="[]",WD=["up","left","shift+tab"],jD=["enter","down","tab","right"],$d="backspace",YD="r",qD="s",$D="a",KD="d",zD="w",QD="i",Kd=[YD,KD,zD,$D,qD,QD],Qp="space",HT=["[","("],zd=[...WD,...jD,Qp,"]"],s_="-",AV="/",aa=s_,gi=s_,XD=[AV],a_=0,UV=["=","+","num_1","num_2","shift+=","shift+-"],sa=["0","1","2","3","4","5","6","7","8","9"].concat(Kd),c_=sa.map(t=>`shift+${t}`),JD=[aa,$d].concat(zd,XD),ZD=[sa,c_,JD].join(","),PV=[ZD,WD,jD,UV].join(","),Bbt=[].concat(...sa,...sa,...JD,...sa,...sa,...sa,...sa,...sa,...sa),u_={OUTCOMEKEYS:Kd,SIDE1KEYS:sa,SIDE2KEYS:c_,MODIFIERS:JD,PROMPT:EV,MOVEUP:WD,MOVEDOWN:jD,HOTKEYS:PV};function Xp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=p_({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==" "?" ":"";return t+o+r}else return r+" "+t}function p_({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of FT){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 qg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=p_({scoreString:e});if(e=s,a)return{scoreString:e,sets:r,outcomeRemoved:!0};let c=r[r.length-1]||{},u=Object.values(c).filter(g=>g!==void 0).length;c.setNumber&&u===1&&(r=r.slice(0,r.length-1),c=r[r.length-1]||{});let{tiebreakSet:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p||{},{isTiebreakEntry:l}=ju({brackets:Cs,scoreString:e}),f=DV(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=ju({brackets:Rs,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=ju({brackets:Cs,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),y=t.isIncompleteSetScore;if(l&&h){let P=o.slice(I+1).split(gi),A=P?.length>0&&P[0]!==void 0&&!isNaN(parseInt(P[0]))&&parseInt(P[0])||void 0,U=P?.length>1&&P[1]!==void 0&&parseInt(P[1])||void 0,N=[A,U];if(U){let D=n===1?1:0;N[D]=(N?.[1-D]||0)+(d?1:2),(N[D]||0)<m&&(N[D]=m),o=e.slice(0,I+1),o+=N.join(gi)}else A!==void 0?(o=e.slice(0,I+1),o+=A):(o=e.slice(0,I),y=!0);c.side1TiebreakScore=N[0]||0,c.side2TiebreakScore=N[1]||0}if(o.length||(o=void 0),y){let E=c.side1Score?.toString();if(E){let P=E?.slice(0,E.length-1);c.side1Score=!isNaN(P)&&parseInt(P)||void 0,c.side1Score===void 0&&(c.side2Score=void 0)}t.isTimedSet?(i=c.side1Score?r:r?.slice(0,r.length-1)||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]}else if(T){let E=c.side2Score?.toString(),P=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let A=E?.slice(0,E.length-1);c.side2Score=!isNaN(A)&&parseInt(A)||void 0}else{let A=P?.slice(0,P.length-1);c.side1Score=!isNaN(A)&&parseInt(A)||void 0}t.isTimedSet?c.side1Score?(i=r||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]:(i=r||[],i[r.length-1]=c),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0})}else g?(i=r||[],Object.assign(i[i.length-1]||{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(l&&!h?i=r?.slice(0,r.length-1)||[]:(i=r,i[r.length-1]=c),l||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0));return{scoreString:o,sets:i}}return{scoreString:e,sets:r}}function ju({brackets:t=Rs,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...ho(r,o)),s=Math.max(...ho(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function m_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=Cs.split(""),i=t.split(""),s=Math.max(...ho(n,i)),a=Math.max(...ho(o,i)),c=Math.max(...ho(gi,i));return r&&s>a&&c>s}function DV(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function WT(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function tN({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:m}=p;return m&&u[m-1]++,u},[0,0])?.indexOf(s)+1||void 0;return i_.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Jp({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,isTimedSet:i,set:s}){if(!s)return{error:st,info:"missing set"};e=e||r&&Ne(r);let a=o&&e.finalSetFormat||e?.setFormat||{},{side1Score:c,side2Score:u}=s,{setTo:p,tiebreakAt:m}=a,d=c||u,l=Zp({set:s}),f=Math.abs(c-u),g=c>=p||u>=p,I=n||c>=p&&u>=p||m&&m<p&&(c===m||u===m),h=t||I&&(l===1&&s.side1TiebreakScore>s.side2TiebreakScore||l===2&&s.side2TiebreakScore>s.side1TiebreakScore),S=!I&&a.NoAD||I||n&&a.tiebreakFormat?.NoAD?1:2,T=f>=S;return!!((i&&d||g&&(T||I)||n)&&(!I||h))}function Zp({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 Qd({analysis:t,set:e}){let r=Zp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Jp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function d_({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=dt(n);let{validSide2Score:s,requiresTiebreak:a}=NV({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Qd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=Rs.split("")[0];e+=u}else t.isDecidingSet||(e+=" ")}return{sets:r,scoreString:e,updated:o}}function NV({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 jT({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===YD?n?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"RET"}),o=t===2?1:2,i=HD):(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=kT):e===KD?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=kT):e===zD?(s=!0,r=[],n="WO",o=t===2?1:2,i=BD):e===qD&&n?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"SUS"}),i=VT,o=void 0):e===$D?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"ABN"}),i=GT,o=void 0):e===QD&&n&&(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"INT"}),i=BT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function f_(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!==$d&&(e=[{setNumber:1}]);let m=e.length-1;if(Kd.includes(c)){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;l&&!f?r="missing side2Score":s.finalSetIsComplete||o?r="final set is already complete":s.isIncompleteSetScore?r="incomplete set scoreString":s.isIncompleteSetScore||({sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=jT({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===$d){if({scoreString:n,sets:e,outcomeRemoved:p}=qg({analysis:s,scoreString:n,sets:e}),n?.trim()===""&&(n=n.trim()),n||(e=[]),p){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;if(l&&f){let g=l>f&&1||f>l&&2||void 0;g&&(d.winningSide=g,e.push({setNumber:e.length+1}))}}i=void 0,o=void 0,u=!0}else if(s.hasOutcome)r="has outcome";else{if(o)return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:!1,info:"matchUp is complete"};if(c===Qp){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d,g=l>f&&1||f>l&&2||void 0;g&&!o&&!s.isIncompleteSetScore&&(e[e.length-1].winningSide=g,e.push({setNumber:e.length+1}),n+=" ",u=!0)}else if(c===aa&&e[m].side1Score!==void 0&&e[m].side2Score===void 0&&n&&s.isNumericEnding)n+="-",e[m].side2Score=0,i=void 0,o=void 0,u=!0;else if(!isNaN(c)){let d;if(e[m].side2Score===void 0){let l=dt((e[m].side1Score||0).toString()+c).toString().slice(0,2);e[m].side1Score=dt(l),d=e[m].side1Score.toString(),u=!0}else{let l=dt((e[m].side2Score||0).toString()+c).toString().slice(0,2);e[m].side2Score=dt(l),d=[e[m].side1Score,e[m].side2Score].join("-"),u=!0}if(u){let l=(e.slice(0,m)||[]).filter(f=>f).map(f=>{let{side1Score:g,side2Score:I}=f;return[g,I].join("-")}).join(" ");l?n=l+" "+d:n=d}}}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function g_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Cs.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=ju({brackets:Cs,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(gi);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=>dt(T)),h=r===1?1:0;I[h]=I[1-h]+(u?1:2),I[h]<c&&(I[h]=c);let S=o[o.length-1];S.side1TiebreakScore=I[0],S.side2TiebreakScore=I[1],n=n.slice(0,(d??0)+1),n+=I.join(gi),s=!0}else{let I=[f[0]||0,f[1]||0].map(S=>dt(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=WT({lowValue:dt(i||0),tiebreakTo:c,NoAD:u}),l=[dt(i),d];r===2&&l.reverse();let f={side1TiebreakScore:l[0],side2TiebreakScore:l[1],setNumber:o?.length+1||1};o.push(f),n+=l.join(gi),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function I_({analysis:t,lowSide:e,scoreString:r,value:n}){let{setTo:o,tiebreakAt:i,NoAD:s}=t?.setFormat||{},a=n===parseInt(i||o);if(i&&i<o&&n>i)return{scoreString:r};if(s&&n===o||n>o)return{scoreString:r};let c=g(),u=[n,c];e===2&&u.reverse();let m=Rs.split("")[0],d=u.join(aa)+(a?m:" ");r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Qd({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 h_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(K=>K?.winningSide)?.length||0)+(r?0:1),a=Ne(t),c=s===a?.bestOf,u=c&&a?.finalSetFormat||a?.setFormat||{},p=u?.timed,m=c&&o[a?.bestOf-1],d=m?.winningSide,{isTiebreakEntry:l}=ju({brackets:Rs,scoreString:e}),{isTiebreakEntry:f}=ju({brackets:Cs,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===aa,y=l&&HT.includes(h),E=f&&HT.includes(h),P=f&&h===gi,A=e?.split(""),[U]=Cs.split(""),N=A&&Math.max(...ho(U,A)),D=A&&Math.max(...ho(gi,A)),M=A&&D>N,R=o[o.length-1]?.winningSide,b=o?.length&&!R,O=FT.find(K=>e?.indexOf(K)>=0),v=!isNaN(n),x=n===Qp,F=zd.includes(n),w=e?.split("").find(K=>HT.includes(K)),L=F&&f&&!E&&(P||!m_({scoreString:e}));return{isTiebreakSetValue:I&&v,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:M,isGameScoreEntry:b,isSpace:x,isCloser:F,isTiebreakCloser:F&&w&&g&&S,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:S,isNumericValue:v,hasOpener:w,hasOutcome:O,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:R,isInvalidSetTiebreakValue:x&&g&&y,isInvalidMatchTiebreakValue:L,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:E,isPartialMatchTiebreakValue:P}}function rN(t){let{lowSide:e=1,value:r}=t,{scoreString:n,sets:o,winningSide:i,matchUpStatus:s}=t,{matchUpFormat:a,shiftFirst:c,auto:u=!0}=t,p,m,d=c&&e===2||!c&&e===1;if(!ZD.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=tN({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=h_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(XD.includes(r)&&(r=aa),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&dt(r)===0&&(f.isTiebreakCloser=!0),zd.includes(r)&&f.hasOpener&&(r=""),zd.includes(r)&&(r=Qp),f.lastSetIsComplete){let g=n?.length&&n[n.length-1];n&&g!==" "&&(n+=" ")}if(f.isTimedSet)({info:m,sets:o,scoreString:n,updated:p,matchUpStatus:s,winningSide:i}=f_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Kd.includes(r))f.finalSetIsComplete||i?m="final set is already complete":!f.isTiebreakEntry&&!f.isIncompleteSetScore?{sets:o,scoreString:n,matchUpStatus:s,winningSide:i,updated:p}=jT({lowSide:e,sets:o,scoreString:n,matchUpStatus:s,winningSide:i,value:r}):f.isTiebreakEntry||f.isIncompleteSetScore?m="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:r});else if(r===$d)p=!0,{scoreString:n,sets:o}=qg({analysis:f,scoreString:n,sets:o,lowSide:e}),n||(o=[]),s=void 0,i=void 0;else if(f.hasOutcome)m="has outcome";else if(r===aa&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=qg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===gi&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=gi);else if([aa,gi].includes(r))m="invalid location for joiner";else{if(i)return{updated:!1,info:"matchUp is complete"};if(f.isIncompleteSetScore)f.isNumericValue&&({sets:o,scoreString:n,updated:p}=d_({analysis:f,scoreString:n,sets:o,value:r}));else if(f.isInvalidMatchTiebreakValue)m="invalid matchUp tiebreak character";else if(f.isInvalidSetTiebreakValue)m="invalid set tiebreak character";else if(f.isTiebreakCloser){let g=f.isSetTiebreakEntry?Rs:Cs,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:E}=T||{},P=Zp({set:S});if(!f.isTiebreakSet){let U=parseInt(n.split(h).reverse()[0]),N=WT({lowValue:U,tiebreakTo:y,NoAD:E});P===1?(S.side1TiebreakScore=N,S.side2TiebreakScore=U):(S.side1TiebreakScore=U,S.side2TiebreakScore=N)}n=(n||"")+I,f.isDecidingSet||(n+=" ");let A=Qd({analysis:f,set:S});S.winningSide=A||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=g_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=Rs.split(""),I=Math.max(...ho(g,n.split(""))),h=n.slice(I+1),S=h&&dt(h)===a_,T=dt(h?h+r:r),{tiebreakFormat:y}=f.setFormat,{tiebreakTo:E,NoAD:P}=y||{};!S&&h.length<2?P&&T>E-1?m="invalid low value for NoAD tiebreak":(p=!0,n=(n||"")+r):m=S?"tiebreak begins with zero":"tiebreak digit limit"}else if(f.isCloser)m=`invalid key: ${r}`;else if(f.isGameScoreEntry)m="game scoreString entry";else if(f.lastSetIsComplete||!o.length){p=!0;let{scoreString:g,set:I}=I_({analysis:f,lowSide:e,scoreString:n,value:dt(r)});I&&(I.setNumber=o?.length+1||1),o=o?.concat(I).filter(Boolean)||[I],n=g||void 0}else console.log("error: unknown outcome")}if(p){o=o?.filter(Boolean);let{matchUpWinningSide:g}=tN({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[Qt,mn].includes(s))?(s=o_,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![VT,GT,BT].includes(s)&&(s=void 0),{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}return{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}var Xd="\\d+-\\d+",tm="\\d+-\\d+\\(\\d+\\)",$g="\\[\\d+-\\d+\\]",OV="\\d+-\\d+\\(\\d+-\\d+\\)",S_=new RegExp(`(${Xd}),`,"g"),T_=new RegExp(`(${tm}),`,"g"),vV=[Xd,tm,$g,OV],_V=["0","1","2","00","01","10","11","002","012","102","112","000","001","010","100","011","101","110","111","002","012","102","112","0002","0012","0102","1002","0112","1012","1102","1112","3","03","13","013","103"],xV=_V.map(t=>{let r=t.split("").map(n=>vV[n]).join(" ");return new RegExp(`^${r}$`)});function nN(t){return!t||xV.some(e=>e.test(t))}function y_(t){let n="[];()",o=["[","("],i=Object.assign({},...n.split("").map(c=>({[c]:0}))),s="",a=t.split("").map(c=>{let u=n.includes(c)&&c,p=o.includes(u);if(p&&u)return i[u]+=1,s=u,c;if(!p&&u&&s&&u!==s){i[s]-=1;let m="[];".includes(s)&&"[];"||"()".includes(s)&&"()"||"",d=m.split("").find(l=>l!==s);if(m.includes(u))i[s]||(s="");else return i[u]||(s=""),d}return c}).join("");return t!==a?a:t}function Jd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function E_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function Ba(t){let r=(n=>n?.split("-").join("").split("/").join(""))(t);if(/^\d+$/.test(r)&&r.length===2){let n=r.split("");return Math.abs(n.reduce((i,s)=>+i-+s))===1}return!1}function em(t,e){let r=[t.slice(e,e+2),e?t.slice(0,1):t.slice(2)].map(i=>parseInt(i.join("")));e&&r.reverse();let n=r;if(Math.abs(n.reduce((i,s)=>+i-+s))>=2)return n.join("-")}function oN(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function A_(t){return t.startsWith("(")&&t.endsWith(")")}function U_({score:t,applied:e}){t=y_(t);let r=/\)(\d+)/g;if(r.test(t))for(let P of t.match(r)){let A=P.replace(")",") ");t=t.replace(P,A)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let P of i||[]){let[A]=P.match(o).slice(1),U=A.replace(/ /g,"");t=t.replace(P,`(${U})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let P=t.match(s);P.length&&P.forEach(A=>{let U=A.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(A,U)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let P=t.match(s);P.length&&P.forEach(A=>{let U=A.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(A,U)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(P=>{let A=new RegExp(`(\\d+)${P}(\\d+)`,"g"),U=t.match(A);U&&U.forEach(N=>t=t.replace(N,N.split(P).join("-")))}),/^[(-/,]+$/.test(t)&&(t=""),/\)[-/,]+$/.test(t)&&(t=t.slice(0,t.length-1)),/\d \/\d/.test(t)&&(t=t.replace(/ \//g,"/")),t.includes(" /")&&(t=t.replace(/ \//g," "));let c=/\(\d+, \)/g;c.test(t)&&t.match(c).forEach(A=>{let[U]=A.match(/\((\d+), \)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&U==="6"&&(t=t.replace(A,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(A=>{let[U]=A.match(/\((\d+)\/\)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&U==="6"?t=t.replace(A,"(6-0)"):t=t.replace(A,`(${U})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(A=>{let[U]=A.match(/(\d\/\d)\/,/).slice(1);t=t.replace(A,`${U},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(A=>{let[U]=A.match(/\(\/(\d+)\)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&parseInt(U)<6?t=t.replace(A,`(6-${U})`):t=t.replace(A,`(${U})`)});let d,l,f,g,I,h=()=>{I=Er(t.split("")),l=I["("]===(I[")"]||0)+1,d=(I["("]||0)+1===I[")"],f=I["["]===I["]"]+1,g=l&&!f};h();let S=/(\d+-\d+\(\d+)0,/;if(S.test(t)){let[P]=t.match(S).slice(1);t=t.replace(S,P+")")}if(I["("]===I[")"]&&I["("]>1){let P=t.split(")(").join(") (").split(" ");P.every(A_)?t=P.map(A=>{let U=A.slice(1,A.length-1);return U.length>2?U:A}).join(" "):t=P.join(" ")}h();let T=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!T&&!y)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(P=>I[P])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(P=>I[P]>1)&&(t=t.slice(1,t.length-1)),t.startsWith("(")&&t.endsWith("))")&&(t=t.slice(1,t.length-1)),I["("]>(I[")"]||0)&&t[t.length-1]==="("&&(t=t.slice(0,t.length-1)+")",h()),I["("]===1&&!I[")"]&&t[0]==="("&&(t=t+")",h()),I["("]>(I[")"]||0)&&t.slice(0,2)==="(("&&(t=t.slice(1)),d){if(/^9\d/.test(t))t="("+t.slice(1);else if(t[0]!=="(")t="("+t;else{let P=[],A=0;for(let U of t.split("").reverse())U===")"&&(A?P.push("("):A+=1),U==="("&&(A-=1),P.push(U);P.reverse(),t=P.join("")}h()}if(I[")"]>(I["("]||0)&&t[0]===")"&&(t="("+t.slice(1),h()),g&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",h()),g&&(!t.endsWith(")")||t.startsWith("(("))&&(t=t+")",h()),g){let P="",A=0;for(let U of t.split(""))U==="("&&(A?P+=")":A+=1),U===")"&&(A-=1),P+=U;t=P}h(),f&&!l&&(t=t+"]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),h()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),h(),I[")"]===1&&!I["("]&&t.endsWith(")")&&(t=t.slice(0,t.length-1)),t.startsWith("(")&&t.endsWith(")")&&I["("]===1&&I[")"]===1&&(t=t.slice(1,t.length-1),h());let E=P=>{let A=P.indexOf("("),U=P.indexOf(")");return A>=0&&U>=0&&A<U};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let P=t.slice(1,t.length-1);E(P)&&(t=P,h())}return{score:t,applied:e}}function Yu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=ho("-",t.split(""));if(!e.length)return t;let r=t.split("-"),n=!(r.length%2),o=!!(e.length%2);return n&&o&&e.length>r.length/2&&e.filter((s,a)=>a%2).forEach(s=>{t=t.substring(0,s)+" "+t.substring(s+1)}),t}function P_({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map(r=>r.trim()).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map(r=>r.trim()).join(")")),[S_,T_].forEach(r=>{let n=t.match(r);n?.length&&(n.forEach(o=>{t=t.replace(o,o.slice(0,o.length-1)+" ")}),e.push("setsEndComma"))}),t=t.split(" ").filter(Boolean).map(Yu).join(" "),{score:t,applied:e}}function D_({score:t}){if(typeof t!="string")return{score:t};let e=d=>d?.split("-").join("").split("/").join(""),r=d=>d.split("[").join("(").split("]").join(")");t=t.split(", ").join(" ");let n=t.split(" ");t=n.map(d=>{let l=/^-(\d+)$/;if(l.test(d)){let[f]=d.match(l).slice(1);if(f.length===2)return f.split("").join("-")}return d}).join(" "),n=t.split(" ");let o=n.filter(Jd),i=0,s="";for(let d of o){let l=ho(d,n).filter(h=>!i||h>i)[0],f=n.slice(i,l-1),g=n[l-1],I=e(g);if(/^\d+$/.test(I)&&I.length===2){let h=I.split(""),S=Math.abs(h.reduce((T,y)=>+T-+y));if(S===1){let T=[f.join(" "),[g,d].join("")].join(" ");s+=T,i=l+1}else if(S===0){let T=Math.max(...h);if([4,5,6,7,8,9].includes(T)){let y=[6,4].includes(T)?T+1:T-1,E=[T,y].sort().reverse().join("-"),P=[f.join(" "),[E,d].join("")].join(" ");s+=P,i=l+1}}}}if(o.length&&s.length){let d=n.slice(i).join(" ");return s=[s,d].join(" "),{score:s.trim()}}if(n.length===2&&["(","["].some(d=>n[1].includes(d))){let l=e(n[0]).split("");if(Math.abs(l.reduce((g,I)=>+g-+I,0))===1)return n[1]=r(n[1]),{score:n.join("")}}let a=n.map(d=>E_(d)&&"bracket"||Ba(d)&&"set");if(a.includes("set")&&a.includes("bracket")){let d,l="";return n.forEach((f,g)=>{a[g]==="bracket"&&d==="set"?(f=r(f),l+=f):l+=` ${f}`,d=a[g]}),{score:l.trim()}}n=t.split(" ");let c,u=n.map(d=>{let l=new RegExp(/^(\d+)-(\d+)$/);if(l.test(d)){let[f,g]=d.match(l).slice(1),I=Math.abs([f,g].reduce((S,T)=>+S-+T)),h=Math.max(f,g);if(I===1)return c="tiebreakSet",c;if(I>=2&&h>=7&&c==="tiebreakSet")return c="tiebreak",c}}),p=ho("tiebreak",u);if(p.length){let d="";n.forEach((l,f)=>{p.includes(f)?d+=`(${l}) `:p.includes(f+1)?d+=`${l}`:d+=`${l} `}),t=d.trim()}let m=/(\d+-\d+)\((\d+)-(\d+)\)$/;if(m.test(t)){let[d,l,f]=t.match(m).slice(1),I=Math.max(l,f)>=10;!Ba(d)&&I&&(t=t.replace(m,`${d} [${l}-${f}]`))}return u=[],t=t.split(" ").map(d=>{let l=/^\((.*)\)$/,f=l.test(d),g=new RegExp($g).test(d)&&"super"||new RegExp(tm).test(d)&&"tiebreak"||new RegExp(Xd).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function N_({score:t,applied:e}){for(let D of[".",","," ","/"]){let M=new RegExp(`^(\\d+)\\${D}(\\d+)$`);if(M.test(t)){let R=t.match(M).slice(1).map(O=>parseInt(O)),b=Math.abs(R[0]-R[1]);b<=10&&b>=2&&(t=t.split(D).join("-"),e.push("variedJoinerPattern"))}}t.includes(";")&&(t=t.split(";").join(" "),e.push("semicolon set separation"));let r=/(^|\s)(\d)\/(\d)(\d)\/(\d)(\(|$)/;if(r.test(t)){let[D,M,R,b,O,v]=t.match(r).slice(1);t=t.replace(r,`${D}${M}-${R} ${b}-${O}${v}`),e.push("smashSlashPattern")}/.*\s6[/-]+$/.test(t)&&(t+="0",e.push("incompleteFinalSetPattern"));let o=/\(6,\)/g;o.test(t)&&(t=t.replace(o,"(6, 0)"),e.push("missingZeroPattern1"));let i=/^\d{3,}\(/,s=/\(\d+\)\d+/;[i,s].forEach(()=>{t=t.split(" ").map(M=>(i.test(M)&&(M=M.replace("("," (")),s.test(M)&&(M=M.replace(")",") ")),M)).join(" "),e.push("spaceConsiderationPatterns")});let c=Yu(t);c!==t&&(t=c,e.push("deDashMash"));let u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){let[D,M,R]=t.match(u).slice(1),[b,O]=M.split("");t=`${D}-${b} ${O}-${R}`,e.push("smashSetPattern")}let p=/^(\d+)[ -](\d+)$/,m=/^([\d -]+)\/([\d -]+)$/;if(m.test(t)){let[D,M]=t.match(m).slice(1),R=D.trim(),b=M.trim();if(p.test(R)&&p.test(b)){let O=R.match(p).slice(1,3).join("-"),v=b.match(p).slice(1,3).join("-");t=`${O} ${v}`,e.push("slashSeparationPattern")}}let d=/^([\d -]+),([\d -]+)$/;if(d.test(t)){let[D,M]=t.match(d).slice(1),R=D.trim(),b=M.trim();if(p.test(R)&&p.test(b)){let O=R.match(p).slice(1,3).join("-"),v=b.match(p).slice(1,3).join("-");t=`${O} ${v}`,e.push("commaSeparationPattern")}}let l=/^\d \d,/;if(l.test(t)){let D=t.match(l)[0],M=D.slice(0,D.length-1).split(" ").join("-");t=t.replace(D,M),e.push("singleSetCommaSeparationPattern")}let f=0,g=/(\d+)-(\d{2})-(\d+)/;for(;g.test(t)&&f<3;){let[D,M,R]=t.match(g).slice(1),b=M.split(""),O=`${D}-${b[0]} ${b[1]}-${R}`;t=t.replace(g,O),e.push("noSetSeparationPattern"),f+=1}let I=/(^|\s)7-6\s(\d+)\s/g,h=t.match(I);if(h?.length){let D=/(^|\s)7-6\s(\d+)\s/;h.forEach(M=>{let R=M.match(D).slice(2)[0];t=t.replace(M,`7-6(${R}) `),e.push("floatingTiebreakPattern1")})}let S=t.match(/\d \d /);S?.forEach(D=>{let M=D.slice(0,D.length-1).split(" ").join("-");t=t.replace(D,M),e.push("spaceSeparatedSetPattern1")}),S=t.match(/ \d \d$/),S?.forEach(D=>{let M=" "+D.slice(1).split(" ").join("-");t=t.replace(D,M),e.push("spaceSeparatedSetPattern2")});let T=/^\d, *\d\/\d, *\d/;if(T.test(t)){let D=t.match(T)[0],M=D.split("/").map(R=>`(${R})`).join(" ")+" ";t=t.replace(D,M),e.push("slashCommaSetPattern")}let y=/\(6-\)/g;y.test(t)&&(t=t.replace(y,"(6-0)"),e.push("missingZeroPattern2"));let E=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(E.test(t)){let D=t.match(E),M=/(?<!-)(\d+)\/(\d+)(?!-)/,R=t;D.forEach(b=>{let[O,v]=b.match(M).slice(1),x=`${O}-${v}`;R=R.replace(b,x)}),t=R,e.push("slashSetPattern")}let P=/(.*)\s(1\d)\s(\d+)$/;if(P.test(t)){let[D,M,R]=t.match(P).slice(1);D.replace(/\D/g,"").length>=4&&(t=D+` ${M}${R}`,e.push("spaceSeparatedSuperPattern"))}let A=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(let D of t.match(A)||[]){let[M,R,b,O]=D.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[v,x]=R.split("-").map(w=>parseInt(w));Math.abs(v-x)===1&&(t=t.replace(D,`${M}${R}(${b})${O}`),e.push("spaceSeparatedSetPattern"))}let U=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let D of t.match(U)||[]){let M=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[R,b,O]=D.match(M).slice(1),[v,x]=R.split("-").map(w=>parseInt(w));Math.abs(v-x)===1&&(t=t.replace(D,`${R}(${b})${O}`),e.push("floatingTiebreakPattern2"))}let N=/(^|\s)(\d \d)\(/g;for(let D of t.match(N)||[]){let M=/(^|\s)(\d \d)\(/,[R,b]=D.match(M).slice(1);t=t.replace(D,`${R}${b.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}}function M_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(Ba(c[0]))return c[0]+`(${c[1].slice(0,c[1].length-1)})`}return a}).join(" ");let n=new RegExp(/(\([\d ]+\))/g);if(n.test(t))for(let a of t.match(n)){let u=a.replace(" ","-").match(/\((.*)\)/)?.[1];if(Jt(u)&&u?.[0]>2){if([2,4].includes(u.length))u=u.split("").join("-");else if(u.length===3){let p=u.indexOf("1");u=em(u.split(""),p)}}t=t.replace(a,`(${u})`)}r=t?.split(" ");let o=new RegExp(/^(\d[-/]+\d)\((\d+)[-/]+(\d+)\)$/),i=r.length-1;t=r.map((a,c)=>{let u=[void 0,"","COMPLETED"].includes(e)||c!==i;if(o.test(a)&&u){let[p,m,d]=Array.from(a.match(o)).slice(1),l=Math.min(m,d);return`${p}(${l})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^(\d{2})\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1),p=c.split("");return`${p[0]}-${p[1]}(${u})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^\((\d[-/]+\d)\)(\d+)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1);return Ba(c)?`${c}(${u})`:c}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^1-0\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c]=a.match(o).slice(1);return`[${c<9?10:parseInt(c)+2}-${c}]`}return a}).join(" ");let s=/\((\d)+0 /;if(s.test(t)){let a=t.match(s)[1];t=t.replace(s,`(${a}) `)}return{score:t}}function R_({score:t,attributes:e,identifier:r}){if(typeof t!="string")return{score:t,identifier:r};let n=new RegExp(/\([\d,/ ]+\)/g),o=t.match(n);for(let m of o||[]){let l=m.match(/^\((.*)\)$/)?.slice(1)?.[0],g=t.split(m)[0].split(")").reverse()[0].replace(/\D/g,"");if(l?.length===2&&g?.length>=2){let S=g.slice(g.length-2).split("").map(y=>parseInt(y));if(Math.abs(S[0]-S[1])===1)continue}let I=oN(l),h=Yu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=oN(m.match(/^\[(.*)\]$/)[1]);t=t.replace(m,`(${d}) `).trim()});let a=[")","]"],c=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&a.some(m=>t.endsWith(m))&&c.some(m=>t.includes(m))){let m="",d=t.split(/[)\]]/).filter(Boolean).map(h=>(h.startsWith(",")&&(h=h.slice(1)),h.trim())),l=d.every(h=>h.includes(",")||Jd(h)),f=d.every(h=>h.includes("/")||Jd(h)),g=d.every(h=>h.includes("-")||Jd(h)),I=l&&","||g&&"-"||f&&"/";if(I){let h;d.forEach(S=>{if(S.startsWith("("))if(h==="set"&&(m+=" "),S.includes(I))m+=S.slice(1).split(I).map(T=>T.trim()).join("-"),h="set";else{let T=S.slice(1);m+=`(${T}) `,h="tiebreak"}else if(S.startsWith("[")){let T=S.slice(1).split(I).map(E=>parseInt(E.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=Er(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&Ba(t)&&Jt(e?.removed)&&(t=t+`(${e.removed})`,e.removed=void 0));let p=/\(\)/g;return p.test(t)&&(t=t.replace(p,"").trim()),{score:t}}function YT({score:t}){let e=t.split(""),r=[],n,o=()=>n=[void 0,void 0,void 0],i=()=>{let a=`${n[0]}-${n[1]}`;return n[2]&&(a+=` (${n[2]})`),o(),n.push(n),a};o();let s=()=>n[0]!==void 0&&n[1]!==void 0&&Math.abs(parseInt(n[0])-parseInt(n[1]));for(;e.length;){let a=e.shift(),c=Jt(a)&&parseInt(a),u=n[0]!==void 0&&n[1]!==void 0;if(Jt(c)){if(n[0]===void 0){n[0]=c;continue}if(n[1]===void 0&&(n[1]=c,s())){r.push(i()),n=[void 0,void 0];continue}if(u&&e.length===1&&Jt(e[0])){let p=e.pop();n[0]=n[0].toString()+n[1].toString(),n[1]=p,r.push(i()),n=[void 0,void 0]}u&&s()}}return{sets:r}}function Kg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=em(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=em(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function iN(t){let{score:e}=t,{applied:r,matchUpStatus:n}=t,o=e?.toString().split(""),i=o?.every(a=>Jt(a)),s=a=>Math.abs(a[0]-a[1]);if(typeof e=="number"||i){e=e.toString().toLowerCase(),i&&(e=o.join(""));let a=i?o.map(u=>parseInt(u)):e.split("").map(u=>parseInt(u)),{sets:c}=YT({score:e});if(a.length,e.length===3&&s(a.slice(0,2))===1){let[u,p,m]=a;e=`${u}-${p}(${m})`,r.push("numericTiebreakPattern1")}else if(e.length===3&&a[0]===1){let[u,p,m]=a;e=`[${u}${p}-${m}]`,r.push("numericTiebreakPattern2")}else if(e.length===4&&s(a.slice(0,2))===1&&"987654".split("").includes(a[0].toString())){let[u,p,m,d]=a,l=Math.min(m,d);e=`${u}-${p}(${l})`,r.push("numericTiebreakPattern3")}else if(e.length===4&&a[0]===1&&a[2]===1){let[u,p,m,d]=a;e=`[${u}${p}-${m}${d}]`,r.push("bigSuper")}else if(e.length===4){let[u,p,m,d]=a;e=`${u}${p} ${m}${d}`,r.push("split4")}else if(e.length===5&&s(a.slice(0,2))===1){let[u,p,m,d,l]=a;e=`${u}-${p}(${m}) ${d}-${l}`,r.push("numericTiebreakPattern4")}else if(e.length===5&&s(a.slice(3))===1){let[u,p,m,d,l]=a;e=`${u}-${p} ${m}-${d}(${l})`,r.push("numericTiebreakPattern5")}else if(a.length===7)if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&a[4]===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} [${l}${f}-${g}]`,r.push("numericTiebreakPattern6")}else if(s(a.slice(0,2))===1&&s(a.slice(3,5))>1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p}(${m}) ${d}-${l} ${f}-${g}`,r.push("numericTiebreakPattern7")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))===1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d}(${l}) ${f}-${g}`,r.push("numericTiebreakPattern8")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&s(a.slice(4,6))===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} ${l}-${f}(${g})`,r.push("numericTiebreakPattern9")}else e=e.slice(0,2)+" "+e.slice(2,4)+" "+e.slice(4),r.push("numericMatchTiebreakPattern");else if(e.length%2){let u=Kg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Ae(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(P=>parseInt(P)),y=Math.abs(S-T),E=S>T?1:2;return y>1&&E||E*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=Er(p),l=p.map(h=>Math.abs(h)),f=Er(l),g=p[0]<0,I=!g&&p[1]<0;if(p[0]>0&&p[1]>0&&p[0]!==p[1])e=[u.slice(0,2).join(" "),u.slice(2).join("-")].join(" "),r.push("numeric3rdSetTiebreakPattern");else if(m)e=u.join(" "),r.push("chunkSplit");else if(a.length===6){if(d[1]===2||d[2]===2)if(!Object.values(f).includes(3))e=u.join(" "),r.push("chunkSplit");else{let[h,S,T,y,E,P]=a,A=p.reduce((U,N,D)=>N<0?D:U,void 0);if(A===0){let U=Math.min(T,y);e=`${h}-${S}(${U}) ${E}-${P}`,r.push("chunkSplitTiebreak1")}else if(A===1){let U=Math.min(E,P);e=`${h}-${S} ${T}-${y}(${U})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${y}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,y,E,P,A,U]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${y}-${E} [${P}${A}-${U}]`:e=`${h}-${S} ${T}-${y}(${E}) [${P}${A}-${U}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function qT(t){let e=[0,0],r=[],n=t.split(" "),o=/(\d+)-(\d+)/;n.forEach(c=>{if(o.test(c)){let u=c.match(o).slice(1).map(m=>parseInt(m)),p=u[0]>u[1]&&1||u[1]>u[0]&&2;p&&(e[p-1]+=1,r.push(p))}});let i=e[0]>e[1]&&1||e[1]>e[0]&&2,s=e[0]>0&&e[0]===e[1],a=e.reduce((c,u)=>c+u,0);return{setsWon:e,setsTied:s,setWinners:r,totalSets:a,winningSide:i}}function C_({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(tm).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!Ba(f)&&!e){let I=Math.max(...g),h=f.indexOf(I),S=[I,I-1];return h&&S.reverse(),S.join("-")+l}}else if(p.length===2&&Jt(p))return p.split("").join("-");p=Yu(p);let d=new RegExp(`^${$g}$`).test(p)&&"super"||new RegExp(`^${tm}$`).test(p)&&"tiebreak"||new RegExp(`^${Xd}$`).test(p)&&"standard"||"unknown";if(n.push(d),s>1&&d==="standard"&&m<2){let[l,f]=p.split("-"),g=Math.abs(parseInt(l)-parseInt(f)),I=Math.max(l,f),h=Math.min(l,f),S=[parseInt(l),parseInt(f)].indexOf(h);if(I>9&&g>2){let T=I.toString().split(""),y=T.find(E=>parseInt(E)>h||m&&parseInt(E)<=o)??T[0];y&&(p=S?[y,h].join("-"):[h,y].join("-"))}I>(o||0)&&(o=I)}if(d==="standard"){let[l,f]=p.split("-");if(!Math.abs(parseInt(l)-parseInt(f))&&e!=="RETIRED")return""}return p}).filter(Boolean).join(" ");let{setsWon:a,setWinners:c,totalSets:u}=qT(t);if(u===1&&r?.removed==="6"&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...a)>=2&&c[0]===c[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...a)>2){let p=[0,0];t=t.split(" ").map((m,d)=>(p[c[d]]+=1,Math.max(...p)>2?void 0:m)).filter(Boolean).join(" ")}return{score:t,profile:n}}function b_({score:t}){let{setsTied:e,winningSide:r}=qT(t),n=/\s\((\d+)\)$/;if(!r&&e&&n.test(t)){let a=t.match(n).slice(1)[0],c=a<=8?10:a+2;t=t.replace(n,` [${c}-${a}]`)}let o=t.split(" "),i=o[o.length-1];if(!i.includes("-")||i.indexOf("(")>0)return{score:t};let s=i.split("(").join("").split(")").join("").split("-");if(!s.every(a=>Jt(a)))return{score:t};if(s[0]==="76"){let a=s[1].length===2?Math.min(...s[1].split("").map(c=>parseInt(c))):s[1];t=[...o.slice(0,o.length-1),`7-6(${a})`].join(" ")}else{s=s.map(u=>parseInt(u));let a=Math.max(...s),c=Math.abs(s[0]-s[1]);if(a>=10){if(c>2&&s.every(u=>+u>=10)){let u=s.map(p=>p===a?p-10:10).sort();c=Math.abs(u[0]-u[1]),c>2&&(s=u)}t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" ")}else o.length===3&&a>=7&&c>2&&(t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" "))}return{score:t}}function wV({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function LV({score:t,applied:e}){return typeof t!="string"?{score:t}:(t.toLowerCase().includes("o")&&(t=t.toLowerCase().split(" ").map(r=>r.split("o").join("0")).join(" "),e.push("replaceOh")),{score:t,applied:e})}function FV({score:t,applied:e}){return typeof t!="string"?{score:t}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length>2){let n=r.indexOf("1");if(r.length%2){if(r.length===3&&n===0){let o=em(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=iN({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function kV({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&Kg(t)?{score:Kg(t)}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length===1){e.push("removeErroneous1");return}return r}).filter(Boolean).join(" "),{score:t,applied:e})}function GV({score:t,applied:e}){return["walkover","wo","w/o","w-o"].includes(t?.toString().toLowerCase())?(e.push("handleWalkover"),{matchUpStatus:"walkover",score:"",applied:e}):{score:t}}function VV({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(ret|con)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleRetired"),{score:a.trim(),matchUpStatus:"retired",applied:r}}let o=e?.matchUpStatuses?.retired,s=["rtd",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleRetired"),{matchUpStatus:"retired",score:t?.replace(s,"").trim(),applied:r}):{score:t}}function BV({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(def|defaulted)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleDefaulted"),{score:a.trim(),matchUpStatus:"defaulted",applied:r}}let o=e?.matchUpStatuses?.defaulted,s=["dft",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleDefaulted"),{matchUpStatus:"defaulted",score:t?.replace(s,"").trim(),applied:r}):{score:t}}function HV({score:t,attributes:e}){(t.endsWith(" am")||t.endsWith(" pm"))&&(t=""),t=t.replace(/[A-Za-z]+/g,"").trim(),[".",","].some(o=>t.endsWith(o))&&(t=t.slice(0,t.length-1));let r="()/-".split("").some(o=>t.includes(o));/ \d$/.test(t)&&r&&(e={removed:t.slice(t.length-2).trim()},t=t.slice(0,t.length-2));let n=/(.*)[A-Za-z]+$/;return n.test(t)&&(t=t.match(n).slice(1)[0].trim()),{score:t,attributes:e}}function WV({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function jV({score:t}){let e=new RegExp(/^\d+\/\d+/),r=t.split(" ");r.some(o=>e.test(o))&&(t=r.map(o=>e.test(o)?o.replace("/","-"):o).join(" "));let n=/^(\d+), *(\d+)$/;if(n.test(t)){let[o,i]=t.match(n).slice(1);t=[o,i].join("-")}return{score:t}}function YV({score:t}){let e=new RegExp(/\(\d+\/\d+\)/g),r=t.match(e);for(let n of r||[]){let o=n.replace("/","-");t=t.replace(n,o)}return{score:t}}function qV({score:t}){if(t.includes(",")){let e=t.split(",").map(o=>o.trim()),r=o=>/\d \d/.test(o);e.every(r)&&(t=e.map(o=>{let i=/\d+ \d+/g;for(let s of o.match(i)){let[a,c]=s.match(/(\d+) (\d+)/).slice(1);o=o.replace(s,`${a}-${c}`)}return o}).join(" "))}if(t.includes(" ")){let e=t.replace(/[ ,]/g,"");e.split("").every(n=>Jt(n))&&e.length===4&&(t=e)}return{score:t}}function $V({score:t}){let e=new RegExp(/^\[\d+\](.*)$/);e.test(t)&&(t=t.match(e).slice(1)[0].trim());let r=/\(,/g;return r.test(t)&&(t=t.replace(r,"(")),{score:t}}var O_={handleTiebreakSlashSeparation:YV,handleSetSlashSeparation:WV,punctuationAdjustments:U_,handleGameSeparation:jV,joinFloatingTiebreak:D_,handleBracketSpacing:P_,handleSpaceSeparator:qV,separateScoreBlocks:FV,matchKnownPatterns:N_,removeDanglingBits:HV,removeErroneous:kV,handleDefaulted:BV,handleWalkover:GV,properTiebreak:M_,handleNumeric:iN,handleRetired:VV,containedSets:R_,sensibleSets:C_,stringScore:wV,superSquare:b_,setBuilder:YT,excisions:$V,replaceOh:LV};var sN={},KV=[],zV=["handleNumeric","handleWalkover","handleRetired","handleDefaulted","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],QV=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function aN(t){if(!t.score)return{error:B};let{score:e,sheetName:r,identifier:n,fileName:o,stepLog:i,fullLog:s,profile:a}=t,c=[],u,p=[],m,d,l=e,f=I=>{I.forEach(h=>{d=O_[h]({profile:a,identifier:n,matchUpStatus:u,attributes:m,applied:p,score:l});let S=d.score!==l;S&&c.push({method:h,score:d.score}),i&&(s||S||d.matchUpStatus!==u)&&console.log(u?{score:d.score,matchUpStatus:u}:{score:d.score},h),d.matchUpStatus&&(u=d.matchUpStatus),d.attributes&&(m=d.attributes),d.applied&&(p=d.applied),l=d.score})};f(zV);let g=nN(l);return g||(l=e.toString().replaceAll(/\D/g,""),m?.removed&&(m.removed=void 0),f(QV),g=nN(l),g||(KV.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{sN[I]||(sN[I]=0),sN[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var mN={};Xt(mN,{analyzeScore:()=>zg,analyzeSet:()=>qu,checkScoreHasValue:()=>he,checkSetIsComplete:()=>Jp,getSetComplement:()=>Xg,getTiebreakComplement:()=>rm,isValidMatchUpFormat:()=>Nr,parseScoreString:()=>nm,validateMatchUpScore:()=>uN,validateScore:()=>Qg,validateSetScore:()=>$T,validateTieFormat:()=>ar});function XV(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 JV(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 ZV(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 t1(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 e1(t,e,r,n,o){if(t<n)return{isValid:!1,error:`Set winner must reach ${n} games, got ${t}`};let i=o&&t===n&&e===o&&r===1;if(r<2&&!i)return{isValid:!1,error:`Set must be won by at least 2 games, got ${t}-${e}`};if(o){if(e>=o&&!i)return{isValid:!1,error:`When tied at ${o}-${o}, must play tiebreak. Use format like ${o+1}-${o}(5)`};let s=o===n?n+1:n;if(t>s)return{isValid:!1,error:`With tiebreak format, set score cannot exceed ${s}-${o}. Got ${t}-${e}`}}else if(t>n+10)return{isValid:!1,error:`Set score ${t}-${e} exceeds reasonable limits`};return{isValid:!0}}function r1(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 n1(t,e,r,n,o,i,s){if(r&&n){let c=JV(t,e,r,n);if(!c.isValid)return c}return(o!==void 0||i!==void 0)&&s?ZV(o,i,s):{isValid:!0}}function o1(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 i1(t,e,r){let{side1:n,side2:o,winner:i,loser:s,diff:a}=t,{setTo:c,tiebreakAt:u}=e;if(c&&u){let p=t1(n,o,c,u);if(!p.isValid)return p}return r?o1(i,s,c):c?e1(i,s,a,c,u):{isValid:!0}}function $T(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 A=t.side1Score??0,U=t.side2Score??0;if(A===0&&U===0)return{isValid:!1,error:"Timed set requires at least one side to have scored"};if(i.based==="P"&&A===U&&A>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,m=!!p&&!s,d=t.side1TiebreakScore!==void 0&&t.side2TiebreakScore!==void 0,{side1Score:l,side2Score:f,side1TiebreakScore:g,side2TiebreakScore:I}=r1(t,m,d),h=Math.max(l,f),S=Math.min(l,f),T=h-S;if(m){let A=i.tiebreakSet?.NoAD??!1;return XV(h,S,T,p,n??!1,A)}let y=g!==void 0||I!==void 0,E=s&&h===s+1&&S===s;return y||E?n1(h,S,s,a,g,I,c):i1({side1:l,side2:f,winner:h,loser:S,diff:T},{setTo:s,tiebreakAt:a},n)}function uN(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=[Me,Bt,Gt].includes(r||"");for(let s=0;s<t.length;s++){let a=t[s],c=s+1===o,u=a.winningSide!==void 0,d=$T(a,e,c,i||r===void 0&&!u);if(!d.isValid)return{isValid:!1,error:`Set ${s+1}: ${d.error}`}}return{isValid:!0}}function s1(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 a1(t,e,r,n,o,i){let a=e+1===n,{side1Score:c,side2Score:u,side1TiebreakScore:p,side2TiebreakScore:m,winningSide:d}=t,l=Math.max(c??0,u??0),f=p??m,{finalSetFormat:g,setFormat:I}=r,h=a&&g||I;return f&&!s1(h?.tiebreakFormat,p,m,d,o,i)?!1:h.setTo?!(!h.noTiebreak&&l>h.setTo+1):!0}function c1(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 u1(t,e,r,n,o){return(!o||t===e)&&r===1&&n.indexOf(t)+1||void 0}function zg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(U=>U?.winningSide)||[]).reduce((U,N)=>{let{winningSide:D}=N;if(!D)return U;let M=D-1;return U[M]++,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],m=u!==void 0&&a[u],d=e?Ne(e):void 0,l=Math.max(...a),f=Er(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf||d?.exactly,h=I&&Math.ceil(I/2)||1,S=r??t,T=!!(S&&[Gt,Me,Bt].includes(S)),y=!d||!i.length||i.every((U,N)=>a1(U,N,d,I??0,N===i.length-1,T)),E=d?.setFormat?.based==="A"||d?.finalSetFormat?.based==="A",P=E&&i.length>0?c1(i):u1(l,h,f,a,e);return{valid:!!(y&&(n&&E&&n===P||n&&!E&&p>m&&n===P||n&&T||!n&&!P&&(![ge,Gt,Me,Bt].includes(S)||g&&S===ge)))}}function Qg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:B};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:B,info:c};if(a!==void 0&&typeof a!="string")return{error:B,info:c};if(i!==void 0&&!Array.isArray(i))return{error:B,info:li("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(u).length)return{error:B,info:"setNumbers not unique"};for(let m of i){let{side1Score:d,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,side1PointScore:I,side2PointScore:h,winningSide:S,setNumber:T}=m;if(![[d,l],[f,g],[I,h]].filter(P=>P.some(A=>![void 0,null].includes(A))).every(P=>P.every(A=>It(A))))return{error:B,info:"non-numeric values"};if(![T,S].filter(P=>![void 0,null].includes(P)).every(P=>It(P)))return{error:B,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:B,info:"winningSide must be 1 or 2"}}let{valid:p}=zg({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:IA,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Xg=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=dt(r);s?.toString().length>2&&(s=parseInt(s.toString().slice(0,2))),o&&o<n&&s>o&&(s=o);let a;return i&&!o?(s>n&&(a=n),a=s<n?n:n-1):a=s+1<n&&n||o&&o<n&&s===o&&n||!o&&s+2||n+1,[e?s:a,e?a:s]},rm=t=>{let{isSide1:e,lowValue:r,tiebreakTo:n,tiebreakNoAd:o}=t;if(r===void 0)return!1;let i=typeof r=="string"?parseInt(r):r;i?.toString().length>2&&(i=parseInt(i.toString().slice(0,2))),o&&i>n-1&&(i=n-1);let s=p1({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function p1(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function pN(t,e){return t>e&&1||t<e&&2||void 0}function m1(t,e){return e?{side1Score:t[0],side2Score:t[1],winningSide:pN(t[0],t[1])}:{side1TiebreakScore:t[0],side2TiebreakScore:t[1],winningSide:pN(t[0],t[1])}}function nm({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,m)=>u({set:p,setNumber:m+1}));function i(p,m){if(!n||!m)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 d=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;return d?.tiebreakSet?.tiebreakTo??d?.tiebreakFormat?.tiebreakTo??t}function a(p,m,d){let l=p[1],f=s(d),g=rm({lowValue:l,isSide1:m===2,tiebreakTo:f});return Array.isArray(g)?[g[0],g[1]]:[void 0,void 0]}function c(p,m,d,l){let g=(m&&p.replace(m[0],"")||d&&p.replace(d[0],"")||p).split("-").map(E=>Number.parseInt(E)),I=g[0],h=g[1],S=pN(I,h),T,y;if(m&&([T,y]=a(m,S,l)),d){let E=d[1].split("-").map(P=>Number.parseInt(P));T=E[0],y=E[1]}return{side1Score:I,side2Score:h,side1TiebreakScore:T,side2TiebreakScore:y,winningSide:S}}function u({set:p,setNumber:m}){let d=/\(([^)]+)\)/,l=/\[([^\]]+)\]/,f=d.exec(p),g=l.exec(p),I=p?.startsWith("[")&&g,h=i(m,!!I),S=s(m),T=h&&S===1,y;if(I){let E=g[1].split("-").map(P=>Number.parseInt(P));y=m1(E,h)}else y=c(p,f,g,m);return{side1Score:y.side1Score,side2Score:y.side2Score,side1TiebreakScore:y.side1TiebreakScore,side2TiebreakScore:y.side2TiebreakScore,winningSide:y.winningSide,setNumber:m,...T&&{NoAD:!0},...h&&{tiebreakSet:!0}}}}function v_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=Zp({set:o});return Jp({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function qu(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:ef};let{setNumber:n}=e||{},{bestOf:o,exactly:i}=r||{},s=o||i,a=!!(n&&s&&n===s),c=a&&r?.finalSetFormat||r?.setFormat,u=!!c?.tiebreakSet,p=!!c?.timed,m=!u&&!p,d=!!(n&&s&&n<=s),l=[e?.side1Score,e?.side2Score],f=[e?.side1PointScore,e?.side2PointScore],g=[e?.side1TiebreakScore,e?.side2TiebreakScore],I=l.filter(w=>w!==void 0).length,h=f.filter(w=>w!==void 0).length,S=g.filter(w=>w!==void 0).length,T=l?.filter(w=>!isNaN(w)).length,y=g?.filter(w=>!isNaN(w)).length,{tiebreakAt:E}=c||{},P=E&&l.filter(w=>w>=E).length===2,A=P&&(l[0]>l[1]&&1||l[1]>l[0]&&2||void 0),U=!!(y&&!T),N=!!e?.winningSide,{error:D,result:M}=d1({sideTiebreakScores:g,sideGameScores:l,setFormat:c,setObject:e}),{error:R,result:b}=l1({sideTiebreakScores:g,setObject:e,setFormat:c}),O=m&&!U&&M||u&&U&&b||p,v=d&&!(u&&!U)&&!(m&&U)&&(!N||O),x=v_({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:U,setObject:e}),F={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:P,isCompletedSet:N,isDecidingSet:a,isTiebreakSet:U,isValidSet:v,isValidSetNumber:d,isValidSetOutcome:O,leadingSide:A,setFormat:c,sideGameScores:l,sideGameScoresCount:I,sidePointScores:f,sidePointScoresCount:h,sideTiebreakScores:g,sideTiebreakScoresCount:S,winningSide:x};return e?.winningSide!==void 0&&(U?(F.isValidTiebreakSetOutcome=b,b||(F.tiebreakSetError=R)):(F.isValidStandardSetOutcome=M,M||(F.standardSetError=D))),F}function d1({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:ef};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:B};if(!(r?.filter(M=>!isNaN(M)).length===2))return{result:!1,error:KI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(M=>M>=a)))return{result:!1,error:KI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:_m};let l=t?.winningSide-1,f=1-l,g=r[l],I=r[f],h=g-I;if(!(g>I))return{result:!1,error:{message:"winningSide game scoreString is not high"}};let T=c&&u,y=n?.filter(M=>!isNaN(M)).length===2,E=n?.[l],P=n?.[f],A=c&&r.filter(M=>M>=c).length===2;if(T){let{NoAD:M,tiebreakTo:R}=u;if(A){if(h>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!y)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(R))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(R&&n?.find(k=>k>=R)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let v=c<a?a:a+1;if(g>v)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!E||!P||E<P)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let x=M?1:2,F=E-P,w=P>=R-1;if(F&&w&&F<x)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(g>a&&!A)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}let U=p?1:2,N=I>=a-1;return h&&N&&!A&&h<U?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>U&&g>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function l1({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:ef};let n=!!e?.tiebreakSet,o=!!e?.timed;if(!e||!n||o)return{result:!1,error:{message:"not tiebreak set"}};let i=[1,2].includes(t?.winningSide);if(!t||!i)return{result:!1,error:_m};let{tiebreakSet:s}=e||{},{NoAD:a,tiebreakTo:c}=s||{};if(!(r?.filter(T=>!isNaN(T)).length===2))return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(c))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!r?.find(T=>T>=c))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let m=t?.winningSide-1,d=1-m,l=r[m],f=r[d];if(!l||!f||l<f)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let g=a?1:2,I=l-f,h=f>=c-1;return I&&h&&I<g?{result:!1,error:{message:"invalid tiebreak scores (3)"}}:{result:!0}}function __(t){let{existingDrawDefinition:e,hydrateCollections:r,enforceGender:n,tieFormatName:o,matchUpType:i,eventType:s,isMock:a,event:c}=t,{tieFormat:u,matchUpFormat:p}=t;if(i===_e&&s===_e){let m=e?.structures?.find(({stage:d})=>d===rt)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&io({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||io({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=bn));if(u){let m=ar({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function x_(t){let e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:r,appliedPolicies:n,qualifyingOnly:o,drawEntries:i,structureId:s,tieFormat:a,idPrefix:c,isMock:u,event:p}=t,m=t.qualifyingProfiles,d=m?.length?OT({hasExistingDrawDefinition:!0,uuids:t.uuids,qualifyingProfiles:m,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,idPrefix:c,isMock:u}):void 0;if(d?.error)return d;e.structures=e.structures?.filter(({structureId:E})=>E!==r),e.links=e.links?.filter(({source:E})=>E.structureId!==r);let{qualifiersCount:l,qualifyingDrawPositionsCount:f,qualifyingDetails:g}=d??{};f&&(d?.structures&&e.structures?.push(...d.structures),d?.links&&e.links?.push(...d.links));let I=e.structures?.find(({stage:E,stageSequence:P})=>E===rt&&P===1),{qualifiersCount:h}=Us({stageSequence:1,drawDefinition:e,structureId:s,stage:rt}),S=Math.max(l??0,h??0),T=$S({qualifiersCount:S,drawDefinition:e,stage:rt});if(T.error||(T=Hp({drawSize:f,stage:ct,drawDefinition:e}),T.error))return T;f1({drawDefinition:e,drawEntries:i,event:p});let y=g1({mainStructure:I,qualifyingDetails:g,drawDefinition:e});return y.error?y:{drawDefinition:e,structureId:s}}function f1({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===ct)){let o={...n,entryStage:n.entryStage??rt,drawDefinition:t,event:r};Pd(o)}}function g1({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=[]),r.links.push(u))}return{error:void 0}}function KT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Xr.includes(o)}).map(St)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return _({result:{error:ln},info:{invalidParticipantIds:n}})}else e=r;return t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>e.length-1&&(!t.enableDoubleRobin||t.roundsCount>(e.length-1)*2)?{error:B,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:B,info:"roundsCount must be less than 32"}:{participantIds:e}}function Zd(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=KT(t);if(p.error)return p;for(let m of tt(1,r+1)){let d=Wu({restrictMatchUpsCount:t.restrictMatchUpsCount,ignoreLastRoundNumber:!!u,newRound:!u,drawDefinition:n,matchUpsCount:o,structureId:i,roundNumber:u,idPrefix:s,isMock:a,event:c});if(d.error)return _({result:d,info:{iteration:m}});d.matchUps?.length&&e.push(...d.matchUps),u=(d?.roundNumber??1)+1}return{matchUps:e}}function L_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??je[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=w_({scaleName:`${n}.${Qm}`,participant:u,eventType:o});!p&&n&&(p=w_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function w_({scaleType:t=Ui,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Po({scaleAttributes:{eventType:o??qs,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&ht(a)?a[e]:a}function tl(t){let e=h1(t);if(e?.error)return e;let r=KT(t);if(r.error)return r;let n=I1(t);if(n.error)return n;let o=L_(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of tt(1,(t.roundsCount??1)+1)){let m=qd({...t,participantIds:r.participantIds,structure:n.structure,ignoreLastRoundNumber:!0,iterationMatchUps:a,adHocRatings:o,roundNumber:u,eventType:s,isMock:i});if(m.error)return m;let{matchUps:d,...l}=m;l.modifiedScaleValues&&(o=l.modifiedScaleValues),c.push({...l,iteration:p,matchUpsCount:d?.length}),u=(l?.roundNumber??1)+1,d?.length&&a.push(...d)}return{...C,matchUps:a,roundResults:c}}function I1(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&&$s[s.stage];return cr({structure:s})&&a>($s[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?cr({structure:n})?{structure:n}:{error:Sa}:{error:_t}}function h1(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:B,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==Fr?{error:Sa}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:B,info:"Missing Entries"}:{error:void 0}}function F_(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,idPrefix:o,isMock:i,event:s}=t,a=s?.entries?.filter(({entryStage:p,entryStatus:m})=>(!p||p===rt)&&m&&Xr.includes(m)),c=a?.map(St),u=a?Math.floor(a.length/2):0;if(t.automated)return S1({...t,participantIds:c});{let p=Zd({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&Gd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...C}}function S1(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=tl({...t,eventType:t.drawMatic?.eventType??t.matchUpType,generateMatchUps:r??!0,scaleAccessor:s??t.scaleAccessor,scaleName:i??t.scaleName,participantIds:t.participantIds,roundsCount:t.roundsCount,restrictEntryStatus:e,structureId:n,matchUpIds:o});return a.error?a:(a?.matchUps?.length&&Gd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...C})}function k_({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:r,participantsCount:n,participantCount:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,seedsCount:u}){n=n??o;let p=at({drawDefinition:s,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:_t};let{positionAssignments:d}=Ie({structure:m}),l=d?.length||0;if(u>l)return{error:$E};let f=m.structures?.length,g=It(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=Dg({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=Hu({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[Vn]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=tt(1,u+1).map(S=>{let T=I?.find(P=>P.includes(S)),y=T&&Math.min(...T),E=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:E}}),bt({drawDefinition:s,structureIds:[c]}),{...C,seedLimit:u}}function ca({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:q};return i=i??s?.entries??[],{scaledEntries:i.filter(d=>(!a||!d.entryStage||d.entryStage===a)&&(!o||!d.entryStageSequence||d.entryStageSequence===o)&&Xr.includes(d.entryStatus)).map(d=>{let{participantId:l}=d,{scaleItem:f}=wc({tournamentRecord:e,scaleAttributes:r,participantId:l});return{...d,...f}}).filter(d=>{let l=d.scaleValue;return!n&&(isNaN(l)||!parseFloat(l))?!1:l}).sort(n||p)};function p(d,l){return t?m(l)-m(d):m(d)-m(l)}function m(d){return parseFloat(d.scaleValue||(t?-1:1e5))}}function zT(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 _({result:{error:_t},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=N1({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&E1({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==Fr&&!(t.qualifyingOnly&&t.stage!==ct),m=(n?.length||0)>1,d=p?y1({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function T1({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=mt({name:vn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&mi.includes(o.entryStatus)})}function y1(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Mc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function E1(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(St);e?A1({...t,enteredParticipantIds:i}):(o||r)&&U1({...t,enteredParticipantIds:i})}function A1(t){let{provisionalPositioning:e,enteredParticipantIds:r,seededParticipants:n,tournamentRecord:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,structure:u,event:p}=t,m=u?Ns({provisionalPositioning:e,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structure:u}):void 0;n.filter(({participantId:d})=>r.includes(d)).filter(d=>!d.seedNumber||d.seedNumber<=n.length).sort((d,l)=>d.seedNumber<l.seedNumber?-1:d.seedNumber<l.seedNumber?1:0).forEach(d=>{let{participantId:l,seedNumber:f,seedValue:g}=d;ra({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function U1(t){let e=t.seedsCount,{provisionalPositioning:r,enteredParticipantIds:n,seedAssignmentProfile:o,assignSeedsCount:i,tournamentRecord:s,drawDefinition:a,seedByRanking:c,seedingProfile:u,structureId:p,event:m}=t,{categoryName:d,ageCategoryCode:l}=m?.category||{},f=m?.eventType,g=P1({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&D1({...t,ageCategoryCode:l,categoryName:d,eventType:f}),I=g?.length??0;I<e&&(e=I),g?.filter(({participantId:h})=>n.includes(h)).slice(0,i||e).forEach((h,S)=>{let T=S+1,{participantId:y,scaleValue:E}=h,P=o?.[T]||E||T;ra({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:P,event:m})})}function P1(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:Ao,eventType:u};return ca({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function D1(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ca({scaleAttributes:{scaleName:s||a,scaleType:Ai,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function N1(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=T1(t);e>r.length&&(e=r.length);let{seedLimit:n}=k_({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 G_(t){let e=jd({...t,modifyOriginal:!1});if(e.error)return e;let r=e.drawDefinition,{suppressDuplicateEntries:n=!0,ignoreStageSpace:o,appliedPolicies:i,qualifyingOnly:s,seedingProfile:a,participants:c,drawEntries:u,placeByes:p,drawSize:m,drawType:d,entries:l}=t,f=[],g=[],I=M1({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===Ki?0:dt(t.seedsCount??0),S=zT({...t,qualifyingOnly:!m||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:rt,seedsCount:h,placeByes:p,drawSize:m,entries:l});if(S.error&&!S.conflicts)return S;S.positioningReport?.length&&f.push({[rt]:S.positioningReport});let T=S.structureId;return S.conflicts&&(g=S.conflicts),d===Fr&&t.roundsCount&&F_({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function M1(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,entries:i}=t;for(let s of i){if(n&&s.entryStage&&s.entryStage!==rt)continue;let a={...s,ignoreStageSpace:e??o===Fr,entryStage:s.entryStage??rt,event:t.event,drawDefinition:r,drawType:o},c=Pd(a);if(n&&c.error)return c}return{error:void 0}}var R1=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var V_=R1;function B_(t){let{drawId:e=Nt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=V_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function el(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=et(t,[{[Ce]:!0,[$m]:!0}]);if(c.error)return c;if(!Nr({matchUpFormat:o}))return{error:tc};let u="setMatchUpFormat";if(s){let p=Vt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===_e)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:dr};m&&(m.matchUpFormat=o,gt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===_e)return{error:$n};for(let p of e){let m=at({drawDefinition:n,structureId:p});if(m.error)return m;m.structure&&(m.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===_e)return{error:$n};let p=at({drawDefinition:n,structureId:i});if(p.error)return p;p.structure&&(p.structure.matchUpFormat=o)}else n&&(n.matchUpFormat=o);return e=e??(i?[i]:void 0),bt({drawDefinition:n,structureIds:e}),{...C}}function H_({tieFormat:t}){let e=ar({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Nt());return{tieFormat:t}}function W_({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=H_({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=el({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 gN={};Xt(gN,{attachPolicies:()=>ss,findPolicy:()=>pi,getAppliedPolicies:()=>Tt,getPolicyDefinitions:()=>Go,mutate:()=>lN,query:()=>fN,removePolicy:()=>dN});var lN={};Xt(lN,{attachPolicies:()=>ss,removePolicy:()=>dN});function dN(t){let e=et(t,[{[fb]:!0,_anyOf:{[Re]:!1,[ne]:!1,[Ce]:!1,[co]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return j_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:q};for(let i of o){let s=t.tournamentRecords[i],a=j_(t,s);if(a.error)return a;r=!0}}else return{error:q};return r?{...C}:{error:qc}}function j_(t,e){let r=Tt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?At({element:e,extension:{name:du,value:r}}):Ir({element:e,name:du}),{...C}):{error:qc}}var fN={};Xt(fN,{findPolicy:()=>pi,getAppliedPolicies:()=>Tt,getPolicyDefinitions:()=>Go});var IN={[Vn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Eo]:{positioning:Ti},[On]:{positioning:Ti}},positioning:ab},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}]}},Zg=IN;function Y_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:B},stack:n});let o={[mu]:t?.[mu]};return e?C1({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&ss({drawDefinition:r,policyDefinitions:o}),!t?.[Vn]&&!e?.[Vn]&&(ss({policyDefinitions:Zg,drawDefinition:r}),t&&Object.assign(t,Zg)),{error:void 0}}function C1({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&&(ss({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function q_(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,m=p?.structures?.find(h=>h.stage===rt&&h.stageSequence===1)?.structureId,d=p?p.structures?.filter(h=>h.stage===ct):[],l=d?.length===1&&!d[0].matchUps?.length&&d[0].structureId;p&&a!==p.drawType&&(p.drawType=a);let f=p??B_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),g=W_({existingQualifyingStructures:d,tournamentRecord:e,drawDefinition:f,matchUpFormat:o,matchUpType:i,tieFormat:s,event:u});if(g.error)return _({result:g,stack:c});let I=Y_({appliedPolicies:n,policyDefinitions:r,drawDefinition:f,stack:c});return I.error?I:{drawDefinition:f,structureId:m,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:l}}function $_(t){let e="generateOrGetExisting",r=[],n=[],o=q_(t);if(o.error)return _({result:o,stack:e});let i=o.existingDrawDefinition,s=o.drawDefinition??{},a=o.structureId,c=t.drawEntries??t.eventEntries??[],u=o.existingQualifyingPlaceholderStructureId&&x_({...t,...o})||G_({...t,...o,entries:c});return u.error?_({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 K_(t){let{qualifyingPlaceholder:e,existingDrawDefinition:r,positioningReports:n,qualifyingProfiles:o,appliedPolicies:i,qualifyingOnly:s,drawDefinition:a,seedingProfile:c,participants:u,structureId:p,tieFormat:m,entries:d,stack:l}=t,f=e&&!o?.length&&!r,g=[];if(o){let I=(y,E)=>y.stageSequence-E.stageSequence,h=(y,E)=>y.roundTarget-E.roundTarget,S=[],T=1;o.sort(h);for(let y of o){if(!Array.isArray(y.structureProfiles))return _({info:li("structureProfiles"),result:{error:st},stack:l});T=y.roundTarget||T;let E=y.structureProfiles?.sort(I)||[],P=1;for(let A of E){let{qualifyingRoundNumber:U,qualifyingPositions:N,seededParticipants:D,seedingScaleName:M,seedsCount:R=0,seedByRanking:b,placeByes:O,drawSize:v}=A,x=zT({...t,seedingProfile:A.seedingProfile??c,stageSequence:P,qualifyingRoundNumber:U,preparedStructureIds:S,qualifyingPositions:N,seededParticipants:D,stage:ct,seedingScaleName:M,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:b,participants:u,roundTarget:T,seedsCount:R,placeByes:O,drawSize:v,entries:d});if(x.error)return x;x.structureId&&S.push(x.structureId),P+=1,x.conflicts?.length&&g.push(...x.conflicts),x.positioningReport?.length&&n.push({[ct]:x.positioningReport})}T+=1}}else if(p&&f){let I=yn({structureName:Qe(ct),stage:ct,qualifyingOnly:s,tieFormat:m}),{link:h}=La({sourceStructureId:I.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:Fn});a.structures||(a.structures=[]),a.structures.push(I),a.links||(a.links=[]),a.links.push(h)}return{qualifyingConflicts:g,error:void 0}}var FN={};Xt(FN,{addGoesTo:()=>rs,allCompetitionMatchUps:()=>Mn,allDrawMatchUps:()=>nr,allEventMatchUps:()=>to,allPlayoffPositionsFilled:()=>WS,allTournamentMatchUps:()=>ye,analyzeDraws:()=>Vu,analyzeMatchUp:()=>cm,analyzeTournament:()=>sy,bulkUpdatePublishedEventIds:()=>cy,calculateWinCriteria:()=>Os,categoryCanContain:()=>tu,checkMatchUpIsComplete:()=>Ts,checkValidEntries:()=>Hd,compareTieFormats:()=>ni,competitionScheduleMatchUps:()=>Ku,courtGridRows:()=>dl,credits:()=>z_,drawMatchUps:()=>Dy,eventMatchUps:()=>Il,filterMatchUps:()=>_i,filterParticipants:()=>bu,findDrawDefinition:()=>gT,findExtension:()=>mt,findVenue:()=>ti,getAggregateTeamResults:()=>iy,getAllDrawMatchUps:()=>ie,getAllEventData:()=>uy,getAllStructureMatchUps:()=>yt,getAllowedDrawTypes:()=>rl,getAllowedMatchUpFormats:()=>ey,getAppliedPolicies:()=>Tt,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getCategoryAgeDetails:()=>Ys,getCheckedInParticipantIds:()=>Is,getCompetitionDateRange:()=>ol,getCompetitionMatchUps:()=>am,getCompetitionParticipants:()=>QT,getCompetitionPenalties:()=>ry,getCompetitionVenues:()=>om,getCourtInfo:()=>Td,getCourts:()=>Ny,getDrawData:()=>cl,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getEntriesAndSeedsCount:()=>ll,getEvent:()=>Cy,getEventData:()=>ul,getEventMatchUpFormatTiming:()=>Iy,getEventProperties:()=>My,getEventPublishStatus:()=>Jr,getEventStructures:()=>Mg,getEventTimeItem:()=>Au,getEvents:()=>Ry,getFlightProfile:()=>Ht,getHomeParticipantId:()=>yy,getLinkedTournamentIds:()=>fu,getMatchUpCompetitiveProfile:()=>Du,getMatchUpContextIds:()=>Ey,getMatchUpDailyLimits:()=>Sl,getMatchUpDailyLimitsUpdate:()=>hy,getMatchUpDependencies:()=>an,getMatchUpFormat:()=>Ay,getMatchUpFormatTiming:()=>Nu,getMatchUpFormatTimingUpdate:()=>fy,getMatchUpScheduleDetails:()=>yd,getMatchUpType:()=>Ed,getMatchUpsMap:()=>Pe,getMatchUpsStats:()=>Uy,getMatchUpsToSchedule:()=>pl,getMaxEntryPosition:()=>dy,getModifiedMatchUpFormatTiming:()=>fl,getPairedParticipant:()=>Sn,getParticipantEventDetails:()=>XT,getParticipantIdFinishingPositions:()=>fT,getParticipantMembership:()=>JT,getParticipantResults:()=>ku,getParticipantScaleItem:()=>wc,getParticipantSchedules:()=>ZT,getParticipantSignInStatus:()=>ty,getParticipantTimeItem:()=>sS,getParticipants:()=>Ft,getPersonRequests:()=>ki,getPolicyDefinitions:()=>Go,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getPredictiveAccuracy:()=>Ty,getProfileRounds:()=>ml,getPublishState:()=>As,getRandomQualifierList:()=>RT,getRoundMatchUps:()=>Ke,getRounds:()=>Py,getScaleValues:()=>Aa,getScaledEntries:()=>ca,getScheduledRoundsDetails:()=>$u,getSchedulingProfile:()=>oi,getSchedulingProfileIssues:()=>my,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getTieFormat:()=>al,getTimeItem:()=>nn,getTournamentIds:()=>Np,getTournamentInfo:()=>bs,getTournamentPenalties:()=>nl,getTournamentPersons:()=>oy,getTournamentPoints:()=>il,getTournamentPublishStatus:()=>Ru,getTournamentStructures:()=>HS,getTournamentTimeItem:()=>cd,getValidGroupSizes:()=>Gp,getVenueData:()=>Ac,getVenuesAndCourts:()=>Ro,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,isValidMatchUpFormat:()=>Nr,matchUpActions:()=>Bd,participantScaleItem:()=>Po,participantScheduledMatchUps:()=>Sy,positionActions:()=>MT,publicFindCourt:()=>PS,publicFindVenue:()=>US,tallyParticipantResults:()=>Fa,tieFormatGenderValidityCheck:()=>km,tournamentMatchUps:()=>hl,validMatchUp:()=>pg,validMatchUps:()=>Br,validateCollectionDefinition:()=>eu,validateLineUp:()=>Cd});function z_(){return`
|
|
4
|
+
`)}function eD({participantResults:t,participantIds:e,attribute:r}){return rD({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 rD(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var zG=[{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}],nD={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function oD(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!QG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=eD({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let p=Object.keys(a).map(S=>parseFloat(S)).sort((S,T)=>T-S).map(S=>a[S]).map(S=>{let T=Mv({participantIds:S,...t});return i.push(...T.report??[]),T.order}).map((S,T)=>S.map(y=>y.resolved?y:{...y,subGroup:[T].concat(...y.subGroup??[])})).flat(),m,d=0,l=1,f;p.forEach((S,T)=>{T&&(S.resolved||f&&!S.resolved)&&(l+=1),f=S.resolved;let y=parseInt(S.subGroup?.join("")||0);S.resolved?(S.position=T+1,l=S.position):(m&&y>m&&(l+=d,d=0),S.position=l,d+=1),m=y});let g=p.map(({position:S})=>S),I=Er(g);return p.forEach(S=>{let{participantId:T,position:y}=S||{},E=r[T];S.GEMscore=h(E);let P=I[y];S?.position!==void 0&&(P>1&&(S.ties=P,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(nD).filter(E=>o.GEMscore.includes(E)):Object.keys(nD)).map(E=>(S[E]||0)*Math.pow(10,nD[E].toFixed(3))).reduce((E,P)=>E+P,0)}}function QG({participantResults:t,participantsCount:e}){let n=rD({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function XG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,groupTotals:n,tallyPolicy:o,attribute:i,idsFilter:s,matchUps:a,reversed:c}){let{participantResults:u}=ku({participantIds:s&&e,groupingTotal:n&&i,matchUpFormat:r,tallyPolicy:o,matchUps:a}),p=eD({participantResults:u,participantIds:e,attribute:i}),m=[{attribute:i,reversed:c,groups:p,idsFilter:s,groupTotals:n}],d;return Object.keys(p).length>1&&e.length&&(d=Object.keys(p).map(g=>parseFloat(g)).sort((g,I)=>c?g-I:I-g).map(g=>p[g]).map(g=>{let I=Mv({participantResults:u,disableHeadToHead:t,participantIds:g,matchUpFormat:r,tallyPolicy:o,matchUps:a});return m.push(...I.report??[]),I.order}).map((g,I)=>g.map(h=>h.resolved?h:{...h,subGroup:[I].concat(...h.subGroup??[])})).flat()),{order:d,report:m}}function Mv({participantResults:t,disableHeadToHead:e,participantIds:r,matchUpFormat:n,tallyPolicy:o,matchUps:i}){let s=[],a=[],c;if(r?.length===1)return{order:[{resolved:!0,participantId:r[0]}]};if(r?.length===2&&(!o?.headToHead||!o.headToHead.disabled&&!e)){let m=JG({participantIds:r,participantResults:t});if(m){let d=m[0].participantId;return a.push({attribute:"head2Head",participantIds:r,headToHeadWinner:d}),{order:m,headToHeadWinner:d,report:a}}}let p=(o?.tallyDirectives||zG).filter(m=>{let d=!(Jt(m.maxParticipants)&&r?.length>m.maxParticipants);return d||s.push(m),d});return s.length&&a.push({excludedDirectives:s,participantIds:r}),p.every(({attribute:m,reversed:d,idsFilter:l,groupTotals:f,disableHeadToHead:g})=>(c=XG({disableHeadToHead:g,participantIds:r,matchUpFormat:n,groupTotals:f,tallyPolicy:o,attribute:m,idsFilter:l,matchUps:i,reversed:d}),a.push(c.report),!c.order)),c.order?{order:c.order,report:a}:{order:r?.map(m=>({participantId:m})),report:a}}function JG({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 Fa({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Br(o))return{error:no};let a=pt(o.map(({structureId:y})=>y));if(a.length!==1)return _({result:{error:B,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!=="BYE"),u=c.length&&pt(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>Ts({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:E})=>y===Wt&&E?.every(P=>Ts({matchUp:P}))),d=t?.[kf],l=o.filter(y=>Ts({matchUp:y})??y.matchUpType===Wt),{participantResults:f}=ku({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=oD({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,subOrderMap:i,tallyPolicy:d});if(r&&ZG({participantResults:f}),p&&h)g=S,I=h,h.forEach(y=>{let{participantId:E,groupOrder:P,rankOrder:A,subOrder:U,ties:N,GEMscore:D}=y,M=f[E];Object.assign(M,{groupOrder:P,rankOrder:A,GEMscore:D,subOrder:U,ties:N})});else{let{groupOrder:y,report:E}=oD({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=E,I=y,y&&y.forEach(P=>{let{participantId:A,groupOrder:U,GEMscore:N}=P,D=f[A];Object.assign(D,{provisionalOrder:U,GEMscore:N})})}let T={completedTieMatchUps:m,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||m)&&(T.order=I),e||Dr({tally:!0})){let y=Nv({matchUps:o,report:g,order:I});Dr({tally:!0})&&console.log(y),T.readableReport=y}return T}function ZG({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 iT({positionAssignments:t}){let e=(t||[]).filter(Hr(ao)).map(i=>{let{extension:s}=mt({element:i,name:fc}),a=dt(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=Er(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function Ld({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Br(o))return{error:B};if(!t)return{error:B};let{policyDefinitions:s}=Go({policyTypes:[kf],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=iT({positionAssignments:t}),c=o.length?Fa({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;if(c?.error)return c;let{participantResults:u={},bracketComplete:p,report:m}=c??{},d=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;if(d.includes(f)){let g={value:u[f],name:Lo};At({element:l,extension:g}),u[f].ties||Ir({element:l,name:fc})}else Ir({element:l,name:Lo}),Ir({element:l,name:fc})}),bt({drawDefinition:r}),{...C,participantResults:u,bracketComplete:p,report:m}}function sT({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Vt(t){let e=et(t,[{[Ce]:!0,[gn]:!0}]);if(e.error)return e;let{tournamentParticipants:r,afterRecoveryTimes:n,contextProfile:o,drawDefinition:i,matchUpsMap:s,matchUpId:a,inContext:c,context:u,event:p}=t,{structures:m=[]}=hn({drawDefinition:i}),d=t.contextContent||o&&Zn({contextProfile:o,drawDefinition:i});for(let l of m){let{matchUps:f}=yt({tournamentParticipants:r,afterRecoveryTimes:n,contextContent:d,drawDefinition:i,contextProfile:o,matchUpsMap:s,inContext:c,structure:l,context:u,event:p}),{matchUp:g}=sT({matchUps:f,matchUpId:a});if(g)return{matchUp:g,structure:l}}return{error:we}}function $p(t){return!ht(t)||!t.notes?{error:st}:ht(t.element)?!kt(t.notes)&&!t.notes?.testing?{error:B}:(Object.assign(t.element,{notes:t.notes}),{...C}):{error:B}}function Fg(t){return ht(t)?ht(t.element)?(t.element.notes&&delete t.element.notes,{...C}):{error:B}:{error:st}}var Gu={matchUpStatus:Qt,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:m,event:d,notes:l,score:f}=t,I=t.appliedPolicies&&Object.keys(t.appliedPolicies).length?t.appliedPolicies:Tt({policyTypes:[rn],tournamentRecord:s,drawDefinition:a,structure:o,event:d})?.appliedPolicies,h=n.matchUpType===Wt;if(h&&a){if(m&&n.matchUpId!==m){let U=Vt({drawDefinition:a,matchUpId:m,event:d});if(!U.matchUp)return{error:we};({matchUp:n,structure:o}=U)}}else n.matchUpId!==m&&console.log("!!!!!");c&&[Bt,oe].includes(c)||u?Object.assign(n,{...Gu}):f&&(n.score=f);let S=c&&n?.matchUpStatus===Gt&&c!==Gt;c&&(n.matchUpStatus=c),r&&(n.matchUpFormat=r),i&&(n.matchUpStatusCodes=i),p&&(n.winningSide=p),t.removeWinningSide&&(n.winningSide=void 0),!o&&a&&({structure:o}=Vt({drawDefinition:a,matchUpId:m,event:d})),c&&!n.winningSide&&he(n)&&!ae.includes(c)&&![gc,ls,mn].includes(c)&&(n.matchUpStatus=Hn);let T;if((S&&n?.processCodes?.length||c===Gt)&&(T=I?.[rn]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let U=o?.structureType===Ve,N=cr({structure:o});if(gd({drawDefinition:a,structure:o})||N||U){let D=b=>{r=h?"SET1-S:T100":r??n.matchUpFormat??b?.matchUpFormat??a?.matchUpFormat??d?.matchUpFormat;let O=h?{matchUpTypes:[Wt]}:void 0,{matchUps:v}=yt({afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,matchUpFilters:O,drawDefinition:a,structure:b,event:d});return N&&(b.positionAssignments=pt(v.flatMap(x=>(x.sides??[]).map(F=>F.participantId)).filter(Boolean)).map(x=>({participantId:x}))),Ld({positionAssignments:b.positionAssignments,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUps:v,event:d})},M=U&&o.structures.find(b=>b?.matchUps.find(O=>O.matchUpId===m)),R=D(M||o);if(R.error)return _({result:R,stack:e})}}if(l){let U=$p({element:n,notes:l});if(U.error)return _({result:U,stack:e})}let y=s?.tournamentId,E=Lr().topics.includes(Rp),P=(E||T)&&Pe({drawDefinition:a}),A=P&&ie({matchUpFilters:{matchUpIds:[m]},nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:a,matchUpsMap:P}).matchUps?.[0];if(E&&A&&Cb({tournamentId:y,inContextMatchUp:A}),Array.isArray(T)&&A&&!A.sides?.every(({participantId:U})=>U))if(c===Gt)n.processCodes=pt([...n.processCodes??[],...T]);else for(let U of T||[]){let N=U&&n?.processCodes?.lastIndexOf(U);n?.processCodes?.splice(N,1)}return gt({eventId:d?.eventId,context:e,drawDefinition:a,tournamentId:y,matchUp:n}),{...C}}function Fd(t){let{propagateExitStatus:e,matchUpStatusCodes:r,autoCalcDisabled:n,inContextMatchUp:o,matchUpStatus:i,dualMatchUp:s,structure:a,matchUp:c}=t,u=Oa({matchUpStatus:i})||[po,vr].includes(i)&&s||n,p=c?.sides?.map(h=>h.participantId).filter(Boolean).length||o?.sides?.map(h=>h.participantId).filter(Boolean).length,m="attemptToModifyScore";if(!(cr({structure:a})&&p===1||i===Gt&&p||tV({structure:a,matchUp:c,inContextMatchUp:o})||t.appliedPolicies?.[rn]?.requireParticipantsForScoring===!1||pr(i)&&p===1&&e))return _({result:{error:Ql},stack:m});let f=[Bt].includes(i),g=u?i:t.winningSide&&ge||mn,I=Yn({...t,winningSide:t.winningSide,matchUpStatusCodes:u&&r||[],matchUpStatus:g,context:m,removeScore:f});return _({result:I,stack:m})}function tV({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=Ie({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 aT({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=>dt(n));return{groupValueGroups:e,groupValueNumbers:r}}function Rv({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=>ae.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),It(d)?i.forEach(S=>{S.winningSide&&(s[S.winningSide-1]+=d)}):It(g)?i.forEach(S=>{S.score?.sets?.forEach(T=>{T.winningSide&&(s[T.winningSide-1]+=g)})}):It(f)?i.forEach(S=>{S.score?.sets?.forEach(T=>{let{side1TiebreakScore:y=0,side2TiebreakScore:E=0,side1Score:P=0,side2Score:A=0}=T;(S.matchUpStatus===ge||S.winningSide||T.winningSide)&&(P||A?(s[0]+=P,s[1]+=A):(y||E)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,y=eV({collectionDefinition:t,collectionPosition:T});It(y)&&(s[S.winningSide-1]+=y)}}),It(m)){let S;if(l?.aggregateValue)c&&(It(d||g||f)&&s[0]!==s[1]?S=s[0]>s[1]?1:2:h[0]!==h[1]&&(S=h[0]>h[1]?1:2));else if(l?.valueGoal)S=s.reduce((T,y,E)=>y>=l.valueGoal?E+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((y,E,P)=>E>=T?P+1:y,0)}S&&(I?r[p].values[S-1]+=m:a[S-1]+=m)}else I?(r[p].values[0]+=s[0]||0,r[p].values[1]+=s[1]||0):a=s;I?(r[p].sideWins[0]+=h[0]||0,r[p].sideWins[1]+=h[1]||0,r[p].allGroupMatchUpsCompleted=r[p].allGroupMatchUpsCompleted&&c,r[p].matchUpsCount+=i.length):a.forEach((S,T)=>n[T]+=S||0)}function eV({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function vc(t){let{sideAdjustments:e=[0,0],separator:r="-",drawDefinition:n,matchUpsMap:o,structure:i,matchUp:s,event:a}=t;if(!Array.isArray(e)||e.length!==2||isNaN(e.reduce((y,E)=>y+E)))return{error:B};if(!s)return{error:mr};let c=We({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:ks};let u=ar({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=aT(c);for(let y of p)Rv({collectionDefinition:y,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let y of f){let E=l[y],{allGroupMatchUpsCompleted:P,matchUpCount:A,winCriteria:U,groupValue:N,sideWins:D,values:M}=E,R;if(U?.aggregateValue)P&&M[0]!==M[1]&&(R=M[0]>M[1]?1:2);else if(U?.valueGoal)R=M.reduce((b,O,v)=>O>=U.valueGoal?v+1:b,void 0);else{let b=Math.floor(A/2)+1;R=D.reduce((O,v,x)=>v>=b?x+1:O,void 0)}R&&(d[R-1]+=N||0)}let g=d.map((y,E)=>(y||0)+e[E]),I={side1Score:g[0],side2Score:g[1],winningSide:void 0},h=g.join(r),S=g.slice().reverse().join(r),T;if(c?.winCriteria){let{valueGoal:y,aggregateValue:E,tallyDirectives:P}=c.winCriteria;if(y?T=g.map((U,N)=>({sideNumber:N+1,points:U})).find(({points:U})=>U>=y)?.sideNumber:E&&m.every(U=>U.matchUpStatus&&ae.includes(U.matchUpStatus)||U.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&P){let A=s.matchUpId,U=s.hasContext?s:o?.drawMatchUps?.[A]||n&&Vt({inContext:!0,drawDefinition:n,matchUpId:A})?.matchUp;if(U){let{completedTieMatchUps:N,order:D}=Fa({matchUps:[U]});if(N&&D?.length){let M=D[0].participantId;T=U.sides.find(({participantId:R})=>R===M)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function ka({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Vt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=mt({element:e,name:wo}),s=J(i?.value||{},!1,!0),a=({displaySideNumber:c,drawPosition:u,sideNumber:p})=>({drawPosition:u,sideNumber:p,displaySideNumber:c});n.sides=t?.sides?.map(c=>{let u=c.participantId,p=u&&s[u]||void 0,{lineUp:m,...d}=n.sides?.find(({sideNumber:f})=>f===c.sideNumber)??{},l=m?.length?m:p;return{...a(c),...d,lineUp:l}}),gt({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function or(t){if(t)return J(t,!1,!0)}function kg(t){let e=et(t,[{[Re]:!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 cT({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=kg({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function go(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&&cT({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:q};let m=Vt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:we};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:dr};ka({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=mt({name:Ua,element:d});if(f?.value)if(o)Ir({element:d,name:Ua});else return{...C,score:d.score};let g=We({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=or(g);let I=vc({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:y}=I,E=S?.side1Score||S?.side2Score;if(e&&!d.score&&!E)return{...C};let P={scoreStringSide1:T,scoreStringSide2:y,sets:S?[S]:[]},A=h&&[1,2].includes(h),U=A&&ge||Ig({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:P})&&Hn||Qt,N=!!(d.winningSide&&!A),D=d.tieMatchUps.find(({score:R,winningSide:b,matchUpStatus:O})=>R?.sets?.length&&(R.sets[0].side1Score||R.sets[0].side2Score)||O&&ae.includes(O)||b),M;if(d.tieFormat&&!A&&!D){let R=We({drawDefinition:r,structure:l,event:a})?.tieFormat;R&&JSON.stringify(g)===JSON.stringify(R)&&(d.tieFormatId=void 0,d.tieFormat=void 0,M=!0)}return Yn({appliedPolicies:t.appliedPolicies,matchUpStatus:U,score:P,removeWinningSide:N,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...C,score:P,removeWinningSide:N,tieFormatRemoved:M,winningSide:h}}function Cv({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:r,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}){let l="directWinner";if(s){let f=u.drawPositions||[],g=f[t],I=s.source.structureId,h=at({structureId:I,drawDefinition:c});if(h.error)return h;let{structure:S}=h,{positionAssignments:T}=Ie({structureId:I,drawDefinition:c}),E=T?.find(R=>R.drawPosition===o)?.participantId,P=s.target.structureId,{positionAssignments:A}=Ie({structureId:P,drawDefinition:c}),N=A?.find(R=>R.participantId===E)?.drawPosition,D=A?.filter(R=>{let b=f.includes(R.drawPosition),O=!R.participantId&&!R.bye&&!R.qualifier;return b&&O}).map(R=>R.drawPosition),M=D?.includes(g);if(E&&s.target.roundNumber===1&&M)jn({drawPosition:g,participantId:E,structureId:P,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(E&&D?.length){let R=D.pop();R&&jn({participantId:E,structureId:P,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:R,matchUpsMap:m,event:d})}else if(N){let R=wa({drawPosition:N,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(R.error)return _({result:R,stack:l})}else if(S?.stage!==ct){let R="winner target position unavaiallble";console.log(R),_({stack:l,result:{error:R}})}if(S?.seedAssignments&&S.structureId!==P){let R=S.seedAssignments.find(({participantId:O})=>O===E),b=R?.participantId;R&&b&&ra({eventId:u?.eventId,structureId:P,...R,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=wa({matchUpId:u.matchUpId,drawPosition:o,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(f.error)return f}if(p&&r){let f=p.sides?.find(g=>g.sideNumber===r);if(f?.lineUp){let g=p.roundPosition,I=u.roundPosition,h=g===I&&g!==1||Math.floor(g/2)===I?2:1,S=m?.drawMatchUps?.find(({matchUpId:E})=>E===u.matchUpId),T=[1,2].map(E=>({...S.sides?.find(A=>A.sideNumber===E)||{},sideNumber:E}));S.sides=T;let y=S.sides.find(E=>E.sideNumber===h);if(y){let E=f.lineUp?.filter(P=>P?.participantId);y.lineUp=Rd({lineUp:E}),gt({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...C}}function bv(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,propagateExitStatus:o,sourceMatchUpStatus:i,loserDrawPosition:s,tournamentRecord:a,loserTargetLink:c,drawDefinition:u,loserMatchUp:p,dualMatchUp:m,matchUpsMap:d,event:l}=t,f="directLoser",g=c.linkCondition,I=p.drawPositions||[],h=g===kn&&p.roundNumber===2&&Math.min(...I.filter(Boolean)),S=h||I[e],T=h||I[1-e],y=c.source.structureId,{structure:E}=at({structureId:y,drawDefinition:u}),{matchUps:P}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:u,structure:E,event:l}),U=P.filter(V=>V.drawPositions?.includes(s)).filter(V=>{let $=V.sides.find(W=>W.drawPosition===s),X=V.matchUpStatus===Bt||V.matchUpStatus===Gt&&!he(V);return $?.sideNumber===V.winningSide&&!X}),N=g===kn&&U.length===0,{positionAssignments:D}=Ie({structureId:y,drawDefinition:u}),R=D?.find(V=>V.drawPosition===s)?.participantId,b={loserParticipantId:R},O=c.target.structureId,{positionAssignments:v}=Ie({structureId:O,drawDefinition:u}),x=v?.filter(({drawPosition:V})=>I.includes(V)),F=x?.some(V=>V.participantId&&R&&V.participantId===R),w=o&&[Me,Bt,Gt].includes(i||"");if(F)return{...C,stack:f};let L=x?.filter(V=>{let $=I.includes(V.drawPosition),X=!V.participantId&&!V.bye&&!V.qualifier;return $&&X}).map(V=>V.drawPosition),k=L?.includes(S),G=c.target.roundNumber>1&&L?.length,H=c.target.roundNumber===1&&k;if(h){let V=K();if(V.context&&Object.assign(b,V.context),V.error)return _({result:V,stack:f})}else if(H){let V=j();if(V.context&&Object.assign(b,V.context),V.error)return _({result:V,stack:f})}else if(R&&G){L.sort(le);let V=L[0],$=jn({participantId:R,structureId:O,drawPosition:V,inContextDrawMatchUps:r,sourceMatchUpStatus:i,tournamentRecord:a,drawDefinition:u,matchUpsMap:d,event:l});if($.error)return _({result:$,stack:f});if(!$.error&&w&&o)return{stack:f,context:{progressExitStatus:!0,loserParticipantId:R}}}else return _({context:{loserDrawPosition:s,loserTargetLink:c,targetDrawPositionIsUnfilled:k},result:{error:k?Ls:CC},stack:f});if(E?.seedAssignments&&E.structureId!==O){let V=E.seedAssignments.find(({participantId:X})=>X===R),$=V?.participantId;V&&$&&ra({eventId:p?.eventId,structureId:O,...V,tournamentRecord:a,drawDefinition:u,participantId:$})}if(m&&n){let V=m.sides?.find($=>$.sideNumber===3-n);if(V?.lineUp){let{roundNumber:$,eventId:X}=p,{roundPosition:W}=m,it=$===1?2-W%2:1,z=d?.drawMatchUps?.find(({matchUpId:ot})=>ot===p.matchUpId),Q=[1,2].map(ot=>({...z.sides?.find(Rt=>Rt.sideNumber===ot)||{},sideNumber:ot}));z.sides=Q;let ut=z.sides.find(ot=>ot.sideNumber===it);ut&&(ut.lineUp=Rd({lineUp:V.lineUp}),gt({tournamentId:a?.tournamentId,matchUp:z,context:f,drawDefinition:u,eventId:X}))}}return _({result:{...C},stack:f,context:b});function K(){let V="loserLinkFedFMLC";return N?_({result:j(),stack:V}):_({result:Y(),stack:V})}function Y(){let V=Wr({drawPosition:T,structureId:O,tournamentRecord:a,drawDefinition:u,event:l});return _({result:V,stack:"assignLoserPositionBye"})}function j(){let V=R?jn({drawPosition:S,participantId:R,structureId:O,inContextDrawMatchUps:r,sourceMatchUpStatus:i,tournamentRecord:a,drawDefinition:u,matchUpsMap:d,event:l}):{error:se};return!V.error&&w&&o?{stack:f,context:{progressExitStatus:!0}}:_({result:V,stack:"assignLoserDrawPosition"})}}function uT(t){let e="directParticipants",r=Fd(t);if(r.error)return _({result:r,stack:e});let n=Oa({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:p,matchUpStatus:m,dualMatchUp:d,matchUpsMap:l,winningSide:f,targetData:g,matchUpId:I,structure:h,matchUp:S,event:T}=t,y=!!S.collectionId,E=cr({structure:h}),P=S.drawPositions,A;if(y){let{matchUpTieId:U,matchUpsMap:N}=t,D=go({appliedPolicies:t.appliedPolicies,matchUpId:U,tournamentRecord:u,drawDefinition:p,matchUpsMap:N,event:T});if(A=D&&{tieMatchUpResult:D},P=i.find(({matchUpId:R})=>R===U)?.drawPositions,!o)return _({result:{...C,...A},stack:e})}if(E)return _({result:{...C,...A},stack:e});if(P){let U=s?s-1:f-1,N=1-U,D=P[U],M=P[N],R={},{targetLinks:{loserTargetLink:b,winnerTargetLink:O,byeTargetLink:v},targetMatchUps:{winnerMatchUpDrawPositionIndex:x,loserMatchUpDrawPositionIndex:F,winnerMatchUp:w,loserMatchUp:L,byeMatchUp:k}}=g;if(w){let G=Cv({sourceMatchUpStatus:n&&m||ge,winnerMatchUpDrawPositionIndex:x,sourceMatchUpId:I,inContextDrawMatchUps:i,projectedWinningSide:s,winningDrawPosition:D,tournamentRecord:u,winnerTargetLink:O,drawDefinition:p,winnerMatchUp:w,dualMatchUp:d,matchUpsMap:l,event:T});if(G.error)return _({result:G,stack:e})}if(L){let G=bv({sourceMatchUpStatus:n&&m||ge,sourceMatchUpStatusCodes:c||[],sourceWinningSide:f,loserMatchUpDrawPositionIndex:F,sourceMatchUpId:I,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,loserDrawPosition:M,tournamentRecord:u,loserTargetLink:b,drawDefinition:p,loserMatchUp:L,winningSide:f,matchUpsMap:l,dualMatchUp:d,event:T});if(G.context?.progressExitStatus&&Object.assign(R,G.context,{sourceMatchUpStatus:n&&m||ge,sourceMatchUpStatusCodes:c||[],loserMatchUp:L,matchUpsMap:l}),G.error)return _({result:G,stack:e})}if(k){let G=k.drawPositions||[],H=Math.min(...G.filter(Boolean)),K=v.target.structureId,Y=Wr({drawPosition:H,structureId:K,tournamentRecord:u,drawDefinition:p,event:T});if(Y.error)return _({result:Y,stack:e})}return _({result:{...C,...A},stack:e,context:R})}else return _({result:{error:Ja},stack:e})}function kd(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:Z},stack:e});let r=Lu(t);if(r.error)return _({result:r,stack:e});let{structureId:n,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:m,exitProfileLimit:d,roundProfiles:l,roundNumbers:f,idPrefix:g,isMock:I,event:h,uuids:S}=t,T=J(t.drawDefinition,!1,!0),{structure:y}=at({structureId:n,drawDefinition:T});if(!y)return _({result:{error:_t},stack:e});if(y.structureType===Ve||y.structures)return gv({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:E,playoffRounds:P}=r,{playoffPositionsReturned:A,error:U,playoffSourceRounds:N,playoffRoundsRanges:D}=XS(t);if(U)return _({result:{error:U},stack:e});let M=l?.length&&Object.assign({},...l),R=f||typeof l=="object"&&l.map(W=>Object.keys(W)).flat(),b=Array.isArray(R)&&R.map(W=>!isNaN(W)&&dt(W)).filter(Boolean);if(b){if(!Array.isArray(b))return _({result:{error:B},context:{validRoundNumbers:b},stack:e});b.forEach(W=>{if(!P?.includes(W))return _({result:{error:B},context:{roundNumber:W},stack:e})})}u&&u.forEach(W=>{if(!A?.includes(W))return _({result:{error:B},context:{playoffPosition:W},stack:e})});let O=b||N,v=b?E:D,x=[],F=[];for(let W of O??[]){let it=v?.find(qt=>qt.roundNumber===W);if(!it)return _({result:{error:B},context:{roundNumber:W},stack:e});let z=it.finishingPositions.length,Q=Math.min(...it.finishingPositions)-1,ut=2,ot=W&&M?.[W]&&ut+M[W]-1,Dt=Rc({exitProfile:`0-${W}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:Q,playoffAttributes:c,exitProfileLimit:d,stage:fe,roundOffset:0,drawDefinition:T,sequenceLimit:ot,stageSequence:ut,drawSize:z,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(Dt.error)return _({result:Dt,stack:e});let{structures:Rt,links:De}=Dt;if(Rt?.length&&x.push(...Rt),De?.length&&F.push(...De),Dt.structureId&&W){let qt={linkType:so,source:{structureId:n,roundNumber:W},target:{structureId:Dt.structureId,feedProfile:Nn,roundNumber:1}};F.push(qt)}}if(!x.length)return _({result:{error:B},info:"No structures generated",stack:e});T.structures.push(...x),T.links.push(...F);let{matchUps:w,matchUpsMap:L}=ie({inContext:!0,drawDefinition:T}),k=x.map(({structureId:W})=>W),G=w?.filter(({structureId:W})=>k.includes(W)).map(Ue),H=L?.drawMatchUps?.filter(({matchUpId:W})=>G?.includes(W));if(H?.length){let W=We({drawDefinition:T,event:h})?.tieFormat;W&&H.forEach(it=>{let{tieMatchUps:z}=Li({matchUp:it,tieFormat:W,isMock:I});Object.assign(it,{tieMatchUps:z,matchUpType:Wt})})}w?.filter(W=>Ts({matchUp:W})&&W.structureId===n)?.forEach(W=>{let{matchUpId:it,score:z,winningSide:Q}=W,ut=ur({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:it}),ot=uT({inContextDrawMatchUps:w,tournamentRecord:m,drawDefinition:T,matchUpsMap:L,winningSide:Q,targetData:ut,matchUpId:it,structure:y,matchUp:W,score:z,event:h});ot.error&&console.log(ot.error)}),w?.filter(W=>W.matchUpStatus==="BYE"&&W.structureId===n)?.forEach(W=>{let{matchUpId:it}=W,z=ur({inContextDrawMatchUps:w,drawDefinition:T,matchUpId:it}),{targetLinks:{loserTargetLink:Q},targetMatchUps:{loserMatchUpDrawPositionIndex:ut,loserMatchUp:ot}}=z;if(Q&&ot){let Dt=Q.target.structureId,Rt=ot.drawPositions[ut],De=Wr({drawPosition:Rt,structureId:Dt,tournamentRecord:m,drawDefinition:T,event:h});De.error&&console.log(De.error)}});let j=[],V=rs({inContextDrawMatchUps:w,drawDefinition:T,matchUpsMap:L}).goesToMap,{structure:$}=at({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:X}=yt({structure:$});return X.forEach(W=>{let it=V?.loserMatchUpIds[W.matchUpId];if(it&&W.loserMatchUpId!==it){W.loserMatchUpId=it;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:W};j.push(Q)}let z=V?.winnerMatchUpIds[W.matchUpId];if(z&&W.winnerMatchUpId!==z){W.winnerMatchUpId=z;let Q={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:W};j.push(Q)}}),{structures:x,matchUpModifications:j,links:F,drawDefinition:T,...C}}function pT({element:t}){if(!t)return{error:B};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:B};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function ro(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:mf};let i=oS(t);if(i.error)return i;if(!(ht(o)&&kt(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:pf};if(!i.timeItems)i.timeItems=[];else if(rV({element:i,duplicateValues:e,timeItem:o}))return{...C};if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let c=new Date().toISOString();Object.assign(o,{createdAt:c})}return n&&(i.timeItems=i.timeItems.filter(({itemType:c})=>o.itemType!==c)),n&&!o.itemValue||i.timeItems.push(o),{...C}}function rV({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&nn({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function Gg({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:q};if(!o)return{error:se};let s=Uo({tournamentRecord:r,participantId:o});return s.error?s:ro({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function _c(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:q};let s=ro({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=pT({element:r});return lt({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:Xi}),s}function is(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?ro({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:qr}}function iD(t){return Bg({...t,itemType:"attachConsolationStructures"})}function Vg(t){return Bg({...t,itemType:"attachPlayoffStructures"})}function Bg({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:Z};if(!Array.isArray(o)||!Array.isArray(i))return _({result:{error:B},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 _({result:{error:If},info:"playoff structure exists",stack:a});i.length&&n.links?.push(...i);let m=o.map(({structureId:h})=>h),d=n.structures?.map(({structureId:h})=>h);n.structures=(n.structures??[]).map(h=>m.includes(h.structureId)?o.find(({structureId:S})=>S===h.structureId):h);let l=o?.filter(({structureId:h})=>!d?.includes(h));l.length&&n.structures.push(...l),rs({drawDefinition:n});let f=o.map(h=>yt({structure:h})?.matchUps||[]).flat();Fo({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(bt({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,...P}=h[y.matchUpId].matchUp;if(Object.assign(y,P),E?.length){let A={};E.forEach(U=>h[U.matchUpId]=U),y.tieMatchUps.forEach(U=>Object.assign(U,A[U.matchUpId]))}h[y.matchUpId].matchUp=y,gt(h[y.matchUpId])}})};n.structures.forEach(T=>{if(d?.includes(T.structureId))if(T.structures)for(let y of T.structures)S(y);else S(T)})}let I=l.map(Hr("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};ro({element:r,timeItem:S})}return{...C,addedStructureIds:I}}function Kp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=kd(t);if(o)return{error:o};let i=t.drawDefinition;return Vg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function ss(t){let e=et(t,[{_anyOf:{[Re]:!1,[ne]:!1,[Ce]:!1,[co]:!1},[_f]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=Ov(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&bt({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:q};for(let i of o){let s=t.tournamentRecords[i],a=Ov(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:q};return r.length?{...C,applied:r}:{error:$I}}function Ov(t,e){let r=Tt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:op};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!ht(s))return{error:B};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!kt(a))return{error:B};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...At({element:e,extension:{name:du,value:r}}),applied:n}:{applied:n,error:$I}}function Hg({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:B},context:{drawName:n}});r||(r=Ht({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:pn,value:{...r,flights:r.flights}};xo({event:i,extension:a})}return e&&(e.drawName=n,bt({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:Z}:{...C,flight:s}}function sD({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!ht(r))return{error:B};let i=Ht({event:o}).flightProfile,s=r.drawName&&Hg({drawName:r.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:i,drawId:n,event:o});if(s?.error)return s?.error;let a=s?.flight||i?.flights?.find(c=>c.drawId===n);if(!a&&!e)return{error:Z};if(a){let c={name:pn,value:{...i,flights:i.flights}};xo({event:o,extension:c})}return e&&(r.policyDefinitions&&ss({policyDefinitions:r.policyDefinitions,drawDefinition:e}),bt({tournamentId:t?.tournamentId,drawDefinition:e})),{...C}}function aD({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:Z};let n=Pe({drawDefinition:r}),o=s=>n?.drawMatchUps?.find(a=>a.matchUpId===s);for(let s of r.structures||[]){let{positionAssignments:a,stage:c,stageSequence:u}=s;a&&(u!==1||![ct,rt].includes(c))&&(s.positionAssignments=a.map(d=>(delete d.participantId,d)),s.seedAssignments=[]);let{matchUps:p,isRoundRobin:m}=yt({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:n,structure:s});for(let d of p){let{matchUpId:l,roundNumber:f}=d,g=d.sides||[],I=o(l);if(I){if(delete I.extensions,delete I.notes,I.matchUpStatus!=="BYE"&&Object.assign(I,Gu),f&&f>1&&I.drawPositions?.length&&!m){let h=g?.map(({drawPosition:T,participantFed:y})=>!y&&T).filter(Boolean),S=I.drawPositions.map(T=>h.includes(T)?void 0:T);I.drawPositions=S}e?delete I.timeItems:I.timeItems?.length&&(I.timeItems=I.timeItems.filter(h=>h.itemType&&![lo,Jo,Ji,dg,Zi,ts].includes(h.itemType))),gt({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}r.extensions=r.extensions.filter(s=>s.name!==lc);let i=(r.structures||[]).map(({structureId:s})=>s);return bt({drawDefinition:r,structureIds:i}),{...C}}function Vu({tournamentRecord:t}){if(!t)return{error:q};let e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={};return(t.events?.map(o=>{let i=o.eventId;return r[i]=o,(o?.drawDefinitions||[]).map(s=>({drawDefinition:s,eventId:i}))}).flat().filter(Boolean)).forEach(({drawDefinition:o,eventId:i})=>{let s=0,a=0,c=0,{allStructuresLinked:u}=_u({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(E=>{let{stage:P,stageSequence:A,structureId:U}=E,N=$s[P],{inContextStructureMatchUps:D}=va({drawDefinition:o,structure:E,event:p}),M=D?.filter(({winningSide:Y})=>Y),R=M.filter(Boolean).length||0;a+=R,c+=D.length-a;let b=Math.max(M.filter(({roundNumber:Y})=>Y===1).map(({roundPosition:Y})=>Y)),{positionAssignments:O}=Ct({structure:E}),v=O?.filter(({participantId:Y})=>Y);s+=v?.length??0;let x=(O?.length??0)-(v?.length??0),{roundMatchUps:F,roundProfile:w,roundNumbers:L,maxMatchUpsCount:k}=Ke({matchUps:D}),G=w&&Object.keys(w).filter(Y=>!w[Y].inactiveRound).map(Y=>parseInt(Y)),H=w&&Object.keys(w).filter(Y=>w[Y].inactiveRound).map(Y=>parseInt(Y)),K=w&&Object.values(w).every(Y=>Y.inactiveRound);return{positionsAssignedCount:v?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:x,inactiveStructure:K,maxMatchUpsCount:k,inactiveRounds:H,roundMatchUps:F,activeRounds:G,roundNumbers:L,roundProfile:w,structureId:U,stageSequence:A,orderNumber:N,stage:P}}),l=d.find(E=>E.orderNumber===2&&E.stageSequence===1),f=d.filter(({inactiveStructure:E})=>!E).length,{links:g}=Js({structureId:l.structureId,drawDefinition:o}),I=dt(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=d?.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:d,inactiveDraw:h,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=y}),{...C,drawsAnalysis:e}}function cD({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:q};if(!r)return{error:Z};let o=[],{drawsAnalysis:i}=Vu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=hn({stageSequence:1,drawDefinition:r,stage:rt}),u=a.structuresData.find(({structureId:l})=>c.structureId===l),p=(c.matchUps??[]).sort((l,f)=>l.roundPosition-f.roundPosition);o=p.filter(({roundNumber:l})=>!u.inactiveRounds.includes(l));let m=o.map(Ue),d=p.map(Ue).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Ue),g=m.filter(T=>!f.includes(T));d.push(...g);let h=l.flatMap(T=>T.drawPositions??[]).filter(Boolean).flat(),S=Object.assign({},...h.map((T,y)=>({[T]:y+1})));if(l.forEach(T=>{t?T.drawPositions=T.drawPositions.map(y=>S[y]):delete T.drawPositions}),t){let T=c?.positionAssignments?.filter(y=>h.includes(y.drawPosition)).map(y=>(y.drawPosition=S[y.drawPosition],y));c.positionAssignments=T}else c.positionAssignments=[];c.matchUps=l,o=l}_n({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),bt({drawDefinition:r})}return{...C,matchUps:o}}function uD({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,qualifier:i,event:s,bye:a}){if(!e)return{error:Z};if(!n)return{error:Fs};if(!o)return{error:Pr};if(a){let c=Wr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:pp};{let c=jn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...C}}function mT(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:_t};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:_t};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===zi)return{error:si};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Ue);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function pD(t){let e=et(t,[{[Ce]:!0},{[Ks]:{[mc]:!1,roundNumbers:!1},[kr]:B,[He]:Be}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=mT(t);if(c.error)return c;let{structure:u,structureId:p,existingMatchUps:m,matchUpIds:d}=c,l=[],f=m?.filter(({matchUpId:h,score:S,winningSide:T})=>{if(T&&!o)return!1;if(T||he({score:S})){if(!T&&!r)return!1;l.push(h)}else if(!n)return!1;return d?.includes(h)})??[],g=f.map(Ue),I=f.map(({tieMatchUps:h})=>h?.map(Ue)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),_n({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=pt(u.matchUps.map(Hr("roundNumber"))),S=PC(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,gt({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=pt(u.matchUps.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,E=c.existingMatchUps.some(N=>N.matchUpType===xr)?{matchUpTypes:[xr]}:void 0,{matchUps:P}=yt({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:E,structure:u,event:a});cr({structure:u})&&(u.positionAssignments=pt(P.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N})));let U=Ld({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:P,event:a});U.error&&console.log(U)}bt({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:oc}:{...C,deletedMatchUpsCount:[...g,...I].length}}function mD({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:q};if(!r)return{error:Z};if(!o)return _({result:{error:st},info:"roundNumber required"});let s=at({drawDefinition:r,structureId:n});if(s.error)return s;let a=s.structure;return a?.structures?{error:si}:cr({structure:a})?nV({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...C})}function nV({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:r,roundNumber:n,structure:o,eventId:i}){let s=o?.matchUps??[],a=[],c=[],u=!1;if(s.reduce((m,d)=>{let l=d?.roundNumber;return l?m.includes(l)?m:m.concat(l):m},[]).sort(le).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!ae.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Ue))),!l});c.length&&(_n({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,gt({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...C}}function Gd(t){let{suppressNotifications:e,tournamentRecord:r,drawDefinition:n,matchUps:o,event:i}=t;if(typeof n!="object")return{error:Z};let s=t?.structureId;if(!s&&n.structures?.length===1&&(s=n.structures?.[0]?.structureId),typeof s!="string")return{error:Pr};if(!Br(o))return{error:B,info:li("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:_t};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===zi)return{error:si};let p=ye({tournamentRecord:r,inContext:!1})?.matchUps?.map(Ue)??[],m=o.map(Ue);if(ke(p,m))return{error:YA,info:"One or more matchUpIds already present in tournamentRecord"};a.matchUps.push(...o);let d=o.map(({tieMatchUps:l})=>l).filter(Boolean).flat();return e||(Fo({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),bt({drawDefinition:n,structureIds:[s]})),{...C}}function dD({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:Z};if(!n)return{error:Pr};if(!r)return{error:Fs};let{structure:s}=at({drawDefinition:e,structureId:n});if(!s)return{error:_t};let a=s;s.structures&&s.structureType===Ve&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&At({element:u,extension:{name:fc,value:o}});let d=(i?.eventType===Wt||e.matchUpType===Wt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[Wt]},{matchUps:l}=yt({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return Ld({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),bt({drawDefinition:e,structureIds:[n]}),{...C}}var PD={};Xt(PD,{addGoesTo:()=>rs,allPlayoffPositionsFilled:()=>WS,checkValidEntries:()=>Hd,findDrawDefinition:()=>gT,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getMatchUpsMap:()=>Pe,getParticipantIdFinishingPositions:()=>fT,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getRandomQualifierList:()=>RT,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getValidGroupSizes:()=>Gp,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,positionActions:()=>MT});function dT({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:r,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:m,winsLimit:d,event:l}){if(!a)return{error:Z};let f=[rt,fe];r&&f.push(ct);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?to({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:nr({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=bi({stage:$e,drawDefinition:a}).map(({participantId:L})=>L),y={},E={},P={},A={};o||(o=Go({policyTypes:[Bh],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let U=o?.[Bh];t=t.length&&t||U?.excludedMatchUpStatuses||[],e=e??U?.includeEventParticipants,m=m??U?.allEntries,n=n??U?.finishingRoundLimit,i=i??U?.roundNumberLimit,c=c??U?.matchUpsLimit,u===void 0&&(u=U?.requirePlay!==void 0?U.requirePlay:!0),p===void 0&&(p=U?.requireLoss!==void 0?U.requireLoss:!0),d=d??U?.winsLimit;for(let L of h){if(u&&L.winningSide&&![1,2].includes(L.winningSide)&&L.matchUpStatus!==oe||L.finishingRound&&n&&L.finishingRound>=n||L.finishingRound&&i&&L.finishingRound<=i)continue;let k=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===3-L.winningSide),G=L.sides?.find(({sideNumber:H})=>L.winningSide&&H===L.winningSide);if(L.sides?.forEach(H=>{let K=H?.participant?.participantId;K&&(P[K]=H.participant,L.matchUpStatus===oe&&!u&&(E[K]=H.participant,y[K]||(y[K]=0),(!L.matchUpStatus||!t.includes(L.matchUpStatus))&&(y[K]+=1)))}),k?.participant){let H=k.participant.participantId;E[H]=k.participant,y[H]||(y[H]=0),L.matchUpStatus&&!t.includes(L.matchUpStatus)&&(y[H]+=1)}if(G?.participant){let H=G.participant.participantId;A[H]||(A[H]=0),A[H]+=1,y[H]||(y[H]=0),L.matchUpStatus&&!t.includes(L.matchUpStatus)&&(y[H]+=1)}}let N=s?.participants&&!u&&!p&&m,D=N?((e&&l?l.entries:a.entries)??[]).filter(L=>![mo,Vr].includes(L.entryStatus)).map(({participantId:L})=>L):[],M=Object.keys(E),R=N?(s?.participants??[]).filter(({participantId:L})=>D.includes(L)):p&&Object.values(E)||Object.values(P),b=L=>!p||M.includes(L),O=L=>!u||(y[L]||0)>=0,v=L=>!d||(A[L]||0)<=d,x=L=>!c||y[L]<=c,F=L=>!T.includes(L);return{eligibleParticipants:R.filter(L=>b(L.participantId)&&O(L.participantId)&&v(L.participantId)&&x(L.participantId)&&F(L.participantId)).map(L=>({...L,individualParticipants:L.individualParticipantIds?.map(k=>s?.participants?.find(G=>G.participantId===k))})),losingParticipantIds:M,...C}}function Vd(t){let e=et(t,[{drawDefinition:!0}]);if(e.error)return e;let{drawDefinition:r,roundNumber:n}=t,o=t.structureId??(r.structures?.length===1&&r.structures?.[0]?.structureId);if(typeof o!="string")return{error:Pr};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:_t};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===zi)return{error:si};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return Xr.includes(I)})??[],p=Math.floor(u?.length/2)||1,m=n??c??1,d=i.matchUps?.filter(g=>g.roundNumber===m)?.length??0,l=p-d,f=l>0?l:0;return{...C,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function lT({drawDefinition:t}){let e=mt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function vv({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:Z};let n=ie({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=J(n.matchUps,!1,!0),i=pt(o.reduce((a,c)=>a.concat(...c.sides.map(u=>u.participantId).filter(Boolean)),[])),s=Object.assign({},...i.map(a=>{let c=o.filter(u=>u.sides.map(m=>m.participantId).filter(Boolean).includes(a));return{[a]:c}}));return{participantIds:i,participantIdMatchUps:s}}function fT({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:Z};let{participantIds:n,participantIdMatchUps:o}=vv({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[ge,"BYE"].includes(d.matchUpStatus)||d.winningSide),u=c.map(d=>{let l=d.sides.find(I=>I.bye),f=d.sides.find(I=>I.participantId===s).sideNumber;return(d.winningSide||t&&l&&f)===f?d.finishingPositionRange.winner:d.finishingPositionRange.loser}),p=d=>Math.abs(d[0]-d[1]),m=u.reduce((d,l)=>d&&p(d)<p(l)?d:l,void 0);return{[s]:{relevantMatchUps:c,finishingPositionRanges:u,finishingPositionRange:m}}})||[];return Object.assign({},...i)}function jo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:q};if(!n)return{error:cn};if(!e&&t){if(typeof r!="string"&&(r=cT({tournamentRecords:t,drawId:n}),!r))return{error:ha};if(e=t[r],!e)return{error:q}}let o=e&&ze({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...C}:_({result:{error:br},stack:"findDrawDefinition"})}function gT(t){let{drawDefinition:e,error:r}=jo(t);return r?{error:r}:{drawDefinition:J(e)}}function _v({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Vr,Ci].includes(a)).map(({participantId:a})=>a)||[];if(s.length){let a=n.individualParticipantIds,c=e?t.filter(({participantId:m})=>s.includes(m)):void 0,u=e?t.filter(({participantId:m})=>a.includes(m)):void 0;return{validModifyAssignedPairAction:nt({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:nv,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:vg},!1,!1,!0)}}return{}}function Fi(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===kn&&r?.matchUp?.matchUpStatus==="BYE")return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&ur({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,m=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,d=p?.sides[m]?.participant,l=pr(s?.matchUpStatus),f=l&&!d,g=s?.sides?.reduce((E,P)=>P?.participant?++E:E,0)??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||!pr(a?.matchUpStatus))))return!0;let S=a&&ur({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),T=u&&Fi({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(S&&Fi({targetData:S,inContextDrawMatchUps:e,drawDefinition:n})||T)}var IT={[Jn]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ct,rt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[xu,ia,Wp,oa],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var Wg="positionAction",hT="matchUpAction";function ST({actionType:t=Wg,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===Wg&&Jn||t===hT&&er,i=t===Wg&&IT||t===hT&&IP,s=o&&(e?.[o]||i?.[o]),c=r.links?.filter(d=>d?.target?.structureId===n?.structureId)?.map(({target:d})=>d.feedProfile)??[],{enabledStructures:u,disabledStructures:p}=s||{},m=p?.find(d=>{let{stages:l,stageSequences:f,structureTypes:g,feedProfiles:I}=d;return(!I?.length||Array.isArray(I)&&I.some(h=>c.includes(h)))&&(!l?.length||Array.isArray(l)&&l?.includes(n?.stage))&&(!g?.length||Array.isArray(g)&&g?.includes(n?.structureType))&&(!f?.length||Array.isArray(f)&&f.includes(n?.stageSequence))});return{enabledStructures:u,actionsDisabled:m,actionsPolicy:s}}function fD({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function TT({enabledStructures:t,drawDefinition:e,structure:r}){if(t===!1)return{};if(!t?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};let{stage:n,stageSequence:o,structureType:i}=r||{},a=e.links?.filter(u=>u?.target?.structureId===r?.structureId)?.map(({target:u})=>u.feedProfile)||[];return{policyActions:t.find(u=>{let{stages:p,stageSequences:m,structureTypes:d,feedProfiles:l}=u||{},f=!p?.length||Array.isArray(p)&&p.includes(n),g=!m?.length||Array.isArray(m)&&m.includes(o),I=!d?.length||Array.isArray(d)&&d.includes(i),h=!l?.length||Array.isArray(l)&&l.some(S=>a.includes(S));return g&&I&&h&&u&&f})}}function qn({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 gD="replaceTieMatchUpParticipantId",ID="assignTieMatchUpParticipantId",yT="removeTieMatchUpParticipantId",hD="assignMatchUpSideParticipant",xv="removeMatchUpSideParticipant",SD="substituteParticipant",ET="REMOVE_SUBSTITUTION",TD="REPLACE_PARTICIPANT",jg="REMOVE_PARTICIPANT",AT="setMatchUpStatus",UT="SUBSTITUTION",yD="SCHEDULE",oV="PENALTY",PT="REFEREE",ED="STATUS",DT="START",AD="SCORE";var wv={REPLACE_TEAM_POSITION_METHOD:gD,ASSIGN_TEAM_POSITION_METHOD:ID,REMOVE_TEAM_POSITION_METHOD:yT,REPLACE_PARTICIPANT:TD,SUBSTITUTION_METHOD:SD,REMOVE_SUBSTITUTION:ET,REMOVE_PARTICIPANT:jg,SCHEDULE_METHOD:AT,SUBSTITUTION:UT,SCHEDULE:yD,PENALTY:oV,REFEREE:PT,STATUS:ED,SCORE:AD,START:DT,END:"END"};function Lv({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:m,side:d}){let l=[],f=o.sides?.find(F=>F.participant),g=en(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(St),E=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),P=E?.map(St),U=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:w,person:L})=>!P?.includes(w)&&(!S||To(S)||L.sex===S||en(S)&&!g||g&&L.sex!==g))),N=c?U?.[c-1]:U?.map((F,w)=>({participants:F,sideNumber:w+1})),D=c?U?.[c-1]?.map(St):U?.map((F,w)=>({participants:F?.map(St),sideNumber:w+1})),M=c&&(de(Ia)(I)&&!P?.length||de(Gi)(I)&&(P?.length??0)<2)||!c&&(de(Ia)(I)&&(P?.length??0)<2||de(Gi)(I)&&(P?.length??0)<4),R=D?.filter(F=>!y?.includes(F)),b=N?.filter(({participantId:F})=>R.includes(F));if(M&&R?.length&&l.push({availableParticipantIds:R,method:ID,availableParticipants:b,type:Ms,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),P?.length&&(!he(p)||d?.substitutions?.length)&&l.push({method:yT,type:jg,existingParticipantIds:P,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&P?.length||c&&d?.participant)&&l.push({availableParticipantIds:R,method:gD,availableParticipants:b,type:TD,existingParticipantIds:P,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),qn({policyActions:i,action:ET})&&d?.substitutions?.length){let F=d.participant?.participantType===Et&&[d.participantId]||d.participant?.participantType===ft&&d.participant.individualParticipantIds||[],w=d.substitutions.map(L=>L.participantId).filter(L=>F.includes(L));(!a||w.includes(a))&&l.push({method:yT,type:ET,substitutedParticipantIds:w,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let O=t?.[er],v=O?.substituteWithoutScore,x=O?.substituteAfterCompleted;if(qn({policyActions:i,action:UT})&&r.length===2&&(!c&&P?.length||c&&d?.participant)&&(v||he(p))&&(x||p.matchUpStatus&&!ae.includes(p.matchUpStatus))&&E?.length&&N.length){let F=E.map(St);l.push({info:"list of team players available for substitution",method:SD,availableParticipantIds:D,existingParticipantIds:F,availableParticipants:N,existingParticipants:E,type:UT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function Fv({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:r,positionAssignments:n,returnParticipants:o,appliedPolicies:i,drawDefinition:s,drawPosition:a,validActions:c,structureId:u,structure:p,drawId:m,event:d}){if(r.includes(a))return{};let l=c.find(U=>U.type===Ms)?.availableParticipantIds,f=i?.[Jn]?.otherFlightEntries,g=i?.[Jn]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:U})=>!g||(p.stage===ct?U===ct:U!==ct)).sort((U,N)=>(U.entryPosition??1/0)-(N.entryPosition??1/0)).map(({participantId:U})=>U).filter(Boolean),{allPositionedParticipantIds:h}=Xh({drawDefinition:s}),S=n.map(U=>U.participantId).filter(Boolean),T=I.filter(U=>p.stage&&[ct,rt,fe].includes(p.stage)?!h?.includes(U):!S.includes(U)),E=(d?.entries??[]).filter(U=>U.entryStatus===on&&UD({restrictQualifyingAlternates:g,structure:p,entry:U})&&(p.stage&&[ct,rt,fe].includes(p.stage)?!h?.includes(U.participantId):!S.includes(U.participantId))).sort((U,N)=>(U.entryPosition??1/0)-(N.entryPosition??1/0)).map(U=>U.participantId),P=pt(T.concat(E));if(f){let N=(d?Ht({event:d}).flightProfile:void 0)?.flights?.filter(D=>D.drawId!==m).map(D=>D.drawEntries.filter(M=>M.participantId&&![mo,Vr,Ci].includes(M.entryStatus)&&!I.includes(M.participantId)).map(({participantId:M})=>M)).flat().filter(Boolean);N?.length&&P.push(...N)}l?.length&&(P=P.filter(U=>!l.includes(U)));let A=o?t?.filter(U=>P.includes(U.participantId)):void 0;return A?.forEach(U=>{let N=(s.entries??[]).find(D=>D.participantId===U.participantId);U.entryPosition=N?.entryPosition}),A?.sort((U,N)=>(U.entryPosition||1/0)-(N.entryPosition||1/0)),P.length?{validAlternatesAction:nt({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:ev,availableAlternatesParticipantIds:P,type:_g,availableAlternates:A})}:{}}function UD({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===ct&&!t||r.entryStage===rt&&n===qe)return!0}function kv({eventEntries:t,structure:e}){let r=o=>o.entryStatus===on&&UD({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(St)}function Gv({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:m}){let d=[],l=c?.matchUps??[],g=u.sides?.find(N=>N.sideNumber===s)?.participantId,I=l.filter(({roundNumber:N})=>N===u.roundNumber),h=o?.entries?.filter(({entryStatus:N})=>N&&mi.includes(N)).map(St)??[],S=I.map(N=>(N.sides??[]).flatMap(St)).flat().filter(Boolean),T=h.filter(N=>!r.includes(N)&&(!t||!S.includes(N))),y=e?.filter(N=>T?.includes(N.participantId)).map(N=>J(N,void 0,!0));y?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),T.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:hD,type:Ms,availableParticipantIds:T,participantsAvailable:y});let E=m?.entries??[],P=kv({eventEntries:E,structure:c}),A=pt(h.concat(P));if(n){let D=(m?Ht({event:m}):void 0)?.flights?.filter(M=>M.drawId!==p).flatMap(M=>M.drawEntries.filter(R=>R.participantId&&![mo,Vr,Ci].includes(R.entryStatus)).map(({participantId:R})=>R)).filter(Boolean);D?.length&&A.push(...D)}A=A.filter(N=>!r.includes(N)&&!T.includes(N)&&(!t||!S.includes(N)));let U=e?.filter(N=>A.includes(N.participantId)).map(N=>J(N,void 0,!0));if(U?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),U?.sort((N,D)=>(N.entryPosition||1/0)-(D.entryPosition||1/0)),A.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:A,participantsAvailable:U,method:hD,type:on}),!he(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:xv,type:jg});let N=w=>w.sides.map(St),D=({matchUpId:w})=>w!==u.matchUpId,M=w=>!he(w),R=u.sides?.find(w=>w.sideNumber!==s)?.participantId,O=l.filter(({roundNumber:w})=>w!==u.roundNumber).filter(D).map(N),v=[R,...O.filter(w=>w.includes(g)).flat()].filter(Boolean),x=w=>!v.flat().includes(w),F=I.filter(M).filter(D).map(N).flat().filter(x);if(F.length){let w=e?.filter(L=>F.includes(L.participantId)).map(L=>J(L,void 0,!0));d.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:ov,type:Yp,swappableParticipants:w})}}return d}function Bd(t){if(!t)return{error:B};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&&kt(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:q};if(!c||!kt(c))return{error:sr};if(a&&![1,2].includes(a))return _({result:{error:B},context:{sideNumber:a}});if(!e){let Q=(ye({tournamentRecord:u}).matchUps??[]).find(ot=>ot.matchUpId===c);r=(u?.events??[]).find(ot=>ot.eventId===Q?.eventId);let ut=(r?.drawDefinitions??[]).find(ot=>ot.drawId===Q?.drawId);ut&&(e=ut)}if(!e)return{error:Z};let p=Ft({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Vt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:we};let f=Tt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[Jn]?.otherFlightEntries,I=f?.[er]??Ps[er],{enabledStructures:h}=ST({actionType:hT,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=TT({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??Pe({drawDefinition:e}),y=t.inContextDrawMatchUps??ie({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,E=y?.find(z=>z.matchUpId===c),P=a&&E?.sides?.find(z=>z.sideNumber===a),A=E?.sides?.map(z=>z.participantId||z.participant?.participantid).filter(Boolean)??[],{assignedPositions:U,allPositionsAssigned:N}=Ie({structure:l}),{structureId:D}=l??{},M=[];if(!D)return{validActions:M};let R=cr({structure:l}),b=!!d.collectionId;if(R&&!b){let z=Gv({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:A,otherFlightEntries:g,drawDefinition:e,structureId:D,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r});M.push(...z)}let O=Do({drawDefinition:e,structure:l}),v=U?.filter(z=>z.participantId).map(z=>z.drawPosition),x=U?.filter(z=>z.bye).map(z=>z.drawPosition),F=d.matchUpStatus==="BYE"||!b&&d.drawPositions?.reduce((z,Q)=>x?.includes(Q)||z,!1);if(F)return{validActions:M,isByeMatchUp:F};qn({policyActions:S,action:PT})&&M.push({type:PT,payload:{matchUpId:c}});let w=!Oa({matchUpStatus:d.matchUpStatus}),L=f?.scoring?.structures,k=l?.stage&&L?.stage&&L?.stage[l.stage],G=l?.stageSequence&&k?.stageSequence&&k.stageSequence[l.stageSequence],K=!(f?.scoring?.requireAllPositionsAssigned||k?.requireAllPositionsAssigned||G?.requireAllPositionsAssigned)||N,Y=d.sides&&d.sides.filter(z=>z?.participantId).length===2,j=d.matchUpStatus&&[oe,be].includes(d.matchUpStatus),V=ur({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),$=Fi({inContextDrawMatchUps:y,drawDefinition:e,targetData:V}),W=(E?.drawPositions?.length===2&&E.drawPositions.every(z=>v?.includes(z))&&E?.sides?.length===2&&E.sides.every(({participantId:z})=>z)||Y)&&!(j&&$),it={method:zS,type:ia,payload:{drawId:m,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(w&&M.push({payload:{drawId:m,matchUpId:c,schedule:{}},method:AT,type:yD}),qn({policyActions:S,action:ia})&&(P?.participant||!a&&A?.length)&&M.push(it),w&&W&&M.push({type:ED}),K&&W){let{matchUpId:z,matchUpFormat:Q}=d,ut={drawId:m,matchUpId:z,matchUpFormat:Q,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};M.push({info:"set outcome and winningSide",method:AT,type:AD,payload:ut}),qn({policyActions:S,action:DT})&&M.push({type:DT}),qn({policyActions:S,action:"END"})&&M.push({type:"END"})}if(b&&E){let z=Lv({specifiedPolicyDefinitions:o,inContextDrawMatchUps:y,matchUpParticipantIds:A,matchUpActionsPolicy:I,inContextMatchUp:E,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:P});M.push(...z)}return{structureIsComplete:O,validActions:M,isDoubleExit:j,...C}}function Bv({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:o,positionAssignments:i,drawDefinition:s,drawPosition:a,structureId:c,structure:u,drawId:p,event:m}){if(o.includes(a)||n&&!e)return{};let{sourceStructureIds:d,targetStructureIds:l}=s.links?.reduce((h,S)=>{let T=S.source?.structureId,y=S.target?.structureId;return h.sourceStructureIds.includes(T)||h.sourceStructureIds.push(T),h.targetStructureIds.includes(y)||h.targetStructureIds.push(y),h},{sourceStructureIds:[],targetStructureIds:[]})||{},f=[],g=s.links?.filter(h=>h.target?.structureId===u.structureId)??[];for(let h of g){let S=h?.source?.structureId,{structure:T}=at({structureId:S,drawDefinition:s}),y=T?.finishingPosition===zi&&(d?.length!==1||l?.length!==1),E={};if(y){let{matchUps:N}=yt({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:D}=Es({drawPosition:a,matchUps:N}),R=s.links?.find(b=>b.target?.structureId===u?.structureId&&b.target.roundNumber===D)?.source?.roundNumber;E.roundNumbers=[R]}let{completedMatchUps:P}=Mu({structureId:S,inContext:!0,matchUpFilters:E,drawDefinition:s}),A=i.map(N=>N.participantId).filter(Boolean);P?.filter(({matchUpType:N,winningSide:D})=>D&&(m?.eventType!==_e||N===_e)).map(({winningSide:N,sides:D})=>N&&D?.[1-(N-1)]).map(St).filter(N=>N&&!A.includes(N))?.forEach(N=>{f.includes(N)||f.push(N)})}let I=t?.filter(h=>f?.includes(h.participantId));return I?.forEach(h=>{let S=(s.entries??[]).find(T=>T.participantId===h.participantId);h.entryPosition=S?.entryPosition}),f?.length?{validLuckyLosersAction:{type:wg,method:rv,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function Hv({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:o,isWinRatioFedStructure:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,seedingProfile:p,isByePosition:m,drawPosition:d,structureId:l,event:f}){let{drawId:g}=u,I=[],h,S,T=[],y=c?.[Vn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=xS({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)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:av,type:"BYE"}),i&&y){let E=s.map(D=>D.participantId).filter(Boolean),P={structureIds:t},{completedMatchUps:A}=Zs({inContext:!0,matchUpFilters:P,drawDefinition:u}),U=pt((A??[]).filter(({matchUpType:D})=>f?.eventType!==_e||D===_e)?.map(({sides:D})=>D?.map(St)).flat().filter(D=>D&&!E.includes(D))),N=a?o?.filter(D=>U?.includes(D.participantId)).map(D=>J(D,void 0,!0)):void 0;return N?.forEach(D=>{let M=(u.entries??[]).find(R=>R.participantId===D.participantId);D.entryPosition=M?.entryPosition}),N?.length&&I.push(nt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:YP,type:Ms,availableParticipantIds:U,participantsAvailable:N})),{validAssignmentActions:I}}if(T.includes(d)||m){let E;if(S?.length){let A=S.filter(U=>h?.includes(U.participantId));A.sort(iV),E=A.map(U=>U.participantId)}else E=e;let P=a?o?.filter(A=>E.includes(A.participantId)).map(A=>J(A,void 0,!0)):void 0;P?.length&&I.push(nt({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:YP,type:Ms,availableParticipantIds:E,participantsAvailable:P}))}return{validAssignmentActions:I}}function iV(t,e){return t.bye||Nc(t.seedValue)<Nc(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function Wv({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:r,returnParticipants:n,appliedPolicies:o,drawDefinition:i,drawPosition:s,structureId:a,drawId:c}){let u=[],p=[],m=[],d=[],l=r.map(E=>E.participantId).filter(Boolean),f=o?.[Jn],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=vu({targetRoundNumber:g,linkType:Xn,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=vu({targetRoundNumber:g,linkType:Fn,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let E of S){let P=i.structures?.find(U=>U.structureId===E.source.structureId);if(P?.stage!==ct)continue;let A=Do({structureId:E.source.structureId,drawDefinition:i});if(!I||A){let U=P.qualifyingRoundNumber,{matchUps:N}=yt({matchUpFilters:{roundNumbers:[U],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:P});for(let D of N){let M=D.sides.find(b=>b?.sideNumber===D.winningSide),R=D.matchUpStatus==="BYE"&&D.sides?.find(({participantId:b})=>b);if(M||R){let{participantId:b,participant:O}=M||R||{};b&&!l.includes(b)&&(O&&n&&u.push(O),p.push(b))}}}}for(let E of y){let P=i.structures?.find(U=>U.structureId===E.source.structureId);if(P?.stage!==ct)continue;let A=Do({structureId:E.source.structureId,drawDefinition:i});if(!I||A){let{positionAssignments:U}=Ct({structure:P}),N=U?.map(D=>{let M=D.participantId,R=mt({element:D,name:Lo}).extension?.value;return R?{participantId:M,groupOrder:R?.groupOrder}:{}}).filter(({groupOrder:D,participantId:M})=>D===1&&!l.includes(M)).map(({participantId:D})=>D)??[];if(N&&p.push(...N),n){let D=e.filter(({participantId:M})=>N.includes(M));u.push(...D)}}}return p.length&&m.push(nt({qualifyingParticipants:n?u:void 0,method:ZO,type:Wp,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:m,sourceStructureIds:d}}function jv({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:r,inactiveDrawPositions:n,activeDrawPositions:o,positionAssignments:i,returnParticipants:s,byeDrawPositions:a,drawDefinition:c,isByePosition:u,drawPosition:p,structureId:m,structure:d,drawId:l,event:f}){if(o.includes(p))return{};let g=D=>!t||D.participantId||D.qualifier||D.bye,I=n?.filter(D=>D!==p&&!(u&&a.includes(D))),h=i?.filter(D=>g(D)&&I?.includes(D.drawPosition))??[],S=h.map(({drawPosition:D})=>D),{matchUps:T}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:D})=>ke(D,S)),E=Object.assign({},...y.map(D=>D.sides?.filter(({sourceDrawPositionRange:M})=>M).map(({drawPosition:M,sourceDrawPositionRange:R})=>({[M]:R}))).flat()),P=h.map(D=>D.participantId).filter(Boolean),A=(r??[]).filter(D=>P.includes(D.participantId)),U=Object.assign({},...A.map(D=>({[D.participantId]:D}))),N=h.map(D=>{let M=U?.[D.participantId],R=E[D.drawPosition];return nt({...D,participant:s?J(M,!1,!0):void 0,sourceDrawPositionRange:R})});return N.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:KS,type:Yp,availableAssignments:N}}:{}}function MT(t){let e=et(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return e;let{policyDefinitions:r,returnParticipants:n=!0,provisionalPositioning:o,tournamentRecord:i,drawDefinition:s,drawPosition:a,event:c}=t,u=t.tournamentParticipants??(i&&Ft({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=at({structureId:t.structureId,drawDefinition:s});if(p.error)return p;let m=p.containingStructure||p.structure;if(!m)return{error:_t};let d=m.structureId;if(p=va({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:Fs};if(p.isAdHoc)return Bd(t);if(p.error)return p;let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=Tt({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:y}=ST({actionType:Wg,appliedPolicies:h,drawDefinition:s,structure:m}),E=S?.activePositionOverrides||[],{sourceStructureIds:P}=vu({finishingPosition:Ei,targetRoundNumber:1,linkType:Fn,drawDefinition:s,structureId:d})||{},A;P?.length&&(A=P.every(W=>Do({structureId:W,drawDefinition:s})));let U=P.length,N=P.length&&!A,{policyActions:D}=TT({enabledStructures:T,drawDefinition:s,structure:m}),M=![ct,rt].includes(m.stage)||m.stageSequence!==1,{drawId:R}=s,b=[],{assignedPositions:O,positionAssignments:v}=Ie({structure:m}),x=O?.find(W=>W.drawPosition===a),F=!!x;if(!v?.map(W=>W.drawPosition)?.includes(a))return{error:Ls};let{stage:L,stageSequence:k}=m,G=[L];L===qe&&G.push(rt),L===rt&&G.push(qe);let H=bi({entryStatuses:mi,provisionalPositioning:o,drawDefinition:s,stageSequence:k,structureId:d,stages:G}),K=wi({drawDefinition:s,stages:G}).assignedParticipantIds??[],Y=H.filter(W=>!K.includes(W.participantId)).map(W=>W.participantId),j=I.includes(a),V=g.includes(a);if(y)return{info:"Actions Disabled for structure",isActiveDrawPosition:V,isDrawPosition:!0,hasPositionAssigned:F,validActions:[],isByePosition:j};if(qn({policyActions:D,action:Ms})&&!V&&v&&!N&&(!x||j)){let{validAssignmentActions:W}=Hv({positionSourceStructureIds:P,unassignedParticipantIds:Y,possiblyDisablingAction:M,isWinRatioFedStructure:U,tournamentParticipants:u,positionAssignments:v,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:j,drawPosition:a,structureId:d,event:c});W?.forEach(it=>b.push(it))}if(qn({policyActions:D,action:Wp})&&!V){let{validAssignmentActions:W}=Wv({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:v,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:R});W?.forEach(it=>b.push(it))}let{participantId:$}=x||{},X=$&&u.find(W=>W.participantId===$);if(x){qn({policyActions:D,action:QS})&&!V&&(b.push({type:QS,method:jP,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),j||b.push({type:xg,method:tv,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),qn({policyActions:D,action:"BYE"})&&!j&&b.push({type:"BYE",method:jP,payload:{drawId:R,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:M}));let W=m.stage===ct||m.stage===rt&&m.stageSequence===1;if(!j&&fD({activePositionOverrides:E,activeDrawPositions:g,action:oa})&&qn({policyActions:D,action:oa})&&Vp({drawDefinition:s,structureId:d,drawPosition:a})&&W){let{seedAssignments:it}=sn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z,seedValue:Q}=it?.find(ut=>ut.participantId===$)??{};b.push({type:oa,method:cv,participant:X,seedNumber:z,payload:{drawId:R,structureId:d,participantId:$,seedValue:Q}})}if(!j&&fD({activePositionOverrides:E,activeDrawPositions:g,action:jp})&&qn({policyActions:D,action:jp})&&Vp({drawDefinition:s,structureId:d,drawPosition:a})&&W){let{seedAssignments:it}=sn({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:z}=it?.find(Q=>Q.participantId===$)??{};b.push({method:sv,type:jp,participant:X,seedNumber:z,payload:{participantId:$,structureId:d,drawId:R}})}if(!j&&$){if(qn({policyActions:D,action:ia})){let it={type:ia,method:zS,participant:X,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};b.push(it)}if(qn({policyActions:D,action:xu})){let it={type:xu,method:iv,participant:X,payload:{participantId:$,otherName:void 0}};b.push(it)}}if(qn({policyActions:D,action:Yp})){let{validSwapAction:it}=jv({possiblyDisablingAction:M,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:v,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:j,drawPosition:a,structureId:d,structure:m,drawId:R});it&&b.push(it)}}if(qn({policyActions:D,action:_g})&&!N){let{validAlternatesAction:W}=Fv({possiblyDisablingAction:M,tournamentParticipants:u,positionAssignments:v,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:b,structureId:d,structure:m,drawId:R,event:c});W&&b.push(W)}if(qn({policyActions:D,action:wg})&&!N&&!V&&v){let{validLuckyLosersAction:W}=Bv({sourceStructuresComplete:A,possiblyDisablingAction:M,isWinRatioFedStructure:U,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:v,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:R});W&&b.push(W)}if(X?.participantType===ft&&qn({policyActions:D,action:vg})){let{validModifyAssignedPairAction:W}=_v({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:X,drawId:R,event:c});W&&b.push(W)}return{isActiveDrawPosition:V,isDrawPosition:!0,hasPositionAssigned:F,isByePosition:j,validActions:b,...C}}function Bu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Xm]?.drawTypeCoercion,o=e?.[Xm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}var RT=({drawDefinition:t})=>{let e=et({drawDefinition:t},[{[Ce]:!0}]);if(e.error)return e;let r=t.structures?.find(o=>o.stage===rt&&o.stageSequence===1);if(!r)return _({result:{error:zl}});let{qualifierPositions:n}=Ie({structure:r});return tt(0,n.length).sort(()=>Math.random()-.5)};function CT({structureId:t,drawDefinition:e}){if(!e)return{error:Z};if(!kt(t))return{error:B};let r=Js({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!jt([yi,Nn,Sp,Ti],n).length;return{...C,valid:o}}function zp({tournamentRecord:t,drawDefinition:e,stage:r=rt,structureId:n,structure:o}){if(!t)return{error:q};if(!o&&!e)return{error:Z};if(!o&&!n&&e?.structures?.filter(a=>a.stage===r).length===1&&(o=e.structures.find(a=>a.stage===r)),!o&&!n)return{error:Pr};let{error:i,positionAssignments:s}=Ct({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function bT({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:B};let r=us(t);return r?{drawSize:r}:_({result:{error:B},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function Hu(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=Go({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return _({result:I,stack:c});r=I.policyDefinitions}let p=It(u);if(u&&!p)return _({result:{error:B},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:UA},stack:c});if(isNaN(n))if(u)({drawSize:n}=bT({participantsCount:u}));else return _({result:{error:Za},stack:c});let m=o&&u||n;if(m&&m>n)return{error:of};let d=r?.[Vn];if(!d)return{error:pA};let l=d.seedsCountThresholds;return l?(d.drawSizeProgression!==void 0&&(e=d.drawSizeProgression),{seedsCount:l.filter(I=>e?I.drawSize<=n:n===I.drawSize).reduce((I,h)=>u&&u>=h.minimumParticipantCount?h.seedsCount:I,0)}):{error:KE}}function Hd({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=Ft({tournamentRecord:r})),!s)return{error:ec};if(!Array.isArray(s))return{error:B};if(!a)return{error:Ot};let c=e?.[er]??n?.[er]??Ps[er],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===Ko,l=p===Or&&wt||d&&ft||Et,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=sV({participant:S,participantType:l,eventType:p,entryStatusMap:f}),y=aV({genderEnforced:u,participantMap:o,eventGender:m,participant:S,isDoubles:d,mismatch:T});return T||!y});if(h.length){let S=h.map(T=>T.participantId);return{error:nA,invalidParticipantIds:S}}return{...C,valid:!0}}function sV({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[Ko,Or].includes(r)&&t.participantType===Et&&(ta(o)||o===mo);return t.participantType!==e&&!i}function aV(t){let{participant:e,participantMap:r,eventGender:n,mismatch:o,isDoubles:i,genderEnforced:s}=t,a=!o&&i&&pt(e?.individualParticipantIds?.map(m=>r?.[m]?.participant?.person?.sex).filter(Boolean)??[])||[],c=!n||!a?.length||To(n)||Dn(n)&&yr(a[0])===yr(n)||en(n)&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||en(n)||To(n)||Dn(n)&&yr(u)===yr(n);return!s||c&&p}function OT({hasExistingDrawDefinition:t,qualifyingProfiles:e,appliedPolicies:r,qualifyingOnly:n,tieFormat:o,idPrefix:i,isMock:s,uuids:a}){let c="generateQualifyingSTructures",u=[],p=[],m=[],d=(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,P,A,U;for(let N of(T||[]).sort(d)){let D=Rm(N.drawSize||N.participantsCount),{qualifyingRoundNumber:M,structureOptions:R,matchUpFormat:b,structureName:O,structureId:v,drawType:x}=N,F=N.matchUpType,w=N.qualifyingPositions||cV({drawSize:D,qualifyingRoundNumber:M}),L,k,G;if(!It(D))return _({result:{error:Za},stack:c});let H=e.length>1?`${h}-`:"",K=T.length>1||H?y:"",Y=O||(H||K?`${Qe(ct)} ${H}${K}`:Qe(ct));if(x===On){let{structures:j,groupCount:V,maxRoundNumber:$}=xa({structureName:N.structureName||Y,structureId:v||a?.pop(),hasExistingDrawDefinition:t,stage:ct,structureOptions:R,appliedPolicies:r,qualifyingOnly:n,stageSequence:y,matchUpType:F,roundTarget:h,tieFormat:o,drawSize:D,idPrefix:i,isMock:s,uuids:a});E=V,L=$,k=j[0],I=[1]}else({drawSize:D,matchUps:G,roundLimit:L}=xn({qualifyingRoundNumber:M,qualifyingPositions:w,matchUpType:F,drawSize:D,idPrefix:i,isMock:s,uuids:a})),k=yn({structureName:N.structureName||Y,structureId:v||a?.pop(),qualifyingRoundNumber:L,hasExistingDrawDefinition:t,stage:ct,qualifyingOnly:n,matchUpFormat:b,stageSequence:y,matchUpType:F,roundLimit:L,tieFormat:o,matchUps:G}),h&&At({extension:{name:vn,value:h},element:k}),E=G?.filter(j=>j.roundNumber===L)?.length||0;if(y>1){let{link:j}=La({sourceStructureId:A,sourceRoundNumber:P,targetStructureId:k.structureId,finishingPositions:U===Fn?[1]:void 0,linkType:U});m.push(j),f+=(D||0)-E}else f+=D||0;U=x===On?Fn:Xn,A=k.structureId,P=L,o&&(G=yt({structure:k})?.matchUps||[],G?.forEach(j=>{let{tieMatchUps:V}=Li({tieFormat:o,matchUp:j,isMock:s});Object.assign(j,{tieMatchUps:V,matchUpType:F})})),p.push(k),y+=1}g+=E,u.push({qualifiersCount:E,finalQualifyingRoundNumber:P,finalQualifyingStructureId:A,finishingPositions:I,roundTarget:h,linkType:U}),h+=1}return{qualifiersCount:g,qualifyingDrawPositionsCount:f,qualifyingDetails:u,structures:p,...C,links:m}}function cV({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function vT(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=dt(t.drawSize),o=e&&t.drawType!==Fr&&(typeof e=="boolean"||e<=2)&&n===2&&yo||t.drawType||yo,i=DU.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=yo;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:np},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function Yv(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Qe(rt),...t,stage:rt},{structures:i,groupCount:s,groupSize:a}=xa(o);if(s<1)return{error:GA};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Qe(fe)}],[u]=i,{structures:p,links:m}=rT({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...C,structures:i,links:m}}function qv({mainStructure:t,consolationStructure:e,deciderStructure:r}){let o=e.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),i=t.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),s=e.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),a=o.map((p,m)=>{let l=o.indexOf(p)%2?Nn:yi,f=1+m;return{linkType:so,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:Xn,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:Nn,roundNumber:i,structureId:t.structureId}},u=[{linkType:Xn,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Nn,roundNumber:1,structureId:r.structureId}},{linkType:so,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Nn,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function $v({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=fi({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=Ds({structureName:t||Qe(rt),structureId:i?.pop(),stageSequence:1,stage:rt,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=fi({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=Ds({structureName:Qe(PU),matchUps:p,structureId:i?.pop(),stage:qe,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=xn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=Ds({structureName:Qe(UU),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:fe,matchUpType:e});s.push(l);let f=qv({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...C}}function Kv(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(Ln(s))return xn(t);let u=uV(s),p=u.shift(),m=tt(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=qp({roundNumber:l,matchUpType:o,idPrefix:i,matchUps:d,isMock:a,nodes:m,uuids:c})),l++;let f=t.roundLimit||e;for(let I of u){let h=I.participantsCount/2,S=tt(1,h+1);n&&h===n&&(f=l-1);let T=S.map(y=>{let E=vd({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:E}});d.push(...T),l++}let g=l-1;return d=ba({finishingPositionOffset:r,lucky:!0,roundsCount:g,roundLimit:f,matchUps:d}),f&&(d=d.filter(I=>I.roundNumber<=f)),{matchUps:d,roundsCount:g,roundLimit:f}}function uV(t){let e=dt(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 _T(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=rt,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??Tt(t),m=t.policyDefinitions?.[dc]||p?.[dc];t.skipRounds=t.skipRounds||s<=4&&(m?.feedFromMainFinal?0:1)||0;let d=t.structureName??e?.["0"]?.name??Qe(rt),l=()=>{let{matchUps:g}=xn(t);return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,tieFormat:o,matchUps:g,stage:n})],links:[],...C}};return{generators:{[Fr]:()=>({structures:[yn({finishingPosition:Ei,stageSequence:r,structureName:d,matchUps:[],matchUpType:i,structureId:u,stage:n})],links:[],...C}),[Ki]:()=>{let{matchUps:g}=Kv(t);return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,matchUps:g,stage:n})],links:[],...C}},[yo]:()=>l(),[su]:()=>$v(t),[ou]:()=>Rc({...t,roundOffsetLimit:3,playoffAttributes:e??Of}),[iu]:()=>Rc({...t,roundOffsetLimit:2,playoffAttributes:e??vf}),[fe]:()=>Rc(t),[Ea]:()=>{let{matchUps:g}=fi({drawSize:s,uuids:a,matchUpType:i});return{structures:[yn({stageSequence:r,structureName:d,matchUpType:i,structureId:u,stage:rt,tieFormat:o,matchUps:g})],links:[],...C}},[Tp]:()=>JS(t),[au]:()=>bc({...t,feedRounds:1,fmlc:!0}),[AU]:()=>bc({...t,feedRounds:1}),[bh]:()=>bc({...t,feedsFromFinal:1}),[Oh]:()=>bc({...t,feedsFromFinal:2}),[vh]:()=>bc({...t,feedsFromFinal:3}),[yp]:()=>bc(t),[bf]:()=>tT(t),[On]:()=>xa(t),[Eo]:()=>Yv(t)}}}function Wd(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,qualifyingOnly:o,staggeredEntry:i,drawDefinition:s,tieFormat:a,isMock:c,uuids:u}=t||{},p=dt(t.drawSize),m=t.drawTypeCoercion??Bu({appliedPolicies:n,drawType:t.drawType}),d="generateDrawStructuresAndLinks",l=vT({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:m,drawSize:p});if(l.error)return l;let f=l.drawType,g=[],I=[],h=t?.matchUpType??Lt,S=s?.structures?.filter(({stage:K})=>K===ct);S&&g.push(...S);let T=S?.map(({structureId:K})=>K),y=s?.structures?.find(({stage:K,stageSequence:Y})=>K===rt&&Y===1),E=s?.links?.filter(K=>K.target.structureId===y?.structureId&&T?.includes(K.source.structureId)),P=(K,Y)=>{if(K.linkType===Fn&&Y?.structures){let j=K.source.finishingPositions||[];return Y.structures.length*j.length}else if(K.linkType===Xn&&Y?.matchUps?.length){let j=K.source.roundNumber;return Y.matchUps.filter(({roundNumber:$})=>$===j).length}},A=S?.map(K=>{let Y=E?.find(W=>W.target.structureId===K.structureId),j=Ct({structure:K})?.positionAssignments?.length??0;if(!Y)return j;let V=Y?.source.structureId,$=s.structures?.find(W=>W.structureId===V),X=P(Y,$)||0;return j-X}).filter(Boolean).reduce((K,Y)=>K+Y,0),U=E?.map(K=>{let Y=K.source.structureId,j=S?.find(V=>V.structureId===Y);return P(K,j)}).filter(Boolean).reduce((K,Y)=>K+Y,0),N=!!(y&&!y?.matchUps?.length);if(S?.length&&!N)return{error:ZI};let D=!S?.length&&t.qualifyingProfiles,M=D?.length&&OT({idPrefix:t.idPrefix,qualifyingProfiles:D,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,isMock:c,uuids:u});if(M?.error)return M;let{qualifyingDrawPositionsCount:R,qualifyingDetails:b,qualifiersCount:O}=M||{qualifyingDrawPositionsCount:A,qualifiersCount:U};R&&(M?.structures&&g.push(...M.structures),M?.links&&I.push(...M.links)),Object.assign(t,nt({drawSize:p,matchUpType:h,tieFormat:a}));let v=f!==Fr&&(!p||p<2||!i&&![Ea,Ki].includes(f)&&([Eo,On].includes(f)&&p<3||![On,Eo].includes(f)&&!Ln(p)));if(v&&!R)return _({context:{drawSize:p,invalidDrawSize:v},result:{error:np},stack:d});let{generators:x,error:F}=_T(t);if(F)return{error:F};let w=x[f];if(!w)return{error:ql};let L=w?.();if(L.error)return L;let{structures:k,links:G}=L;if(k?.length){let K=k.find(({stage:Y,stageSequence:j})=>Y===rt&&j===1);if(y&&K){if(N){let Y=K.structureId;if(K.structureId=y.structureId,G?.length)for(let j of G)j.source.structureId===Y&&(j.source.structureId=y.structureId),j.target.structureId===Y&&(j.target.structureId=y.structureId)}else if(!r)return{error:ZI}}g.push(...k)}g.sort(Ni),G?.length&&I.push(...G);let H=L.structures.find(({stage:K,stageSequence:Y})=>K===rt&&Y===1);for(let K of b||[]){let{finalQualifyingRoundNumber:Y,finalQualifyingStructureId:j,roundTarget:V,finishingPositions:$,linkType:X}=K,W=H&&La({targetStructureId:H.structureId,sourceStructureId:j,sourceRoundNumber:Y,finishingPositions:$,targetEntryRound:V,linkType:X})?.link;if(W?.error)return W;W&&I.push(W)}return E&&I.push(...E),{...C,qualifyingResult:{qualifyingDrawPositionsCount:R,qualifiersCount:O},structures:g,links:I}}function jd(t){let{modifyOriginal:e=!0,stageSequence:r=1,isMock:n}=t||{},o="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return _({result:{error:Z},stack:o});let i=e?t.drawDefinition:J(t.drawDefinition,!1,!0),{tieFormat:s,matchUpType:a}=t;if(s){let T=ar({tieFormat:s});if(T.error)return T}s=or(s??We({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||Lt),t.tieFormat=s,t.matchUpType=a;let c=Fp({drawDefinition:i,stage:rt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&Hp({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:rt});let u=Pe({drawDefinition:i}).drawMatchUps.map(Ue),p=Wd(t);if(p.error)return _({result:p,stack:o});let{structures:m,links:d,qualifyingResult:l}=p;i.structures=m,i.links=d;let f=Math.max(t.qualifiersCount??0,l?.qualifiersCount||0);if(l?.qualifyingDrawPositionsCount&&!Fp({stage:ct,drawDefinition:i})){let y=Hp({drawSize:l.qualifyingDrawPositionsCount,stage:ct,drawDefinition:i});if(y.error)return y}if(f){let T=$S({qualifiersCount:f,drawDefinition:i,stage:rt});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,nt({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=ie({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=Li({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=rs({drawDefinition:i,matchUpsMap:h});return bt({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...C,structures:m,matchUps:I,links:d}}function xc(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!zv({scaleItem:o}))return{error:rc};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===Ar&&o?.eventType!==Or)return{error:rc};let a=Qv({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=Lr();c.includes(rr)&<({topic:rr,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...C,info:ff,existingValue:o?.scaleValue}||s&&{...C,newValue:o?.scaleValue}||{error:re}}function DD(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:q};if(!n.participants)return{error:ec};let s=0,a={},c=[];for(let m of e){let d=m?.participantId;if(Array.isArray(m?.scaleItems))for(let l of m.scaleItems)if(zv({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:rc}}for(let m of n.participants){let{participantId:d}=m||{};if(Array.isArray(a[d]))for(let l of a[d]){if(m.participantType===Ar&&l?.eventType!==Or)return _({context:{participantId:d,scaleItem:l,participantType:m.participantType},info:"Invalid participantType for eventType",result:{error:rc}});Qv({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++}}let u=s?void 0:Bs,{topics:p}=Lr();if(p.includes(rr)&&s&<({topic:rr,payload:{tournamentId:n.tournamentId,participants:c}}),i){let{eventId:m,drawId:d,...l}=i,f=l.scaleAttributes?.scaleType&&[l.scaleAttributes.scaleType];if(Object.keys(l).length){let g={itemType:Yf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=ze({tournamentRecord:n,eventId:m,drawId:d});d&&Og({drawDefinition:I,timeItem:g}),m&&is({event:h,timeItem:g})}else _c({tournamentRecord:n,timeItem:g})}}return o&&p.includes(Mi)&<({topic:Mi,payload:o}),nt({...C,modificationsApplied:s,info:u})}function zv({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function Qv({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Wi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:rc};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=Po({scaleAttributes:r,participant:e}),c=p=>[void 0,null,""].includes(p),u=!(c(a?.scaleValue)&&c(r.scaleValue))&&JSON.stringify(a?.scaleValue)!==JSON.stringify(r.scaleValue);if(u){let{scaleType:p,eventType:m,scaleName:d}=r,l=[Pi,p,m,d].join("."),f=nt({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...C,valueChanged:u,newValue:r.scaleValue}}function Yg(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=et(t,[{[ne]:!0},{modifiedScaleValues:!0,[He]:zr}]);if(o.error)return o;for(let i in r){let s=xc({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...C}}function wc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:se};let{participant:i,tournamentId:s}=Uo({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...Po({participant:i,scaleAttributes:r}),tournamentId:s}:{error:re}}var pV=(t=0)=>250/Math.pow(t+5,.4),mV=()=>1;function dV(t=3,e=2){let r=t/e;return isNaN(r)?Yd.kDefault():r}var Yd={nSpread:400,diffThreshold:.125,kCalc:pV,kMultiplier:dV,kDefault:mV};function xT(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=je,winnerCountables:o=1,loserCountables:i=0,ratingType:s="ELO",maxCountables:a,countables:c}=t||{},u=n?.[s];if(!u)return{error:st};let p=u.range||t.ratingRange;e=e||u.defaultInitialization,r=r||u.defaultInitialization;let m=p[0]>p[1],d=u.decimalsCount||0,l=m?p.slice().reverse():p,f=(x,F)=>parseFloat(F)>=Math.min(...x)&&parseFloat(F)<=Math.max(...x);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=Fu({targetRange:je["ELO"].range,sourceRange:l,value:m?p[0]-e:e}),I=Fu({targetRange:je["ELO"].range,sourceRange:l,value:m?p[0]-r:r}),h=(x,F)=>1/(1+Math.pow(10,(F-x)/Yd.nSpread)),S=h(g,I),T=h(I,g),y=Yd.kCalc(o),E=Yd.kCalc(i),P=Yd.kMultiplier(a,c),A=g+P*y*(1-S),U=I+P*E*(0-T),N=Fu({sourceRange:je["ELO"].range,value:A,targetRange:l}),D=Fu({sourceRange:je["ELO"].range,value:U,targetRange:l}),M=m?p[0]-N:N,R=parseFloat(M.toFixed(d)),b=m?p[0]-D:D,O=parseFloat(b.toFixed(d)),v=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(N>D&&v>Yd.diffThreshold||R<0||O<0)&&(R=e,O=r),{newWinnerRating:R,newLoserRating:O}}var Xv=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function wT(t){let e=et(t,[{[ne]:!0},{matchUpIds:!0,[He]:Be,[In]:ps},{ratingType:!1,[tr]:S=>je[S]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i="ELO",refreshDynamic:s,considerGames:a,drawDefinition:c,matchUpIds:u,asDynamic:p}=t,m=je[i],{accessor:d}=m,l={},f=(t.matchUps||s&&nr({drawDefinition:c,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:ae}}).matchUps||ye({matchUpFilters:{matchUpIds:u,matchUpStatuses:ae},tournamentRecord:o,inContext:!0}).matchUps)??[],g=`${i}.${Qm}`,I=p?g:i;f.sort(xi);for(let S of f){let{endDate:T,matchUpFormat:y,score:E,sides:P,winningSide:A}=S,U=S.matchUpType,N={eventType:U,scaleName:i,scaleType:Ui},D={scaleName:g,eventType:U,scaleType:Ui},M=Object.assign({},...(P??[]).map(k=>{let{sideNumber:G,participant:H}=k;return G&&{[G]:[H?.participantId,...H?.individualParticipantIds??[]].filter(Boolean).flat()}})),R=Object.assign({},...Object.values(M).flat().map(k=>{let G=l[k],K=!s||G?wc({scaleAttributes:D,tournamentRecord:o,participantId:k}).scaleItem:void 0,Y=wc({tournamentRecord:o,scaleAttributes:N,participantId:k}).scaleItem,j=d?{[d]:void 0}:void 0;return k&&{[k]:K??Y??{scaleName:I,eventType:U,scaleDate:T,scaleType:Ui,scaleValue:j}}})),b=y?Ne(y):{},O=b?.bestOf||1,v=b?.setsTo||1,x=a?O&v:O,F=E?.sets&&Xv(E.sets)||A===1&&[1,0]||[0,1],w=A?M[A]:[],L=A?M[3-A]:[];for(let k of w){let G=R[k]?.scaleValue,H=typeof G=="object"?G[d]:G;for(let K of L){let Y=R[K]?.scaleValue,j=typeof Y=="object"?Y[d]:Y,V=A?F[A]:[0,0],$=A?F[3-A]:[0,0],{newWinnerRating:X,newLoserRating:W}=xT({winnerCountables:V,loserCountables:$,maxCountables:x,winnerRating:H,loserRating:j,ratingType:i}),it=d?{...G,[d]:X}:X,z=d?{...Y,[d]:W}:W;R[k].scaleValue=it,R[K].scaleValue=z,R[k].scaleName=I,R[K].scaleName=I}}Object.assign(l,R),r&&Yg({tournamentRecord:o,modifiedScaleValues:l,removePriorValues:n})}let h=f.map(({matchUpId:S})=>S);return{...C,modifiedScaleValues:l,outputScaleName:I,processedMatchUpIds:h}}function Wu(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:Z};let{participantIdPairings:a,matchUpsCount:c}=t,u=Vd(t);if(u.error)return _({result:u});let{lastRoundNumber:p,availableMatchUpsCount:m=0,roundMatchUpsCount:d=0}=u;if(!c)o?c=d:m>0&&(c=m);else if(c>d&&t.restrictMatchUpsCount!==!1)return _({result:{error:B,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!It(c)||e&&!Array.isArray(e)||!a&&!c)return{error:B,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:B,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:B,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??tt(0,c).map(()=>({participantIds:[void 0,void 0]}));let f=I=>{if(!t.idPrefix)return;let h=r.drawId,S=t.idPrefix??"ah";return`${h}-${S}-${l}-${I}`},g=a?.map((I,h)=>{let S=I?.participantIds??[void 0,void 0];S.push(void 0,void 0);let y=S.slice(0,2).map((P,A)=>nt({sideNumber:A+1,participantId:P})),E=e[h]??f(h)??Nt();return{roundNumber:l,matchUpStatus:Qt,matchUpId:E,sides:y}});if(g?.length){let I=We({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=Li({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:Wt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...C}}function Zv({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:r,valueObjects:n,deltaObjects:o}){let i=Object.assign({},...e.map(S=>({[S.pairing]:S.value}))),s=Object.keys(r),a=[],c=Jv({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[ND(c)];a.push(c);let p=c.value,m=c,d=1,l=0,f=s.length,g;do f-=1,g=s.length*r[s[0]].length;while(g>t&&f>5);let I=[];s.forEach(S=>{r[S].slice(0,f).forEach(y=>{l+=1;let E=Ga(S,y.opponent);if(!I.includes(E)){let P=Jv({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(ND(P))){u.push(ND(P)),a.push(P);let{maxDelta:A,value:U}=P;A<m.maxDelta&&(m=P),(U<p||U===p&&Math.round(Math.random()))&&(p=U),I.push(E),d+=1}}}),a=a.filter(y=>Math.abs(y.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=tn(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function ND(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function Jv({valueSortedPairings:t,stipulated:e=[],pairingValueMap:r,deltaObjects:n,valueObjects:o,actorsCount:i}){let s=[].concat(...e),a=[],c=0;e.filter(Boolean).forEach(d=>{let[l,f]=d,g=Ga(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),Ae(t,i).map(d=>Tr(d).map(l=>({...l,value:l.value+Math.random()*Math.round(Math.random())}))).flat().forEach(d=>{let l=d.pairing.split("|");if(!l.reduce((g,I)=>s.includes(I)||g,!1)){s.push(...l);let g=d.value;c+=g,a.push({participantIds:l,value:g})}}),a.sort((d,l)=>d.value-l.value);let p=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Ga(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=Ga(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function Ga(t,e){return[t,e].sort(Cu).join("|")}function MD({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 t_({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(St);if(n.length===2){let[o,i]=n,s=Ga(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function e_({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 lV=0;function r_({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=je[n]?.defaultInitialization??lV;return o.split("|").map(s=>{if(r===Kr){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 n_(t){let{tournamentParticipants:e,adHocRatings:r={},possiblePairings:n,uniquePairings:o,maxIterations:i,minimizeDelta:s,deltaObjects:a,valueObjects:c,eventType:u,scaleName:p,salted:m}=t;o.forEach(T=>{let y=r_({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),E=typeof m=="number"&&m||.5,P=m&&(Math.round(Math.random())?E:E*-1)||0,A=Math.abs(y[0]-y[1])+P,U=Math.abs(y[0]-y[1]);a[T]=U,c[T]||(c[T]=0),c[T]+=A?Math.pow(A,2):0});let d=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=e_({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=Zv({valueSortedPairings:d,maxIterations:i,pairingValues:l,deltaObjects:a,valueObjects:c}),{participantIdPairings:S}=s?I:f;return{participantIdPairings:S,candidatesCount:g,deltaCandidate:I,iterations:h,candidate:f}}var fV=100,gV=100,IV=4e3;function qd(t){let{encounterValue:e=fV,sameTeamValue:r=gV,maxIterations:n=IV,updateParticipantRatings:o,generateMatchUps:i=!0,ignoreLastRoundNumber:s,iterationMatchUps:a,tournamentRecord:c,dynamicRatings:u,refreshDynamic:p,participantIds:m,drawDefinition:d,roundNumber:l,structureId:f,matchUpIds:g,eventType:I,scaleName:h,idPrefix:S,isMock:T,salted:y,event:E}=t;if(!d)return{error:Z};if(!t.structure&&!f)return{error:_t};let P=t.structure||at({drawDefinition:d,structureId:f}).structure;if(!ht(P))return{error:Si};if(!m?.length)return{error:bo};let A=[...a??[],...P?.matchUps??[]],{encounters:U}=t_({matchUps:A}),N=c?.participants??[],D={};if(u){let V=pt(P?.matchUps?P.matchUps.map(({roundNumber:X})=>X):[]),$=Math.max(...V,0);if($){let X=P?.matchUps?.filter(({roundNumber:it})=>it===$).map(({matchUpId:it})=>it),W=wT({ratingType:h??E?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,refreshDynamic:p,drawDefinition:d,matchUpIds:X});if(W.error)return W;W.modifiedScaleValues&&(D=W.modifiedScaleValues)}}let{valueObjects:M}=hV({tournamentParticipants:N,encounterValue:e,sameTeamValue:r,encounters:U}),{uniquePairings:R,possiblePairings:b,deltaObjects:O}=MD({participantIds:m}),v=Object.values(D).length?D:t.adHocRatings,x={tournamentParticipants:N,possiblePairings:b,participantIds:m,uniquePairings:R,drawDefinition:d,maxIterations:n,adHocRatings:v,deltaObjects:O,valueObjects:M,eventType:I,scaleName:h,structure:P,salted:y},{candidatesCount:F,participantIdPairings:w,deltaCandidate:L,iterations:k,candidate:G}=n_(x);if(!F)return{error:ap};let H,K;if(i){let V=Wu({structureId:P?.structureId,ignoreLastRoundNumber:s,participantIdPairings:w,newRound:!0,drawDefinition:d,roundNumber:l,matchUpIds:g,idPrefix:S,isMock:T,event:E});if(V.error)return V;H=V.roundNumber,K=V.matchUps}let{maxDelta:Y,maxDiff:j}=G;return{roundNumber:H,participantIdPairings:w,modifiedScaleValues:D,candidatesCount:F,deltaCandidate:L,...C,iterations:k,matchUps:K,maxDelta:Y,maxDiff:j}}function hV({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===wt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=MD({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function LT(t){let{drawType:e=yo,attachConsolation:r=!0,applyPositioning:n=!0,tournamentRecord:o,staggeredEntry:i,automated:s,placeByes:a,isMock:c,event:u}=t,p=t?.drawDefinition;if(!p)return{error:Z};let m=$e,d=bi({stageSequence:1,drawDefinition:p,stage:m}),l=[On,su,Eo].includes(e)?d.length:us(d.length);if(!i&&e===Ea&&d.length<2||e===On&&d.length<3)return{error:np};let{tieFormat:f,matchUpType:g}=t;if(f){let R=ar({tieFormat:f});if(R.error)return R}f=or(f??We({drawDefinition:p})?.tieFormat),g=g??p.matchUpType;let{structures:I}=hn({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:iA};if(I?.[0]?.matchUps?.length)return{error:If};let S=I?.[0]?.structureId;Object.assign(t,nt({structureName:t.structureName??Qe($e),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:m}));let T=_T(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:ql};let E=y?.();if(E.error)return E;let{structures:P,links:A}=E,U=P.map(R=>yt({structure:R}).matchUps).flat();f&&U.forEach(R=>{let{tieMatchUps:b}=Li({matchUp:R,tieFormat:f,isMock:c});Object.assign(R,{tieMatchUps:b,matchUpType:g})}),(!n||!r)&&(p=J(p,!1,!0)),p.links||(p.links=[]),A.length&&p.links.push(...A);let N=P.map(({structureId:R})=>R);p.structures||(p.structures=[]);let D=p.structures.map(({structureId:R})=>R);p.structures=p.structures.map(R=>N.includes(R.structureId)?P.find(({structureId:b})=>b===R.structureId):R);let M=P.filter(({structureId:R})=>!D.includes(R));return M.length&&p.structures.push(...M),s&&Mc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&bt({drawDefinition:p}),{links:A,structures:P,...C}}var Jg={};Xt(Jg,{addGame:()=>xD,addPoint:()=>_D,addSet:()=>LD,addShot:()=>wD,analyzeScore:()=>zg,analyzeSet:()=>qu,calculateHistoryScore:()=>bD,checkScoreHasValue:()=>he,checkSetIsComplete:()=>Jp,clearHistory:()=>vD,generate:()=>CD,generateScoreString:()=>Mo,generateTieMatchUpScore:()=>vc,getSetComplement:()=>Xg,getTiebreakComplement:()=>rm,helpers:()=>cN,isValidMatchUpFormat:()=>Nr,keyValueScore:()=>rN,mutate:()=>VD,parseMatchUpFormat:()=>Ne,parseScoreString:()=>nm,query:()=>mN,redo:()=>FD,reverseScore:()=>RD,setServingSide:()=>OD,stringifyMatchUpFormat:()=>gp,tidyScore:()=>aN,umo:()=>GD,undo:()=>kD,validateMatchUpScore:()=>uN,validateScore:()=>Qg,validateSetScore:()=>$T,validateTieFormat:()=>ar});var CD={};Xt(CD,{generateScoreString:()=>Mo,generateTieMatchUpScore:()=>vc,reverseScore:()=>RD});function Mo(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:st,info:"missing sets"};let p=s&&Ne(s),{bestOf:m,finalSetFormat:d,setFormat:l}=p??{},g=o||!(!e||!c||c===1),I=n?SV({matchUpStatus:i}):"",h=u?.sort(TV).map(S).filter(Boolean).join(" ")||"";if(!I)return h;if(c===2)return`${I} ${h}`;return`${h} ${I}`;function S(T){let E=m&&T.setNumber===m&&d?d:l,P=V=>Jt(V?.side1Score)||Jt(V?.side2Score),U=(V=>Jt(V?.side1TiebreakScore)||Jt(V?.side2TiebreakScore))(T),N=E?.tiebreakSet||!P(T)&&U,{side1Score:D,side2Score:M,side1TiebreakScore:R,side2TiebreakScore:b}=T,O=R||(Jt(R)||U&&a?0:""),v=b||(Jt(b)||U&&a?0:"");if(N){let V=P(T)&&!U,$=V?D:O,X=V?M:v;return`[${(g?[X,$]:[$,X]).join("-")}]`}let x=U?Math.min(O,v):"",F=x===O?1:2,w=Jt(x)?`(${x})`:"",L=D||(Jt(D)||a?0:""),k=M||(Jt(M)||a?0:""),G=V=>!r&&F===V?w:"",H=`${L}${G(1)}`,K=`${k}${G(2)}`,Y=r&&U?`(${x})`:"",j=g?`${[K,H].join("-")}${Y}`:`${[H,K].join("-")}${Y}`;return["-"," "].includes(j)&&(j=""),j}}function SV({matchUpStatus:t}){let e={[Me]:"RET",[Bt]:"WO",[be]:"DF/DF",[oe]:"WO/WO",[ls]:"SUS",[vr]:"ABN",[Gt]:"DEF",[Iu]:"DR"};return t&&e[t]||""}function TV(t,e){return t.setNumber-e.setNumber}function RD(t){if(!t?.score)return{error:st};let{sets:e}=t.score,r=e.map(s=>{let{side1TiebreakScore:a,side2TiebreakScore:c,winningSide:u,side1Score:p,side2Score:m,setNumber:d}=s;return nt({winningSide:u?3-u:void 0,side1TiebreakScore:c,side2TiebreakScore:a,side1Score:m,side2Score:p,setNumber:d})}),n=t?.setTBlast,o=Mo({setTBlast:n,sets:r}),i=Mo({sets:r,reversed:!0,setTBlast:n});return{reversedScore:{sets:r,scoreStringSide1:o,scoreStringSide2:i},...C}}var VD={};Xt(VD,{addGame:()=>xD,addPoint:()=>_D,addSet:()=>LD,addShot:()=>wD,calculateHistoryScore:()=>bD,clearHistory:()=>vD,redo:()=>FD,setServingSide:()=>OD,umo:()=>GD,undo:()=>kD});function ei({matchUp:t}){let{extension:e}=mt({name:rd,element:t});if(!e)return{error:Oe};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...C}}function bD(t){if(!t)return{error:st};let{matchUp:e,updateScore:r}=t;if(!e)return{error:mr};let n=ei({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:B,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Zl};if(!Nr({matchUpFormat:o}))return{error:Jl};let i=Ne(o),{bestOf:s,finalSetFormat:a,setFormat:c}=i,u=["0","15","30","40","A","G"],p={sets:[]},m=[],d,l=[0,0],f=1,g=0,I,h=0,S=D=>[1,2].includes(D),T=()=>(g+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:g,games:[]}),y=()=>({winningSide:void 0,points:[]}),E=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),P=E(),A=y(),U=T(),N=0;for(let D of n){N+=1,I=p.sets.length+1===s;let M=I&&a?a:c,{tiebreakAt:R,setTo:b,NoAD:O,tiebbreakFormat:v}=M,x=U.side1Score===R&&U.side1Score===U.side2Score,F=!!M.tiebreakSet,w=F?M.tiebreakSet:v,{tiebreakTo:L,NoAD:k}=w||{},G=()=>{d=void 0,l=[0,0],f=3-f,U.side1TiebreakScore="",U.side2TiebreakScore="",U.side1PointScore="",U.side2PointScore="",h=0},H=j=>{U.winningSide=j;let{s:V,...$}=U;p.sets.push($),P=E(),A=y(),U=T(),G()},K=j=>{A.winningSide=j;let{g:V,...$}=A;U.games.push($),P=E(),A=y(),G();let X=`side${j}Score`;U[X]+=1},Y=j=>{P.winningSide=j;let{p:V,...$}=P;A.points.push($),P=E(),h=0;let X=()=>l.reduce((Q,ut)=>Q+ut)%4/4>.5?f:3-f,W=j-1;if(x||F){l[W]+=1,d=X(),U[`side${j}TiebreakScore`]=l[W],U[`side${3-j}TiebreakScore`]=l[1-W];let it=k?1:2;if(l[W]>=L&&l[W]>=l[1-W]+it)return K(j),{gameCompleted:!0}}else if(l[1-W]===4&&l[W]===3?l[1-W]-=1:l[W]+=1,U.side1PointScore=u[l[0]],U.side2PointScore=u[l[1]],l[W]===5||l[W]===4&&l[1-W]<3||O&&l[W]===4)return K(j),{gameCompleted:!0}};if(S(D.srv)&&(f=D.srv),["p","s","g","o"].includes(D.u)&&m.push(D.u),D.shotOutcome&&(P.shots.push(D),D.shotType==="SERVE"&&["OUT","NET"].includes(D.shotOutcome)&&(h+=1),h===2)){let V=3-f;Y(V)}if(S(D.p)||It(D.pointNumber)){let j=D.winningSide||D.p;if(Y(j)?.gameCompleted)continue}if(S(D.g)||It(D.gameNumber)){let j=D.winningSide||D.g;A.winningSide=j;let V=`side${j}Score`,$=`side${3-j}Score`;if(m.length&&(m.includes("p"),m=[]),K(j),U[V]===b&&U[V]-U[$]>=(O?1:2)&&(H(j),I))break}if(S(D.s)||It(D.setNumber)){let j=D.winningSide||D.s;if(H(j),m.length&&(m.includes("p"),m.includes("g"),m=[]),I)break}}return N!==n.length&&console.log({error:"Match completed with excess history"}),(U.side1Score||U.side2Score||U.games.length||U.side1TiebreakScore||U.side2TiebreakScore)&&p.sets.push(U),p.scoreStringSide1=Mo({...p,matchUpFormat:o}),p.scoreStringSide2=Mo({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...C,servingSide:f,score:p}}function ri({undoHistory:t,history:e,matchUp:r}){return At({element:r,extension:{value:{history:e,undoHistory:t},name:rd}})}function OD({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:tf};let{history:r=[]}=ei({matchUp:t});return r.push({srv:e}),ri({matchUp:t,history:r})}function vD({matchUp:t}){return ri({matchUp:t})}function _D({matchUp:t,point:e}){if(!e||!t)return{error:st};if(typeof e!="object")return{error:B,context:{point:e}};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function xD({matchUp:t,game:e}){if(typeof e!="object")return{error:B,context:{game:e}};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function wD({matchUp:t,shot:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function LD({matchUp:t,set:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=ei({matchUp:t});return r.push(e),ri({matchUp:t,history:r})}function FD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=ei({matchUp:t});return r.length&&e.push(r.pop()),ri({matchUp:t,history:e,undoHistory:r})}function kD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=ei({matchUp:t});return r.push(e.pop()),ri({matchUp:t,history:e,undoHistory:r})}var GD={};var cN={};Xt(cN,{keyValueScore:()=>rN,parseMatchUpFormat:()=>Ne,stringifyMatchUpFormat:()=>gp,tidyScore:()=>aN});var o_="COMPLETED";var yV="WO/WO";var FT=["RET","DEF","WO",yV,"ABN","SUS","INT"];var kT="DEFAULTED";var BD="WALKOVER";var GT="ABANDONED",VT="SUSPENDED",HD="RETIRED",BT="INTERRUPTED";var i_=[HD,kT,BD],EV="Enter Score",Rs="()",Cs="[]",WD=["up","left","shift+tab"],jD=["enter","down","tab","right"],$d="backspace",YD="r",qD="s",$D="a",KD="d",zD="w",QD="i",Kd=[YD,KD,zD,$D,qD,QD],Qp="space",HT=["[","("],zd=[...WD,...jD,Qp,"]"],s_="-",AV="/",aa=s_,gi=s_,XD=[AV],a_=0,UV=["=","+","num_1","num_2","shift+=","shift+-"],sa=["0","1","2","3","4","5","6","7","8","9"].concat(Kd),c_=sa.map(t=>`shift+${t}`),JD=[aa,$d].concat(zd,XD),ZD=[sa,c_,JD].join(","),PV=[ZD,WD,jD,UV].join(","),Bbt=[].concat(...sa,...sa,...JD,...sa,...sa,...sa,...sa,...sa,...sa),u_={OUTCOMEKEYS:Kd,SIDE1KEYS:sa,SIDE2KEYS:c_,MODIFIERS:JD,PROMPT:EV,MOVEUP:WD,MOVEDOWN:jD,HOTKEYS:PV};function Xp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=p_({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==" "?" ":"";return t+o+r}else return r+" "+t}function p_({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of FT){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 qg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=p_({scoreString:e});if(e=s,a)return{scoreString:e,sets:r,outcomeRemoved:!0};let c=r[r.length-1]||{},u=Object.values(c).filter(g=>g!==void 0).length;c.setNumber&&u===1&&(r=r.slice(0,r.length-1),c=r[r.length-1]||{});let{tiebreakSet:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p||{},{isTiebreakEntry:l}=ju({brackets:Cs,scoreString:e}),f=DV(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=ju({brackets:Rs,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=ju({brackets:Cs,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),y=t.isIncompleteSetScore;if(l&&h){let P=o.slice(I+1).split(gi),A=P?.length>0&&P[0]!==void 0&&!isNaN(parseInt(P[0]))&&parseInt(P[0])||void 0,U=P?.length>1&&P[1]!==void 0&&parseInt(P[1])||void 0,N=[A,U];if(U){let D=n===1?1:0;N[D]=(N?.[1-D]||0)+(d?1:2),(N[D]||0)<m&&(N[D]=m),o=e.slice(0,I+1),o+=N.join(gi)}else A!==void 0?(o=e.slice(0,I+1),o+=A):(o=e.slice(0,I),y=!0);c.side1TiebreakScore=N[0]||0,c.side2TiebreakScore=N[1]||0}if(o.length||(o=void 0),y){let E=c.side1Score?.toString();if(E){let P=E?.slice(0,E.length-1);c.side1Score=!isNaN(P)&&parseInt(P)||void 0,c.side1Score===void 0&&(c.side2Score=void 0)}t.isTimedSet?(i=c.side1Score?r:r?.slice(0,r.length-1)||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]}else if(T){let E=c.side2Score?.toString(),P=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let A=E?.slice(0,E.length-1);c.side2Score=!isNaN(A)&&parseInt(A)||void 0}else{let A=P?.slice(0,P.length-1);c.side1Score=!isNaN(A)&&parseInt(A)||void 0}t.isTimedSet?c.side1Score?(i=r||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]:(i=r||[],i[r.length-1]=c),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0})}else g?(i=r||[],Object.assign(i[i.length-1]||{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(l&&!h?i=r?.slice(0,r.length-1)||[]:(i=r,i[r.length-1]=c),l||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0));return{scoreString:o,sets:i}}return{scoreString:e,sets:r}}function ju({brackets:t=Rs,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...ho(r,o)),s=Math.max(...ho(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function m_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=Cs.split(""),i=t.split(""),s=Math.max(...ho(n,i)),a=Math.max(...ho(o,i)),c=Math.max(...ho(gi,i));return r&&s>a&&c>s}function DV(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function WT(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function tN({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:m}=p;return m&&u[m-1]++,u},[0,0])?.indexOf(s)+1||void 0;return i_.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Jp({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,isTimedSet:i,set:s}){if(!s)return{error:st,info:"missing set"};e=e||r&&Ne(r);let a=o&&e.finalSetFormat||e?.setFormat||{},{side1Score:c,side2Score:u}=s,{setTo:p,tiebreakAt:m}=a,d=c||u,l=Zp({set:s}),f=Math.abs(c-u),g=c>=p||u>=p,I=n||c>=p&&u>=p||m&&m<p&&(c===m||u===m),h=t||I&&(l===1&&s.side1TiebreakScore>s.side2TiebreakScore||l===2&&s.side2TiebreakScore>s.side1TiebreakScore),S=!I&&a.NoAD||I||n&&a.tiebreakFormat?.NoAD?1:2,T=f>=S;return!!((i&&d||g&&(T||I)||n)&&(!I||h))}function Zp({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 Qd({analysis:t,set:e}){let r=Zp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Jp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function d_({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=dt(n);let{validSide2Score:s,requiresTiebreak:a}=NV({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Qd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=Rs.split("")[0];e+=u}else t.isDecidingSet||(e+=" ")}return{sets:r,scoreString:e,updated:o}}function NV({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 jT({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===YD?n?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"RET"}),o=t===2?1:2,i=HD):(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=kT):e===KD?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=kT):e===zD?(s=!0,r=[],n="WO",o=t===2?1:2,i=BD):e===qD&&n?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"SUS"}),i=VT,o=void 0):e===$D?(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"ABN"}),i=GT,o=void 0):e===QD&&n&&(s=!0,n=Xp({scoreString:n,lowSide:t,outcome:"INT"}),i=BT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function f_(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!==$d&&(e=[{setNumber:1}]);let m=e.length-1;if(Kd.includes(c)){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;l&&!f?r="missing side2Score":s.finalSetIsComplete||o?r="final set is already complete":s.isIncompleteSetScore?r="incomplete set scoreString":s.isIncompleteSetScore||({sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=jT({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===$d){if({scoreString:n,sets:e,outcomeRemoved:p}=qg({analysis:s,scoreString:n,sets:e}),n?.trim()===""&&(n=n.trim()),n||(e=[]),p){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;if(l&&f){let g=l>f&&1||f>l&&2||void 0;g&&(d.winningSide=g,e.push({setNumber:e.length+1}))}}i=void 0,o=void 0,u=!0}else if(s.hasOutcome)r="has outcome";else{if(o)return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:!1,info:"matchUp is complete"};if(c===Qp){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d,g=l>f&&1||f>l&&2||void 0;g&&!o&&!s.isIncompleteSetScore&&(e[e.length-1].winningSide=g,e.push({setNumber:e.length+1}),n+=" ",u=!0)}else if(c===aa&&e[m].side1Score!==void 0&&e[m].side2Score===void 0&&n&&s.isNumericEnding)n+="-",e[m].side2Score=0,i=void 0,o=void 0,u=!0;else if(!isNaN(c)){let d;if(e[m].side2Score===void 0){let l=dt((e[m].side1Score||0).toString()+c).toString().slice(0,2);e[m].side1Score=dt(l),d=e[m].side1Score.toString(),u=!0}else{let l=dt((e[m].side2Score||0).toString()+c).toString().slice(0,2);e[m].side2Score=dt(l),d=[e[m].side1Score,e[m].side2Score].join("-"),u=!0}if(u){let l=(e.slice(0,m)||[]).filter(f=>f).map(f=>{let{side1Score:g,side2Score:I}=f;return[g,I].join("-")}).join(" ");l?n=l+" "+d:n=d}}}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function g_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Cs.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=ju({brackets:Cs,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(gi);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=>dt(T)),h=r===1?1:0;I[h]=I[1-h]+(u?1:2),I[h]<c&&(I[h]=c);let S=o[o.length-1];S.side1TiebreakScore=I[0],S.side2TiebreakScore=I[1],n=n.slice(0,(d??0)+1),n+=I.join(gi),s=!0}else{let I=[f[0]||0,f[1]||0].map(S=>dt(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=WT({lowValue:dt(i||0),tiebreakTo:c,NoAD:u}),l=[dt(i),d];r===2&&l.reverse();let f={side1TiebreakScore:l[0],side2TiebreakScore:l[1],setNumber:o?.length+1||1};o.push(f),n+=l.join(gi),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function I_({analysis:t,lowSide:e,scoreString:r,value:n}){let{setTo:o,tiebreakAt:i,NoAD:s}=t?.setFormat||{},a=n===parseInt(i||o);if(i&&i<o&&n>i)return{scoreString:r};if(s&&n===o||n>o)return{scoreString:r};let c=g(),u=[n,c];e===2&&u.reverse();let m=Rs.split("")[0],d=u.join(aa)+(a?m:" ");r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Qd({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 h_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(K=>K?.winningSide)?.length||0)+(r?0:1),a=Ne(t),c=s===a?.bestOf,u=c&&a?.finalSetFormat||a?.setFormat||{},p=u?.timed,m=c&&o[a?.bestOf-1],d=m?.winningSide,{isTiebreakEntry:l}=ju({brackets:Rs,scoreString:e}),{isTiebreakEntry:f}=ju({brackets:Cs,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===aa,y=l&&HT.includes(h),E=f&&HT.includes(h),P=f&&h===gi,A=e?.split(""),[U]=Cs.split(""),N=A&&Math.max(...ho(U,A)),D=A&&Math.max(...ho(gi,A)),M=A&&D>N,R=o[o.length-1]?.winningSide,b=o?.length&&!R,O=FT.find(K=>e?.indexOf(K)>=0),v=!isNaN(n),x=n===Qp,F=zd.includes(n),w=e?.split("").find(K=>HT.includes(K)),L=F&&f&&!E&&(P||!m_({scoreString:e}));return{isTiebreakSetValue:I&&v,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:M,isGameScoreEntry:b,isSpace:x,isCloser:F,isTiebreakCloser:F&&w&&g&&S,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:S,isNumericValue:v,hasOpener:w,hasOutcome:O,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:R,isInvalidSetTiebreakValue:x&&g&&y,isInvalidMatchTiebreakValue:L,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:E,isPartialMatchTiebreakValue:P}}function rN(t){let{lowSide:e=1,value:r}=t,{scoreString:n,sets:o,winningSide:i,matchUpStatus:s}=t,{matchUpFormat:a,shiftFirst:c,auto:u=!0}=t,p,m,d=c&&e===2||!c&&e===1;if(!ZD.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=tN({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=h_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(XD.includes(r)&&(r=aa),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&dt(r)===0&&(f.isTiebreakCloser=!0),zd.includes(r)&&f.hasOpener&&(r=""),zd.includes(r)&&(r=Qp),f.lastSetIsComplete){let g=n?.length&&n[n.length-1];n&&g!==" "&&(n+=" ")}if(f.isTimedSet)({info:m,sets:o,scoreString:n,updated:p,matchUpStatus:s,winningSide:i}=f_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Kd.includes(r))f.finalSetIsComplete||i?m="final set is already complete":!f.isTiebreakEntry&&!f.isIncompleteSetScore?{sets:o,scoreString:n,matchUpStatus:s,winningSide:i,updated:p}=jT({lowSide:e,sets:o,scoreString:n,matchUpStatus:s,winningSide:i,value:r}):f.isTiebreakEntry||f.isIncompleteSetScore?m="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:r});else if(r===$d)p=!0,{scoreString:n,sets:o}=qg({analysis:f,scoreString:n,sets:o,lowSide:e}),n||(o=[]),s=void 0,i=void 0;else if(f.hasOutcome)m="has outcome";else if(r===aa&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=qg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===gi&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=gi);else if([aa,gi].includes(r))m="invalid location for joiner";else{if(i)return{updated:!1,info:"matchUp is complete"};if(f.isIncompleteSetScore)f.isNumericValue&&({sets:o,scoreString:n,updated:p}=d_({analysis:f,scoreString:n,sets:o,value:r}));else if(f.isInvalidMatchTiebreakValue)m="invalid matchUp tiebreak character";else if(f.isInvalidSetTiebreakValue)m="invalid set tiebreak character";else if(f.isTiebreakCloser){let g=f.isSetTiebreakEntry?Rs:Cs,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:E}=T||{},P=Zp({set:S});if(!f.isTiebreakSet){let U=parseInt(n.split(h).reverse()[0]),N=WT({lowValue:U,tiebreakTo:y,NoAD:E});P===1?(S.side1TiebreakScore=N,S.side2TiebreakScore=U):(S.side1TiebreakScore=U,S.side2TiebreakScore=N)}n=(n||"")+I,f.isDecidingSet||(n+=" ");let A=Qd({analysis:f,set:S});S.winningSide=A||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=g_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=Rs.split(""),I=Math.max(...ho(g,n.split(""))),h=n.slice(I+1),S=h&&dt(h)===a_,T=dt(h?h+r:r),{tiebreakFormat:y}=f.setFormat,{tiebreakTo:E,NoAD:P}=y||{};!S&&h.length<2?P&&T>E-1?m="invalid low value for NoAD tiebreak":(p=!0,n=(n||"")+r):m=S?"tiebreak begins with zero":"tiebreak digit limit"}else if(f.isCloser)m=`invalid key: ${r}`;else if(f.isGameScoreEntry)m="game scoreString entry";else if(f.lastSetIsComplete||!o.length){p=!0;let{scoreString:g,set:I}=I_({analysis:f,lowSide:e,scoreString:n,value:dt(r)});I&&(I.setNumber=o?.length+1||1),o=o?.concat(I).filter(Boolean)||[I],n=g||void 0}else console.log("error: unknown outcome")}if(p){o=o?.filter(Boolean);let{matchUpWinningSide:g}=tN({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[Qt,mn].includes(s))?(s=o_,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![VT,GT,BT].includes(s)&&(s=void 0),{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}return{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}var Xd="\\d+-\\d+",tm="\\d+-\\d+\\(\\d+\\)",$g="\\[\\d+-\\d+\\]",OV="\\d+-\\d+\\(\\d+-\\d+\\)",S_=new RegExp(`(${Xd}),`,"g"),T_=new RegExp(`(${tm}),`,"g"),vV=[Xd,tm,$g,OV],_V=["0","1","2","00","01","10","11","002","012","102","112","000","001","010","100","011","101","110","111","002","012","102","112","0002","0012","0102","1002","0112","1012","1102","1112","3","03","13","013","103"],xV=_V.map(t=>{let r=t.split("").map(n=>vV[n]).join(" ");return new RegExp(`^${r}$`)});function nN(t){return!t||xV.some(e=>e.test(t))}function y_(t){let n="[];()",o=["[","("],i=Object.assign({},...n.split("").map(c=>({[c]:0}))),s="",a=t.split("").map(c=>{let u=n.includes(c)&&c,p=o.includes(u);if(p&&u)return i[u]+=1,s=u,c;if(!p&&u&&s&&u!==s){i[s]-=1;let m="[];".includes(s)&&"[];"||"()".includes(s)&&"()"||"",d=m.split("").find(l=>l!==s);if(m.includes(u))i[s]||(s="");else return i[u]||(s=""),d}return c}).join("");return t!==a?a:t}function Jd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function E_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function Ba(t){let r=(n=>n?.split("-").join("").split("/").join(""))(t);if(/^\d+$/.test(r)&&r.length===2){let n=r.split("");return Math.abs(n.reduce((i,s)=>+i-+s))===1}return!1}function em(t,e){let r=[t.slice(e,e+2),e?t.slice(0,1):t.slice(2)].map(i=>parseInt(i.join("")));e&&r.reverse();let n=r;if(Math.abs(n.reduce((i,s)=>+i-+s))>=2)return n.join("-")}function oN(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function A_(t){return t.startsWith("(")&&t.endsWith(")")}function U_({score:t,applied:e}){t=y_(t);let r=/\)(\d+)/g;if(r.test(t))for(let P of t.match(r)){let A=P.replace(")",") ");t=t.replace(P,A)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let P of i||[]){let[A]=P.match(o).slice(1),U=A.replace(/ /g,"");t=t.replace(P,`(${U})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let P=t.match(s);P.length&&P.forEach(A=>{let U=A.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(A,U)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let P=t.match(s);P.length&&P.forEach(A=>{let U=A.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(A,U)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(P=>{let A=new RegExp(`(\\d+)${P}(\\d+)`,"g"),U=t.match(A);U&&U.forEach(N=>t=t.replace(N,N.split(P).join("-")))}),/^[(-/,]+$/.test(t)&&(t=""),/\)[-/,]+$/.test(t)&&(t=t.slice(0,t.length-1)),/\d \/\d/.test(t)&&(t=t.replace(/ \//g,"/")),t.includes(" /")&&(t=t.replace(/ \//g," "));let c=/\(\d+, \)/g;c.test(t)&&t.match(c).forEach(A=>{let[U]=A.match(/\((\d+), \)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&U==="6"&&(t=t.replace(A,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(A=>{let[U]=A.match(/\((\d+)\/\)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&U==="6"?t=t.replace(A,"(6-0)"):t=t.replace(A,`(${U})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(A=>{let[U]=A.match(/(\d\/\d)\/,/).slice(1);t=t.replace(A,`${U},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(A=>{let[U]=A.match(/\(\/(\d+)\)/).slice(1);U.length===2?t=t.replace(A,`(${U})`):U.length===1&&parseInt(U)<6?t=t.replace(A,`(6-${U})`):t=t.replace(A,`(${U})`)});let d,l,f,g,I,h=()=>{I=Er(t.split("")),l=I["("]===(I[")"]||0)+1,d=(I["("]||0)+1===I[")"],f=I["["]===I["]"]+1,g=l&&!f};h();let S=/(\d+-\d+\(\d+)0,/;if(S.test(t)){let[P]=t.match(S).slice(1);t=t.replace(S,P+")")}if(I["("]===I[")"]&&I["("]>1){let P=t.split(")(").join(") (").split(" ");P.every(A_)?t=P.map(A=>{let U=A.slice(1,A.length-1);return U.length>2?U:A}).join(" "):t=P.join(" ")}h();let T=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!T&&!y)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(P=>I[P])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(P=>I[P]>1)&&(t=t.slice(1,t.length-1)),t.startsWith("(")&&t.endsWith("))")&&(t=t.slice(1,t.length-1)),I["("]>(I[")"]||0)&&t[t.length-1]==="("&&(t=t.slice(0,t.length-1)+")",h()),I["("]===1&&!I[")"]&&t[0]==="("&&(t=t+")",h()),I["("]>(I[")"]||0)&&t.slice(0,2)==="(("&&(t=t.slice(1)),d){if(/^9\d/.test(t))t="("+t.slice(1);else if(t[0]!=="(")t="("+t;else{let P=[],A=0;for(let U of t.split("").reverse())U===")"&&(A?P.push("("):A+=1),U==="("&&(A-=1),P.push(U);P.reverse(),t=P.join("")}h()}if(I[")"]>(I["("]||0)&&t[0]===")"&&(t="("+t.slice(1),h()),g&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",h()),g&&(!t.endsWith(")")||t.startsWith("(("))&&(t=t+")",h()),g){let P="",A=0;for(let U of t.split(""))U==="("&&(A?P+=")":A+=1),U===")"&&(A-=1),P+=U;t=P}h(),f&&!l&&(t=t+"]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),h()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),h(),I[")"]===1&&!I["("]&&t.endsWith(")")&&(t=t.slice(0,t.length-1)),t.startsWith("(")&&t.endsWith(")")&&I["("]===1&&I[")"]===1&&(t=t.slice(1,t.length-1),h());let E=P=>{let A=P.indexOf("("),U=P.indexOf(")");return A>=0&&U>=0&&A<U};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let P=t.slice(1,t.length-1);E(P)&&(t=P,h())}return{score:t,applied:e}}function Yu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=ho("-",t.split(""));if(!e.length)return t;let r=t.split("-"),n=!(r.length%2),o=!!(e.length%2);return n&&o&&e.length>r.length/2&&e.filter((s,a)=>a%2).forEach(s=>{t=t.substring(0,s)+" "+t.substring(s+1)}),t}function P_({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map(r=>r.trim()).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map(r=>r.trim()).join(")")),[S_,T_].forEach(r=>{let n=t.match(r);n?.length&&(n.forEach(o=>{t=t.replace(o,o.slice(0,o.length-1)+" ")}),e.push("setsEndComma"))}),t=t.split(" ").filter(Boolean).map(Yu).join(" "),{score:t,applied:e}}function D_({score:t}){if(typeof t!="string")return{score:t};let e=d=>d?.split("-").join("").split("/").join(""),r=d=>d.split("[").join("(").split("]").join(")");t=t.split(", ").join(" ");let n=t.split(" ");t=n.map(d=>{let l=/^-(\d+)$/;if(l.test(d)){let[f]=d.match(l).slice(1);if(f.length===2)return f.split("").join("-")}return d}).join(" "),n=t.split(" ");let o=n.filter(Jd),i=0,s="";for(let d of o){let l=ho(d,n).filter(h=>!i||h>i)[0],f=n.slice(i,l-1),g=n[l-1],I=e(g);if(/^\d+$/.test(I)&&I.length===2){let h=I.split(""),S=Math.abs(h.reduce((T,y)=>+T-+y));if(S===1){let T=[f.join(" "),[g,d].join("")].join(" ");s+=T,i=l+1}else if(S===0){let T=Math.max(...h);if([4,5,6,7,8,9].includes(T)){let y=[6,4].includes(T)?T+1:T-1,E=[T,y].sort().reverse().join("-"),P=[f.join(" "),[E,d].join("")].join(" ");s+=P,i=l+1}}}}if(o.length&&s.length){let d=n.slice(i).join(" ");return s=[s,d].join(" "),{score:s.trim()}}if(n.length===2&&["(","["].some(d=>n[1].includes(d))){let l=e(n[0]).split("");if(Math.abs(l.reduce((g,I)=>+g-+I,0))===1)return n[1]=r(n[1]),{score:n.join("")}}let a=n.map(d=>E_(d)&&"bracket"||Ba(d)&&"set");if(a.includes("set")&&a.includes("bracket")){let d,l="";return n.forEach((f,g)=>{a[g]==="bracket"&&d==="set"?(f=r(f),l+=f):l+=` ${f}`,d=a[g]}),{score:l.trim()}}n=t.split(" ");let c,u=n.map(d=>{let l=new RegExp(/^(\d+)-(\d+)$/);if(l.test(d)){let[f,g]=d.match(l).slice(1),I=Math.abs([f,g].reduce((S,T)=>+S-+T)),h=Math.max(f,g);if(I===1)return c="tiebreakSet",c;if(I>=2&&h>=7&&c==="tiebreakSet")return c="tiebreak",c}}),p=ho("tiebreak",u);if(p.length){let d="";n.forEach((l,f)=>{p.includes(f)?d+=`(${l}) `:p.includes(f+1)?d+=`${l}`:d+=`${l} `}),t=d.trim()}let m=/(\d+-\d+)\((\d+)-(\d+)\)$/;if(m.test(t)){let[d,l,f]=t.match(m).slice(1),I=Math.max(l,f)>=10;!Ba(d)&&I&&(t=t.replace(m,`${d} [${l}-${f}]`))}return u=[],t=t.split(" ").map(d=>{let l=/^\((.*)\)$/,f=l.test(d),g=new RegExp($g).test(d)&&"super"||new RegExp(tm).test(d)&&"tiebreak"||new RegExp(Xd).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function N_({score:t,applied:e}){for(let D of[".",","," ","/"]){let M=new RegExp(`^(\\d+)\\${D}(\\d+)$`);if(M.test(t)){let R=t.match(M).slice(1).map(O=>parseInt(O)),b=Math.abs(R[0]-R[1]);b<=10&&b>=2&&(t=t.split(D).join("-"),e.push("variedJoinerPattern"))}}t.includes(";")&&(t=t.split(";").join(" "),e.push("semicolon set separation"));let r=/(^|\s)(\d)\/(\d)(\d)\/(\d)(\(|$)/;if(r.test(t)){let[D,M,R,b,O,v]=t.match(r).slice(1);t=t.replace(r,`${D}${M}-${R} ${b}-${O}${v}`),e.push("smashSlashPattern")}/.*\s6[/-]+$/.test(t)&&(t+="0",e.push("incompleteFinalSetPattern"));let o=/\(6,\)/g;o.test(t)&&(t=t.replace(o,"(6, 0)"),e.push("missingZeroPattern1"));let i=/^\d{3,}\(/,s=/\(\d+\)\d+/;[i,s].forEach(()=>{t=t.split(" ").map(M=>(i.test(M)&&(M=M.replace("("," (")),s.test(M)&&(M=M.replace(")",") ")),M)).join(" "),e.push("spaceConsiderationPatterns")});let c=Yu(t);c!==t&&(t=c,e.push("deDashMash"));let u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){let[D,M,R]=t.match(u).slice(1),[b,O]=M.split("");t=`${D}-${b} ${O}-${R}`,e.push("smashSetPattern")}let p=/^(\d+)[ -](\d+)$/,m=/^([\d -]+)\/([\d -]+)$/;if(m.test(t)){let[D,M]=t.match(m).slice(1),R=D.trim(),b=M.trim();if(p.test(R)&&p.test(b)){let O=R.match(p).slice(1,3).join("-"),v=b.match(p).slice(1,3).join("-");t=`${O} ${v}`,e.push("slashSeparationPattern")}}let d=/^([\d -]+),([\d -]+)$/;if(d.test(t)){let[D,M]=t.match(d).slice(1),R=D.trim(),b=M.trim();if(p.test(R)&&p.test(b)){let O=R.match(p).slice(1,3).join("-"),v=b.match(p).slice(1,3).join("-");t=`${O} ${v}`,e.push("commaSeparationPattern")}}let l=/^\d \d,/;if(l.test(t)){let D=t.match(l)[0],M=D.slice(0,D.length-1).split(" ").join("-");t=t.replace(D,M),e.push("singleSetCommaSeparationPattern")}let f=0,g=/(\d+)-(\d{2})-(\d+)/;for(;g.test(t)&&f<3;){let[D,M,R]=t.match(g).slice(1),b=M.split(""),O=`${D}-${b[0]} ${b[1]}-${R}`;t=t.replace(g,O),e.push("noSetSeparationPattern"),f+=1}let I=/(^|\s)7-6\s(\d+)\s/g,h=t.match(I);if(h?.length){let D=/(^|\s)7-6\s(\d+)\s/;h.forEach(M=>{let R=M.match(D).slice(2)[0];t=t.replace(M,`7-6(${R}) `),e.push("floatingTiebreakPattern1")})}let S=t.match(/\d \d /);S?.forEach(D=>{let M=D.slice(0,D.length-1).split(" ").join("-");t=t.replace(D,M),e.push("spaceSeparatedSetPattern1")}),S=t.match(/ \d \d$/),S?.forEach(D=>{let M=" "+D.slice(1).split(" ").join("-");t=t.replace(D,M),e.push("spaceSeparatedSetPattern2")});let T=/^\d, *\d\/\d, *\d/;if(T.test(t)){let D=t.match(T)[0],M=D.split("/").map(R=>`(${R})`).join(" ")+" ";t=t.replace(D,M),e.push("slashCommaSetPattern")}let y=/\(6-\)/g;y.test(t)&&(t=t.replace(y,"(6-0)"),e.push("missingZeroPattern2"));let E=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(E.test(t)){let D=t.match(E),M=/(?<!-)(\d+)\/(\d+)(?!-)/,R=t;D.forEach(b=>{let[O,v]=b.match(M).slice(1),x=`${O}-${v}`;R=R.replace(b,x)}),t=R,e.push("slashSetPattern")}let P=/(.*)\s(1\d)\s(\d+)$/;if(P.test(t)){let[D,M,R]=t.match(P).slice(1);D.replace(/\D/g,"").length>=4&&(t=D+` ${M}${R}`,e.push("spaceSeparatedSuperPattern"))}let A=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(let D of t.match(A)||[]){let[M,R,b,O]=D.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[v,x]=R.split("-").map(w=>parseInt(w));Math.abs(v-x)===1&&(t=t.replace(D,`${M}${R}(${b})${O}`),e.push("spaceSeparatedSetPattern"))}let U=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let D of t.match(U)||[]){let M=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[R,b,O]=D.match(M).slice(1),[v,x]=R.split("-").map(w=>parseInt(w));Math.abs(v-x)===1&&(t=t.replace(D,`${R}(${b})${O}`),e.push("floatingTiebreakPattern2"))}let N=/(^|\s)(\d \d)\(/g;for(let D of t.match(N)||[]){let M=/(^|\s)(\d \d)\(/,[R,b]=D.match(M).slice(1);t=t.replace(D,`${R}${b.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}}function M_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(Ba(c[0]))return c[0]+`(${c[1].slice(0,c[1].length-1)})`}return a}).join(" ");let n=new RegExp(/(\([\d ]+\))/g);if(n.test(t))for(let a of t.match(n)){let u=a.replace(" ","-").match(/\((.*)\)/)?.[1];if(Jt(u)&&u?.[0]>2){if([2,4].includes(u.length))u=u.split("").join("-");else if(u.length===3){let p=u.indexOf("1");u=em(u.split(""),p)}}t=t.replace(a,`(${u})`)}r=t?.split(" ");let o=new RegExp(/^(\d[-/]+\d)\((\d+)[-/]+(\d+)\)$/),i=r.length-1;t=r.map((a,c)=>{let u=[void 0,"","COMPLETED"].includes(e)||c!==i;if(o.test(a)&&u){let[p,m,d]=Array.from(a.match(o)).slice(1),l=Math.min(m,d);return`${p}(${l})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^(\d{2})\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1),p=c.split("");return`${p[0]}-${p[1]}(${u})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^\((\d[-/]+\d)\)(\d+)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1);return Ba(c)?`${c}(${u})`:c}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^1-0\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c]=a.match(o).slice(1);return`[${c<9?10:parseInt(c)+2}-${c}]`}return a}).join(" ");let s=/\((\d)+0 /;if(s.test(t)){let a=t.match(s)[1];t=t.replace(s,`(${a}) `)}return{score:t}}function R_({score:t,attributes:e,identifier:r}){if(typeof t!="string")return{score:t,identifier:r};let n=new RegExp(/\([\d,/ ]+\)/g),o=t.match(n);for(let m of o||[]){let l=m.match(/^\((.*)\)$/)?.slice(1)?.[0],g=t.split(m)[0].split(")").reverse()[0].replace(/\D/g,"");if(l?.length===2&&g?.length>=2){let S=g.slice(g.length-2).split("").map(y=>parseInt(y));if(Math.abs(S[0]-S[1])===1)continue}let I=oN(l),h=Yu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=oN(m.match(/^\[(.*)\]$/)[1]);t=t.replace(m,`(${d}) `).trim()});let a=[")","]"],c=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&a.some(m=>t.endsWith(m))&&c.some(m=>t.includes(m))){let m="",d=t.split(/[)\]]/).filter(Boolean).map(h=>(h.startsWith(",")&&(h=h.slice(1)),h.trim())),l=d.every(h=>h.includes(",")||Jd(h)),f=d.every(h=>h.includes("/")||Jd(h)),g=d.every(h=>h.includes("-")||Jd(h)),I=l&&","||g&&"-"||f&&"/";if(I){let h;d.forEach(S=>{if(S.startsWith("("))if(h==="set"&&(m+=" "),S.includes(I))m+=S.slice(1).split(I).map(T=>T.trim()).join("-"),h="set";else{let T=S.slice(1);m+=`(${T}) `,h="tiebreak"}else if(S.startsWith("[")){let T=S.slice(1).split(I).map(E=>parseInt(E.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=Er(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&Ba(t)&&Jt(e?.removed)&&(t=t+`(${e.removed})`,e.removed=void 0));let p=/\(\)/g;return p.test(t)&&(t=t.replace(p,"").trim()),{score:t}}function YT({score:t}){let e=t.split(""),r=[],n,o=()=>n=[void 0,void 0,void 0],i=()=>{let a=`${n[0]}-${n[1]}`;return n[2]&&(a+=` (${n[2]})`),o(),n.push(n),a};o();let s=()=>n[0]!==void 0&&n[1]!==void 0&&Math.abs(parseInt(n[0])-parseInt(n[1]));for(;e.length;){let a=e.shift(),c=Jt(a)&&parseInt(a),u=n[0]!==void 0&&n[1]!==void 0;if(Jt(c)){if(n[0]===void 0){n[0]=c;continue}if(n[1]===void 0&&(n[1]=c,s())){r.push(i()),n=[void 0,void 0];continue}if(u&&e.length===1&&Jt(e[0])){let p=e.pop();n[0]=n[0].toString()+n[1].toString(),n[1]=p,r.push(i()),n=[void 0,void 0]}u&&s()}}return{sets:r}}function Kg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=em(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=em(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function iN(t){let{score:e}=t,{applied:r,matchUpStatus:n}=t,o=e?.toString().split(""),i=o?.every(a=>Jt(a)),s=a=>Math.abs(a[0]-a[1]);if(typeof e=="number"||i){e=e.toString().toLowerCase(),i&&(e=o.join(""));let a=i?o.map(u=>parseInt(u)):e.split("").map(u=>parseInt(u)),{sets:c}=YT({score:e});if(a.length,e.length===3&&s(a.slice(0,2))===1){let[u,p,m]=a;e=`${u}-${p}(${m})`,r.push("numericTiebreakPattern1")}else if(e.length===3&&a[0]===1){let[u,p,m]=a;e=`[${u}${p}-${m}]`,r.push("numericTiebreakPattern2")}else if(e.length===4&&s(a.slice(0,2))===1&&"987654".split("").includes(a[0].toString())){let[u,p,m,d]=a,l=Math.min(m,d);e=`${u}-${p}(${l})`,r.push("numericTiebreakPattern3")}else if(e.length===4&&a[0]===1&&a[2]===1){let[u,p,m,d]=a;e=`[${u}${p}-${m}${d}]`,r.push("bigSuper")}else if(e.length===4){let[u,p,m,d]=a;e=`${u}${p} ${m}${d}`,r.push("split4")}else if(e.length===5&&s(a.slice(0,2))===1){let[u,p,m,d,l]=a;e=`${u}-${p}(${m}) ${d}-${l}`,r.push("numericTiebreakPattern4")}else if(e.length===5&&s(a.slice(3))===1){let[u,p,m,d,l]=a;e=`${u}-${p} ${m}-${d}(${l})`,r.push("numericTiebreakPattern5")}else if(a.length===7)if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&a[4]===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} [${l}${f}-${g}]`,r.push("numericTiebreakPattern6")}else if(s(a.slice(0,2))===1&&s(a.slice(3,5))>1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p}(${m}) ${d}-${l} ${f}-${g}`,r.push("numericTiebreakPattern7")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))===1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d}(${l}) ${f}-${g}`,r.push("numericTiebreakPattern8")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&s(a.slice(4,6))===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} ${l}-${f}(${g})`,r.push("numericTiebreakPattern9")}else e=e.slice(0,2)+" "+e.slice(2,4)+" "+e.slice(4),r.push("numericMatchTiebreakPattern");else if(e.length%2){let u=Kg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=Ae(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(P=>parseInt(P)),y=Math.abs(S-T),E=S>T?1:2;return y>1&&E||E*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=Er(p),l=p.map(h=>Math.abs(h)),f=Er(l),g=p[0]<0,I=!g&&p[1]<0;if(p[0]>0&&p[1]>0&&p[0]!==p[1])e=[u.slice(0,2).join(" "),u.slice(2).join("-")].join(" "),r.push("numeric3rdSetTiebreakPattern");else if(m)e=u.join(" "),r.push("chunkSplit");else if(a.length===6){if(d[1]===2||d[2]===2)if(!Object.values(f).includes(3))e=u.join(" "),r.push("chunkSplit");else{let[h,S,T,y,E,P]=a,A=p.reduce((U,N,D)=>N<0?D:U,void 0);if(A===0){let U=Math.min(T,y);e=`${h}-${S}(${U}) ${E}-${P}`,r.push("chunkSplitTiebreak1")}else if(A===1){let U=Math.min(E,P);e=`${h}-${S} ${T}-${y}(${U})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${y}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,y,E,P,A,U]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${y}-${E} [${P}${A}-${U}]`:e=`${h}-${S} ${T}-${y}(${E}) [${P}${A}-${U}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function qT(t){let e=[0,0],r=[],n=t.split(" "),o=/(\d+)-(\d+)/;n.forEach(c=>{if(o.test(c)){let u=c.match(o).slice(1).map(m=>parseInt(m)),p=u[0]>u[1]&&1||u[1]>u[0]&&2;p&&(e[p-1]+=1,r.push(p))}});let i=e[0]>e[1]&&1||e[1]>e[0]&&2,s=e[0]>0&&e[0]===e[1],a=e.reduce((c,u)=>c+u,0);return{setsWon:e,setsTied:s,setWinners:r,totalSets:a,winningSide:i}}function C_({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(tm).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!Ba(f)&&!e){let I=Math.max(...g),h=f.indexOf(I),S=[I,I-1];return h&&S.reverse(),S.join("-")+l}}else if(p.length===2&&Jt(p))return p.split("").join("-");p=Yu(p);let d=new RegExp(`^${$g}$`).test(p)&&"super"||new RegExp(`^${tm}$`).test(p)&&"tiebreak"||new RegExp(`^${Xd}$`).test(p)&&"standard"||"unknown";if(n.push(d),s>1&&d==="standard"&&m<2){let[l,f]=p.split("-"),g=Math.abs(parseInt(l)-parseInt(f)),I=Math.max(l,f),h=Math.min(l,f),S=[parseInt(l),parseInt(f)].indexOf(h);if(I>9&&g>2){let T=I.toString().split(""),y=T.find(E=>parseInt(E)>h||m&&parseInt(E)<=o)??T[0];y&&(p=S?[y,h].join("-"):[h,y].join("-"))}I>(o||0)&&(o=I)}if(d==="standard"){let[l,f]=p.split("-");if(!Math.abs(parseInt(l)-parseInt(f))&&e!=="RETIRED")return""}return p}).filter(Boolean).join(" ");let{setsWon:a,setWinners:c,totalSets:u}=qT(t);if(u===1&&r?.removed==="6"&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...a)>=2&&c[0]===c[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...a)>2){let p=[0,0];t=t.split(" ").map((m,d)=>(p[c[d]]+=1,Math.max(...p)>2?void 0:m)).filter(Boolean).join(" ")}return{score:t,profile:n}}function b_({score:t}){let{setsTied:e,winningSide:r}=qT(t),n=/\s\((\d+)\)$/;if(!r&&e&&n.test(t)){let a=t.match(n).slice(1)[0],c=a<=8?10:a+2;t=t.replace(n,` [${c}-${a}]`)}let o=t.split(" "),i=o[o.length-1];if(!i.includes("-")||i.indexOf("(")>0)return{score:t};let s=i.split("(").join("").split(")").join("").split("-");if(!s.every(a=>Jt(a)))return{score:t};if(s[0]==="76"){let a=s[1].length===2?Math.min(...s[1].split("").map(c=>parseInt(c))):s[1];t=[...o.slice(0,o.length-1),`7-6(${a})`].join(" ")}else{s=s.map(u=>parseInt(u));let a=Math.max(...s),c=Math.abs(s[0]-s[1]);if(a>=10){if(c>2&&s.every(u=>+u>=10)){let u=s.map(p=>p===a?p-10:10).sort();c=Math.abs(u[0]-u[1]),c>2&&(s=u)}t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" ")}else o.length===3&&a>=7&&c>2&&(t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" "))}return{score:t}}function wV({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function LV({score:t,applied:e}){return typeof t!="string"?{score:t}:(t.toLowerCase().includes("o")&&(t=t.toLowerCase().split(" ").map(r=>r.split("o").join("0")).join(" "),e.push("replaceOh")),{score:t,applied:e})}function FV({score:t,applied:e}){return typeof t!="string"?{score:t}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length>2){let n=r.indexOf("1");if(r.length%2){if(r.length===3&&n===0){let o=em(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=iN({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function kV({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&Kg(t)?{score:Kg(t)}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length===1){e.push("removeErroneous1");return}return r}).filter(Boolean).join(" "),{score:t,applied:e})}function GV({score:t,applied:e}){return["walkover","wo","w/o","w-o"].includes(t?.toString().toLowerCase())?(e.push("handleWalkover"),{matchUpStatus:"walkover",score:"",applied:e}):{score:t}}function VV({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(ret|con)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleRetired"),{score:a.trim(),matchUpStatus:"retired",applied:r}}let o=e?.matchUpStatuses?.retired,s=["rtd",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleRetired"),{matchUpStatus:"retired",score:t?.replace(s,"").trim(),applied:r}):{score:t}}function BV({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(def|defaulted)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleDefaulted"),{score:a.trim(),matchUpStatus:"defaulted",applied:r}}let o=e?.matchUpStatuses?.defaulted,s=["dft",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleDefaulted"),{matchUpStatus:"defaulted",score:t?.replace(s,"").trim(),applied:r}):{score:t}}function HV({score:t,attributes:e}){(t.endsWith(" am")||t.endsWith(" pm"))&&(t=""),t=t.replace(/[A-Za-z]+/g,"").trim(),[".",","].some(o=>t.endsWith(o))&&(t=t.slice(0,t.length-1));let r="()/-".split("").some(o=>t.includes(o));/ \d$/.test(t)&&r&&(e={removed:t.slice(t.length-2).trim()},t=t.slice(0,t.length-2));let n=/(.*)[A-Za-z]+$/;return n.test(t)&&(t=t.match(n).slice(1)[0].trim()),{score:t,attributes:e}}function WV({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function jV({score:t}){let e=new RegExp(/^\d+\/\d+/),r=t.split(" ");r.some(o=>e.test(o))&&(t=r.map(o=>e.test(o)?o.replace("/","-"):o).join(" "));let n=/^(\d+), *(\d+)$/;if(n.test(t)){let[o,i]=t.match(n).slice(1);t=[o,i].join("-")}return{score:t}}function YV({score:t}){let e=new RegExp(/\(\d+\/\d+\)/g),r=t.match(e);for(let n of r||[]){let o=n.replace("/","-");t=t.replace(n,o)}return{score:t}}function qV({score:t}){if(t.includes(",")){let e=t.split(",").map(o=>o.trim()),r=o=>/\d \d/.test(o);e.every(r)&&(t=e.map(o=>{let i=/\d+ \d+/g;for(let s of o.match(i)){let[a,c]=s.match(/(\d+) (\d+)/).slice(1);o=o.replace(s,`${a}-${c}`)}return o}).join(" "))}if(t.includes(" ")){let e=t.replace(/[ ,]/g,"");e.split("").every(n=>Jt(n))&&e.length===4&&(t=e)}return{score:t}}function $V({score:t}){let e=new RegExp(/^\[\d+\](.*)$/);e.test(t)&&(t=t.match(e).slice(1)[0].trim());let r=/\(,/g;return r.test(t)&&(t=t.replace(r,"(")),{score:t}}var O_={handleTiebreakSlashSeparation:YV,handleSetSlashSeparation:WV,punctuationAdjustments:U_,handleGameSeparation:jV,joinFloatingTiebreak:D_,handleBracketSpacing:P_,handleSpaceSeparator:qV,separateScoreBlocks:FV,matchKnownPatterns:N_,removeDanglingBits:HV,removeErroneous:kV,handleDefaulted:BV,handleWalkover:GV,properTiebreak:M_,handleNumeric:iN,handleRetired:VV,containedSets:R_,sensibleSets:C_,stringScore:wV,superSquare:b_,setBuilder:YT,excisions:$V,replaceOh:LV};var sN={},KV=[],zV=["handleNumeric","handleWalkover","handleRetired","handleDefaulted","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],QV=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function aN(t){if(!t.score)return{error:B};let{score:e,sheetName:r,identifier:n,fileName:o,stepLog:i,fullLog:s,profile:a}=t,c=[],u,p=[],m,d,l=e,f=I=>{I.forEach(h=>{d=O_[h]({profile:a,identifier:n,matchUpStatus:u,attributes:m,applied:p,score:l});let S=d.score!==l;S&&c.push({method:h,score:d.score}),i&&(s||S||d.matchUpStatus!==u)&&console.log(u?{score:d.score,matchUpStatus:u}:{score:d.score},h),d.matchUpStatus&&(u=d.matchUpStatus),d.attributes&&(m=d.attributes),d.applied&&(p=d.applied),l=d.score})};f(zV);let g=nN(l);return g||(l=e.toString().replaceAll(/\D/g,""),m?.removed&&(m.removed=void 0),f(QV),g=nN(l),g||(KV.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{sN[I]||(sN[I]=0),sN[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var mN={};Xt(mN,{analyzeScore:()=>zg,analyzeSet:()=>qu,checkScoreHasValue:()=>he,checkSetIsComplete:()=>Jp,getSetComplement:()=>Xg,getTiebreakComplement:()=>rm,isValidMatchUpFormat:()=>Nr,parseScoreString:()=>nm,validateMatchUpScore:()=>uN,validateScore:()=>Qg,validateSetScore:()=>$T,validateTieFormat:()=>ar});function XV(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 JV(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 ZV(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 t1(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 e1(t,e,r,n,o){if(t<n)return{isValid:!1,error:`Set winner must reach ${n} games, got ${t}`};let i=o&&t===n&&e===o&&r===1;if(r<2&&!i)return{isValid:!1,error:`Set must be won by at least 2 games, got ${t}-${e}`};if(o){if(e>=o&&!i)return{isValid:!1,error:`When tied at ${o}-${o}, must play tiebreak. Use format like ${o+1}-${o}(5)`};let s=o===n?n+1:n;if(t>s)return{isValid:!1,error:`With tiebreak format, set score cannot exceed ${s}-${o}. Got ${t}-${e}`}}else if(t>n+10)return{isValid:!1,error:`Set score ${t}-${e} exceeds reasonable limits`};return{isValid:!0}}function r1(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 n1(t,e,r,n,o,i,s){if(r&&n){let c=JV(t,e,r,n);if(!c.isValid)return c}return(o!==void 0||i!==void 0)&&s?ZV(o,i,s):{isValid:!0}}function o1(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 i1(t,e,r){let{side1:n,side2:o,winner:i,loser:s,diff:a}=t,{setTo:c,tiebreakAt:u}=e;if(c&&u){let p=t1(n,o,c,u);if(!p.isValid)return p}return r?o1(i,s,c):c?e1(i,s,a,c,u):{isValid:!0}}function $T(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 A=t.side1Score??0,U=t.side2Score??0;if(A===0&&U===0)return{isValid:!1,error:"Timed set requires at least one side to have scored"};if(i.based==="P"&&A===U&&A>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,m=!!p&&!s,d=t.side1TiebreakScore!==void 0&&t.side2TiebreakScore!==void 0,{side1Score:l,side2Score:f,side1TiebreakScore:g,side2TiebreakScore:I}=r1(t,m,d),h=Math.max(l,f),S=Math.min(l,f),T=h-S;if(m){let A=t.NoAD??i.tiebreakSet?.NoAD??!1;return XV(h,S,T,p,n??!1,A)}let y=g!==void 0||I!==void 0,E=s&&h===s+1&&S===s;return y||E?n1(h,S,s,a,g,I,c):i1({side1:l,side2:f,winner:h,loser:S,diff:T},{setTo:s,tiebreakAt:a},n)}function uN(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=[Me,Bt,Gt].includes(r||"");for(let s=0;s<t.length;s++){let a=t[s],c=s+1===o,u=a.winningSide!==void 0,d=$T(a,e,c,i||r===void 0&&!u);if(!d.isValid)return{isValid:!1,error:`Set ${s+1}: ${d.error}`}}return{isValid:!0}}function s1(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 a1(t,e,r,n,o,i){let a=e+1===n,{side1Score:c,side2Score:u,side1TiebreakScore:p,side2TiebreakScore:m,winningSide:d}=t,l=Math.max(c??0,u??0),f=p??m,{finalSetFormat:g,setFormat:I}=r,h=a&&g||I;return f&&!s1(h?.tiebreakFormat,p,m,d,o,i)?!1:h.setTo?!(!h.noTiebreak&&l>h.setTo+1):!0}function c1(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 u1(t,e,r,n,o){return(!o||t===e)&&r===1&&n.indexOf(t)+1||void 0}function zg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(U=>U?.winningSide)||[]).reduce((U,N)=>{let{winningSide:D}=N;if(!D)return U;let M=D-1;return U[M]++,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],m=u!==void 0&&a[u],d=e?Ne(e):void 0,l=Math.max(...a),f=Er(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf||d?.exactly,h=I&&Math.ceil(I/2)||1,S=r??t,T=!!(S&&[Gt,Me,Bt].includes(S)),y=!d||!i.length||i.every((U,N)=>a1(U,N,d,I??0,N===i.length-1,T)),E=d?.setFormat?.based==="A"||d?.finalSetFormat?.based==="A",P=E&&i.length>0?c1(i):u1(l,h,f,a,e);return{valid:!!(y&&(n&&E&&n===P||n&&!E&&p>m&&n===P||n&&T||!n&&!P&&(![ge,Gt,Me,Bt].includes(S)||g&&S===ge)))}}function Qg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:B};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:B,info:c};if(a!==void 0&&typeof a!="string")return{error:B,info:c};if(i!==void 0&&!Array.isArray(i))return{error:B,info:li("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(u).length)return{error:B,info:"setNumbers not unique"};for(let m of i){let{side1Score:d,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,side1PointScore:I,side2PointScore:h,winningSide:S,setNumber:T}=m;if(![[d,l],[f,g],[I,h]].filter(P=>P.some(A=>![void 0,null].includes(A))).every(P=>P.every(A=>It(A))))return{error:B,info:"non-numeric values"};if(![T,S].filter(P=>![void 0,null].includes(P)).every(P=>It(P)))return{error:B,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:B,info:"winningSide must be 1 or 2"}}let{valid:p}=zg({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:IA,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Xg=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=dt(r);s?.toString().length>2&&(s=parseInt(s.toString().slice(0,2))),o&&o<n&&s>o&&(s=o);let a;return i&&!o?(s>n&&(a=n),a=s<n?n:n-1):a=s+1<n&&n||o&&o<n&&s===o&&n||!o&&s+2||n+1,[e?s:a,e?a:s]},rm=t=>{let{isSide1:e,lowValue:r,tiebreakTo:n,tiebreakNoAd:o}=t;if(r===void 0)return!1;let i=typeof r=="string"?parseInt(r):r;i?.toString().length>2&&(i=parseInt(i.toString().slice(0,2))),o&&i>n-1&&(i=n-1);let s=p1({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function p1(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function pN(t,e){return t>e&&1||t<e&&2||void 0}function m1(t,e){return e?{side1Score:t[0],side2Score:t[1],winningSide:pN(t[0],t[1])}:{side1TiebreakScore:t[0],side2TiebreakScore:t[1],winningSide:pN(t[0],t[1])}}function nm({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,m)=>u({set:p,setNumber:m+1}));function i(p,m){if(!n||!m)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 d=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;return d?.tiebreakSet?.tiebreakTo??d?.tiebreakFormat?.tiebreakTo??t}function a(p,m,d){let l=p[1],f=s(d),g=rm({lowValue:l,isSide1:m===2,tiebreakTo:f});return Array.isArray(g)?[g[0],g[1]]:[void 0,void 0]}function c(p,m,d,l){let g=(m&&p.replace(m[0],"")||d&&p.replace(d[0],"")||p).split("-").map(E=>Number.parseInt(E)),I=g[0],h=g[1],S=pN(I,h),T,y;if(m&&([T,y]=a(m,S,l)),d){let E=d[1].split("-").map(P=>Number.parseInt(P));T=E[0],y=E[1]}return{side1Score:I,side2Score:h,side1TiebreakScore:T,side2TiebreakScore:y,winningSide:S}}function u({set:p,setNumber:m}){let d=/\(([^)]+)\)/,l=/\[([^\]]+)\]/,f=d.exec(p),g=l.exec(p),I=p?.startsWith("[")&&g,h=i(m,!!I),S=s(m),T=h&&S===1,y;if(I){let E=g[1].split("-").map(P=>Number.parseInt(P));y=m1(E,h)}else y=c(p,f,g,m);return{side1Score:y.side1Score,side2Score:y.side2Score,side1TiebreakScore:y.side1TiebreakScore,side2TiebreakScore:y.side2TiebreakScore,winningSide:y.winningSide,setNumber:m,...T&&{NoAD:!0},...h&&{tiebreakSet:!0}}}}function v_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=Zp({set:o});return Jp({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function qu(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:ef};let{setNumber:n}=e||{},{bestOf:o,exactly:i}=r||{},s=o||i,a=!!(n&&s&&n===s),c=a&&r?.finalSetFormat||r?.setFormat,u=!!c?.tiebreakSet,p=!!c?.timed,m=!u&&!p,d=!!(n&&s&&n<=s),l=[e?.side1Score,e?.side2Score],f=[e?.side1PointScore,e?.side2PointScore],g=[e?.side1TiebreakScore,e?.side2TiebreakScore],I=l.filter(w=>w!==void 0).length,h=f.filter(w=>w!==void 0).length,S=g.filter(w=>w!==void 0).length,T=l?.filter(w=>!isNaN(w)).length,y=g?.filter(w=>!isNaN(w)).length,{tiebreakAt:E}=c||{},P=E&&l.filter(w=>w>=E).length===2,A=P&&(l[0]>l[1]&&1||l[1]>l[0]&&2||void 0),U=!!(y&&!T),N=!!e?.winningSide,{error:D,result:M}=d1({sideTiebreakScores:g,sideGameScores:l,setFormat:c,setObject:e}),{error:R,result:b}=l1({sideTiebreakScores:g,setObject:e,setFormat:c}),O=m&&!U&&M||u&&U&&b||p,v=d&&!(u&&!U)&&!(m&&U)&&(!N||O),x=v_({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:U,setObject:e}),F={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:P,isCompletedSet:N,isDecidingSet:a,isTiebreakSet:U,isValidSet:v,isValidSetNumber:d,isValidSetOutcome:O,leadingSide:A,setFormat:c,sideGameScores:l,sideGameScoresCount:I,sidePointScores:f,sidePointScoresCount:h,sideTiebreakScores:g,sideTiebreakScoresCount:S,winningSide:x};return e?.winningSide!==void 0&&(U?(F.isValidTiebreakSetOutcome=b,b||(F.tiebreakSetError=R)):(F.isValidStandardSetOutcome=M,M||(F.standardSetError=D))),F}function d1({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:ef};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:B};if(!(r?.filter(M=>!isNaN(M)).length===2))return{result:!1,error:KI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(M=>M>=a)))return{result:!1,error:KI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:_m};let l=t?.winningSide-1,f=1-l,g=r[l],I=r[f],h=g-I;if(!(g>I))return{result:!1,error:{message:"winningSide game scoreString is not high"}};let T=c&&u,y=n?.filter(M=>!isNaN(M)).length===2,E=n?.[l],P=n?.[f],A=c&&r.filter(M=>M>=c).length===2;if(T){let{NoAD:M,tiebreakTo:R}=u;if(A){if(h>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!y)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(R))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(R&&n?.find(k=>k>=R)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let v=c<a?a:a+1;if(g>v)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!E||!P||E<P)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let x=M?1:2,F=E-P,w=P>=R-1;if(F&&w&&F<x)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(g>a&&!A)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}let U=p?1:2,N=I>=a-1;return h&&N&&!A&&h<U?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>U&&g>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function l1({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:ef};let n=!!e?.tiebreakSet,o=!!e?.timed;if(!e||!n||o)return{result:!1,error:{message:"not tiebreak set"}};let i=[1,2].includes(t?.winningSide);if(!t||!i)return{result:!1,error:_m};let{tiebreakSet:s}=e||{},{NoAD:a,tiebreakTo:c}=s||{};if(!(r?.filter(T=>!isNaN(T)).length===2))return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(c))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!r?.find(T=>T>=c))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let m=t?.winningSide-1,d=1-m,l=r[m],f=r[d];if(!l||!f||l<f)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let g=a?1:2,I=l-f,h=f>=c-1;return I&&h&&I<g?{result:!1,error:{message:"invalid tiebreak scores (3)"}}:{result:!0}}function __(t){let{existingDrawDefinition:e,hydrateCollections:r,enforceGender:n,tieFormatName:o,matchUpType:i,eventType:s,isMock:a,event:c}=t,{tieFormat:u,matchUpFormat:p}=t;if(i===_e&&s===_e){let m=e?.structures?.find(({stage:d})=>d===rt)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&io({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||io({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=bn));if(u){let m=ar({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function x_(t){let e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:r,appliedPolicies:n,qualifyingOnly:o,drawEntries:i,structureId:s,tieFormat:a,idPrefix:c,isMock:u,event:p}=t,m=t.qualifyingProfiles,d=m?.length?OT({hasExistingDrawDefinition:!0,uuids:t.uuids,qualifyingProfiles:m,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,idPrefix:c,isMock:u}):void 0;if(d?.error)return d;e.structures=e.structures?.filter(({structureId:E})=>E!==r),e.links=e.links?.filter(({source:E})=>E.structureId!==r);let{qualifiersCount:l,qualifyingDrawPositionsCount:f,qualifyingDetails:g}=d??{};f&&(d?.structures&&e.structures?.push(...d.structures),d?.links&&e.links?.push(...d.links));let I=e.structures?.find(({stage:E,stageSequence:P})=>E===rt&&P===1),{qualifiersCount:h}=Us({stageSequence:1,drawDefinition:e,structureId:s,stage:rt}),S=Math.max(l??0,h??0),T=$S({qualifiersCount:S,drawDefinition:e,stage:rt});if(T.error||(T=Hp({drawSize:f,stage:ct,drawDefinition:e}),T.error))return T;f1({drawDefinition:e,drawEntries:i,event:p});let y=g1({mainStructure:I,qualifyingDetails:g,drawDefinition:e});return y.error?y:{drawDefinition:e,structureId:s}}function f1({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===ct)){let o={...n,entryStage:n.entryStage??rt,drawDefinition:t,event:r};Pd(o)}}function g1({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=[]),r.links.push(u))}return{error:void 0}}function KT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Xr.includes(o)}).map(St)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return _({result:{error:ln},info:{invalidParticipantIds:n}})}else e=r;return t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>e.length-1&&(!t.enableDoubleRobin||t.roundsCount>(e.length-1)*2)?{error:B,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:B,info:"roundsCount must be less than 32"}:{participantIds:e}}function Zd(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=KT(t);if(p.error)return p;for(let m of tt(1,r+1)){let d=Wu({restrictMatchUpsCount:t.restrictMatchUpsCount,ignoreLastRoundNumber:!!u,newRound:!u,drawDefinition:n,matchUpsCount:o,structureId:i,roundNumber:u,idPrefix:s,isMock:a,event:c});if(d.error)return _({result:d,info:{iteration:m}});d.matchUps?.length&&e.push(...d.matchUps),u=(d?.roundNumber??1)+1}return{matchUps:e}}function L_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??je[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=w_({scaleName:`${n}.${Qm}`,participant:u,eventType:o});!p&&n&&(p=w_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function w_({scaleType:t=Ui,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Po({scaleAttributes:{eventType:o??qs,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&ht(a)?a[e]:a}function tl(t){let e=h1(t);if(e?.error)return e;let r=KT(t);if(r.error)return r;let n=I1(t);if(n.error)return n;let o=L_(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of tt(1,(t.roundsCount??1)+1)){let m=qd({...t,participantIds:r.participantIds,structure:n.structure,ignoreLastRoundNumber:!0,iterationMatchUps:a,adHocRatings:o,roundNumber:u,eventType:s,isMock:i});if(m.error)return m;let{matchUps:d,...l}=m;l.modifiedScaleValues&&(o=l.modifiedScaleValues),c.push({...l,iteration:p,matchUpsCount:d?.length}),u=(l?.roundNumber??1)+1,d?.length&&a.push(...d)}return{...C,matchUps:a,roundResults:c}}function I1(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&&$s[s.stage];return cr({structure:s})&&a>($s[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?cr({structure:n})?{structure:n}:{error:Sa}:{error:_t}}function h1(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:B,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==Fr?{error:Sa}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:B,info:"Missing Entries"}:{error:void 0}}function F_(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,idPrefix:o,isMock:i,event:s}=t,a=s?.entries?.filter(({entryStage:p,entryStatus:m})=>(!p||p===rt)&&m&&Xr.includes(m)),c=a?.map(St),u=a?Math.floor(a.length/2):0;if(t.automated)return S1({...t,participantIds:c});{let p=Zd({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&Gd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...C}}function S1(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=tl({...t,eventType:t.drawMatic?.eventType??t.matchUpType,generateMatchUps:r??!0,scaleAccessor:s??t.scaleAccessor,scaleName:i??t.scaleName,participantIds:t.participantIds,roundsCount:t.roundsCount,restrictEntryStatus:e,structureId:n,matchUpIds:o});return a.error?a:(a?.matchUps?.length&&Gd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...C})}function k_({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:r,participantsCount:n,participantCount:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,seedsCount:u}){n=n??o;let p=at({drawDefinition:s,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:_t};let{positionAssignments:d}=Ie({structure:m}),l=d?.length||0;if(u>l)return{error:$E};let f=m.structures?.length,g=It(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=Dg({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=Hu({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[Vn]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=tt(1,u+1).map(S=>{let T=I?.find(P=>P.includes(S)),y=T&&Math.min(...T),E=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:E}}),bt({drawDefinition:s,structureIds:[c]}),{...C,seedLimit:u}}function ca({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:q};return i=i??s?.entries??[],{scaledEntries:i.filter(d=>(!a||!d.entryStage||d.entryStage===a)&&(!o||!d.entryStageSequence||d.entryStageSequence===o)&&Xr.includes(d.entryStatus)).map(d=>{let{participantId:l}=d,{scaleItem:f}=wc({tournamentRecord:e,scaleAttributes:r,participantId:l});return{...d,...f}}).filter(d=>{let l=d.scaleValue;return!n&&(isNaN(l)||!parseFloat(l))?!1:l}).sort(n||p)};function p(d,l){return t?m(l)-m(d):m(d)-m(l)}function m(d){return parseFloat(d.scaleValue||(t?-1:1e5))}}function zT(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 _({result:{error:_t},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=N1({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&E1({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==Fr&&!(t.qualifyingOnly&&t.stage!==ct),m=(n?.length||0)>1,d=p?y1({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function T1({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=mt({name:vn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&mi.includes(o.entryStatus)})}function y1(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Mc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function E1(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(St);e?A1({...t,enteredParticipantIds:i}):(o||r)&&U1({...t,enteredParticipantIds:i})}function A1(t){let{provisionalPositioning:e,enteredParticipantIds:r,seededParticipants:n,tournamentRecord:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,structure:u,event:p}=t,m=u?Ns({provisionalPositioning:e,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structure:u}):void 0;n.filter(({participantId:d})=>r.includes(d)).filter(d=>!d.seedNumber||d.seedNumber<=n.length).sort((d,l)=>d.seedNumber<l.seedNumber?-1:d.seedNumber<l.seedNumber?1:0).forEach(d=>{let{participantId:l,seedNumber:f,seedValue:g}=d;ra({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function U1(t){let e=t.seedsCount,{provisionalPositioning:r,enteredParticipantIds:n,seedAssignmentProfile:o,assignSeedsCount:i,tournamentRecord:s,drawDefinition:a,seedByRanking:c,seedingProfile:u,structureId:p,event:m}=t,{categoryName:d,ageCategoryCode:l}=m?.category||{},f=m?.eventType,g=P1({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&D1({...t,ageCategoryCode:l,categoryName:d,eventType:f}),I=g?.length??0;I<e&&(e=I),g?.filter(({participantId:h})=>n.includes(h)).slice(0,i||e).forEach((h,S)=>{let T=S+1,{participantId:y,scaleValue:E}=h,P=o?.[T]||E||T;ra({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:P,event:m})})}function P1(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:Ao,eventType:u};return ca({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function D1(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ca({scaleAttributes:{scaleName:s||a,scaleType:Ai,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function N1(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=T1(t);e>r.length&&(e=r.length);let{seedLimit:n}=k_({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 G_(t){let e=jd({...t,modifyOriginal:!1});if(e.error)return e;let r=e.drawDefinition,{suppressDuplicateEntries:n=!0,ignoreStageSpace:o,appliedPolicies:i,qualifyingOnly:s,seedingProfile:a,participants:c,drawEntries:u,placeByes:p,drawSize:m,drawType:d,entries:l}=t,f=[],g=[],I=M1({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===Ki?0:dt(t.seedsCount??0),S=zT({...t,qualifyingOnly:!m||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:rt,seedsCount:h,placeByes:p,drawSize:m,entries:l});if(S.error&&!S.conflicts)return S;S.positioningReport?.length&&f.push({[rt]:S.positioningReport});let T=S.structureId;return S.conflicts&&(g=S.conflicts),d===Fr&&t.roundsCount&&F_({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function M1(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,entries:i}=t;for(let s of i){if(n&&s.entryStage&&s.entryStage!==rt)continue;let a={...s,ignoreStageSpace:e??o===Fr,entryStage:s.entryStage??rt,event:t.event,drawDefinition:r,drawType:o},c=Pd(a);if(n&&c.error)return c}return{error:void 0}}var R1=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var V_=R1;function B_(t){let{drawId:e=Nt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=V_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function el(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=et(t,[{[Ce]:!0,[$m]:!0}]);if(c.error)return c;if(!Nr({matchUpFormat:o}))return{error:tc};let u="setMatchUpFormat";if(s){let p=Vt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===_e)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:dr};m&&(m.matchUpFormat=o,gt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===_e)return{error:$n};for(let p of e){let m=at({drawDefinition:n,structureId:p});if(m.error)return m;m.structure&&(m.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===_e)return{error:$n};let p=at({drawDefinition:n,structureId:i});if(p.error)return p;p.structure&&(p.structure.matchUpFormat=o)}else n&&(n.matchUpFormat=o);return e=e??(i?[i]:void 0),bt({drawDefinition:n,structureIds:e}),{...C}}function H_({tieFormat:t}){let e=ar({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Nt());return{tieFormat:t}}function W_({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=H_({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=el({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 gN={};Xt(gN,{attachPolicies:()=>ss,findPolicy:()=>pi,getAppliedPolicies:()=>Tt,getPolicyDefinitions:()=>Go,mutate:()=>lN,query:()=>fN,removePolicy:()=>dN});var lN={};Xt(lN,{attachPolicies:()=>ss,removePolicy:()=>dN});function dN(t){let e=et(t,[{[fb]:!0,_anyOf:{[Re]:!1,[ne]:!1,[Ce]:!1,[co]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return j_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:q};for(let i of o){let s=t.tournamentRecords[i],a=j_(t,s);if(a.error)return a;r=!0}}else return{error:q};return r?{...C}:{error:qc}}function j_(t,e){let r=Tt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?At({element:e,extension:{name:du,value:r}}):Ir({element:e,name:du}),{...C}):{error:qc}}var fN={};Xt(fN,{findPolicy:()=>pi,getAppliedPolicies:()=>Tt,getPolicyDefinitions:()=>Go});var IN={[Vn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Eo]:{positioning:Ti},[On]:{positioning:Ti}},positioning:ab},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}]}},Zg=IN;function Y_({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:B},stack:n});let o={[mu]:t?.[mu]};return e?C1({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&ss({drawDefinition:r,policyDefinitions:o}),!t?.[Vn]&&!e?.[Vn]&&(ss({policyDefinitions:Zg,drawDefinition:r}),t&&Object.assign(t,Zg)),{error:void 0}}function C1({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&&(ss({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function q_(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,m=p?.structures?.find(h=>h.stage===rt&&h.stageSequence===1)?.structureId,d=p?p.structures?.filter(h=>h.stage===ct):[],l=d?.length===1&&!d[0].matchUps?.length&&d[0].structureId;p&&a!==p.drawType&&(p.drawType=a);let f=p??B_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),g=W_({existingQualifyingStructures:d,tournamentRecord:e,drawDefinition:f,matchUpFormat:o,matchUpType:i,tieFormat:s,event:u});if(g.error)return _({result:g,stack:c});let I=Y_({appliedPolicies:n,policyDefinitions:r,drawDefinition:f,stack:c});return I.error?I:{drawDefinition:f,structureId:m,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:l}}function $_(t){let e="generateOrGetExisting",r=[],n=[],o=q_(t);if(o.error)return _({result:o,stack:e});let i=o.existingDrawDefinition,s=o.drawDefinition??{},a=o.structureId,c=t.drawEntries??t.eventEntries??[],u=o.existingQualifyingPlaceholderStructureId&&x_({...t,...o})||G_({...t,...o,entries:c});return u.error?_({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 K_(t){let{qualifyingPlaceholder:e,existingDrawDefinition:r,positioningReports:n,qualifyingProfiles:o,appliedPolicies:i,qualifyingOnly:s,drawDefinition:a,seedingProfile:c,participants:u,structureId:p,tieFormat:m,entries:d,stack:l}=t,f=e&&!o?.length&&!r,g=[];if(o){let I=(y,E)=>y.stageSequence-E.stageSequence,h=(y,E)=>y.roundTarget-E.roundTarget,S=[],T=1;o.sort(h);for(let y of o){if(!Array.isArray(y.structureProfiles))return _({info:li("structureProfiles"),result:{error:st},stack:l});T=y.roundTarget||T;let E=y.structureProfiles?.sort(I)||[],P=1;for(let A of E){let{qualifyingRoundNumber:U,qualifyingPositions:N,seededParticipants:D,seedingScaleName:M,seedsCount:R=0,seedByRanking:b,placeByes:O,drawSize:v}=A,x=zT({...t,seedingProfile:A.seedingProfile??c,stageSequence:P,qualifyingRoundNumber:U,preparedStructureIds:S,qualifyingPositions:N,seededParticipants:D,stage:ct,seedingScaleName:M,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:b,participants:u,roundTarget:T,seedsCount:R,placeByes:O,drawSize:v,entries:d});if(x.error)return x;x.structureId&&S.push(x.structureId),P+=1,x.conflicts?.length&&g.push(...x.conflicts),x.positioningReport?.length&&n.push({[ct]:x.positioningReport})}T+=1}}else if(p&&f){let I=yn({structureName:Qe(ct),stage:ct,qualifyingOnly:s,tieFormat:m}),{link:h}=La({sourceStructureId:I.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:Fn});a.structures||(a.structures=[]),a.structures.push(I),a.links||(a.links=[]),a.links.push(h)}return{qualifyingConflicts:g,error:void 0}}var FN={};Xt(FN,{addGoesTo:()=>rs,allCompetitionMatchUps:()=>Mn,allDrawMatchUps:()=>nr,allEventMatchUps:()=>to,allPlayoffPositionsFilled:()=>WS,allTournamentMatchUps:()=>ye,analyzeDraws:()=>Vu,analyzeMatchUp:()=>cm,analyzeTournament:()=>sy,bulkUpdatePublishedEventIds:()=>cy,calculateWinCriteria:()=>Os,categoryCanContain:()=>tu,checkMatchUpIsComplete:()=>Ts,checkValidEntries:()=>Hd,compareTieFormats:()=>ni,competitionScheduleMatchUps:()=>Ku,courtGridRows:()=>dl,credits:()=>z_,drawMatchUps:()=>Dy,eventMatchUps:()=>Il,filterMatchUps:()=>_i,filterParticipants:()=>bu,findDrawDefinition:()=>gT,findExtension:()=>mt,findVenue:()=>ti,getAggregateTeamResults:()=>iy,getAllDrawMatchUps:()=>ie,getAllEventData:()=>uy,getAllStructureMatchUps:()=>yt,getAllowedDrawTypes:()=>rl,getAllowedMatchUpFormats:()=>ey,getAppliedPolicies:()=>Tt,getAssignedParticipantIds:()=>wi,getAvailableMatchUpsCount:()=>Vd,getAvailablePlayoffProfiles:()=>Lu,getCategoryAgeDetails:()=>Ys,getCheckedInParticipantIds:()=>Is,getCompetitionDateRange:()=>ol,getCompetitionMatchUps:()=>am,getCompetitionParticipants:()=>QT,getCompetitionPenalties:()=>ry,getCompetitionVenues:()=>om,getCourtInfo:()=>Td,getCourts:()=>Ny,getDrawData:()=>cl,getDrawDefinitionTimeItem:()=>iS,getDrawParticipantRepresentativeIds:()=>lT,getDrawStructures:()=>hn,getDrawTypeCoercion:()=>Bu,getEligibleVoluntaryConsolationParticipants:()=>dT,getEntriesAndSeedsCount:()=>ll,getEvent:()=>Cy,getEventData:()=>ul,getEventMatchUpFormatTiming:()=>Iy,getEventProperties:()=>My,getEventPublishStatus:()=>Jr,getEventStructures:()=>Mg,getEventTimeItem:()=>Au,getEvents:()=>Ry,getFlightProfile:()=>Ht,getHomeParticipantId:()=>yy,getLinkedTournamentIds:()=>fu,getMatchUpCompetitiveProfile:()=>Du,getMatchUpContextIds:()=>Ey,getMatchUpDailyLimits:()=>Sl,getMatchUpDailyLimitsUpdate:()=>hy,getMatchUpDependencies:()=>an,getMatchUpFormat:()=>Ay,getMatchUpFormatTiming:()=>Nu,getMatchUpFormatTimingUpdate:()=>fy,getMatchUpScheduleDetails:()=>yd,getMatchUpType:()=>Ed,getMatchUpsMap:()=>Pe,getMatchUpsStats:()=>Uy,getMatchUpsToSchedule:()=>pl,getMaxEntryPosition:()=>dy,getModifiedMatchUpFormatTiming:()=>fl,getPairedParticipant:()=>Sn,getParticipantEventDetails:()=>XT,getParticipantIdFinishingPositions:()=>fT,getParticipantMembership:()=>JT,getParticipantResults:()=>ku,getParticipantScaleItem:()=>wc,getParticipantSchedules:()=>ZT,getParticipantSignInStatus:()=>ty,getParticipantTimeItem:()=>sS,getParticipants:()=>Ft,getPersonRequests:()=>ki,getPolicyDefinitions:()=>Go,getPositionAssignments:()=>zp,getPositionsPlayedOff:()=>Cc,getPredictiveAccuracy:()=>Ty,getProfileRounds:()=>ml,getPublishState:()=>As,getRandomQualifierList:()=>RT,getRoundMatchUps:()=>Ke,getRounds:()=>Py,getScaleValues:()=>Aa,getScaledEntries:()=>ca,getScheduledRoundsDetails:()=>$u,getSchedulingProfile:()=>oi,getSchedulingProfileIssues:()=>my,getSeedingThresholds:()=>_S,getSeedsCount:()=>Hu,getStructureSeedAssignments:()=>sn,getTeamLineUp:()=>Ss,getTieFormat:()=>al,getTimeItem:()=>nn,getTournamentIds:()=>Np,getTournamentInfo:()=>bs,getTournamentPenalties:()=>nl,getTournamentPersons:()=>oy,getTournamentPoints:()=>il,getTournamentPublishStatus:()=>Ru,getTournamentStructures:()=>HS,getTournamentTimeItem:()=>cd,getValidGroupSizes:()=>Gp,getVenueData:()=>Ac,getVenuesAndCourts:()=>Ro,isAdHoc:()=>cr,isCompletedStructure:()=>Do,isValidForQualifying:()=>CT,isValidMatchUpFormat:()=>Nr,matchUpActions:()=>Bd,participantScaleItem:()=>Po,participantScheduledMatchUps:()=>Sy,positionActions:()=>MT,publicFindCourt:()=>PS,publicFindVenue:()=>US,tallyParticipantResults:()=>Fa,tieFormatGenderValidityCheck:()=>km,tournamentMatchUps:()=>hl,validMatchUp:()=>pg,validMatchUps:()=>Br,validateCollectionDefinition:()=>eu,validateLineUp:()=>Cd});function z_(){return`
|
|
5
5
|
This project would not have been possible without the generous input and patience
|
|
6
6
|
of tournament organizers and directors who worked with early versions of CourtHive/TMX.
|
|
7
7
|
|
|
@@ -23,5 +23,5 @@ var yL=Object.defineProperty;var Xt=(t,e)=>{for(var r in e)yL(t,r,{get:e[r],enum
|
|
|
23
23
|
`}var hN={};Xt(hN,{filterParticipants:()=>bu,getCompetitionParticipants:()=>QT,getPairedParticipant:()=>Sn,getParticipantEventDetails:()=>XT,getParticipantMembership:()=>JT,getParticipantScaleItem:()=>wc,getParticipantSchedules:()=>ZT,getParticipantSignInStatus:()=>ty,getParticipantTimeItem:()=>sS,getParticipants:()=>Ft,getScaleValues:()=>Aa,participantScaleItem:()=>Po,validateLineUp:()=>Cd});function QT(t){let{tournamentRecords:e}=t||{};if(typeof e!="object"||!Object.keys(e).length)return{error:xt};let r=[],n={},o={},i={},s=[],a={},c=[];for(let u of Object.values(e)){let{participantIdsWithConflicts:p,mappedMatchUps:m,participantMap:d,participants:l,matchUps:f,derivedEventInfo:g,derivedDrawInfo:I}=Ft({...t,tournamentRecord:u});Object.assign(a,m),Object.assign(n,d),Object.assign(o,g),Object.assign(i,I),r.push(...l??[]),s.push(...f??[]),p?.forEach(h=>{c.includes(h)||c.push(h)})}return{participantIdsWithConflicts:c,derivedEventInfo:o,derivedDrawInfo:i,participantMap:n,mappedMatchUps:a,participants:r,...C,matchUps:s}}function XT({tournamentRecord:t,participantId:e}){if(!t)return{error:q};if(!e)return{error:se};let r=[e].concat((t.participants??[]).filter(o=>o?.participantType&&[wt,ft].includes(o.participantType)&&o.individualParticipantIds?.includes(e)).map(o=>o.participantId));return{eventDetails:(t.events??[]).filter(o=>{let i=(o?.entries??[]).map(s=>s.participantId);return ke(i,r)}).map(o=>({eventName:o.eventName,eventId:o.eventId}))}}function JT({tournamentRecord:t,participantId:e}){if(!t)return{error:q};if(!e)return{error:se};let{participants:r}=Ft({participantFilters:{participantTypes:[wt,ft,Qr]},tournamentRecord:t});return(r??[]).filter(o=>o.individualParticipantIds?.includes(e)).reduce((o,i)=>{let s=i.participantType;return s&&(o[s]||(o[s]=[]),o[s].push(i)),o},{})}function ZT({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:q};if(typeof t!="object")return{error:So,context:{participantFilters:t}};let r={eventIds:t.eventIds},n=ye({tournamentRecord:e,contextFilters:r}).matchUps??[],o=Object.assign({},...n.map(p=>({[p.matchUpId]:p}))),i=n.filter(({schedule:p})=>p&&Object.keys(p).length),s=an({tournamentRecord:e,matchUps:n}).sourceMatchUpIds??[],a={};for(let p of i){let{sides:m}=p,d,l=m?.map(g=>{if(g.participant)return[g.participant].concat(...g.participant.individualParticipants||[]);s[p.matchUpId]&&!d&&(d=(s[p.matchUpId]||[]).map(I=>o[I]).filter(({winningSide:I,bye:h})=>!I&&!h))}).filter(Boolean).flat()??[];for(let g of l){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].matchUps.push(p)}let f=d?.map(({sides:g})=>g).flat().map(({participant:g})=>g&&[g].concat(...g.individualParticipants||[])).filter(Boolean).flat()||[];for(let g of f){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].potentialMatchUps.push(p)}}return{participantSchedules:Object.values(a).filter(({participant:p})=>!(t.participantIds&&!t.participantIds.includes(p.participantId)||t.participantTypes&&!t.participantTypes.includes(p.participantType))),...C}}function ty({tournamentRecord:t,participantId:e}){if(!t)return{error:q};if(!e)return{error:se};let{participant:r}=Uo({tournamentRecord:t,participantId:e});if(!r)return{error:re};let{timeItem:n}=nn({itemType:Ic,element:r});return n&&n.itemValue===Tu&&Tu}var TN={};Xt(TN,{analyzeDraws:()=>Vu,analyzeTournament:()=>sy,getAggregateTeamResults:()=>iy,getAllowedDrawTypes:()=>rl,getAllowedMatchUpFormats:()=>ey,getAppliedPolicies:()=>Tt,getCompetitionDateRange:()=>ol,getCompetitionPenalties:()=>ry,getPolicyDefinitions:()=>Go,getTournamentInfo:()=>bs,getTournamentPenalties:()=>nl,getTournamentPersons:()=>oy,getTournamentPoints:()=>il,getTournamentStructures:()=>HS,getTournamentTimeItem:()=>cd});function ey({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:q};let{appliedPolicies:n}=Tt({tournamentRecord:t});return(n?.[rn]?.matchUpFormats||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function rl({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:q};let{appliedPolicies:n}=Tt({tournamentRecord:t});return(n?.[Xm]?.allowedDrawTypes||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function nl({tournamentRecord:t}){if(!t)return{error:q};let r=(t?.participants??[]).reduce((n,o)=>{let{participantId:i}=o;return(o.penalties??[]).forEach(s=>{let{penaltyId:a}=s||{};n[a]?n[a].participants.push(i):n[a]={...s,participantIds:[i]}}),n},{});return{penalties:Object.values(r)}}function ry({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let e=[];for(let r of Object.values(t)){let{penalties:n}=nl({tournamentRecord:r});e.push(...n??[])}return{penalties:e}}function ny({event:t}){return{eventInfo:(({eventId:r,eventName:n,eventType:o,eventLevel:i,surfaceCategory:s,matchUpFormat:a,category:c,gender:u,startDate:p,endDate:m,ballType:d,discipline:l,onlineResources:f,notes:g})=>({eventId:r,eventName:n,eventType:o,eventLevel:i,surfaceCategory:s,matchUpFormat:a,category:c,gender:u,startDate:p,endDate:m,ballType:d,discipline:l,onlineResources:f,notes:g}))(t)}}var b1={[zs]:{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}}}},Q_=b1;function bs(t){let{tournamentRecord:e}=t??{};if(!e)return{error:q};let r=(({tournamentId:c,tournamentRank:u,tournamentStatus:p,formalName:m,tournamentName:d,promotionalName:l,onlineResources:f,localTimeZone:g,activeDates:I,startDate:h,endDate:S,hostCountryCode:T,venues:y,notes:E,updatedAt:P})=>({tournamentId:c,tournamentRank:u,tournamentStatus:p,formalName:m,tournamentName:d,promotionalName:l,onlineResources:f,localTimeZone:g,activeDates:I,startDate:h,endDate:S,hostCountryCode:T,venues:y,notes:E,updatedAt:P}))(e),o=Ft({participantFilters:{participantRoles:[hP,Sg,SP,TP,EP]},policyDefinitions:Q_,tournamentRecord:e})?.participants??[];o&&(r.tournamentContacts=o);let i=As({tournamentRecord:e})?.publishState,s=i?.tournament?.status?.publishedEventIds||[],a=[];for(let c of e.events??[])if(!t?.usePublishState||s.includes(c.eventId)){let u=ny({event:c}).eventInfo;u&&a.push(u)}return r.timeItemValues=pT({element:e}),r.publishState=i?.tournament,r.eventInfo=a,{tournamentInfo:J(nt(r),!1,!0),...C}}function ol({tournamentRecords:t}){if(!ht(t))return{error:xt};let r=Object.keys(t??{}).reduce((i,s)=>{let a=t[s],{tournamentInfo:{startDate:c,endDate:u}}=bs({tournamentRecord:a}),p=c&&new Date(Ut(c));(!i.startDate||p&&p<i.startDate)&&(i.startDate=p);let m=u&&new Date(Ut(u));return(!i.endDate||m&&m>i.endDate)&&(i.endDate=m),i},{startDate:void 0,endDate:void 0}),n=r.startDate&&Ut(r.startDate.toISOString()),o=r.endDate&&Ut(r.endDate.toISOString());return!n||!o?{error:dA}:{startDate:n,endDate:o}}function oy({tournamentRecord:t,participantFilters:e}){if(!t)return{error:q};let r=t.participants||[];e&&(r=bu({participants:r,participantFilters:e,tournamentRecord:t}));let n={},o=i=>{if(i.person){let{personId:s}=i.person;n[s]?n[s].participantIds.push(i.participantId):n[s]={...i.person,participantIds:[i.participantId]}}};return r.forEach(i=>{i.person&&o(i)}),{tournamentPersons:Object.values(n)}}function iy(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let r=t.finishingPositionRangeBounsPoints||{},n={},o=m=>{let d=m?.individualParticipants?.map(l=>l.teams?.length===1&&l.teams[0]);return m?.teams?.length===1&&m?.teams?.[0]||d?.[0].participantId===d?.[1].participantId&&d?.[0]},{matchUps:i,participants:s}=Ft({participantFilters:{participantTypes:[Et]},withRankingProfile:!0,withStatistics:!0,...t});for(let m of s??[]){if(m.participantType===Ar)continue;m.draws?.[0]?.drawId==="draw-0-3"&&console.log(m.participantType,m.draws[0].finishingPositionRange);let d=o(m);if(d)for(let l of m?.draws??[]){let f=l?.finishingPositionRange?.join("-");if(f&&r?.[f]){let g=d?.participantId,I=l?.drawId,h=`${g}|${I}|${f}`;n[h]=r[f]}}}let a=m=>({teamName:m,standingPoints:0,pointsPlayed:0,pointsPct:0,points:0,bonus:0,diff:0,loss:0,win:0}),c=(m,d,l)=>{m[d]===void 0&&(m[d]=0),m[d]+=l},u={},p={};for(let m of i??[]){let{sides:d,matchUpFormat:l}=m,f=l&&Ne(l);if(d?.length===2&&f.setFormat?.timed&&(!f.finalSetFormat||f.finalSetFormat?.timed))for(let g of d){let I=o(g.participant),h=I?.participantId,S=g.participant?.participantId,T=I?.participantName,y=g.sideNumber,E=g.participant?.individualParticipantIds||S&&[S]||[];if(E.forEach(P=>{P&&!u[P]&&(u[P]=a(T))}),h&&y){p[h]||(p[h]=a(T));let P=[...E.map(U=>u[U]),p[h]];m.winningSide&&(y===m.winningSide?P.forEach(U=>c(U,"win",1)):P.forEach(U=>c(U,"loss",1)));let A=m.score?.sets||[];for(let U of A){let N=U?.[`side${3-y}Score`]||0,D=U?.[`side${y}Score`]||0,M=D-N;P.forEach(R=>c(R,"pointsPlayed",D+N)),P.forEach(R=>c(R,"points",D)),P.forEach(R=>c(R,"diff",M))}}}}for(let m of Object.keys(n)){let[d]=m.split("|");p[d]&&(p[d].bonus+=n[m],p[d].pointsPct=parseFloat((p[d].points/p[d].pointsPlayed).toFixed(2)),p[d].standingPoints=p[d].win+p[d].bonus)}for(let m of Object.keys(u))u[m].pointsPct=parseFloat((u[m].points/u[m].pointsPlayed).toFixed(2));return{...C,individualResults:u,teamResults:p}}function X_(t){let r=t.participants?.filter(({participantType:a})=>a===wt)?.length===2,n=t.events?.length===1&&t.events[0],o=n?.drawDefinitions?.length===1&&n.drawDefinitions[0],s=(o?.structures?.length===1&&o.structures[0])?.positionAssignments?.length===2;return!!(n.tieFormat&&r&&s)}function sy({tournamentRecord:t}){if(!t)return{error:q};let{drawsAnalysis:e}=Vu({tournamentRecord:t}),r={isDual:X_(t),drawsAnalysis:e},n=Ft({tournamentRecord:t});return n.missingParticipantIds?.length&&(r.missingParticipantIds=n.missingParticipantIds),{...C,analysis:r}}function ay(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||typeof e=="object"&&e[t]}function J_(t){let{participation:e={},awardProfiles:r,startDate:n,eventType:o,drawSize:i,drawType:s,category:a,endDate:c,level:u}=t,{participationOrder:p,flightNumber:m,rankingStage:d}=e,l=g=>!n&&!c||!g.dateRanges?!0:g.dateRanges.some(I=>{let h=!n||!I.startDate||new Date(n)>new Date(I.startDate),S=!c||!I.endDate||new Date(c)<=new Date(I.endDate);return h&&S});return{awardProfile:r.find(g=>l(g)&&(!g.maxFlightNumber||m<=g.maxFlightNumber)&&(!g.drawTypes?.length||g.drawTypes?.includes(s))&&(!g.drawSizes?.length||g.drawSizes.includes(i))&&(!g.stages?.length||g.stages.includes(d))&&(!g.levels?.length||g.levels.includes(u))&&(!g.maxDrawSize||i<=g.maxDrawSize)&&(!g.drawSize||g.drawSize===i)&&(!g.maxLevel||u<=g.maxLevel)&&(!m||!g.flights?.flightNumbers?.length||g.flights.flightNumbers.includes(m))&&(!g.participationOrder||g.participationOrder===p)&&(!g.category?.ageCategoryCodes||g.category.ageCategoryCodes.includes(a?.ageCategoryCode))&&(!g.eventTypes?.length||g.eventTypes?.includes(o)))}}function SN({participantWon:t,flightNumber:e,valueObj:r,drawSize:n,flights:o,level:i}){let s=(f,g)=>{if(f){if(Array.isArray(g)){let I=g.find(h=>h.flight===f||h.f===f);return I.value||I.v}if(typeof g=="object"){let I=g.flights||g.f;if(Array.isArray(I))return I[f-1]}}},a=(f,g)=>{let I=f?.value||f?.v||(It(f)?f:0),h=ay(i,f?.level);return{value:s(g,h)||It(h)&&h||I}},c=0,u,p,m,d,l=t&&"won"||t===!1&&"lost"||void 0;if(Array.isArray(r)){let f=r.find(h=>h.drawSize===n||h.drawSizes?.includes(n)),g=r.find(h=>h.drawSize&&h.threshold&&n>h.drawSize),I=r.find(h=>!h.drawSize&&!h.drawSizes?.length);l!==void 0&&(f=f?.[l],g=g?.[l],I=I?.[l]),p=a(f,e).value,m=a(g,e).value,d=a(I,e).value,c=p||m||d,u=p&&f.requireWin||m&&g.requireWin||I?.requireWin}else if(typeof r=="object"){let f=r?.drawSizes?.[n],g=r;l!==void 0&&(f=f?.[l],g=g?.[l]),p=a(f,e).value,d=a(g,e).value,c=p||d,u=p?f.requireWin:g?.requireWin}else It(r)&&l===void 0&&(c=r);return e&&o?.pct?.[e]&&(c=Math.round(c*o.pct[e])),{awardPoints:c,requireWin:u}}function il({participantFilters:t,policyDefinitions:e,tournamentRecord:r,level:n}){if(!r)return{error:q};let{policyDefinitions:o}=Go({policyTypes:[Gf],tournamentRecord:r}),i=e?.[Gf]??o?.[Gf];if(!i)return{error:op};let s=i.awardProfiles,a=i.requireWinFirstRound,c=i.requireWinForPoints,{participants:u,derivedEventInfo:p,derivedDrawInfo:m,mappedMatchUps:d}=Ft({withRankingProfile:!0,participantFilters:t,tournamentRecord:r}),l=u?.filter(h=>h.draws?.length),f={},g={},I={};for(let h of l??[]){let{participantType:S,participantId:T,person:y,draws:E}=h;for(let P of E){let{drawId:A,structureParticipation:U,eventId:N}=P,D=p[N],M=m[A],R=M?.drawType,{category:b,eventType:O}=D||{},v=P.startDate||D.startDate||r.startDate,x=P.endDate||D.endDate||r.endDate;if(O===Or&&T!==Ar)continue;let F;if(s){let w=c,L=0,k=0,G=0,H;for(let K of U){let{finishingPositionRange:Y,participationOrder:j,participantWon:V,flightNumber:$,rankingStage:X,winCount:W}=K;L+=W||0;let it=M?.drawSize,{awardProfile:z}=J_({awardProfiles:s,participation:K,eventType:O,startDate:v,category:b,drawSize:it,drawType:R,endDate:x,level:n});if(z){if(!it)continue;let Q=Array.isArray(Y)&&Math.max(...Y),ut=pt(Y||[]).join("-"),ot=Q&&X!==ct&&Y?.includes(it);z.requireWinForPoints!==void 0&&(w=z.requireWinForPoints),z.requireWinFirstRound!==void 0&&(a=z.requireWinFirstRound);let{finishingPositionPoints:Dt={},finishingPositionRanges:Rt,finishingRound:De,pointsPerWin:qt,flights:Se}=z,_r=Array.isArray(z.perWinPoints)?z.perWinPoints?.find(Pt=>Pt.participationOrders?.includes(j)):z.perWinPoints,dn=Dt.participationOrders,hr=0,Xe;if((!dn||dn.includes(j))&&Rt&&Q){let Pt=Rt[Q];Pt&&({awardPoints:hr,requireWin:Xe}=SN({flightNumber:$,valueObj:Pt,drawSize:it,flights:Se,level:n}))}if(!hr&&De&&j===1&&Q){let Pt=De[Q];Pt&&({awardPoints:hr,requireWin:Xe}=SN({participantWon:V,flightNumber:$,valueObj:Pt,drawSize:it,flights:Se,level:n}))}if(ot&&a!==void 0&&(w=a),Xe!==void 0&&(w=Xe),hr>k&&(!w||W)&&(k=hr,H=Q),!hr&&qt&&W&&(G+=W*qt,H=ut),!hr&&W&&_r){let Pt=ay(n,_r?.level);Pt?G+=W*Pt:_r.value&&(G+=W*_r.value)}}if(F=k+G,S===Ar){let Q=(h.matchUps||[]).filter(({structureId:ut})=>ut===K.structureId);for(let{matchUpId:ut}of Q){let ot=d[ut],Dt=ot.sides.find(Rt=>Rt.participantId===T).sideNumber;if(ot.winningSice===Dt)for(let Rt of ot.tieMatchUps)Rt.winningSide}}}if(G||k){let K={winCount:L,positionPoints:k,rangeAccessor:H,perWinPoints:G,eventType:O,drawId:A,points:F},Y=y?.personId;Y?(f[Y]||(f[Y]=[]),f[Y].push(K)):S===ft?(I[T]||(I[T]=[]),I[T].push(K)):S===Ar&&(g[T]||(g[T]=[]),g[T].push(K))}}}}return{participantsWithOutcomes:l,personPoints:f,pairPoints:I,teamPoints:g,...C}}var EN={};Xt(EN,{compareTieFormats:()=>ni,getTieFormat:()=>al,tieFormatGenderValidityCheck:()=>km,validateCollectionDefinition:()=>eu});function sl(t){if(!t)return{};let e=[],r=t.tieFormatName,n=t.collectionDefinitions?.map(o=>{let{matchUpType:i,matchUpFormat:s,matchUpCount:a,category:c,gender:u}=o;e.includes(s)||e.push(s);let p=c?.ageCategoryCode;return[a,i===Gi?"D":"S",p,s,u].join(";")}).join("|");return{tieFormatName:t&&r||"UNNAMED",matchUpFormats:e,tieFormatDesc:n}}function ni({considerations:t={},descendant:e,ancestor:r}){let n={},o={},{matchUpFormats:i,tieFormatDesc:s}=sl(e),{matchUpFormats:a,tieFormatDesc:c}=sl(r),u=pt((i??[]).filter(E=>!(a??[]).includes(E)).concat((a??[]).filter(E=>!(i??[]).includes(E)))),p=!!(t?.collectionName&&e.collectionDefinitions.map(({collectionName:E})=>E).join("|")!==r.collectionDefinitions.map(({collectionName:E})=>E).join("|")),m=!!(t?.collectionOrder&&e.collectionDefinitions.map(({collectionOrder:E})=>E).join("|")!==r.collectionDefinitions.map(({collectionOrder:E})=>E).join("|")),d=Object.assign({},...(e?.collectionDefinitions||[]).map(E=>({[E.collectionId]:E}))),l=Object.assign({},...(r?.collectionDefinitions||[]).map(E=>({[E.collectionId]:E})));n.collectionIds=FE(Object.keys(d),Object.keys(l)),o.collectionIds=FE(Object.keys(l),Object.keys(d)),n.collectionsValue=Z_(d),o.collectionsValue=Z_(l),n.groupsCount=r?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),o.groupsCount=n.groupsCount?-1*n.groupsCount:0;let f=n.collectionsValue.totalValue-o.collectionsValue.totalValue,g=n.collectionsValue.totalMatchUps-o.collectionsValue.totalMatchUps,I=o.collectionsValue.assignmentValues.length!==n.collectionsValue.assignmentValues.length,h=o.collectionsValue.assignmentValues.some((E,P)=>{let A=n.collectionsValue.assignmentValues[P];return!A||E.valueKey!==A.valueKey||E.value!==A.value?!0:Array.isArray(E.value)?E.value.every((U,N)=>A.value[N]===U):!1}),S=p||m||c!==s||I||h||f!==0,T=[...o.collectionsValue.invalidValues,...n.collectionsValue.invalidValues],y=T.length&&T;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:n,ancestorDifferences:o,orderDifference:m,valueDifference:f,nameDifference:p,descendantDesc:s,ancestorDesc:c,...C,different:S,invalid:y}}function Z_(t){let e=[],r=[],n=0;return{totalValue:Object.keys(t).sort(Cu).reduce((s,a)=>{let c=t[a],{collectionValueProfiles:u,collectionValue:p,matchUpCount:m,matchUpValue:d,scoreValue:l,setValue:f}=c,g={collectionValueProfiles:u,collectionValue:p,matchUpValue:d,scoreValue:l,setValue:f},I=Object.keys(g).filter(S=>![void 0,null].includes(g[S])&&(!Array.isArray(g[S])||g[S].length>0));I.length!==1&&e.push({collectionId:a});let h=I[0];if(h){let S=h==="collectionValueProfiles"?Object.values(u):g[h];r.push({valueKey:h,value:S})}return n+=m,u?.length?s+u.reduce((S,T)=>S+T.value,0):m?It(d)?s+d*m:It(l)?s+l*m:It(f)?s+f*m:s+p:s},0),totalMatchUps:n,invalidValues:e,assignmentValues:r}}function tI(t){Object.assign(t,{inContext:!0});let{matchUp:e,error:r}=yN(t);return{matchUp:J(e,!0,!0),error:r}}function yN({participantsProfile:t,afterRecoveryTimes:e,tournamentRecord:r,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,matchUpId:a,inContext:c,eventId:u,drawId:p,event:m}){if(!r)return{error:q};if(typeof a!="string")return{error:sr};if(!i||!m){let g=(ye({tournamentRecord:r,nextMatchUps:s}).matchUps??[]).find(I=>I.matchUpId===a);if(!g)return{error:we};({eventId:u,drawId:p}=g),{event:m,drawDefinition:i}=ze({tournamentRecord:r,eventId:u,drawId:p})}if(!i)return{error:br};o&&!n&&(n=Zn({tournamentRecord:r,contextProfile:o}));let d={surfaceCategory:m?.surfaceCategory??r.surfaceCategory,indoorOutDoor:m?.indoorOutdoor??r.indoorOutdoor,endDate:m?.endDate??r.endDate,tournamentId:r.tournamentId,eventId:u??m?.eventId,drawId:p},{participants:l=[]}=Xo({participantsProfile:t,tournamentRecord:r,contextProfile:o,inContext:c});if(s){let g=(nr({context:c?d:void 0,participants:l,afterRecoveryTimes:e,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,inContext:c,event:m}).matchUps??[]).find(h=>h.matchUpId===a);if(!g)return{error:we};let I=i?.structures?.find(h=>h.structureId===g.structureId);return{drawDefinition:i,structure:I,matchUp:g}}else{let{matchUp:f,structure:g}=Vt({context:c?d:void 0,tournamentParticipants:l,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:o,matchUpId:a,inContext:c,event:m});return{matchUp:f,structure:g,drawDefinition:i}}}function al({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,structure:o,eventId:i,drawId:s,event:a}){if(!t)return{error:q};if(!s&&!a&&!r&&!n)return _({result:{error:st},stack:"getTieFormat"});i&&!a&&(a=t.events?.find(l=>l.eventId===i));let c=tI({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:s,event:a});if(n&&c?.error)return c;if(!e&&c?.drawDefinition&&(e=c?.drawDefinition),o=o??c?.structure,!o&&r&&!n){if(!e)return{error:cn};let l=at({drawDefinition:e,structureId:r});if(l.error)return l;o=l.structure}let u=(o?.tieFormat||o?.tieFormatId)&&We({structure:o,drawDefinition:e,event:a})?.tieFormat,p=(e?.tieFormat||e?.tieFormatId)&&We({drawDefinition:e,event:a})?.tieFormat,m=We({event:a})?.tieFormat,d=We({matchUp:c?.matchUp,drawDefinition:e,structure:o,event:a})?.tieFormat;return{...C,matchUp:c?.matchUp,structureDefaultTieFormat:or(u),eventDefaultTieFormat:or(m),drawDefaultTieFormat:or(p),tieFormat:or(d),structure:o}}var DN={};Xt(DN,{bulkUpdatePublishedEventIds:()=>cy,getAllEventData:()=>uy,getCourtInfo:()=>Td,getDrawData:()=>cl,getEventData:()=>ul,getEventPublishStatus:()=>Jr,getPublishState:()=>As,getTournamentPublishStatus:()=>Ru,getVenueData:()=>Ac});function cy({tournamentRecord:t,outcomes:e}){if(!t)return{error:q};if(!e?.length)return{error:st,info:"Missing outcomes"};let r=e.reduce((s,a)=>{let{drawId:c,eventId:u}=a;return u&&c&&(s[u]?s[u].includes(c)||s[u].push(c):s[u]=[c]),s},{}),n=Object.keys(r);return{publishedEventIds:(t.events?.filter(s=>n.includes(s.eventId))).filter(s=>{let a=Jr({event:s}),{drawDetails:c,drawIds:u}=a??{},{eventId:p}=s;return r[p].filter(d=>{let l=c?Object.keys(a.drawDetails).filter(f=>Ud({drawId:f,drawDetails:c})):[];return u?.includes(d)||l.includes(d)}).length}).map(s=>s.eventId),eventIdPublishedDrawIdsMap:r}}function AN({dates:t=[],extension:e}){if(!e)return!1;if(typeof e.value=="boolean"&&e.value)return!0;if(!t.length)return!1;let r=ht(e.value)?e.value?.dates:void 0;if(Array.isArray(r))return r?.length?!!r.filter(o=>!t.length||t.includes(o)).length:!1}function UN({convertExtensions:t,ignoreDisabled:e,venue:r,court:n}){let o={...J(n,t,!0),venueId:r.venueId},{extension:i}=mt({name:uo,element:n});if(e&&i){let s=ht(i.value)?i.value?.dates:void 0,a=i?.value===!0?[]:o.dateAvailability.map(c=>{let u=c.date;if(!(!u||s.includes(u)))return c}).filter(Boolean);o.dateAvailability=a}return{inContextCourt:o}}function Ro(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(m=>!t.tournamentId||m===t.tournamentId).forEach(m=>{let d=i[m];for(let l of d.venues??[])if(!(n.length&&!n.includes(l.venueId))){if(r){let{extension:f}=mt({name:uo,element:l});if(f?.value)continue}s.includes(l.venueId)||(u.push(J(l,e,!0)),s.push(l.venueId));for(let f of l.courts??[])if(!a.includes(f.courtId)){if(r){let{extension:I}=mt({name:uo,element:f});if(AN({extension:I,dates:o}))continue}let{inContextCourt:g}=UN({convertExtensions:e,ignoreDisabled:r,venue:l,court:f});c.push(g),a.push(f.courtId)}}}),{courts:c,venues:u,...C}}function O1({convertExtensions:t,tournamentRecord:e,ignoreDisabled:r,dates:n}){if(!e)return{error:xt};let o=J(e.venues??[],t).filter(s=>{if(!r)return s;let{extension:a}=mt({name:uo,element:s});return!a?.value&&s}).filter(Boolean),i=o.reduce((s,a)=>{let c=(a?.courts||[]).filter(u=>{if(!r&&!n?.length)return u;let{extension:p}=mt({name:uo,element:u});return AN({extension:p,dates:n})}).filter(Boolean).map(u=>{let{inContextCourt:p}=UN({convertExtensions:t,ignoreDisabled:r,venue:a,court:u});return p});return c.length?s.concat(c):s},[]);return{venues:o,courts:i}}function om({tournamentRecords:t,requireCourts:e,dates:r}){return typeof t!="object"||!Object.keys(t).length?{error:xt}:Object.keys(t).reduce((o,i)=>{let s=t[i],{venues:a}=O1({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 uy({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:q};let r=t.events||[],n=t?.participants||[],{tournamentInfo:o}=bs({tournamentRecord:t}),{venues:i}=Ro({tournamentRecord:t}),s=r.map(c=>{let{eventId:u}=c,p=ny({event:c}).eventInfo,m=Ra({tournamentRecord:t,event:c}).scheduleTiming,d=(c.drawDefinitions||[]).map(f=>{let g=(({drawId:y,drawName:E,matchUpFormat:P,updatedAt:A})=>({matchUpFormat:P,updatedAt:A,drawName:E,drawId:y}))(f),{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}=Zs({requireParticipants:!0,tournamentParticipants:n,context:{eventId:u},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:m,drawDefinition:f,event:c});return{drawInfo:g,matchUps:{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}}}),l=Jr({event:c});return Object.assign(p,{drawsData:d,publish:l}),p});return{allEventData:{tournamentInfo:o,venuesData:i,eventsData:s}}}function py({publishStatus:t,drawId:e}){return t?.drawDetails?t.drawDetails?.[e]?.publishingDetail?.published:t?.drawIds?t.drawIds.includes(e):!0}var PN="PUBLIC",v1="ADMIN",tx={PUBLIC_DISPLAY:PN,ADMIN_DISPLAY:v1};function cl(t){let{tournamentParticipants:e=[],includePositionAssignments:r,policyDefinitions:n,tournamentRecord:o,inContext:i=!0,usePublishState:s,status:a=Cr,pressureRating:c,refreshResults:u,contextProfile:p,drawDefinition:m,noDeepCopy:d,sortConfig:l,context:f,event:g}=t;if(!m)return{error:Z};let I=(({matchUpFormat:F,updatedAt:w,drawType:L,drawName:k,drawId:G})=>({matchUpFormat:F,updatedAt:w,drawName:k,drawType:L,drawId:G}))(m);I.display=mt({element:m,name:td}).extension?.value;let h={},S,T,{allStructuresLinked:y,sourceStructureIds:E,hasDrawFeedProfile:P,structureGroups:A}=_u({drawDefinition:m});if(!y)return{error:tA};let U=t?.eventPublishState??As({event:g}).publishState,N=t?.publishStatus??Jr({event:g,status:a}),D=U?.status?.drawDetails?.[m.drawId],M=!!U?.status?.published,R=D?.structureDetails,b=!1,O=!1,x=A.map(F=>{let w={},L=F.map(k=>{let{structure:G}=at({drawDefinition:m,structureId:k}),{seedAssignments:H}=sn({drawDefinition:m,structure:G});return G?.stage===rt&&G.stageSequence===1&&(S=H),G?.stage===ct&&(h[G.stageSequence??0]=H),G}).sort((k,G)=>Ni(k,G,l)).map(k=>{if(!k)return;let G=k?.structureId,H=[];k.stage&&[rt,qe,fe].includes(k.stage)&&(H=S),k?.stage===ct&&(H=h[k.stageSequence??0]);let{matchUps:K,roundMatchUps:Y,roundProfile:j}=yt({seedAssignments:k?.seedAssignments?.length?void 0:H,context:{drawId:I.drawId,...f},hydrateParticipants:t.hydrateParticipants,participantsProfile:t.participantsProfile,tournamentParticipants:e,policyDefinitions:n,tournamentRecord:o,usePublishState:s,publishStatus:N,contextProfile:p,drawDefinition:m,inContext:i,structure:k,event:g}),{positionAssignments:V}=Ct({structure:k}),$=V?.filter(Hr(ao)).map(z=>{let Q=mt({element:z,name:Lo})?.extension?.value,{drawPosition:ut,participantId:ot}=z;return O=!0,{participantResult:Q,participantId:ot,drawPosition:ut}});if(K.length&&(!$?.length&&t.allParticipantResults||u&&!k.structures)){let{subOrderMap:z}=iT({positionAssignments:V}),ut=K.some(Dt=>Dt.matchUpType===xr)?K.filter(Dt=>Dt.matchUpType===xr):K,ot=Fa({matchUpFormat:k.matchUpFormat,matchUps:ut,policyDefinitions:n,pressureRating:c,subOrderMap:z});T=ot?.report,$=V?.filter(Hr(ao)).map(Dt=>{let{drawPosition:Rt,participantId:De}=Dt;return O=!0,{participantResult:De&&ot?.participantResults?.[De],participantId:De,drawPosition:Rt}})}let X=k?(({stageSequence:z,structureName:Q,structureType:ut,matchUpFormat:ot,stage:Dt})=>({stageSequence:z,structureName:Q,structureType:ut,matchUpFormat:ot,stage:Dt}))(k):{},W=mt({element:k,name:td}).extension?.value;X.display=W?.[PN]??W,X.sourceStructureIds=E[G],X.hasDrawFeedProfile=P[G],X.positionAssignments=V,X.structureActive=K.reduce((z,Q)=>{let ut=[oe,be,Hn,ge,po,Gt,Me,Bt].includes(Q.matchUpStatus);return z||ut||!!Q.winningSide||!!Q.score?.scoreStringSide1},!1);let it=K.reduce((z,Q)=>z&&["BYE",ge,Me,Bt,Gt,vr].includes(Q.matchUpStatus),!!K.length);return X.structureCompleted=it,w[G]=it,X.structureActive&&(b=!0),{...X,participantResults:$,seedAssignments:H,roundMatchUps:Y,roundProfile:j,structureId:G,report:T}});return L.forEach(k=>{r||delete k.positionAssignments,k.sourceStructuresComplete=k.sourceStructureIds?.every(G=>w[G])}),L}).flat().filter(F=>!s||R?.[F?.structureId]?.published||!0);return I.drawActive=b,I.participantPlacements=O,I.drawGenerated=x?.reduce((F,w)=>F||!!w?.roundMatchUps,!1),I.drawCompleted=x?.reduce((F,w)=>F&&w.structureCompleted,!0),I.drawPublished=s?M&&py({publishStatus:N,drawId:I.drawId}):void 0,{structures:!s||I.drawPublished?d&&x||J(x,!1,!0):void 0,drawInfo:d?I:J(I,!1,!0),...C}}function ul(t){let{includePositionAssignments:e,participantsProfile:r,policyDefinitions:n,usePublishState:o,status:i=Cr,contextProfile:s,sortConfig:a}=t,c=et(t,[{tournamentRecord:!0},{[zm]:{event:!1,eventId:!1}}]);if(c.error)return c;let u=J(t.tournamentRecord,!1,!0),p=t.event?void 0:ze({tournamentRecord:u,eventId:t.eventId}).event,m=t.event?J(t.event,!1,!0):p&&J(p,!1,!0)||void 0;if(!m)return{error:qr};let{eventId:d}=m,{tournamentId:l,endDate:f}=u,g=Jr({event:m,status:i}),I=As({event:m}).publishState??{},h=!!I?.status?.published,{participants:S}=Ft({withGroupings:!0,withEvents:!1,withDraws:!1,policyDefinitions:n,...r,tournamentRecord:u}),T=({stage:O,drawId:v})=>{if(!o)return!0;let x=g?.drawDetails?.[v]?.stageDetails;return!x||!Object.keys(x).length?!0:x[O]?.published},y=({structureId:O,drawId:v})=>{if(!o)return!0;let x=g?.drawDetails?.[v]?.structureDetails;return!x||!Object.keys(x).length?!0:x[O]?.published},E=({drawId:O})=>o?py({publishStatus:g,drawId:O}):!0,P=({drawId:O,structure:v})=>{if(!o)return v;let x=g?.drawDetails?.[O]?.structureDetails?.[v.structureId]?.roundLimit;if(It(x)){let F=tt(1,x+1),w={},L={};for(let k of F)v.roundMatchUps[k]&&(w[k]=v.roundMatchUps[k],L[k]=v.roundProfile[k]);v.roundMatchUps=w,v.roundProfile=L}return v},A=m.drawDefinitions||[],U=!o||h?A.filter(E).map(O=>(({drawInfo:v,structures:x})=>({...v,structures:x}))(cl({allParticipantResults:t.allParticipantResults,hydrateParticipants:t.hydrateParticipants,context:{eventId:d,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:O,publishStatus:g,sortConfig:a,event:m}))).map(({structures:O,...v})=>{let x=O?.filter(({stage:F,structureId:w})=>y({structureId:w,drawId:v.drawId})&&T({stage:F,drawId:v.drawId})).map(F=>P({drawId:v.drawId,structure:F}));return{...v,structures:x}}).filter(O=>O.structures?.length):void 0,D=(Array.isArray(u.venues)?u.venues:[]).map(O=>(({venueData:v})=>({...v}))(Ac({venueId:O.venueId,tournamentRecord:u}))),M=(({eventId:O,eventName:v,eventType:x,eventLevel:F,surfaceCategory:w,matchUpFormat:L,category:k,gender:G,startDate:H,endDate:K,ballType:Y,discipline:j})=>({eventId:O,eventName:v,eventType:x,eventLevel:F,surfaceCategory:w,matchUpFormat:L,category:k,gender:G,startDate:H,endDate:K,ballType:Y,discipline:j}))(m);M.display=mt({element:m,name:td}).extension?.value;let{tournamentInfo:R}=bs({tournamentRecord:u}),b={tournamentInfo:R,venuesData:D,eventInfo:M,drawsData:U};return b.eventInfo.publishState=I,b.eventInfo.published=I?.status?.published,{...C,eventData:b,participants:S}}var CN={};Xt(CN,{courtGridRows:()=>dl,findVenue:()=>ti,getMatchUpsToSchedule:()=>pl,getPersonRequests:()=>ki,getProfileRounds:()=>ml,getScheduledRoundsDetails:()=>$u,getSchedulingProfile:()=>oi,getSchedulingProfileIssues:()=>my,publicFindCourt:()=>PS});function ua({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:r,matchUp:n}){let{individualParticipantIds:o}=Su(n);r=r??n.schedule?.timeAfterRecovery;let i=u=>{t[u]||(t[u]=[]),t[u]=pt(t[u].concat(...o))},s=u=>{r&&(!e[u]||r>e[u])&&(e[u]=r)},a=n.winnerTo?.matchUpId||n.winnerMatchUpId;a&&(r&&s(a),i(a));let c=n.loserTo?.matchUpId||n.loserMatchUpId;c&&(r&&s(c),i(c)),n.sidesTo?.length&&n.sidesTo.forEach(({matchUpId:u})=>{u&&(r&&s(u),i(u))})}function pl(t){let e=et(t,[{[Lf]:!0}]);if(e.error)return e;let{matchUpPotentialParticipantIds:r,dateScheduledMatchUpIds:n=[],scheduleCompletedMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,orderedMatchUpIds:a,clearDate:c,matchUps:u}=t,p=s?Object.keys(s):[],m=(a??[]).map(l=>u.find(f=>f.matchUpId===l)).filter(Boolean).filter(l=>{let f=!c&&(n.includes(l.matchUpId)||p.includes(l.matchUpId)),g=["BYE",Gt,ge,vr,Me,Bt,oe,be].includes(l?.matchUpStatus);return o||!f&&!l.winningSide&&!g}),d=r&&i?m.reduce((l,f)=>{let{drawId:g,tournamentId:I}=f;return l.matchUpMap[I]||(l.matchUpMap[I]={}),l.matchUpMap[I][g]?l.matchUpMap[I][g].push(f):l.matchUpMap[I][g]=[f],ua({matchUpPotentialParticipantIds:r,matchUpNotBeforeTimes:i,matchUp:f}),l},{matchUpMap:{}}).matchUpMap:{};return{matchUpsToSchedule:m,matchUpMap:d}}function im({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:r,matchUpFormat:n,categoryName:o,categoryType:i,tournamentId:s,eventType:a,eventId:c}){if(!Nr({matchUpFormat:n}))return{error:tc};let u=Object.keys(r).filter(m=>!s||m===s),p;return u.forEach(m=>{if(p)return;let d=r[m],l=c?ze({tournamentRecord:d,eventId:c})?.event:void 0;return p=Nu({tournamentRecord:d,matchUpFormat:n,categoryName:o,categoryType:i,eventType:a,event:l}),p?.averageMinutes||p?.recoveryMinutes}),{recoveryMinutes:p?.recoveryMinutes||t,averageMinutes:p?.averageMinutes||e,typeChangeRecoveryMinutes:p?.typeChangeRecoveryMinutes||p?.recoveryMinutes||t}}function $u(t){let e=et(t,[{[zm]:{tournamentRecords:!1,tournamentRecord:!1}},{rounds:!0,[He]:Be}]);if(e.error)return e;let{scheduleCompletedMatchUps:r,periodLength:n=30}=t,o=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{};if(typeof o!="object")return{error:xt};let i={},s=[],a=[],c=t.rounds.toSorted((I,h)=>(I.sortOrder??0)-(h.sortOrder??0)),u=t.containedStructureIds??Object.assign({},...Object.values(o).map(I=>fs({tournamentRecord:I}).containedStructures)),p=t.matchUps??Mn({nextMatchUps:!0,tournamentRecords:o}).matchUps,m=0,d={},l={},f={};return{scheduledRoundsDetails:c.flatMap(I=>{let h=I.periodLength||n,S=[];u?.[I.structureId]?S.push(...u[I.structureId]):S.push(I.structureId);let T=p?_i({tournamentIds:[I.tournamentId],roundNumbers:[I.roundNumber],matchUpIds:I.matchUpIds,eventIds:[I.eventId],drawIds:[I.drawId],processContext:!0,structureIds:S,matchUps:p}).sort(xi):[],{segmentNumber:y,segmentsCount:E}=I.roundSegment||{};if(It(y)&&Ln(T?.length)&&Ln(E)&&y>0&&y<=E&&E<T?.length&&!I.matchUpIds?.length){let N=T.length/E,D=N*(y-1);T=T.slice(D,D+N)}let P=o[I.tournamentId],A=ze({drawId:I.drawId,tournamentRecord:P}).event,U=[];for(let N of T){let D=N.matchUpFormat;D&&(i[D]||(i[D]=[],i[D].push(N)),U.push(D))}for(let N of U){let{eventType:D,category:M}=A??{},{categoryName:R,ageCategoryCode:b}=M??{},{typeChangeRecoveryMinutes:O,recoveryMinutes:v,averageMinutes:x,error:F}=im({categoryName:R??b,categoryType:M?.categoryType,tournamentId:I.tournamentId,eventId:I.eventId,tournamentRecords:o,matchUpFormat:N,eventType:D});if(F)return{error:F,round:I};let w=T.filter(k=>(r||!ae.includes(k.matchUpStatus))&&k.matchUpStatus!=="BYE").map(Ue);w.forEach(k=>{f[k]={typeChangeRecoveryMinutes:O,recoveryMinutes:v,averageMinutes:x},d[k]=v,l[k]=x}),a.push(...w),m=Math.max(x||0,m);let L=`${x}|${h}`;return s.includes(L)||s.push(L),{roundPeriodLength:h,recoveryMinutes:v,averageMinutes:x,matchUpIds:w,hash:L}}}),greatestAverageMinutes:m,matchUpFormatCohorts:i,recoveryMinutesMap:d,averageMinutesMap:l,orderedMatchUpIds:a,minutesMap:f,...C}}function NN({schedulingProfile:t,venueIds:e,eventIds:r,drawIds:n}){let o=[],i=t?.map(a=>{let c=Ut(a?.scheduleDate);if(!c){o.push(`Invalid date: ${a?.scheduledDate}`);return}let u=(a?.venues||[]).map(p=>{let{rounds:m,venueId:d}=p;if(!e?.includes(d)){o.push(`Missing venueId: ${d}`);return}let f=m.filter(g=>{let I=r.includes(g.eventId)&&n.includes(g.drawId);return I||o.push(`Invalid eventId: ${g.eventId} or drawId: ${g.drawId}`),I});if(f.length)return{venueId:d,rounds:f}}).filter(Boolean);return u.length&&c&&{...a,venues:u}}).filter(Boolean),s=o.length;return{updatedSchedulingProfile:i,modifications:s,issues:o}}function sm({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:B};let{venueIds:r,tournamentsMap:n}=x1({tournamentRecords:t}),o,i,s=e.every(a=>{let{scheduleDate:c,venues:u}=a;return Mr(c)?u.every(p=>{let{venueId:m,rounds:d}=p;return typeof m!="string"?(i="venueId should be a string",!1):Array.isArray(d)?r.includes(m)?!!d.every(f=>{if(!f)return i="empty round",!1;let{roundSegment:g,tournamentId:I,structureId:h,roundNumber:S,eventId:T,drawId:y}=f,P=n?.[I]?.[T]?.[y]?.[h]?.includes(S);P||(i="Invalid rounds");let{segmentNumber:A,segmentsCount:U}=g||{},N=!g||It(A)&&Ln(U)&&A<=U;return N||(i="Invalid segment"),P&&N}):(o=ji,!1):(i="rounds should be an array",!1)}):!1});return!s&&!o&&(o=B),{valid:!!s,error:o,info:i}}function _1(t){let{tournamentRecord:e={},tournamentMap:r={},requireCourts:n}=t,o=[],i=[],s=[],a=[],c=(e?.venues||[]).map(({venueId:p,courts:m})=>(!n||m?.length)&&p),u=e?.tournamentId;if(u){o.push(u),r[u]={};let p=e?.events||[];for(let m of p){let d=m.eventId;s.push(d),r[u][d]={};let l=f=>parseInt(f);for(let f of m.drawDefinitions||[]){let g=f.drawId;a.push(g),r[u][d][g]={};let{structures:I}=hn({drawDefinition:f});for(let h of I||[]){let S=h.structureId,{matchUps:T}=yt({structure:h}),{roundMatchUps:y}=Ke({matchUps:T}),E=y&&Object.keys(y).map(l);if(r[u][d][g][S]=E,i.push(S),h.structures?.length)for(let P of h.structures)i.push(P.structureId),r[u][d][g][P.structureId]=E}}}}return{tournamentMap:r,tournamentIds:o,structureIds:i,venueIds:c,eventIds:s,drawIds:a}}function x1(t){let e=t?.tournamentRecords&&Object.values(t?.tournamentRecords)||[],r={},{venueIds:n,eventIds:o,drawIds:i,structureIds:s,tournamentIds:a}=e.reduce((c,u)=>{let{tournamentIds:p,tournamentMap:m,structureIds:d,venueIds:l,eventIds:f,drawIds:g}=_1({tournamentRecord:u});return l.forEach(I=>{c.venueIds.includes(I)||c.venueIds.push(I)}),c.tournamentIds.push(...p),c.structureIds.push(...d),c.eventIds.push(...f),c.drawIds.push(...g),Object.assign(r,m),c},{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:r,tournamentIds:a,structureIds:s,venueIds:n,eventIds:o,drawIds:i}}function oi({tournamentRecords:t,tournamentRecord:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let{extension:r}=mt({element:e,name:Na,tournamentRecords:t,discover:!0}),n=r?.value||[];if(n.length){let{venueIds:o}=om({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:s}=kg({tournamentRecords:t}),{updatedSchedulingProfile:a,modifications:c,issues:u}=NN({schedulingProfile:n,venueIds:o,eventIds:i,drawIds:s});if(c){n=a;let p=Lc({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n});return p.error?p:{schedulingProfile:n,modifications:c,issues:u}}}return{schedulingProfile:n,modifications:0}}function Lc({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r}){let n=sm({tournamentRecords:t,schedulingProfile:r});return n.error?n:r?At({tournamentRecords:t,discover:!0,extension:{name:Na,value:r}}):Ir({element:e,name:Na,tournamentRecords:t,discover:!0})}function Fc(t){let{tournamentRecord:e}=t,r=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){let{modifications:u,issues:p}=oi({tournamentRecords:r,tournamentRecord:e});return{success:!u,modifications:u,issues:p}}let{venueIds:n}=om({tournamentRecords:r}),{eventIds:o,drawIds:i}=kg({tournamentRecords:r}),{updatedSchedulingProfile:s,modifications:a,issues:c}=NN({schedulingProfile:t.schedulingProfile,venueIds:n,eventIds:o,drawIds:i});return a?{...Lc({schedulingProfile:s,tournamentRecords:r}),modifications:a,issues:c}:{...C,modifications:a,issues:c}}function my(t){let{scheduleDates:e=[],tournamentRecords:r,periodLength:n=30}=t??{};if(typeof r!="object")return{error:Qa};if(!Array.isArray(e))return{error:B};if(!e.every(Mr))return{error:Ye};let i=[],s=0,a={},{schedulingProfile:c}=oi({tournamentRecords:r});if(!c)return{issues:i,...C};let{matchUps:u}=Mn({nextMatchUps:!0,tournamentRecords:r});for(let m of c){let{scheduleDate:d,venues:l=[]}=m;if(!e?.length||e.includes(d)){for(let f of l||[])if(f){let{rounds:g}=f,I=[],{orderedMatchUpIds:h,scheduledRoundsDetails:S}=$u({tournamentRecords:r,periodLength:n,matchUps:u,rounds:g}),{matchUpDependencies:T}=an({tournamentRecords:r,matchUps:u}),y=E=>{let P;return S?.find((A,U)=>{let N=A.matchUpIds.includes(E);return N&&(P=U),N}),P};if(h?.forEach((E,P)=>{let A=h.slice(P+1),U=jt(A,T?.[E]?.matchUpIds||[]);U.length&&I.push({matchUpId:E,shouldBeAfter:U})}),I.length){s+=I.length;let E=I.map(({matchUpId:P,shouldBeAfter:A})=>{let U=y(P),N=pt(A.map(y));return a[d]||(a[d]={}),a[d][U]||(a[d][U]=[]),N.forEach(D=>{a[d][U].includes(D)||a[d][U].push(D)}),{matchUpId:P,matchUpRoundIndex:U,earlierRoundIndices:N,shouldBeAfter:A}});i.push(...E)}}}}let p={matchUpIdShouldBeAfter:Object.assign({},...i.map(m=>{let{matchUpId:d,shouldBeAfter:l,earlierRoundIndices:f}=m;return{[d]:{earlierRoundIndices:f,shouldBeAfter:l}}}))};return{issuesCount:s,profileIssues:p,roundIndexShouldBeAfter:a,...C}}function ki(t){let{tournamentRecords:e,requestType:r}=t,n=et(t,[{[Re]:!0}]);if(n.error)return n;let o={};for(let i of Object.values(e)){let{extension:s}=mt({element:i,name:Da}),a=s?.value||[];for(let c of a){let{personId:u,requests:p}=c||{};o[u]||(o[u]=[]);for(let m of p)r&&m.requestType!==r||o[u].push(m)}}return{personRequests:o,...C}}function eI(t){let{containerStructureId:e,roundSegment:r,isRoundRobin:n,tournamentId:o,roundNumber:i,structureId:s,eventId:a,drawId:c}=t,u=n?e:s,p=[o,a,c,u,i].join("|");return nt({structureId:u,roundSegment:r,tournamentId:o,roundNumber:i,eventId:a,drawId:c,id:p})}function MN({round:t,matchUps:e,events:r,tournamentRecords:n}){let o=r.find(d=>d.eventId===t.eventId),{eventType:i,category:s,categoryType:a}=o||{},{categoryName:c,ageCategoryCode:u}=s||{},p=Er(e.map(({matchUpFormat:d})=>d)),m=0;return Object.keys(p).forEach(d=>{let l=p[d],f=im({categoryName:c||u,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:n,matchUpFormat:d,categoryType:a,eventType:i});if(f.error)return f;let g=f.averageMinutes*l;isNaN(m)||(m+=g)}),{roundMinutes:m}}function ex(t){return(t||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((i,s)=>i+s,0),o=(r.finishingPositionRange?.winner||[]).join("-")||"";return!e.minFinishingSum||n<e.minFinishingSum?{minFinishingSum:n,winnerFinishingPositionRange:o}:e},{minFinishingSum:0,winnerFinishingPositionRange:""})}function RN(t){let e=t.length,r=t.filter(({sides:p})=>p?.some(({bye:m})=>m)).length||0,n=t.filter(({winningSide:p,matchUpStatus:m})=>p||ae.includes(m)).length||0,o=t.filter(({schedule:p,matchUpStatus:m})=>p?.scheduledDate&&p?.scheduledTime&&m!=="BYE").length||0,i=e-r,s=i===n,a=i-o,c=i-o;return{unscheduledCount:a,incompleteCount:c,scheduledCount:o,completedCount:n,matchUpsCount:e,isScheduled:i===o,isComplete:s,byeCount:r}}function ml({tournamentRecords:t,schedulingProfile:e,tournamentRecord:r,withRoundId:n}){if(r&&!t){if(typeof r!="object")return{error:Qa};t={[r.tournamentId]:r}}if(e){let s=sm({tournamentRecords:t,schedulingProfile:e});if(s.error)return s}if(!e&&t){let s=oi({tournamentRecords:t});if(s.error)return s;e=s.schedulingProfile}if(!e)return{error:Oe};let o={};return{profileRounds:e.map(({venues:s,scheduleDate:a})=>s.map(({rounds:c})=>c.map(u=>{let p=eI(u);return p.roundSegment?.segmentsCount&&(o[p.id]=p.roundSegment.segmentsCount),nt({id:n?p.id:void 0,scheduleDate:a,...p})}))).flat(1/0),segmentedRounds:o}}function dl({courtPrefix:t="C|",minRowsCount:e,courtsData:r}){if(!Array.isArray(r))return{error:B};let n=r?.reduce((s,a)=>{let c=a.matchUps||[],u=Math.max(0,...c.map(p=>p.schedule.courtOrder||0));return Math.max(u,s)},1),o=Math.max(e||0,n),i=tt(0,o).map(s=>({matchUps:tt(0,r.length).map(a=>{let c=r[a],{courtId:u,venueId:p}=c;return{schedule:{courtOrder:s+1,venueId:p,courtId:u}}})}));return r.forEach((s,a)=>{for(let c of s.matchUps){let u=c.schedule?.courtOrder;u&&(i[u-1].matchUps[a]=c)}}),{courtPrefix:t,rows:i.map((s,a)=>Object.assign({rowId:`rowId-${a+1}`},...s.matchUps.map((c,u)=>({[`${t}${u}`]:c}))))}}var bN={};Xt(bN,{getEntriesAndSeedsCount:()=>ll,getMaxEntryPosition:()=>dy});function ll({policyDefinitions:t,drawDefinition:e,drawSize:r,drawId:n,event:o,stage:i}){if(!o)return{error:Ot};let{entries:s,stageEntries:a}=OS({drawDefinition:e,drawId:n,stage:i,event:o}),c=a.length,{drawSize:u}=bT({participantsCount:c}),p=Hu({drawSize:r??u,participantsCount:c,policyDefinitions:t});if(p.error)return _({result:p,stack:"getEntriesAndSeedsCount"});let{seedsCount:m}=p;return{entries:s,seedsCount:m,stageEntries:a}}function dy(t){let{entries:e=[],entryStatus:r,stage:n}=t;return Math.max(...e.filter(o=>(!n||n===o.entryStage)&&(!r||o.entryStatus===r)&&!isNaN(o.entryPosition)).map(({entryPosition:o})=>dt(o||0)),0)}var xN={};Xt(xN,{allCompetitionMatchUps:()=>Mn,allDrawMatchUps:()=>nr,allEventMatchUps:()=>to,allTournamentMatchUps:()=>ye,analyzeMatchUp:()=>cm,calculateWinCriteria:()=>Os,checkMatchUpIsComplete:()=>Ts,competitionScheduleMatchUps:()=>Ku,drawMatchUps:()=>Dy,eventMatchUps:()=>Il,filterMatchUps:()=>_i,getAllDrawMatchUps:()=>ie,getAllStructureMatchUps:()=>yt,getCheckedInParticipantIds:()=>Is,getCompetitionMatchUps:()=>am,getEventMatchUpFormatTiming:()=>Iy,getHomeParticipantId:()=>yy,getMatchUpCompetitiveProfile:()=>Du,getMatchUpContextIds:()=>Ey,getMatchUpDailyLimits:()=>Sl,getMatchUpDailyLimitsUpdate:()=>hy,getMatchUpDependencies:()=>an,getMatchUpFormat:()=>Ay,getMatchUpFormatTiming:()=>Nu,getMatchUpFormatTimingUpdate:()=>fy,getMatchUpScheduleDetails:()=>yd,getMatchUpType:()=>Ed,getMatchUpsStats:()=>Uy,getModifiedMatchUpFormatTiming:()=>fl,getParticipantResults:()=>ku,getPredictiveAccuracy:()=>Ty,getRoundMatchUps:()=>Ke,getRounds:()=>Py,isValidMatchUpFormat:()=>Nr,matchUpActions:()=>Bd,participantScheduledMatchUps:()=>Sy,tallyParticipantResults:()=>Fa,tournamentMatchUps:()=>hl,validMatchUp:()=>pg,validMatchUps:()=>Br});function ly({tournamentRecords:t,extensionName:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let r=[],n;for(let o of Object.values(t)){let{extension:i}=mt({element:o,name:e});i&&!n&&(r.push({params:{extension:i,discover:!0},method:"addExtension"}),n=!0);let s=o.events??[];for(let a of s){let{eventId:c}=a,{extension:u}=mt({name:e,element:a});u&&r.push({params:{eventId:c,extension:u},method:"addEventExtension"})}}return{methods:r}}function fy({tournamentRecords:t}){return ly({extensionName:Qo,tournamentRecords:t})}var ON="ADULT",vN="JUNIOR",gy="WHEELCHAIR",_N={[_o]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[vt]:30,default:60}}]},defaultDailyLimits:{[Lt]:2,[vt]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[bn],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[gy],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:[ON,gy],minutes:{default:60,[vt]:30}},{categoryTypes:[vN],minutes:{default:60,[vt]: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:[ON,gy],minutes:{default:30}},{categoryTypes:[vN],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:[ON,vN],minutes:{default:30}},{categoryTypes:[gy],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},rx=_N;function Iy({tournamentRecord:t,matchUpFormats:e,categoryType:r,event:n}){if(!n)return{error:Ot};let o=[],i;if(e?.length){let m=[];o=e.map(d=>{let l=typeof d=="string"?{matchUpFormat:d}:d;if(!m.includes(l?.matchUpFormat)&&Nr({matchUpFormat:l?.matchUpFormat}))return m.push(l.matchUpFormat),l}).filter(Boolean)}else{let{policy:m}=pi({policyType:rn,tournamentRecord:t,event:n});if(m?.matchUpFormats)o=m?.matchUpFormats;else{let{extension:d}=mt({name:Qo,element:n}),l,f;d?.value?{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=d.value:{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=rx[_o],o=pt([...(l||[]).map(g=>g.matchUpFormatCodes),...(f||[]).map(g=>g.matchUpFormatCodes)].flat()).map(g=>({matchUpFormat:g})),i="default scheduling policy in use"}}let{eventType:s,eventId:a,category:c}=n,u=c?.categoryName??c?.ageCategoryCode??a;if(!a)return{error:Ot};let p=o.map(({matchUpFormat:m,description:d})=>{let l=Nu({tournamentRecord:t,matchUpFormat:m,categoryName:u,categoryType:r,eventType:s,event:n});return{matchUpFormat:m,description:d,...l}});return nt({eventMatchUpFormatTiming:p,info:i})}function fl(t){let e=et(t,[{[ne]:!0},{[tr]:g=>Nr({matchUpFormat:g}),[kr]:tc,[$m]:!0}]);if(e.error)return e;let{tournamentRecord:r,matchUpFormat:n,event:o}=t,{extension:i}=mt({name:Qo,element:o}),s=i?.value,{extension:a}=mt({element:r,name:Qo}),c=a?.value,u=s?.matchUpAverageTimes&&vp({...s,matchUpFormat:n}),p=c?.matchUpAverageTimes&&vp({...c,matchUpFormat:n}),m=[u,p].find(g=>g),d=s?.matchUpRecoveryTimes&&_p({...s,matchUpFormat:n}),l=c?.matchUpRecoveryTimes&&_p({...c,matchUpFormat:n}),f=[d,l].find(g=>g);return{matchUpFormat:n,recoveryTimes:f,averageTimes:m}}function hy({tournamentRecords:t}){return ly({extensionName:lu,tournamentRecords:t})}var Ha=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter(n=>t.includes(n)).filter(n=>e[n]).length;function Sy({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Br(e))return{error:no};if(!Array.isArray(t))return{error:B};let r=e.filter(Boolean).filter(({schedule:o})=>Ha({schedule:o,scheduleAttributes:t})).reduce((o,i)=>{let{schedule:s}=i,a=Ut(s?.scheduledDate),c=zt(s?.scheduledTime);return a&&c&&(o[a]?o[a].push(i):o[a]=[i]),o},{});return Object.keys(r).forEach(o=>{r[o].sort((i,s)=>ah(zt(i.schedule?.scheduledTime),zt(s.schedule?.scheduledTime)))}),{...C,scheduledMatchUps:r}}function nx({tournamentRecords:t}){let e={},r=[];for(let n of Object.values(t))for(let o of n.events??[]){let i=Jr({event:o}),s=i?.drawDetails;ht(s)?(Object.assign(e,s),r.push(...Object.keys(s).filter(a=>Ud({drawId:a,drawDetails:s})))):i?.drawIds?.length&&r.push(...i.drawIds)}return{drawIds:r,detailsMap:e}}function gl({schedulingProfile:t,matchUps:e=[]}){let r={},n=({eventId:a,drawId:c,structureId:u,roundNumber:p})=>`${a}|${c}|${u}${p}`;t?.length&&t.map(({venues:c})=>c.map(({rounds:u})=>u)).flat().forEach(c=>{c.sort((p,m)=>(p.sortOrder||0)-(m.sortOrder||0)).forEach(({eventId:p,drawId:m,structureId:d,roundNumber:l},f)=>{let g=n({eventId:p,drawId:m,structureId:d,roundNumber:l});r[g]=f})});let o=[],i={noScheduledDate:[]};for(let a of e){let c=a.schedule||{},u=c.scheduledDate&&Ut(c.scheduledDate)||c.scheduledTime&&Ut(c.scheduledTime)||"noScheduledDate";i[u]||(i[u]=[]),i[u].push(a)}let s=Object.keys(i).sort();for(let a of s){let c=i[a],u={noScheduledTime:[]};for(let m of c){let d=m.schedule||{},l=d.scheduledTime&&zt(d.scheduledTime)||"noScheduledTime";u[l]||(u[l]=[]),u[l].push(m)}for(let m of Object.keys(u)){let l=u[m].sort((f,g)=>(f.roundNumber||0)-(g.roundNumber||0));u[m]=l}let p=Object.keys(u).sort();for(let m of p){let d=u[m];d.sort((l,f)=>{let g=r[n(l)]||0,I=r[n(f)]||0;return g-I}),o.push(...d)}}return o}function Il(t){let{participants:e,contextContent:r,participantMap:n}=t,{tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,tournamentId:I,inContext:h,context:S,event:T}=t;if(!T)return{error:Ot};let{eventId:y,eventName:E,endDate:P,eventType:A,category:U,gender:N}=T??{},D={...S,...nt({surfaceCategory:T.surfaceCategory??p?.surfaceCategory,indoorOutDoor:T.indoorOutdoor??p?.indoorOutdoor,tournamentId:I??p?.tournamentId,endDate:P??p?.endDate,eventName:E,eventType:A,category:U,eventId:y,gender:N})},M;!e&&p&&({participants:e,participantMap:n,groupInfo:M}=Xo({participantsProfile:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextProfile:f,inContext:h})),f&&!r&&(r=Zn({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:T}));let R=Jr({event:T});return{...(T.drawDefinitions??[]).reduce((v,x)=>{let F=Zs({hydrateParticipants:t.hydrateParticipants,context:D,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextContent:r,contextFilters:d,matchUpFilters:l,participantMap:n,publishStatus:R,contextProfile:f,drawDefinition:x,nextMatchUps:g,inContext:h,event:T});return Object.keys(F)?.forEach(L=>{Array.isArray(F[L])&&(v[L]||(v[L]=[]),v[L]=v[L].concat(F[L]))}),v},{}),...C,groupInfo:M}}function hl(t){if(!t?.tournamentRecord)return{error:q};let e=t.contextContent,{scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,inContext:a=!0,usePublishState:c,contextFilters:u,matchUpFilters:p,contextProfile:m,nextMatchUps:d,context:l}=t,f=t.tournamentId??s.tournamentId,g=s?.events??[],{participants:I,participantMap:h,groupInfo:S}=Xo({participantsProfile:n,policyDefinitions:i,tournamentRecord:s,contextProfile:m,inContext:a});m&&!e&&(e=Zn({policyDefinitions:i,tournamentRecord:s,contextProfile:m}));let{appliedPolicies:T}=Tt({tournamentRecord:s}),y=u?.eventIds??[];return{...g.filter(A=>!y.includes(A.eventId)).map(A=>{let N={eventDrawsCount:Ht({event:A}).flightProfile?.flights?.length||A.drawDefinitions?.length||0,...l};return Il({hydrateParticipants:t.hydrateParticipants,context:N,tournamentAppliedPolicies:T,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,usePublishState:c,contextFilters:u,contextProfile:m,contextContent:e,matchUpFilters:p,participantMap:h,participants:I,tournamentId:f,nextMatchUps:d,inContext:a,event:A})}).reduce((A,U)=>((U&&Object.keys(U).filter(D=>!["success","matchUpsMap"].includes(D)))?.forEach(D=>{Array.isArray(U[D])&&(A[D]||(A[D]=[]),A[D]=A[D].concat(U[D]),A.matchUpsCount!==void 0?A.matchUpsCount+=U[D].length:A.matchUpsCount=U[D].length)}),A),{matchUpsCount:0}),groupInfo:S,participants:I}}function am({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:r,tournamentRecords:n,useParticipantMap:o,policyDefinitions:i,usePublishState:s,matchUpFilters:a,contextFilters:c,nextMatchUps:u,inContext:p}){if(typeof n!="object"||!Object.keys(n).length)return{error:xt};let d=Object.keys(n).map(I=>{let h=n[I];return hl({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:r,useParticipantMap:o,policyDefinitions:i,tournamentRecord:h,usePublishState:s,matchUpFilters:a,contextFilters:c,nextMatchUps:u,inContext:p})}),l={},f={};return{...d.reduce((I,h)=>(Object.keys(h).forEach(T=>{if(T==="groupInfo")Object.assign(f,h[T]);else if(T==="participants")for(let y of h[T]??[])l[y.participantId]=y;else Array.isArray(h[T])&&(I[T]||(I[T]=[]),I[T]=I[T].concat(h[T]))}),I),{}),groupInfo:f,mappedParticipants:l}}function Ku(t){if(typeof t?.tournamentRecords!="object"||!Object.keys(t?.tournamentRecords).length)return{error:xt};let{courts:e,venues:r}=Ro(t),o=oi(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:s,alwaysReturnCompleted:a,activeTournamentId:c,tournamentRecords:u,withCourtGridRows:p,minCourtGridRows:m,usePublishState:d,status:l=Cr,sortCourtsData:f}=t,g=c??ms()??Object.keys(u)[0],I=d?Ru({tournamentRecord:u[g],status:l}):void 0,h=a?am({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[ge]},contextFilters:t.contextFilters}).completedMatchUps:[];if(d&&!I?.orderOfPlay?.published)return{completedMatchUps:h,dateMatchUps:[],courtsData:[],venues:r};let S,T;d&&({drawIds:S,detailsMap:T}=nx({tournamentRecords:u})),S?.length&&(t.contextFilters??={},t.contextFilters.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter(O=>S.includes(O)):t.contextFilters.drawIds=S),I?.eventIds?.length&&(t.matchUpFilters??={},t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter(O=>I.eventIds.includes(O)):t.matchUpFilters.eventIds=I.eventIds),I?.scheduledDates?.length&&(t.matchUpFilters??={},t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter(O=>I.scheduledDates.includes(O)):t.matchUpFilters.scheduledDates=I.scheduledDates),a&&(t.matchUpFilters??={},t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(ge)||t.matchUpFilters.excludeMatchUpStatuses.push(ge):t.matchUpFilters.excludeMatchUpStatuses=[ge]);let{completedMatchUps:y,upcomingMatchUps:E,pendingMatchUps:P,groupInfo:A,mappedParticipants:U}=am({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters}),N=[...E??[],...P??[]];T&&(!S?.length||Object.keys(T).length)&&(N=N.filter(O=>{let{drawId:v,structureId:x,stage:F}=O;if(!T?.[v]?.publishingDetail?.published)return!1;let w=Object.keys(T[v].stageDetails??{});if(w.length){let k=w.filter(H=>!T[v].stageDetails[H].published),G=w.filter(H=>T[v].stageDetails[H].published);return k.length&&k.includes(F)?!1:G.length&&G.includes(F)?!0:k.length&&!k.includes(F)&&!G.length}let L=Object.keys(T[v].structureDetails??{});if(L.length){let k=L.filter(H=>!T[v].structureDetails[H].published),G=L.filter(H=>T[v].structureDetails[H].published);return k.length&&k.includes(x)?!1:G.length&&G.includes(x)?!0:k.length&&!k.includes(x)&&!G.length}return!0}));let D=i?gl({matchUps:N,schedulingProfile:o}):N,M=e?.map(O=>{let v=b(O);return{surfaceCategory:O?.surfaceCategory??"",matchUps:v,...O}}),R={completedMatchUps:a?h:y,mappedParticipants:t.hydrateParticipants?void 0:U,dateMatchUps:D,courtsData:M,groupInfo:A,venues:r};if(p){let{rows:O,courtPrefix:v}=dl({minRowsCount:Math.max(m||0,D.length||0),courtsData:M});R.courtPrefix=v,R.rows=O}return{...R,...C};function b({courtId:O}){let x=(s?D.concat(y??[]):D).filter(F=>F.schedule?.courtId===O||F.schedule?.allocatedCourts?.map(({courtId:w})=>w).includes(O));return f?gl({matchUps:x,schedulingProfile:o}):x}}function Sl({tournamentRecords:t,tournamentId:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:xt};let r=Object.keys(t).filter(o=>!e||o===e),n;return r.forEach(o=>{let i=t[o],{matchUpDailyLimits:s}=w1({tournamentRecord:i});n=s}),{matchUpDailyLimits:n}}function w1(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{policy:n}=pi({policyType:_o,tournamentRecord:r}),{extension:o}=mt({element:r,name:lu}),i=o?.value?.dailyLimits,s=n?.defaultDailyLimits;return{matchUpDailyLimits:i||s}}function Ty(t){let{matchUps:e}=t,{singlesForDoubles:r,tournamentRecord:n,drawDefinition:o,excludeMargin:i,exclusionRule:s,zoneDoubling:a,matchUpType:c,scaleName:u,eventId:p,zonePct:m,drawId:d,event:l}=t;if(!n&&!e)return{error:q};if(c&&![Lt,vt].includes(c))return{error:B,info:{matchUpType:c}};if(e&&!Br(e))return{error:B,context:{matchUps:e}};let f=je[u],g=f?.ascending??t.ascending??!1,I=f?.accessor??t.valueAccessor,h=Array.isArray(f?.range)?Math.abs(f.range[0]-f.range[1]):0,S=It(m)&&h?(m??0/100)*h:t.zoneMargin??h,T={withScaleValues:!0,withCompetitiveness:!0},y={matchUpTypes:c?[c]:[Lt,vt]},E=n?.participants;e?.[0]?.hasContext?d?e=e.filter(O=>O.drawId===d):p&&(e=e.filter(O=>O.eventId===p)):e===void 0&&(e=d&&!o&&[]||!d&&p&&!l&&[]||d&&nr({inContext:!0,drawDefinition:o,contextFilters:y,contextProfile:T,participants:E})?.matchUps||!d&&p&&to({inContext:!0,contextFilters:y,contextProfile:T,participants:E,event:l})?.matchUps||ye({tournamentRecord:n,contextFilters:y,contextProfile:T})?.matchUps||[]),c&&(e=e.filter(O=>O.matchUpType===c));let P=e.filter(({winningSide:O,score:v,sides:x,matchUpStatus:F})=>![Me,Gt,Bt,Iu,vr].includes(F??"")&&he({score:v})&&x?.length===2&&O),A=F1({matchUps:P,excludeMargin:i,exclusionRule:s,valueAccessor:I,ascending:g,scaleName:u}),U=!a||de(Lt)(c)?S:(S||0)*2,N=S?P.map(({competitiveProfile:O,matchUpType:v,score:x,sides:F})=>{let w=ix({singlesForDoubles:r,valueAccessor:I,matchUpType:v,scaleName:u,sides:F}),L=Math.abs(w[0].value-w[1].value);return{competitiveness:O?.competitiveness,valuesGap:L,score:x}}).filter(({valuesGap:O})=>O<=U):[],D=L1({zoneData:N}),M=D&&[].concat(Object.values(D)).flat().length,R=M&&Object.assign({},...Object.keys(D).map(O=>({[O]:Math.round(1e4*D[O].length/M)/100}))),b=P.length-(N?.length||0);return{...C,relevantMatchUps:P,zoneDistribution:R,zoneData:N,accuracy:A,nonZone:b}}function L1({zoneData:t}){let e={[ud]:[],[hc]:[],[Sc]:[]};for(let r of t){let{competitiveness:n,score:o,valuesGap:i}=r;e[n]&&e[n].push({score:o,valuesGap:i})}return e}function ix({singlesForDoubles:t,exclusionRule:e,valueAccessor:r,matchUpType:n,scaleName:o,sides:i}){let s=e?.range.sort(),a=c=>{let u=c?.[e?.valueAccessor];return{exclude:e&&u>=s[0]&&u<=s[1],exclusionValue:u}};return i.sort((c,u)=>c.sideNumber-u.sideNumber).map(({participant:c})=>{let u=[],p=c?.individualParticipants;if(p?.length){let m=[],d=0;for(let l of p){let{scaleValue:f,value:g}=ox({singlesForDoubles:t,valueAccessor:r,participant:l,matchUpType:n,scaleName:o}),{exclude:I,exclusionValue:h}=a(f);I&&u.push(h),m.push(f),g&&!isNaN(d)?d+=g:d=void 0}return{participantName:c.participantName,exclusionValues:u,scaleValues:m,value:d}}else if(c){let{scaleValue:m,value:d}=ox({singlesForDoubles:t,valueAccessor:r,matchUpType:n,participant:c,scaleName:o}),{exclude:l,exclusionValue:f}=a(m);return l&&u.push(f),{participantName:c.participantName,exclusionValues:u,scaleValue:m,value:d}}else return{}})}function ox({singlesForDoubles:t,valueAccessor:e,matchUpType:r,participant:n,scaleName:o}){let i=t?Lt:r,s=n?.rankings?.[i]?.find(p=>p.scaleName===o),c=(n?.ratings?.[i]?.find(p=>p.scaleName===o)||s)?.scaleValue,u=e?c?.[e]:c;return{scaleValue:c,value:u}}function F1({excludeMargin:t,exclusionRule:e,valueAccessor:r,ascending:n,scaleName:o,matchUps:i}){let s={affirmative:[],negative:[],excluded:[]};for(let u of i){let{matchUpType:p,sides:m,score:d,winningSide:l}=u;if(!l)continue;if(e&&(!e.valueAccessor||!e.range))return{info:"exclusionRule requires valueAccessor and range",error:st};let f=l-1,g=ix({exclusionRule:e,valueAccessor:r,matchUpType:p,scaleName:o,sides:m});if(e){let E=g.map(({exclusionValues:P})=>P).flat();if(E.length){s.excluded.push({scoreString:d?.scoreStringSide1,exclusionValues:E,winningSide:l,sideValues:g});continue}}if(g.filter(E=>![void 0,"",null].includes(E.value)).length<2){s.excluded.push({scoreString:d?.scoreStringSide1,missingValues:!0,winningSide:l,sideValues:g});continue}let I=g[f].value-g[1-f].value,h=parseFloat(t||0),S=h&&Math.abs(I)<h;if(S){s.excluded.push({scoreString:d?.scoreStringSide1,excludeMargin:t,winningSide:l,excludeGap:S,sideValues:g,valuesGap:I});continue}let T=n?I:I*-1,y=l===1?d?.scoreStringSide1:d?.scoreStringSide2;T>0?s.affirmative.push({winningScoreString:y,winningSide:l,sideValues:g,valuesGap:I,score:d}):s.negative.push({winningScoreString:y,winningSide:l,sideValues:g,valuesGap:I,score:d})}let a=s.affirmative.length+s.negative.length,c=a&&s.affirmative.length/a*100;return s.percent=c?Math.round(100*c)/100:0,s}function Os({collectionDefinitions:t=[],collectionGroups:e=[]}){let r=0,{groupValueNumbers:n}=aT({collectionGroups:e}),o;for(let s of t||[]){let{collectionValueProfiles:a,collectionGroupNumber:c,collectionValue:u,matchUpCount:p,matchUpValue:m,scoreValue:d,setValue:l}=s,f=c&&n.includes(c);if(It(l||d))o=!0;else{if(f)continue;if(typeof u=="number"&&It(u))r+=u;else if(Array.isArray(a)&&a?.length)for(let g of a)r+=g.matchUpValue;else typeof m=="number"&&It(m)&&(r+=(p??0)*m)}}for(let s of e)r+=s.groupValue??0;return o||!r?{aggregateValue:!0,...C}:{valueGoal:Math.floor(r/2)+1,...C}}function yy(t){let{timeStamp:e,schedule:r,matchUp:n}=t,o=et(t,[{[Gn]:!0}]);if(o.error)return o;let{itemValue:i,timeStamp:s}=Zo({timeItems:n?.timeItems||[],itemType:Sd});return!r||s&&e&&new Date(s).getTime()>new Date(e).getTime()?{homeParticipantId:i}:r}function Ey({matchUps:t,matchUpId:e}){if(!Br(t))return{error:B};let r=t.find(a=>a.matchUpId===e),{drawId:n,eventId:o,structureId:i,tournamentId:s}=r||{};return{matchUpId:e,drawId:n,eventId:o,structureId:i,tournamentId:s}}function vs(t,e){if(!ht(t))return{error:B};if(!Array.isArray(e))return{error:B};let r={};for(let{param:n,error:o,attr:i}of e){let s=k1({params:t,param:n,attr:i,error:o});if(s?.error)return s;r[n]=s}return r}function k1({params:t,param:e,attr:r,error:n}){if(e===Ep&&ht(t.drawDefinition)&&kt(t.structureId)){let o=(t.drawDefinition.structures??[]).find(({structureId:i})=>i===t.structureId);return!o.length&&n?{error:n}:{structure:o}}if(e===Gn){let o=yN({...t,...r});return o.error&&n?{...o,error:n}:o}return{error:Oe,info:{param:e}}}function Ay(t){let{structureId:e,matchUpId:r,event:n}=t,o=t.drawDefinition,i=et(t,[{[ne]:!0},{[zm]:{[cu]:!1,[gn]:!1,[Gh]:!1,[co]:!1}}]);if(i[In])return i;let a=vs(t,[{[ds]:Gn,[In]:st}])?.matchUp;if(r&&a?.error)return a;!o&&a?.drawDefinition&&(o=a?.drawDefinition);let c=a?.structure;if(!c&&e&&!r){if(!o)return{error:cn};let l=at({drawDefinition:o,structureId:e});if(l.error)return l;c=l.structure}let u=c?.matchUpFormat,p=o?.matchUpFormat,m=n?.matchUpFormat,d=a?.matchUp?.matchUpFormat||u||p||m;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:m,drawDefaultMatchUpFormat:p,matchUpFormat:d}}function Uy({profileBands:t,tournamentRecord:e,matchUps:r}){if(!Br(r))return{error:no};let n=!t&&pi({policyType:Di,tournamentRecord:e}).policy,o=t||n?.profileBands||md[Di].profileBands,i=r.filter(({winningSide:d})=>d),s=i.map(fS),a=(d,l)=>{let f=lS(l,o);return d[f]+=1,d},c=gS(s).reduce((d,l)=>a(d,l),{[ud]:0,[hc]:0,[Sc]:0,[cS]:0}),u=Object.keys(c).reduce((d,l)=>(c[l]||0)+d,0),p=Object.keys(c).map(d=>{let l=parseFloat((c[d]/u).toFixed(4));return{[d]:l*100}}),m=i.filter(({matchUpStatus:d})=>d===XU).length;return p.push({[XU]:parseFloat((m/u).toFixed(4))*100}),{competitiveBands:Object.assign({},...p),...C}}var{stageOrder:sx}=pb;function ax(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(sx[t?.stage]||0)-(sx[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function Py({excludeScheduleDateProfileRounds:t,excludeScheduledRounds:e,excludeCompletedRounds:r,inContextMatchUps:n,tournamentRecords:o,schedulingProfile:i,tournamentRecord:s,withSplitRounds:a,matchUpFilters:c,scheduleDate:u,withRoundId:p,venueId:m,context:d}){if(n&&!Array.isArray(n||typeof n[0]!="object"))return{error:B,inContextMatchUps:n};if(s&&!o){if(typeof s!="object")return{error:Qa};o={[s.tournamentId]:s}}let l=typeof o!="object"||!Object.keys(o).length;if((m||u||!n||!i&&(t||r||i||a))&&l)return{error:xt};let g=Object.assign({},...Object.values(o??{}).map(({venues:A=[],tournamentId:U})=>({[U]:A?.map(({venueId:N})=>N)}))),I=Object.values(o??{}).map(({events:A=[],tournamentId:U,startDate:N,endDate:D})=>A.map(M=>({...M,validVenueIds:g[U],startDate:M.startDate??N,endDate:M.endDate??D}))).flat(),{segmentedRounds:h,profileRounds:S}=o&&(t||r||i||a)&&ml({tournamentRecords:o,schedulingProfile:i})||{},T=t&&Object.assign({},...S.map(A=>({[A.id]:A}))),y=n||o&&Mn({tournamentRecords:o,matchUpFilters:c})?.matchUps||[],E=[],P=y&&Object.values(y.reduce((A,U)=>{let N=eI(U).id,D=h?.[N],M=[...A[N]?.matchUps??[],U],{containerStructureId:R,stageSequence:b,structureName:O,tournamentId:v,isRoundRobin:x,matchUpType:F,roundNumber:w,roundOffset:L,structureId:k,eventName:G,roundName:H,drawName:K,eventId:Y,drawId:j}=U,V=x?R:k;return{...A,[N]:{id:p?N:void 0,structureId:V,stageSequence:b,segmentsCount:D,structureName:O,tournamentId:v,matchUpType:F,roundNumber:w,roundOffset:L,eventName:G,roundName:H,drawName:K,matchUps:M,eventId:Y,drawId:j}}},{})).map(A=>{let{minFinishingSum:U,winnerFinishingPositionRange:N}=ex(A.matchUps),D=A.segmentsCount;if(D){let w=A.matchUps.length/D;return Ae(A.matchUps.sort((k,G)=>k.roundPosition-G.roundPosition),w).map((k,G)=>{let{unscheduledCount:H,incompleteCount:K,matchUpsCount:Y,isScheduled:j,isComplete:V,byeCount:$}=RN(k),X=MN({matchUps:A.matchUps,tournamentRecords:o,events:I,round:A});return nt({...A,...d,roundSegment:{segmentsCount:D,segmentNumber:G+1},winnerFinishingPositionRange:N,unscheduledCount:H,incompleteCount:K,minFinishingSum:U,matchUpsCount:Y,isScheduled:j,roundTiming:X,isComplete:V,byeCount:$,matchUps:k})})}let{unscheduledCount:M,incompleteCount:R,matchUpsCount:b,isScheduled:O,isComplete:v,byeCount:x}=RN(A.matchUps),F=MN({matchUps:A.matchUps,tournamentRecords:o,events:I,round:A});return nt({...A,...d,winnerFinishingPositionRange:N,unscheduledCount:M,incompleteCount:R,minFinishingSum:U,matchUpsCount:b,isScheduled:O,roundTiming:F,isComplete:v,byeCount:x})}).flat().filter(A=>{if(t){let k=Ut(t),G=p?A.id:eI(A).id;if(k&&T[G]&&Ut(T[G].scheduleDate)===k)return!1}let{isComplete:U,isScheduled:N}=A,D=!r||!U,M=!e||!N,R=m||u?I?.find(({eventId:k})=>k===A.eventId):void 0,b=R?.startDate??s?.startDate,O=R?.endDate??s?.endDate,v=!u||!b||new Date(u)>=new Date(b),x=!u||!O||new Date(u)<=new Date(O),F=v&&x,w=!m||R?.validVenueIds.includes(m),L=D&&M&&w&&F;return L||E.push(A),L}).sort(ax)||[];return{...C,rounds:P,excludedRounds:E}}function cm(t){let{matchUp:e,sideNumber:r,setNumber:n,isTiebreakValue:o,isPointValue:i}=t||{},{matchUpFormat:s}=t||{};if(!e)return{error:mr};s=s||e?.matchUpFormat;let a=Ne(s),c=!!e?.winningSide,u=e.score?.sets,p=u?.length,m=n&&n-1,d=!!u?.find((V,$)=>V.setNumber===n&&$===m),l=u?.filter(V=>V?.winningSide)||[],f=l?.length||0,g=n&&u?.slice(n)||[],I=!!(p&&n&&g?.reduce((V,$)=>(!$||!$.side1Score&&!$.side2Score&&!$.side1TiebreakScore&&!$.side2TiebreakScore&&!$.side1PointScore&&!$.side2PointScore)&&V,!0)),h=n<=p&&u.find(V=>V.setNumber===n),S=h&&qu({setObject:h,matchUpScoringFormat:a}),{isCompletedSet:T,sideGameScores:y,sideTiebreakScores:E}=S||{},P=!!(h&&!T&&I||n&&n===p+1&&!c),A=[1,2].includes(r),U=A?r-1:0,N=h&&A&&(!o&&!i&&y[U]!==void 0&&y[U]||o&&E[U]!==void 0&&E[U]),D=!!N,M=l?.map(V=>qu({setObject:V,matchUpScoringFormat:a}).isValidSetOutcome).reduce((V,$)=>V&&$,!0),R=l.reduce((V,$)=>{let{winningSide:X}=$,W=X-1;return V[W]++,V},[0,0]),b=e?.winningSide,O=b&&b-1,v=1-O,x=R[O],F=R[v],w=Math.max(...R),L=Er(R)[w],{bestOf:k,exactly:G}=a??{},H=k&&Math.ceil(k/2)||G||1,K=w===H&&L===1&&R.indexOf(w)+1||void 0,Y=x>F&&b===K;return{completedSetsHaveValidOutcomes:M,validMatchUpWinningSide:Y,calculatedWinningSide:K,matchUpScoringFormat:a,validMatchUpOutcome:K&&M&&Y,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:A,hasExistingValue:D,existingValue:N,isExistingSet:d,isActiveSet:P,...S}}function Dy({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,tournamentId:h,inContext:S,context:T,event:y}){let{eventId:E,eventName:P,endDate:A,eventType:U,category:N,gender:D}=y??{},M={...T,...nt({surfaceCategory:y?.surfaceCategory??a?.surfaceCategory,indoorOutDoor:y?.indoorOutdoor??a?.indoorOutdoor,endDate:A??y?.endDate??a?.endDate,tournamentId:h??a?.tournamentId,eventName:P,eventType:U,category:N,eventId:E,gender:D})},R;return!t?.length&&a&&({participants:t,participantMap:d,groupInfo:R}=Xo({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:f,inContext:S})),y&&f&&!p&&(p=Zn({policyDefinitions:i,tournamentRecord:a,contextProfile:f,drawDefinition:g,event:y})),{...Zs({context:M,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,tournamentParticipants:t,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:c,participantMap:d,contextContent:p,contextFilters:u,matchUpFilters:m,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,inContext:S,event:y}),groupInfo:R}}var wN={};Xt(wN,{getCompetitionVenues:()=>om,getCourts:()=>Ny,getVenuesAndCourts:()=>Ro,publicFindVenue:()=>US});function Ny({tournamentRecord:t,venueId:e,venueIds:r}){return t?{courts:(t.venues||[]).filter(o=>e?o.venueId===e:r?r.includes(o.venueId):!0).map(o=>{let{venueId:i}=o,s=J(o.courts||[]);return s.forEach(a=>Object.assign(a,{venueId:i})),s}).flat()}:{error:q}}var LN={};Xt(LN,{categoryCanContain:()=>tu,getCategoryAgeDetails:()=>Ys,getEvent:()=>Cy,getEventProperties:()=>My,getEventStructures:()=>Mg,getEventTimeItem:()=>Au,getEvents:()=>Ry,getFlightProfile:()=>Ht,getScaledEntries:()=>ca});function My({tournamentRecord:t,event:e}){if(!t)return{error:q};if(!e)return{error:Ot};let r=e.entries||[],n=t.participants||[],o=e.category?.categoryName||e.category?.ageCategoryCode,{eventType:i}=e,s=r.map(d=>d.participantId),a=n.filter(d=>s.includes(d.participantId)),c,u,p;return{entryScaleAttributes:a.map(d=>{let{participantId:l,participantName:f,name:g}=d,I={scaleType:lg,eventType:i,scaleName:o},h=Po({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:rP,eventType:i,scaleName:o};let S=Po({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:eP,eventType:i,scaleName:o};let T=Po({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;return c=!!(c||h),u=!!(u||S),p=!!(p||T),{participantId:l,participantName:f||g,seed:h,ranking:S,rating:T}}),hasSeededParticipants:c,hasRankedParticipants:u,hasRatedParticipants:p}}function Ry({tournamentRecord:t,withScaleValues:e,scaleEventType:r,inContext:n,eventIds:o,drawIds:i,context:s}){if(!t)return{error:q};let{tournamentId:a}=t,c=(t.events??[]).filter(({eventId:p})=>!o||Array.isArray(o)&&o.includes(p)).map(p=>{let m=p.drawDefinitions?.map(gu);if(i?.length&&!jt(i,m).length)return;let d=J(p);return n&&Object.assign(d,{tournamentId:a}),s&&Object.assign(d,s),d}).filter(Boolean),u={};if(e){let p=Ft({withScaleValues:!0,tournamentRecord:t}).participantMap,m=d=>d.reduce((l,f)=>l+parseFloat(f),0);for(let d of c){let l=r??d.eventType,f=d.eventId;u[f]||(u[f]={ratingsStats:{},ratings:{},ranking:{},draws:{}});let I=(d.entries??[]).filter(({entryStatus:A})=>Xr.includes(A)).map(St),h=A=>{if(A?.ratings?.[l])for(let U of A?.ratings?.[l]??[]){let N=U.scaleName;u[f].ratings[N]||(u[f].ratings[N]=[]);let D=je[N]?.accessor;if(D){let M=parseFloat(U.scaleValue?.[D]);M&&u[f].ratings[N].push(M)}}if(A?.rankings?.[l])for(let U of A?.rankings?.[l]??[]){let N=U.scaleName;u[f].ranking[N]||(u[f].ranking[N]=[]),U.scaleValue&&u[f].ranking[N].push(U.scaleValue)}};for(let A of I){let U=p?.[A]?.participant;if(U?.participantType!==Et)for(let N of U?.individualParticipantIds??[]){let D=p?.[N]?.participant;h(D)}else h(U)}let S=u[f].ratings;for(let A of Object.keys(S)){let U=S[A];if(!U.length)continue;let N=xE(U)?.toFixed(2);u[f].ratingsStats[A]={avg:parseFloat((m(U)/U.length).toFixed(2)),median:N?parseFloat(N):void 0,max:Math.max(...U),min:Math.min(...U)}}let T=(A,U)=>{let N=D=>{if(u[f].draws?.[A]&&D?.ratings?.[l])for(let M of D?.ratings?.[l]??[]){let R=M.scaleName;u[f].draws[A]?.ratings[R]||(u[f].draws[A].ratings[R]=[]);let b=je[R]?.accessor;if(b){let O=parseFloat(M.scaleValue?.[b]);O&&u[f].draws[A].ratings[R].push(O)}}if(u[f].draws?.[A]&&D?.rankings?.[l])for(let M of D?.rankings?.[l]??[]){let R=M.scaleName;u[f].draws[A]?.ranking[R]||(u[f].draws[A].ranking[R]=[]);let b=M.scaleValue;b&&u[f].draws[A].ranking[R].push(b)}};for(let D of U.filter(Boolean)){let M=p?.[D]?.participant;if(M?.participantType!==Et)for(let R of M?.individualParticipantIds??[]){let b=p?.[R]?.participant;N(b)}else N(M)}},y=[],E=A=>i?.length&&i.includes(A)||y.includes(A);for(let A of d.drawDefinitions??[]){let U=A.drawId;if(E(U))continue;let N=wi({drawDefinition:A}).assignedParticipantIds??[];u[f].draws[U]||(u[f].draws[U]={ratingsStats:{},ratings:{},ranking:{}}),y.push(U),T(U,N)}let P=Ht({event:d}).flightProfile;for(let A of P?.flights??[]){let U=A.drawId;if(E(U))continue;let N=A.drawEntries.map(St);T(U,N)}for(let A of y){let U=u[f].draws[A].ratings;for(let N of Object.keys(U)){let D=U[N];if(!D.length)continue;let M=xE(D)?.toFixed(2);u[f].draws[A].ratingsStats[N]={avg:parseFloat((m(D)/D.length).toFixed(2)),median:M?parseFloat(M):void 0,max:Math.max(...D),min:Math.min(...D)}}}}}return nt({eventScaleValues:u,events:c,...C})}function Cy({tournamentRecord:t,drawDefinition:e,context:r,event:n}){if(!t)return{error:q};if(!n)return{error:Ot};let o=J(n);r&&Object.assign(o,r);let i=e&&o.drawDefinitions?.find(({drawId:s})=>e.drawId===s);return nt({drawDefinition:i,event:o})}function cx(t){let e="validateAndDeriveDrawValues",{appliedPolicies:r,policyDefinitions:n}=B1(t),o=H1({...t,policyDefinitions:n,appliedPolicies:r}),i=V1(t),s=W1({...t,consideredEntries:i,appliedPolicies:r});if(s?.error)return _({result:s,stack:e});let a=j1({...t,consideredEntries:i}),c=G1({...t,appliedPolicies:r,policyDefinitions:n,drawSize:a});if(c.error)return _({result:c,stack:e});let u=c.drawType;if(isNaN(a)&&u!==Fr)return _({result:{error:Za},stack:e});let p=n?.[Vn]??r?.[Vn],m=t.seedingProfile??p?.seedingProfile?.drawTypes?.[u??""]??p?.seedingProfile;t.seedingProfile&&(n[Vn]||(n[Vn]={...Zg[Vn]}),n[Vn].seedingProfile=m);let d=Y1({...t,drawType:u});return d?.error?_({result:d,stack:e}):{drawSize:a,drawType:u,enforceGender:o,seedingProfile:m,appliedPolicies:r,policyDefinitions:n}}function G1(t){let{policyDefinitions:e,appliedPolicies:r,enforceMinimumDrawSize:n=!0,drawSize:o}=t,i=t.drawTypeCoercion??Bu({drawType:t.drawType,policyDefinitions:e,appliedPolicies:r}),s=vT({drawType:t.drawType,enforceMinimumDrawSize:n,drawTypeCoercion:i,drawSize:o});return s.error?s:{drawType:s.drawType}}function kN(t){return t?.filter(e=>e.entryStatus&&[...Xr,ld].includes(e.entryStatus))}function V1({considerEventEntries:t=!0,drawEntries:e,eventEntries:r,qualifyingOnly:n}){return(n&&[]||kN(e)||(t?r:[])).filter(({entryStage:o})=>!o||o===rt)}function B1(t){let{tournamentRecord:e,event:r}=t,n={...t?.appliedPolicies,...Tt({tournamentRecord:e,event:r}).appliedPolicies??{}},o=J(t.policyDefinitions??{},!1,!0);return{appliedPolicies:n,policyDefinitions:o}}function H1({enforceGender:t,policyDefinitions:e,appliedPolicies:r}){return t??e?.[er]?.participants?.enforceGender??r?.[er]?.participants?.enforceGender}function W1(t){let{consideredEntries:e,appliedPolicies:r,policyDefinitions:n,enforceGender:o,participantMap:i,participants:s,event:a}=t;return a&&s&&Hd({consideredEntries:e,policyDefinitions:n,appliedPolicies:r,participantMap:i,enforceGender:o,participants:s,event:a})}function j1(t){return!t.drawSize&&t.consideredEntries.length&&![Fr,su,Ea,On,Eo].includes(t.drawType??"")&&us(t.consideredEntries.length)||t.drawSize&&dt(t.drawSize)||!1}function Y1(t){let{tournamentRecord:e,event:r,ignoreAllowedDrawTypes:n,drawType:o}=t,i=!n&&e&&rl({tournamentRecord:e,categoryType:r?.category?.categoryType,categoryName:r?.category?.categoryName});return i?.length&&!i.includes(o)?{error:Om}:{...C}}function by(t){let{drawDefinition:e,appliedPolicies:r}=t,n=r?.[vo],o=Pe({drawDefinition:e});return e.structures?.forEach(i=>{let s=Vo({structureId:i.structureId,matchUpsMap:o}),a=dS({roundNamingPolicy:n,drawDefinition:e,structure:i,matchUps:s}),{roundNamingProfile:c,roundProfile:u}=a;(i.structures||[i]).forEach(m=>{(m.matchUps??[]).forEach(d=>{let l=d?.roundNumber?.toString();if(l){let f=c?.[l]?.roundName,g=c?.[l]?.abbreviatedRoundName,I=u?.[l]?.feedRound;Object.assign(d,{abbreviatedRoundName:g,feedRound:I,roundName:f})}})})}),{drawDefinition:e}}function Wa(t){let{voluntaryConsolation:e,tournamentRecord:r,event:n}=t,o="generateDrawDefinition",{participants:i,participantMap:s}=Ft({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:r}),a=kN(n?.entries)??[],c=cx({...t,participantMap:s,participants:i,eventEntries:a});if(c.error)return _({result:c,stack:o});let{appliedPolicies:u,policyDefinitions:p,drawSize:m,drawType:d,enforceGender:l,seedingProfile:f}=c,g=n?.eventType,I=t.matchUpType??g,h=__({...t,enforceGender:l,eventType:g,matchUpType:I});if(h.error)return _({result:h,stack:o});let{matchUpFormat:S,tieFormat:T}=h;if(t.drawId&&typeof t.drawId!="string")return _({result:{error:B},stack:o});let E=$_({...t,policyDefinitions:p,tournamentRecord:r,appliedPolicies:u,matchUpFormat:S,seedingProfile:f,participants:i,eventEntries:a,matchUpType:I,tieFormat:T,drawSize:m,drawType:d,event:n});if(E.error)return _({result:E,stack:o});let{existingDrawDefinition:P,positioningReports:A,drawDefinition:U,structureId:N,conflicts:D,entries:M}=E;if(!U)return _({result:{error:B},stack:o});let R=K_({...t,existingDrawDefinition:P,positioningReports:A,appliedPolicies:u,drawDefinition:U,seedingProfile:f,participants:i,structureId:N,entries:M,params:t,stack:o});if(R.error)return R;let{qualifyingConflicts:b}=R;return U.drawName=t.drawName??(d&&Qe(d)),m&&typeof e=="object"&&m>=4&&Eg({...e,drawDefinition:U,matchUpType:I}),t.hydrateRoundNames&&u?.[vo]&&by({drawDefinition:U,appliedPolicies:u}),{existingDrawDefinition:!!P,qualifyingConflicts:b,positioningReports:A,drawDefinition:U,structureId:N,...C,conflicts:D}}function Oy({scaleAttributes:t,scaledEntries:e,stageEntries:r,seedsCount:n,scaleName:o}){if(!t)return{error:st,info:"missing scaleAttributes"};let i=Object.assign({},...(e||[]).slice(0,n).map(({participantId:c},u)=>({[c]:u+1})));o=o||t.scaleName;let s=new Date().toISOString();return{scaleItemsWithParticipantIds:r.map(({participantId:c})=>({scaleItems:[{scaleValue:i[c],eventType:t.eventType,scaleType:Ao,scaleName:o,scaleDate:s}],participantId:c}))}}function ux({tournamentRecord:t,drawDefinition:e,policyDefinitions:r,scaleAttributes:n,scaleName:o,drawSize:i,drawId:s,event:a,stage:c,sortDescending:u,scaleSortMethod:p}){let m=ll({policyDefinitions:r,drawDefinition:e,drawSize:i,drawId:s,event:a,stage:c});if(m.error)return m;let{entries:d,seedsCount:l,stageEntries:f}=m;if(!f||!l)return{error:B};let g=ca({tournamentRecord:t,scaleAttributes:n,scaleSortMethod:p,sortDescending:u,entries:d,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:I}=Oy({scaleAttributes:n,scaledEntries:g,stageEntries:f,seedsCount:l,scaleName:o});return{scaleItemsWithParticipantIds:I}}var qN={};Xt(qN,{addDrawEntries:()=>hg,addEventEntries:()=>Wn,addEventEntryPairs:()=>WN,destroyPairEntries:()=>UP,destroyPairEntry:()=>yg,getEntriesAndSeedsCount:()=>ll,getMaxEntryPosition:()=>dy,modifyEntriesStatus:()=>Ad,modifyEventEntries:()=>jN,mutate:()=>YN,promoteAlternate:()=>BN,promoteAlternates:()=>_y,query:()=>bN,removeDrawEntries:()=>HN,removeEventEntries:()=>Dc,setEntryPosition:()=>vy,setEntryPositions:()=>VN});var YN={};Xt(YN,{addDrawEntries:()=>hg,addEventEntries:()=>Wn,addEventEntryPairs:()=>WN,destroyPairEntries:()=>UP,destroyPairEntry:()=>yg,modifyEntriesStatus:()=>Ad,modifyEventEntries:()=>jN,promoteAlternate:()=>BN,promoteAlternates:()=>_y,removeDrawEntries:()=>HN,removeEventEntries:()=>Dc,setEntryPosition:()=>vy,setEntryPositions:()=>VN});function vy({tournamentRecord:t,drawDefinition:e,participantId:r,entryPosition:n,skipRefresh:o,event:i}){let s="setEntryPositions";if(!t)return{error:q};if(!r)return _({result:{error:se},stack:s});if(n!==void 0&&!Number.isSafeInteger(n))return{error:B,entryPosition:n};(i?.entries||[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)}),(e?.entries||[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)});let a=c=>{c.entries.forEach(u=>{u.entryPosition===n&&u.participantId!==r&&(u.entryPosition+=.1)})};return o||(i?.entries&&(a(i),i.entries=eo({entries:i.entries})),e?.entries&&(a(e),e.entries=eo({entries:e.entries}))),{...C}}function VN({tournamentRecord:t,entryPositions:e,drawDefinition:r,event:n}){if(!t)return{error:q};if(!Array.isArray(e))return{error:B};for(let o of e){let{participantId:i,entryPosition:s}=o,a=vy({skipRefresh:!0,tournamentRecord:t,drawDefinition:r,participantId:i,entryPosition:s,event:n});if(a.error)return a}return n?.entries&&(n.entries=eo({entries:n.entries})),r?.entries&&(r.entries=eo({entries:r.entries})),{...C}}function BN(t){let{participantId:e}=t;return e&&typeof e!="string"?{error:B,participantId:e}:_y({...t,participantIds:[e].filter(Boolean)})}function _y({tournamentRecord:t,drawDefinition:e,participantIds:r,stageSequence:n,stage:o=rt,eventId:i,event:s}){if(!t)return{error:q};if(!Array.isArray(r))return{error:B,participantIds:r};if(!s)return{error:Ot};let a="promoteAlternates";if(s){let c=px({element:s,participantIds:r,stageSequence:n,stage:o});if(c.error)return c}if(e){let c=px({element:e,participantIds:r,stageSequence:n,stage:o});if(c.error)return i?_({context:{drawPromotionError:c.error,drawId:e.drawId},result:{...C},stack:a}):c}return{...C}}function px({participantIds:t,stageSequence:e,element:r,stage:n}){let o=(r.entries||[]).filter(m=>m.entryStatus===on),i=(r.entries||[]).filter(m=>t.includes(m.participantId)),s=o.reduce((m,d)=>{let{entryPosition:l}=d;return isNaN(l)&&m||(!m||l<m.entryPosition)&&d||m},void 0),a=i.length?i:[s].filter(Boolean);if(!a?.length)return{error:QI};let c=a.filter(({entryStatus:m})=>m!==on);if(c.length)return{error:sf,invalidEntryStatus:c};let u=a.filter(({entryStage:m})=>m&&m!==n);if(u.length)return{error:vC,invalidStage:u};let p=e&&a.filter(m=>m.stageSequence!==e);if(p?.length)return{error:_C,invalidStageSequence:p};for(let m of a){m.entryStatus=Gr;let d=m?.entryPosition;isNaN(d)||r.entries.forEach(f=>{f.entryStatus===on&&f.entryPosition>d&&(f.entryPosition=f.entryPosition-1)});let l=Math.max(...r.entries.filter(f=>f.entryStatus===Gr&&!isNaN(f.entryPosition)).map(({entryPosition:f})=>dt(f||0)),0);m.entryPosition=l||0}return{...C}}function HN({autoEntryPositions:t=!0,participantIds:e,drawDefinition:r,drawId:n,stages:o,event:i}){if(!i)return{error:Ot};if(!n)return{error:cn};if(!e?.length)return{error:bo};let s=wi({drawDefinition:r,stages:o}).assignedParticipantIds??[];if(ke(s,e))return{error:Gs};let c=m=>{let d=m.participantId;return!e.includes(d)},{flightProfile:u}=Ht({event:i}),p=u?.flights?.find(m=>m.drawId===n);return p?.drawEntries&&(p.drawEntries=p.drawEntries.filter(c),t&&(p.drawEntries=eo({entries:p.drawEntries}))),r?.entries&&(r.entries=r.entries.filter(c),t&&(r.entries=eo({entries:r.entries}))),{...C}}function wn(t){let e="addParticipant",{allowDuplicateParticipantIdPairs:r,returnParticipant:n,disableNotice:o,pairOverride:i,participant:s}=t,a=t.tournamentId?t.tournamentRecords?.[t.tournamentId]:t.tournamentRecord??(t.activeTournamentId&&t.tournamentRecords?.[t.activeTournamentId]);if(!a)return{error:q};if(!s)return _({result:{error:Wi},stack:e});s.participantId||(s.participantId=Nt()),a.participants||(a.participants=[]);let{participantId:c,individualParticipantIds:u}=s;if(a.participants.reduce((I,h)=>h.participantId===c||I,!1))return{error:EA};let{participantType:m,participantRole:d}=s;if(!m||!Object.keys(yu).includes(m))return{error:Pn,participantType:m};if(!d)return{error:TA};let l=a.participants||[],f=l.filter(I=>I.participantType===Et).map(I=>I.participantId);if(m!==Et&&s.person)return{error:B,person:s.person};if(u&&!Array.isArray(u))return{error:B,individualParticipantIds:u};if(m===ft){if(s.person)return{error:B,person:s.person};if(s.individualParticipantIds){if(s.individualParticipantIds.length!==2&&!i)return _({info:"PAIR must be 2 individualParticipantIds",result:{error:wr},stack:e});{let S=l.filter(y=>y.participantType===Et).map(y=>y.participantId);if(!Array.isArray(s.individualParticipantIds))return _({result:{error:wr},stack:e});if(!s.individualParticipantIds.reduce((y,E)=>S.includes(E)&&y,!0))return _({result:{error:wr},stack:e})}}else return _({result:{error:bo},stack:e});let I=l.filter(S=>S.participantType===ft).map(S=>({individualParticipantIds:S.individualParticipantIds,participant:S})),h=s.participantType===ft&&I.find(S=>jt(S.individualParticipantIds,s.individualParticipantIds).length===2);if(h&&!r)return{...C,existingParticipant:!0,participant:n&&J(h.participant)};if(!s.participantName){let S=l.filter(y=>s.individualParticipantIds?.includes(y.participantId)),T=S.map(y=>y.person?.standardFamilyName).filter(Boolean).join("/");S.length===1&&(T+="/Unknown"),s.participantName=T}}else if(m===Et){if(!s.person?.standardFamilyName||!s.person?.standardGivenName)return{error:DA};if(!s.participantName){let I=`${s.person.standardFamilyName.toUpperCase()}, ${s.person.standardGivenName}`;s.participantName=I}}else if(m&&[wt,Qr].includes(m)){if(u||(s.individualParticipantIds=[]),s.individualParticipantIds?.length)for(let I of s.individualParticipantIds){if(typeof I!="string")return _({result:{participantId:I,error:B},stack:e});if(!f.includes(I))return _({result:{participantId:I,error:re},stack:e})}}else return{error:Pn};a.participants.push(s),o||lt({payload:{tournamentId:a.tournamentId,participants:[s]},topic:ci});let g={participant:n&&J(s),...C};return nt(g)}function En({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:r,participants:n=[]}){if(!r)return{error:q};r.participants||(r.participants=[]);let i=r.participants.map(d=>d.participantId)||[];n.forEach(d=>{d.participantId||(d.participantId=Nt())});let s=n.filter(d=>!i.includes(d.participantId)),a=n.filter(d=>i.includes(d.participantId)),c=s.filter(d=>d.participantType===Et),u=s.filter(d=>d.participantType!==Et),p=c.concat(...u),m=[];if(p.length){for(let l of p){let f=wn({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:l});if(f.error)return f;f.success&&!f.existingParticipant&&m.push(f.participant)}m.length&<({topic:ci,payload:{tournamentId:r.tournamentId,participants:m}});let d={participants:e&&J(m),addedCount:m.length,...C};return a.length&&Object.assign(d,{notAdded:a,info:sp}),nt(d)}else return{info:"No new participants to add",addedCount:0,...C}}function WN(t){let e=et(t,[{[ne]:!0,[co]:!0}]);if(e.error)return e;let{allowDuplicateParticipantIdPairs:r,entryStatus:n=on,participantIdPairs:o=[],entryStage:i=rt,tournamentRecord:s,drawDefinition:a,event:c,uuids:u}=t;if(c.eventType!==vt)return{error:$n};let p=[],m=new Map;for(let y of s.participants??[]){let{participantType:E,participantId:P,person:A,individualParticipantIds:U}=y;E===Et&&A?.sex?m.set(P,A.sex):E===ft&&U&&p.push(U)}let d=o.filter(y=>{if(y.length!==2)return!0;if(!c.gender||To(c.gender))return!1;if(!m.has(y[0])||!m.has(y[1]))return!0;let E=y.map(A=>m.get(A)),P=Hs(c.gender)&&(!Hs(E[0])||!Hs(E[1]))||$i(c.gender)&&(!$i(E[0])||!$i(E[1]));return en(c.gender)&&(E.sort(Cu),(!$i(E[0])||!Hs(E[1]))&&(P=!0)),P});if(d.length)return{error:wr,invalidParticipantIdPairs:d};let l=o.map(y=>({participantId:u?.pop()??Nt(),participantRole:xe,individualParticipantIds:y,participantType:ft})),f=r?l:l.filter(y=>!p.find(E=>jt(E,y.individualParticipantIds).length===2)),g,I=[];if(f){let y=En({allowDuplicateParticipantIdPairs:r,participants:f,returnParticipants:!0,tournamentRecord:s});if(y.error)return y;I=y.participants||[],g=y.info}let h=o.map(y=>{let E=I.find(A=>jt(A.individualParticipantIds,y).length===2);if(E)return E;let{participant:P}=Sn({tournamentRecord:s,participantIds:y});return P}).map(y=>y.participantId),S=Wn({participantIds:h,tournamentRecord:s,drawDefinition:a,entryStatus:n,entryStage:i,event:c});f.length&<({payload:{participants:f},topic:ci});let T=f.map(St);return{...S,info:g,newParticipantIds:T}}function jN({entryStatus:t=Gr,unpairedParticipantIds:e=[],participantIdPairs:r=[],entryStage:n=rt,tournamentRecord:o,event:i}){if(!o)return{error:q};if(!i)return{error:Ot};let s=o.participants??[],a=s.filter(h=>h.participantType===Et).map(h=>h.participantId),u=e.concat(...r).flat(1/0).filter(h=>!a.includes(h));if(u.length)return{error:wr,invalidParticipantIds:u};let p=r.filter(h=>h.length!==2);if(p.length)return{error:wr,invalidParticipantIdPairs:p};let m=s.filter(h=>h.participantType===ft).map(h=>h.individualParticipantIds),l=r.filter(h=>!m.find(S=>jt(S,h).length===2)).map(h=>({participantType:ft,participantRole:xe,individualParticipantIds:h})),f=En({participants:l,tournamentRecord:o});if(f.error)return f;let g=r.map(h=>{let{participant:S}=Sn({tournamentRecord:o,participantIds:h});return S}).map(h=>({participantId:h,entryStatus:t,entryStage:n})),I=e.map(h=>({entryStatus:Vr,participantId:h,entryStage:n}));return i.entries=(i.entries??[]).filter(h=>h.entryStage===n),i.entries=i.entries.concat(...g,...I),{...C}}var iM={};Xt(iM,{addDrawDefinition:()=>kc,addEvent:()=>pa,addFlight:()=>pm,assignSeedPositions:()=>tM,attachFlightProfile:()=>aI,categoryCanContain:()=>tu,deleteDrawDefinitions:()=>um,deleteEvents:()=>rM,deleteFlightAndFlightDraw:()=>JN,deleteFlightProfileAndFlightDraws:()=>QN,generate:()=>KN,generateEventsFromTieFormat:()=>$N,getCategoryAgeDetails:()=>Ys,getEvent:()=>Cy,getEventProperties:()=>My,getEventStructures:()=>Mg,getEventTimeItem:()=>Au,getEvents:()=>Ry,getFlightProfile:()=>Ht,getScaledEntries:()=>ca,modifyEvent:()=>nM,modifyEventMatchUpFormatTiming:()=>XN,modifyPairAssignment:()=>ZN,mutate:()=>oM,query:()=>LN,refreshEventDrawOrder:()=>sI,removeEventMatchUpFormatTiming:()=>Tl,removeScaleValues:()=>cI,removeSeeding:()=>eM,setEventDates:()=>oI,setEventDisplay:()=>yl,setEventEndDate:()=>Gy,setEventStartDate:()=>ky,updateDrawIdsOrder:()=>iI,validateCategory:()=>Zc});var KN={};Xt(KN,{generateEventsFromTieFormat:()=>$N});function mx({tournamentId:t,event:e}){return e?(lt({payload:{tournamentId:t,event:e},key:e.eventId,topic:HU}),{...C}):{error:Ot}}var dx={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_D3",winCriteria:{valueGoal:5}};var lx={collectionDefinitions:[{collectionName:"Doubles",collectionValue:1,matchUpCount:3,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES"},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_DEFAULT",winCriteria:{valueGoal:5}};var fx={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"COLLEGE_JUCO",winCriteria:{valueGoal:5}};var xy={COLLEGE_D3:dx,COLLEGE_DEFAULT:lx,COLLEGE_JUCO:fx,DOMINANT_DUO:Eh,DOMINANT_DUO_MIXED:hh,LAVER_CUP:Nh,TEAM_DOUBLES_3_AGGREGATION:dh,TIME_TENNIS_DUAL:Sh,TIME_TENNIS_PRO_CIRCUIT:Ih,USTA_BREWER_CUP:Th,USTA_OZAKI_CUP:yh,USTA_COLLEGE:Ah,USTA_GOLD_TEAM_CHALLENGE:mh,USTA_INTERSECTIONAL:gh,USTA_LEVEL_1:Uh,USTA_SECTION_BATTLE:fh,USTA_SOUTHERN_LEVEL_5:lh,USTA_TOC:Mh,USTA_WTT_ITT:Ph,USTA_ZONAL:Dh};function pa({suppressNotifications:t,tournamentRecord:e,internalUse:r,event:n}){if(!e)return{error:q};if(e.events||(e.events=[]),!n)return{error:Ot};let{startDate:o,endDate:i}=e;if(!r&&(n.entries?.length||n.drawDefinitions?.length)){let c=nt({drawDefinitions:!!n.drawDefinitions?.length,entries:!!n.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:B,context:c}}let s={eventType:qs,drawDefinitions:[],entries:[],startDate:o,endDate:i,...n};if(n.eventType===Or){if(n.tieFormat){let c=ar({tieFormat:n.tieFormat});if(c.error)return c}else if(n.tieFormatName){if(!xy[n.tieFormatName])return{context:{tieFormatName:n.tieFormatName},error:B};let c=io({isMock:e?.isMock,namedFormat:n.tieFormatName,event:n});s.tieFormat=c}}if(s.eventId||(s.eventId=Nt()),e.events.reduce((c,u)=>c||u.eventId===s.eventId,void 0))return{error:eA};{let c=s;if(e.events.push(c),!t){let{topics:u}=Lr();if(u.includes(Mp)){let d=to({event:n}).matchUps??[];Fo({tournamentId:e?.tournamentId,eventId:n.eventId,matchUps:d})}let{drawDefinitions:p,...m}=n;for(let d of p||[])Ma({drawDefinition:d});mx({tournamentId:e?.tournamentId,event:m})}return{...C,event:s}}}function $N(t){let e=et(t,[{[Ks]:{[Km]:!0,[xh]:!0}},{[ne]:!0}]);if(e.error)return e;let r=t.tieFormat||io({namedFormat:t.tieFormatName}),n=t.uuids||[ph(r.collectionDefinitions.length)],o={[Le]:[],[lr]:[]};if(t.addEntriesFromTeams){let a=t.tournamentRecord.participants?.filter(c=>c.participantType===Ar)?.flatMap(c=>c.individualParticipantIds??[]);for(let c of t.tournamentRecord.participants??[])if(a?.includes(c.participantId)){let u=c.person?.sex;if(u&&Dn(u)){let p=yr(u);p&&o[p].push(c.participantId)}}}let i=[];for(let s of r.collectionDefinitions??[]){let a=n?.pop()?.toString()||Nt(),c=s.matchUpType,u=s.gender,p={matchUpFormat:s.matchUpFormat,eventName:s.collectionName,category:s.category,gender:u,eventType:c,eventId:a};if(t.addEntriesFromTeams){let m=c===Ko?Vr:t.entryStatus||Gr,d=en(u)?[...o[Le],...o[lr]]:o[yr(u)||$o]??[];if(d.length){let l=Wn({participantIds:d,entryStatus:m,event:p});if(l.error)return l}}if(i.push(p),t.addEvents!==!1){let m=pa({internalUse:!0,tournamentRecord:t.tournamentRecord,event:p});if(m.error)return m}}return{...C,events:i}}var oM={};Xt(oM,{addDrawDefinition:()=>kc,addEvent:()=>pa,addFlight:()=>pm,assignSeedPositions:()=>tM,attachFlightProfile:()=>aI,deleteDrawDefinitions:()=>um,deleteEvents:()=>rM,deleteFlightAndFlightDraw:()=>JN,deleteFlightProfileAndFlightDraws:()=>QN,modifyEvent:()=>nM,modifyEventMatchUpFormatTiming:()=>XN,modifyPairAssignment:()=>ZN,refreshEventDrawOrder:()=>sI,removeEventMatchUpFormatTiming:()=>Tl,removeScaleValues:()=>cI,removeSeeding:()=>eM,setEventDates:()=>oI,setEventDisplay:()=>yl,setEventEndDate:()=>Gy,setEventStartDate:()=>ky,updateDrawIdsOrder:()=>iI,validateCategory:()=>Zc});function ma({removePriorValues:t=!0,status:e=Cr,statusObject:r,event:n}){if(!ht(r))return{error:B};let o=Jr({event:n,status:e}),i=`${Ho}.${Wo}`,s={itemValue:{[e]:{...o,...r}},itemType:i};return is({timeItem:s,removePriorValues:t,event:n})}function da(t){let e=et(t,[{[ne]:!0,[co]:!0},{eventDataParams:!1,[He]:zr}]);if(e.error)return e;let{includePositionAssignments:r,removePriorValues:n,tournamentRecord:o,status:i=Cr,event:s,drawIdsToRemove:a,drawIdsToAdd:c}=t,{appliedPolicies:u}=Tt({tournamentRecord:o,event:s}),p={...u,...t.policyDefinitions},m=s?.drawDefinitions?.map(({drawId:E})=>E)??[],d=t.drawDetails?Object.keys(t.drawDetails):[],l=d.length?[]:t.drawIds,f=(c??[]).concat(...a??[],...l??[],...d),g=f.filter(E=>!m.includes(E));if(g.length)return _({result:{error:br},context:{invalidDrawIds:g}});let I=Jr({event:s,status:i}),h=Object.keys(I?.drawDetails||{}).filter(E=>m.includes(E)).reduce((E,P)=>(E[P]=I.drawDetails[P],E),{});for(let E of m)if((!f.length||f.includes(E))&&(a?.includes(E)||l?.length&&!l.includes(E)?h[E]={...h[E],publishingDetail:{published:!1}}:(c?.includes(E)||l?.includes(E)||!l?.length)&&(h[E]={...h[E],publishingDetail:{published:!0}})),t.drawDetails?.[E]){let P=t.drawDetails[E],A=P.structureDetails??h[E].structureDetails,U=P.stageDetails??h[E].stageDetails??{},{structureIdsToRemove:N=[],structureIdsToAdd:D=[],publishingDetail:M={},stagesToRemove:R=[],stagesToAdd:b=[]}=P;if((D||b)&&(M.published=!0),h[E]={publishingDetail:M,structureDetails:A,stageDetails:U},D.length||N.length){let v=(s?.drawDefinitions?.find(w=>w.drawId===E)?.structures??[]).map(({structureId:w})=>w),F=(D??[]).concat(N??[]).filter(w=>!v.includes(w));if(F.length)return _({result:{error:_t},context:{invalidStructureIds:F}});A=A??{};for(let w of v)N.includes(w)?A[w]={published:!1}:A[w]={published:!0};h[E].structureDetails=A}let O=(s?.drawDefinitions?.find(v=>v.drawId===E)?.structures??[]).map(({stage:v})=>v);if(b.length){for(let v of b)U[v]={published:!0};for(let v of O)U[v]||(U[v]={published:!1})}if(b.length||R.length){for(let v of R)U[v]={published:!1};for(let v of O)U[v]||(U[v]={published:!0})}(b.length||R.length)&&(h[E].stageDetails=U)}ma({statusObject:{drawDetails:h},removePriorValues:n,status:i,event:s});let{topics:S}=Lr(),T=S.includes(tS),y=T||t.returnEventData?ul({includePositionAssignments:r,...t.eventDataParams,usePublishState:!0,tournamentRecord:o,policyDefinitions:p,event:s})?.eventData:void 0;return T&<({payload:{eventData:y,tournamentId:o.tournamentId},topic:tS}),{...C,eventData:y}}var zN="deleteDrawDefinitions",wy="autoSchedulingAudit",rI="deleteEvents",gx={AUTO_SCHEDULING_AUDIT:wy,DELETE_EVENTS:rI,DELETE_DRAW_DEFINITIONS:zN};function um(t){if(!t.tournamentRecord)return{error:q};let e="deleteDrawDefinitions",r=t.drawIds??[],n=t.event,{autoPublish:o=!0,tournamentRecord:i,auditData:s,eventId:a,force:c}=t,{appliedPolicies:u}=Tt({tournamentRecord:i,event:n}),p={...u,...t.policyDefinitions},m=Array.isArray(r)?r[0]:void 0;if(!n){let U=ze({tournamentRecord:i,eventId:a,drawId:m});if(U.error)return U;n=U.event}let d=[],l=[],f=[];if(!n?.drawDefinitions)return _({info:"event has no drawDefinition",result:{...C},stack:e});let g=n.drawDefinitions.map(({drawId:U})=>U);if(r.length||(r=g),r=r.filter(U=>g.includes(U)),!r.length)return _({info:"nothing to do; no matching drawIds in event.",result:{...C},stack:e});let I=J(Ht({event:n}).flightProfile,!1,!0),h=({participantId:U,drawPosition:N,qualifier:D,bye:M})=>({bye:M,qualifier:D,drawPosition:N,participantId:U}),S=c??u?.[rn]?.allowDeletionWithScoresPresent?.drawDefinitions,T=Jr({event:n})??{},y=T.drawIds??(T.drawDetails&&Object.keys(T.drawDetails))??[],E,P=[],A=n.drawDefinitions.filter(U=>{if(r.includes(U.drawId)){let N=nr({event:n,drawDefinition:U})?.matchUps??[];if(N.some(({score:G})=>he({score:G}))&&!S)return P.push(U.drawId),!0;let{drawId:M,drawType:R,drawName:b}=U,O=I?.flights?.find(G=>G.drawId===U.drawId);O&&(O.drawEntries=O.drawEntries?.filter(G=>Xr.includes(G.entryStatus))),y.includes(M)&&(y=y.filter(G=>G!==M),E=!0);let v=hn({stageSequence:1,drawDefinition:U,stage:rt})?.structures?.[0],F=(v?zp({structureId:v.structureId,tournamentRecord:i,drawDefinition:U}):void 0)?.positionAssignments?.map(h),w=hn({stage:ct,drawDefinition:U})?.structures,L=w?.length?w.map(G=>{let H=G.stageSequence;return{positionAssignments:zp({structureId:G.structureId,tournamentRecord:i,drawDefinition:U})?.positionAssignments.map(h),stageSequence:H}}):void 0,k={action:zN,payload:{drawDefinitions:[U],eventId:a??n?.eventId,auditData:s}};f.push(k),d.push(nt({tournamentId:i.tournamentId,eventId:a??n?.eventId,qualifyingPositionAssignments:L,positionAssignments:F,auditData:s,drawType:R,drawName:b,drawId:M})),N?.forEach(({matchUpId:G})=>l.push(G))}return!r.includes(U.drawId)});if(P.length&&!c)return _({context:{drawIdsWithScoresPresent:P},result:{error:oc},stack:e});if(n.drawDefinitions=A,I&&xo({event:n,extension:{name:pn,value:I}}),Fc({tournamentRecord:i}),E){let U={};for(let D of y)U[D]=T.drawDetails?.[D]??{published:!0};let N=ma({statusObject:{drawDetails:U},event:n});if(N.error)return{error:N.error}}if(f.length)if(dp(Mi)){let U=i.tournamentId;lt({topic:Mi,payload:{tournamentId:U,detail:f}});let D=(nn({element:n,itemType:Pa})?.timeItem?.itemValue||0)+1;ro({element:n,timeItem:{itemType:Pa,itemValue:D},removePriorValues:!0})}else z1({appliedPolicies:u,event:n,deletedDrawsDetail:d,auditData:s});if(l.length&&_n({tournamentId:i?.tournamentId,matchUpIds:l}),r.forEach(U=>bb({drawId:U})),o&&E){let U=da({...t.eventDataParams,drawIdsToRemove:r,policyDefinitions:p,tournamentRecord:i,event:n});if(U.error)return{...C,info:U.error}}return{...C}}function z1({appliedPolicies:t,event:e,deletedDrawsDetail:r,auditData:n}){if(t?.audit?.[Pa]===!1)return;let{extension:o}=mt({name:Pa,element:e}),i={...n,deletedDrawsDetail:r},s={value:Array.isArray(o?.value)?o?.value.concat(i):[i],name:Pa};At({element:e,extension:s})}function QN({autoPublish:t=!0,tournamentRecord:e,auditData:r,event:n,force:o}){if(!e)return{error:q};if(!n)return{error:Ot};let{flightProfile:i}=Ht({event:n});if(i){let s=i.flights?.map(({drawId:c})=>c).filter(Boolean),a=um({eventId:n.eventId,tournamentRecord:e,autoPublish:t,auditData:r,drawIds:s,event:n,force:o});return a.error?a:Dp({event:n,name:pn})}return{...C}}function nI(t){let{matchUpFormat:e,recoveryTimes:r,averageTimes:n,tournamentId:o,eventId:i}=t,s=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(s).length)return{error:xt};let a=Object.keys(s).filter(u=>!o||o===u);if(o&&!a.includes(o))return{error:B};let c;for(let u of a){let p=s[u],{event:m}=ze({tournamentRecord:p,eventId:i});i&&m&&(c=!0);let d=Q1({tournamentRecord:p,event:m,matchUpFormat:e,averageTimes:n,recoveryTimes:r});if(d.error)return d}return!i||c?{...C}:{error:qr}}function Q1({tournamentRecord:t,recoveryTimes:e,matchUpFormat:r,averageTimes:n,event:o}){if(!t)return{error:q};if(n&&!Array.isArray(n))return{error:B};if(e&&!Array.isArray(e))return{error:B};let i=Qo;if(o){let{extension:s}=mt({element:o,name:i}),a=s?.value||{},c=Ix({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});At({element:o,extension:{name:i,value:c}})}else{let{extension:s}=mt({element:t,name:i}),a=s?.value||{},c=Ix({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});At({extension:{name:i,value:c},element:t})}return{...C}}function Ix(t){let{matchUpRecoveryTimes:e=[],matchUpAverageTimes:r=[],matchUpFormat:n}=t,{averageTimes:o,recoveryTimes:i}=t;o=(o||[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let s=o?.length&&r.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c})=>c?.length).concat({matchUpFormatCodes:[n],averageTimes:o});i=(i||[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let a=i?.length&&e.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c,averageTimes:u})=>c?.length||u).concat({matchUpFormatCodes:[n],recoveryTimes:i});return{matchUpAverageTimes:s?.length&&s||r,matchUpRecoveryTimes:a?.length&&a||e}}function XN(t){let{tournamentRecord:e,recoveryMinutes:r,averageMinutes:n,matchUpFormat:o,categoryType:i,eventId:s,event:a}=t;if(!e)return{error:q};if(!Nr({matchUpFormat:o}))return{error:B};if(!a)return{error:Ot};let{averageTimes:c=[],recoveryTimes:u=[]}=fl({tournamentRecord:e,matchUpFormat:o,event:a}),p=a.category,m=p?.categoryName||p?.ageCategoryCode||a?.eventId,d={categoryNames:[m],minutes:{}},l={categoryNames:[m],minutes:{}},f=T=>{if(T.categoryTypes?.includes(i)&&console.log("encountered:",{categoryType:i}),!(T.categoryNames?.includes(m)&&(T.categoryNames=T.categoryNames.filter(y=>y!==m),d={minutes:T.minutes,categoryNames:[m]},!T.categoryNames.length)))return T},g=n&&!isNaN(dt(n)),I=r&&!isNaN(dt(r)),h=c.map(f).filter(T=>T?.categoryNames?.length),S=u.map(f).filter(T=>T?.categoryNames?.length);return g&&(Object.assign(d.minutes,{[a?.eventType||Lt]:n}),h.push(d)),I&&(Object.assign(l.minutes,{[a?.eventType||Lt]:r}),S.push(l)),!g&&!I?{error:B}:nI({averageTimes:g&&h,recoveryTimes:I&&S,tournamentRecord:e,matchUpFormat:o,eventId:s,event:a})}function Tl(t){if(t.event)return hx({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});let e=et(t,[{[Re]:!0,[kh]:!0}]);if(e.error)return e;let{tournamentRecords:r,eventId:n}=t;for(let o of Object.values(r??{})){let{event:i}=ze({tournamentRecord:o,eventId:n});if(i)return hx({event:i})}}return{error:qr}}function hx({event:t}){return Dp({event:t,name:Qo})}var Ly={MON:"MON",TUE:"TUE",WED:"WED",THU:"THU",FRI:"FRI",SAT:"SAT",SUN:"SUN"};function Fy(t){return!Array.isArray(t)||pt(t).length!==t.length?!1:t.every(e=>Object.keys(Ly).includes(e))}function ky({tournamentRecord:t,event:e,startDate:r}){if(!t)return{error:q};if(!e)return{error:Ot};if(!Oo.test(r))return{error:Ye};let n=Sx(t);if(n.error)return n;let{tournamentStartDate:o,tournamentEndDate:i}=n,s=new Date(Ut(r)).getTime();if(!o||!i||s<o||s>i)return{error:Ye};let a=e.endDate&&new Date(Ut(e.endDate)).getTime();return a&&s>a&&(e.endDate=r),e.startDate=r,{...C}}function Gy(t){let{tournamentRecord:e,event:r,endDate:n}=t;if(!e)return{error:q};if(!r)return{error:Ot};if(!Oo.test(n))return{error:Ye};let o=Sx(e);if(o.error)return o;let{tournamentStartDate:i,tournamentEndDate:s}=o,a=new Date(Ut(n)).getTime();if(!i||!s||a<i||a>s)return{error:Ye};let c=r.startDate&&new Date(Ut(r.startDate)).getTime();return c&&a<c&&(r.startDate=n),r.endDate=n,{...C}}function oI(t){let e=et(t,[{tournamentRecord:!0,event:!0},{[tr]:c=>Oo.test(c),[kr]:Ye,startDate:!1,endDate:!1},{[tr]:c=>c.filter(Boolean).every(u=>Oo.test(u)),[kr]:Ye,activeDates:!1},{[tr]:Fy,weekdays:!1}]);if(e.error)return e;let{tournamentRecord:r,weekdays:n,event:o,startDate:i,endDate:s}=t,a=t.activeDates?.filter(Boolean);if(i&&s){let c=new Date(Ut(i)).getTime(),u=new Date(Ut(s)).getTime();if(c>u)return{error:B}}if(a){let c=i||r.startDate,u=s||r.endDate,p=!c||a.every(d=>new Date(d)>=new Date(c)),m=!u||a.every(d=>new Date(d)<=new Date(u));if(!p||!m)return{error:Ye}}if(i){let c=ky({tournamentRecord:r,event:o,startDate:i});if(c.error)return c}if(s){let c=Gy({tournamentRecord:r,event:o,endDate:s});if(c.error)return c}return a&&(o.activeDates=a),n&&(o.weekdays=n),{...C}}function Sx(t){let{startDate:e,endDate:r}=t;return!Oo.test(e)||!Oo.test(r)?_({result:{error:gA},context:{startDate:e,endDate:r}}):{tournamentStartDate:new Date(Ut(e)).getTime(),tournamentEndDate:new Date(Ut(r)).getTime()}}function iI({event:t,orderedDrawIdsMap:e}){if(typeof t!="object")return{error:Ot};if(!e)return{error:st,info:"Missing drawIdsOrderMap"};if(typeof e!="object")return{error:B,info:"orderedDrawIdsMap must be an object"};let r=Object.values(e);if(!r.every(i=>!isNaN(i)))return{error:B,info:"drawOrder must be numeric"};if(pt(r).length!==r.length)return{error:B,info:"drawOrder values must be unique"};if(t.drawDefinitions?.length){let i=(t.drawDefinitions||[]).map(({drawId:a})=>a),s=Object.keys(e);if(s?.length&&jt(i,s).length!==i.length)return{error:B,info:"Missing drawIds"};t.drawDefinitions.forEach(a=>{a.drawOrder=e[a.drawId]})}let{flightProfile:o}=Ht({event:t});return o?.flights?.forEach(i=>{i.flightNumber=e[i.drawId]}),{...C}}function sI({tournamentRecord:t,event:e}){if(!t)return{error:q};if(!e)return{error:Ot};let{flightProfile:r}=Ht({event:e}),n=r?.flights&&Object.assign({},...r.flights.sort((o,i)=>o.flightNumber-i.flightNumber).map((o,i)=>({[o.drawId]:i+1})))||e.drawDefinitions?.length&&Object.assign({},...e.drawDefinitions.sort((o,i)=>o.drawOrder-i.drawOrder).map((o,i)=>({[o.drawId]:i+1})))||void 0;return n?iI({event:e,orderedDrawIdsMap:n}):{...C}}function JN({autoPublish:t=!0,tournamentRecord:e,auditData:r,drawId:n,event:o,force:i}){if(!e)return{error:q};if(!n)return{error:cn};if(!o)return{error:Ot};let{flightProfile:s}=Ht({event:o});if(s&&s.flights?.find(u=>u.drawId===n)){let u=s.flights.filter(m=>m.drawId!==n),p={name:pn,value:{...s,flights:u}};xo({event:o,extension:p})}if(o.drawDefinitions?.find(c=>c.drawId===n)){let c=um({drawIds:[n],eventId:o.eventId,tournamentRecord:e,autoPublish:t,auditData:r,event:o,force:i});if(c.error)return c}return sI({tournamentRecord:e,event:o})}function ZN(t){let e=et(t,[{[co]:!0,[ne]:!0,[Ff]:!1},{replacementIndividualParticipantId:!0,[tr]:h=>kt(h),existingIndividualParticipantId:!0,[In]:se,participantId:!0}]),{replacementIndividualParticipantId:r,existingIndividualParticipantId:n,tournamentRecord:o,drawDefinition:i,participantId:s,event:a,uuids:c}=t;if(e.error)return e;if(a?.eventType!==Kr)return{error:$n};if(!(a?.entries?.filter(({entryStatus:h})=>[Vr,Ci].includes(h)).map(({participantId:h})=>h)||[]).includes(r))return{error:ln};let p=(o.participants||[]).find(h=>h.participantId===s);if(p?.participantType!==ft)return{error:Hi,participant:p};let m=p.individualParticipantIds,d=[r,...m.filter(h=>h!==n)],{participant:l}=Sn({participantIds:d,tournamentRecord:o}),f;if(l)f=l.participantId;else{let h={participantId:c?.pop(),participantRole:xe,individualParticipantIds:d,participantType:ft},S=wn({participant:h,returnParticipant:!0,tournamentRecord:o});if(S.error)return S;f=S.participant.participantId}let{flightProfile:g}=Ht({event:a});if(i){let h=g?.flights?.find(({drawId:S})=>S===i.drawId);h&&(h.drawEntries=h.drawEntries.map(S=>S.participantId===s?{...S,participantId:f}:S)),i.entries=i.entries.map(S=>S.participantId===s?{...S,participantId:f}:S);for(let S of i.structures||[])if(S.structures){S.positionAssignments=void 0;for(let T of S.structures)T.positionAssignments=T.positionAssignments.map(y=>y.participantId===s?{...y,participantId:f}:y)}else S.positionAssignments&&(S.positionAssignments=S.positionAssignments.map(T=>T.participantId===s?{...T,participantId:f}:T))}a.entries=a.entries.map(h=>h.participantId===s&&{...h,participantId:f}||h.participantId===r&&{...h,participantId:n}||h);let I=o.events.some(({entries:h,eventId:S,drawDefinitions:T})=>a.eventId===S?T.some(({drawId:y,entries:E})=>y===i?.drawId?!1:E?.find(P=>P.participantId===s)):h?.find(y=>y.participantId===s));if(!I){let h=ns({addIndividualParticipantsToEvents:!1,participantIds:[s],tournamentRecord:o});if(h.error)return h}return{...C,participantOtherEntries:I,newPairParticipantId:f}}function kc(t){let{flight:e,suppressNotifications:r,modifyEventEntries:n,existingDrawCount:o,allowReplacement:i,checkEntryStatus:s,tournamentRecord:a,drawDefinition:c,event:u}=t;if(!c)return{error:Z};if(!u)return{error:Ot};u.drawDefinitions||(u.drawDefinitions=[]);let{drawId:p,drawName:m,entries:d}=c,{entries:l}=u,f=0;if(o!==void 0&&o!==u.drawDefinitions.length)return{error:B,info:"drawDefintions count mismatch"};let{flightProfile:g}=Ht({event:u}),I=e&&g?.flights?.find(O=>O.flightNumber===e.flightNumber),h=g?.links?.find(O=>O?.target?.drawId===p)?.source?.drawId;if(h&&!u.drawDefinitions.find(O=>O.drawId===h))return _({result:{error:Z},info:{sourceDrawId:h}});if(I&&I.drawId!==c.drawId)return _({result:{error:Sa},info:{relevantFlight:I}});let y=d?.every(({participantId:O,entryStatus:v})=>{let x=I?.drawEntries.find(F=>F.participantId===O);return!v||x?.entryStatus===v}),E=!s||l&&d?.every(({participantId:O,entryStatus:v,entryStage:x})=>l.find(w=>w.participantId===O&&(!w.entryStage||w.entryStage===x))?.entryStatus===v);if(I&&!y)return _({result:{error:Sa},context:{drawEntriesPresentInFlight:y,matchingEventEntries:E,relevantFlight:I},info:"Draw entries are not present in flight or do not match entryStatuses"});if(n&&d?.filter(Boolean).forEach(O=>{if(O?.entryStatus&&Xr.includes(O?.entryStatus)){let v=l?.filter(Boolean).find(x=>x.participantId===O.participantId);v&&O.entryStatus&&v?.entryStatus!==O.entryStatus&&(v.entryStatus=O.entryStatus,f+=1)}}),l&&!E)return _({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:E,eventEntries:l},error:Sa}});let P=g?.flights?.map(({flightNumber:O})=>!isNaN(O)&&dt(O))?.filter(Boolean)||[],A=u.drawDefinitions.map(({drawOrder:O})=>O&&dt(O))?.filter(Boolean)||[],U=Math.max(0,...A,...P)+1,N=g?.flights?.find(O=>O.drawId===p),D;if(N){N.drawName=c.drawName,D={name:pn,value:{...g,flights:g.flights}};let O=N.flightNumber;O&&!A.includes(O)?U=O:N.flightNumber=U}else{let O=g?.flights||[];O.push({manuallyAdded:!0,flightNumber:U,drawEntries:d,drawName:m,drawId:p}),D={name:pn,value:{...g||{},flights:O}}}xo({event:u,extension:D}),Object.assign(c,{drawOrder:U});let M=u.drawDefinitions.find(O=>O.drawId===p),R=a?.tournamentId,b=u.eventId;if(M){if(!i)return{error:YE};let v=nr({drawDefinition:M})?.matchUps?.map(Ue)??[],x=nr({drawDefinition:c})?.matchUps;if(!r){v?.length&&_n({matchUpIds:v,action:"modifyDrawDefinition",tournamentId:R,eventId:b}),x?.length&&Fo({matchUps:x,tournamentId:R,eventId:b}),u.drawDefinitions=u.drawDefinitions.map(w=>w.drawId===p?c:w);let F=c.structures?.map(({structureId:w})=>w);bt({drawDefinition:c,tournamentId:R,structureIds:F,eventId:b})}}else if(u.drawDefinitions.push(c),!r){let{matchUps:O}=nr({drawDefinition:c,event:u});O&&Fo({tournamentId:a?.tournamentId,matchUps:O}),Ma({drawDefinition:c,tournamentId:R,eventId:b})}return{...C,modifiedEventEntryStatusCount:f}}function tM(t){let{provisionalPositioning:e,useExistingSeedLimit:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,assignments:a,drawId:c,event:u}=t,p=0;if(!a?.length)return{error:Ql};if(!n)return{error:q};if(!c)return{error:cn};let m=sn({provisionalPositioning:e,drawDefinition:o,structureId:s});if(m.error)return m;let{seedAssignments:d,seedLimit:l}=m,f=Object.assign({},...(d??[]).filter(h=>h.seedNumber).map(h=>({[h.seedNumber]:h})));a.forEach(h=>{let{seedNumber:S}=h;l&&S<=l&&(!r||f[S])&&(f[S]=h)});let g=Object.values(f),I=g.map(h=>h?.participantId).filter(Boolean);if(I.length!==xI(I).length)return{error:qE};for(let h of g){let S=ra({...h,provisionalPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,event:u});if(S?.error)return S;S?.success&&p++}return p?{...C,modifications:p}:{error:Bs}}function aI({deleteExisting:t,event:e,flightProfile:r}){let n="attachFlightProfile";if(!r)return _({result:{error:st},stack:n});if(!e)return _({result:{error:Ot},stack:n});let{flightProfile:o}=Ht({event:e});return o&&!t?_({result:{error:gf},stack:n}):e.drawDefinitions?.length?_({result:{error:HE},stack:n}):(xo({event:e,extension:{name:pn,value:r}}),{flightProfile:J(r,!1,!0),...C})}function Tx({tournamentRecord:t,scaleAttributes:e,participantIds:r}){if(!t)return{error:q};if(!r)return{error:bo};if(!e)return{error:st,info:"scaleAttributes required"};let{scaleType:n,eventType:o,scaleName:i}=e,s=[tP,n,o,i].join(".");return t.participants?.forEach(a=>{r.includes(a.participantId)&&a.timeItems&&(a.timeItems=a.timeItems.filter(c=>c&&c?.itemType!==s))}),{...C}}function cI({tournamentRecord:t,scaleAttributes:e,drawDefinition:r,entryStatuses:n,drawId:o,event:i,stage:s}){if(!i)return{error:Ot};if(n&&!Array.isArray(n))return _({result:{error:B},info:li("entryStatus"),stack:"removeScaleValues"});let a=i.entries;if(o){let{flightProfile:p}=Ht({event:i}),m=p?.flights?.find(d=>d.drawId===o);m?a=m.drawEntries:a=r?.entries}let u=(a||[]).filter(p=>(!s||!p.entryStage||p.entryStage===s)&&(!n||n.includes(p.entryStatus))).map(St);return Tx({tournamentRecord:t,scaleAttributes:e,participantIds:u})}function yl({removePriorValues:t,tournamentRecord:e,displaySettings:r,status:n=Cr,event:o}){if(!e)return _({result:{error:q}});if(!o)return _({result:{error:Ot}});if(!ht(r))return _({result:{error:st}});if(ht(r.draws))for(let s of Object.keys(r.draws)){let a=r.draws[s].scheduleDetails??[];if(a.length){let c=[];for(let u of a){let p=c.find(m=>DC(m.attributes,u.attributes));p?.dates&&u.dates?p.dates.push(...u.dates):c.push(u)}r.draws[s].scheduleDetails=c}}let i=ma({statusObject:{displaySettings:r},removePriorValues:t,status:n,event:o});return i.error?i:{...C}}function eM({tournamentRecord:t,drawDefinition:e,entryStatuses:r,scaleName:n,drawId:o,event:i,stage:s}){if(!t)return{error:q};if(!i)return{error:Ot};n=n||i.category?.categoryName||i.category?.ageCategoryCode;let a={eventType:i.eventType,scaleType:Ao,scaleName:n};return cI({tournamentRecord:t,scaleAttributes:a,drawDefinition:e,entryStatuses:r,drawId:o,event:i,stage:s})}function rM(t){let e=et(t,[{[ne]:!0},{eventIds:!0,[He]:Be}]);if(e.error)return e;let{removePairParticipants:r,tournamentRecord:n,eventIds:o}=t,i=[],s=[],a=[],c=[];if(n.events=(n.events||[]).filter(u=>{if(o.includes(u.eventId)){let d={action:rI,payload:{events:[u]}};i.push(d),s.push({tournamentId:n.tournamentId,eventName:u.eventName,eventType:u.eventType,category:u.category,eventId:u.eventId,gender:u.gender})}let p=u.eventType===Kr?(u.entries||[]).map(({entryStatus:d,participantId:l})=>d!==Vr&&l).filter(Boolean):[],m=o.includes(u.eventId);return m?c.push(...p):a.push(...p),!m}),r){let u=c.filter(p=>!a.includes(p));n.participants=n.participants.filter(({participantId:p})=>!u.includes(p))}if(Fc({tournamentRecord:n}),i.length)if(dp(Mi)){let u=n.tournamentId;lt({topic:Mi,payload:{type:rI,tournamentId:u,detail:i}})}else _c({tournamentRecord:n,timeItem:{itemValue:s,itemType:rI}});return{...C}}function nM(t){let e=et(t,[{tournamentRecord:!0,eventId:!0,event:!0},{eventUpdates:!0,_ofType:zr}]);if(e.error)return e;let{eventUpdates:r,event:n}=t,o="modifyEvent",i=Z1(t),s=t0({enteredParticipants:i}),{enteredParticipantGenders:a,enteredParticipantTypes:c}=s,u=Ht({event:n})?.flightProfile?.flights,p=!n.drawDefinitions?.length&&!u?.length,m=e0({noFlightsNoDraws:p,enteredParticipantGenders:a,eventUpdates:r,stack:o});if(m.error)return m;let d=r0({enteredParticipantTypes:c,eventUpdates:r,stack:o});if(d.error)return d;let l=X1({...t,...s,enteredParticipants:i,stack:o});if(l.error)return l;let f=J1({...t,stack:o});return f.error?f:(r.eventType&&(n.eventType=r.eventType),r.eventName&&(n.eventName=r.eventName),r.gender&&(n.gender=r.gender),{...C})}function X1(t){let e=t.eventUpdates?.category;if(!e)return{...C};let r=Zc({category:e});if(r.error)return r;if(t.event.eventType===_e){let n=t.event?.drawDefinitions?.map(u=>di(u))??[],o=di(t.event),s=(to(t)?.matchUps??[]).map(u=>di(u))??[];if(![o,...n,...s].filter(Boolean).every(u=>u.collectionDefinitions.every(p=>!p.category||tu({category:t.eventUpdates.category,childCategory:p.category}))))return _({result:{error:zc},stack:t.stack})}if(t.enteredParticipants?.length){let n=t.eventUpdates.startDate||t.event.startDate||t.tournamentRecord.startDate,o=t.eventUpdates.endDate||t.event.endDate||t.tournamentRecord.endDate,i=t.enteredParticipants.map(c=>c.participantType===Et?c:c.individualParticpants??[]).flat(),s=Ys({category:e,consideredDate:n}),a=Ys({category:e,consideredDate:o});if(s?.ageMinDate||s?.ageMaxDate||a?.ageMinDate||a?.ageMaxDate)for(let c of i){let u=c.person?.birthDate;if(!u)return _({result:{error:mA},stack:t.stack});let p=new Date(u).getTime();if(s.ageMinDate||s.ageMaxDate){let m=new Date(s.ageMinDate).getTime(),d=new Date(s.ageMaxDate).getTime();if(p<m||p>d)return _({result:{error:zI},stack:t.stack})}if(a.ageMin||a.ageMax){let m=new Date(a.ageMinDate).getTime(),d=new Date(a.ageMaxDate).getTime();if(p<m||p>d)return _({result:{error:zI},stack:t.stack})}}}return{...C}}function J1(t){let{tournamentRecord:e,eventUpdates:r,event:n,stack:o}=t;if(r.startDate||r.endDate){let i=oI({startDate:r.startDate,endDate:r.endDate,tournamentRecord:e,event:n});if(i.error)return _({result:i,stack:o})}return{...C}}function Z1(t){let{tournamentRecord:e,event:r}=t,n=r?.entries?.filter(({entryStatus:o})=>{let i=o;return[...Xr,on].includes(i)}).map(({participantId:o})=>o)??[];return n?Ft({participantFilters:{participantIds:n},withIndividualParticipants:!0,tournamentRecord:e}).participants??[]:[]}function t0({enteredParticipants:t}){let e=[],r=t.reduce((o,i)=>{let s=i.person?.sex?[i.person.sex]:i.individualParticpants?.map(a=>a.person?.sex)||[];return e.push(...s),o.includes(i.participantType)?o:o.concat(i.participantType)},[]),n=pt(e);return{enteredParticipantTypes:r,enteredParticipantGenders:n}}function e0({noFlightsNoDraws:t,enteredParticipantGenders:e,eventUpdates:r,stack:n}){let o=!e.length||!r.gender||To(r.gender)||e.length===1&&e[0]===r.gender||t&&en(r.gender);return r.gender&&!o?_({context:{gender:r.gender,validGender:o},result:{error:cp},stack:n}):{...C}}function r0({enteredParticipantTypes:t,eventUpdates:e,stack:r}){let o=(t.includes(_e)&&[_e]||t.includes(Et)&&[Qn]||t.includes(ft)&&[Kr]||[Kr,Qn,_e]).includes(e.eventType??"");return e.eventType&&!o?_({context:{participantType:e.eventType,validEventType:o},result:{error:$n},stack:r}):{...C}}function pm({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:n,event:o,stage:i}){let s="addFlight";if(!o)return _({result:{error:Ot},stack:s});if(!r)return _({result:{error:st},stack:s});if(e?.length){let g=(o.entries??[]).map(St),I=e.map(St);if(jt(I,g).length!==I.length)return _({result:{error:B},stack:s})}let a=Ht({event:o})?.flightProfile,c=a?.flights?.map(({flightNumber:g})=>!isNaN(g)&&dt(g))?.filter(Boolean)||[],u=Math.max(0,...c)+1,m={drawId:n||Nt(),flightNumber:u,drawEntries:e,drawName:r};if(i&&(m.stage=i),t&&(m.qualifyingPositions=t),(a?.flights||[]).find(({drawId:g})=>g===m.drawId))return _({result:{error:WA},stack:s});let l=(a?.flights||[]).concat(m),f={name:pn,value:{...a||{},flights:l}};return xo({event:o,extension:f})}var pM={};Xt(pM,{drawMatic:()=>tl,garman:()=>uM,generateAdHocMatchUps:()=>Wu,generateAdHocRounds:()=>Zd,generateAndPopulatePlayoffStructures:()=>kd,generateCourts:()=>uI,generateDrawDefinition:()=>Wa,generateDrawMaticRound:()=>qd,generateDrawStructuresAndLinks:()=>Wd,generateDrawTypeAndModifyDrawDefinition:()=>jd,generateFlightProfile:()=>Ex,generateLineUps:()=>By,generateQualifyingStructure:()=>_d,generateSeedingScaleItems:()=>Oy,generateStatCrew:()=>Dx,generateVoluntaryConsolation:()=>LT,roundRobinGroups:()=>DO});var n0="splitLevelBased",sM="splitWaterfall",aM="splitShuttle",yx={SPLIT_LEVEL_BASED:n0,SPLIT_WATERFALL:sM,SPLIT_SHUTTLE:aM};function Ex(t){let{drawNameRoot:e="Flight",attachFlightProfile:r,tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,deleteExisting:s,sortDescending:a,drawNames:c=[],flightsCount:u,splitMethod:p,uuids:m=[],event:d,stage:l}=t;if(!d)return{error:Ot};let f=d.entries??[],{flightProfile:g}=Ht({event:d});if(g&&r&&!s)return{error:gf};let I=t.scaledEntries??ca({tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,sortDescending:a,event:d,stage:l}).scaledEntries,h=I.map(St),S=Tr(f.filter(({participantId:D})=>!h.includes(D)).filter(D=>(!l||!D.entryStage||D.entryStage===l)&&(!D.entryStatus||mi.includes(D.entryStatus)))),T=I.concat(...S),y=T.length,E=Math.ceil(y/u),P=Ae(T,E);p===sM?P=Wl(T,u):p===aM&&(P=Wl(T,u,!0));function A(D){return(D||[]).map(({participantId:M,scaleValue:R})=>{let b=f.find(O=>O.participantId===M);return b?.scaleValue&&R&&(b.scaleValue=R),b}).sort((M,R)=>M.scaleValue-R.scaleValue).map((M,R)=>(M.scaleValue&&(M.seedNumber=R+1),M))}let U=tt(0,u).map(D=>{let M=D+1;return{flightNumber:M,drawId:m?.pop()??Nt(),drawEntries:A(P[D]),drawName:c?.length&&c[D]||`${e} ${M}`}}),N={scaleAttributes:o,splitMethod:p,flights:U};if(r){let D=aI({flightProfile:N,deleteExisting:s,event:d});return{splitEntries:Dr()&&P||void 0,...D}}else return{flightProfile:N,...C}}function cM({json:t,tagName:e}){let r=Object.keys(t).filter(i=>Array.isArray(t[i])).map(i=>({key:i,value:t[i].filter(s=>typeof s=="object"&&Object.keys(s).length===1)})),n=Object.keys(t).filter(i=>typeof t[i]=="object"&&!Array.isArray(t[i])).map(i=>({key:i,value:t[i]})),o=Object.keys(t).filter(i=>["string","number"].includes(typeof t[i])).map(i=>({key:i,value:t[i]}));return Ax({tagName:e,attributes:o,childArrays:r,childObjects:n})}function Ax(t){let{tagName:e,attributes:r=[],childArrays:n=[],childObjects:o}=t,i=`\r
|
|
24
24
|
`,s=l=>{let f=Object.keys(l)[0],g=l[f];return{key:f,value:g}},a=n?.map(({key:l,value:f})=>Ax({tagName:l,childObjects:f.map(s)})).join(`\r
|
|
25
25
|
`),c=o?.map(({key:l,value:f})=>cM({tagName:l,json:f??[]})).join(`\r
|
|
26
|
-
`),u=r?.map(({key:l,value:f})=>`${l}="${f}"`).join(" "),p=u?` ${u}`:"";if(e==="childArray")return c;let m=c?.length?`${i}${c}${i}`:"",d=a?.length?`${i}${a}${i}`:"";return`<${e}${p}>${m}${d}</${e}>`}function Dx(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{startDate:n,tournamentId:o,tournamentName:i}=r,{participantMap:s,matchUps:a,mappedMatchUps:c}=Ft({withMatchUps:!0,withEvents:!0,tournamentRecord:r}),u=r.participants.filter(y=>y.participantType===wt),p=a?.filter(y=>y.matchUpType===wt)??[],m=p?.reduce((y,E)=>{let P=E?.tieMatchUps??[];return P&&[...y,...P]},[])??[],d=a?.filter(y=>y.matchUpType===Lt)??[],l=a?.filter(y=>y.matchUpType===vt)??[],f=m.length===d.length+l.length,g=p.length===1&&f,h={mappedMatchUps:c,participantMap:s,tournamentName:i,tournamentId:o,tournament:f?"N":"Y",startDate:n},S=[],T=[];if(g){let y=p[0],{json:E,xml:P}=Ux({teamParticipants:u,teamMatchUp:y,...h,doubles:l,singles:d});T.push(E),S.push(P)}else for(let y of p){let E=y?.sides?.map(({participant:N})=>N?.participantId).filter(Boolean);if(E?.length!==2)continue;let P=E.map(N=>N&&s?.[N]?.participant),{xml:A,json:U}=Ux({doubles:y.tieMatchUps?.filter(N=>N.matchUpType===vt),singles:y.tieMatchUps?.filter(N=>N.matchUpType===Lt),teamParticipants:P,teamMatchUp:y,...h});T.push(U),S.push(A)}return{json:T,xml:S,...C}}function Ux({teamParticipants:t,mappedMatchUps:e,participantMap:r,tournamentName:n,tournamentId:o,teamMatchUp:i,tournament:s,startDate:a,doubles:c,singles:u}){let p=t?.find(y=>y.participantRoleResponsibilities?.includes("Home")),m=t?.filter(y=>y.participantId!==p?.participantId),d=Kn(a,"/","MDY"),l=p?.participantName||m?.[1]?.participantName,f=p?.participantId||m?.[1]?.participantId,g=m?.[0]?.participantName,I=m?.[0]?.participantId,h={},S=t.map(y=>({team:{...s0({teamParticipant:y,teamMatchUp:i,uniValues:h,participantMap:r,mappedMatchUps:e,homeid:f})}})),T=nt({venue:{tournamentname:s?n:void 0,neutralgame:p?"N":"Y",gameid:o,officials:{},tournament:s,rules:{},homename:l,visname:g,homeid:f,visid:I,date:d},childArray:S,singles_matches:u?.map(y=>Px({matchUp:y,homeid:f,uniValues:h})),doubles_matches:c?.map(y=>Px({matchUp:y,homeid:f,uniValues:h}))});return{json:T,xml:cM({json:T,tagName:"tngame"})}}function o0({homeid:t,uniValues:e,participant:r}){if(!r)return{};let n=r.individualParticipants?.length===2,o=n?pt(r.individualParticipants?.map(g=>g.teams?.[0]?.participantId)):[],i=n?pt(r.individualParticipants?.map(g=>g.teams?.[0]?.teamId)):[],s=!n&&r.teams?.[0]?.participantId||o?.length===1&&o[0]||void 0,a=!n&&r.teams?.[0]?.teamId||i?.length===1&&i[0]||s,c=n?void 0:r.participantName,u=r.individualParticipants?.[0]?.participantName,p=r.individualParticipants?.[1]?.participantName,m=t&&(s===t?"H":"V")||"",d=n?void 0:e[s][r.participantId],l=e[s][r.individualParticipants?.[0]?.participantId],f=e[s][r.individualParticipants?.[1]?.participantId];return nt({vh:m,uni:d,uni_1:l,uni_2:f,team:a,name:c,name_1:u,name_2:p})}function i0({sets:t,sideNumber:e}){return Object.assign({},...t?.map(r=>{let{setNumber:n,side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a}=r,c=`set_${n}`,u=`tie_${n}`,p=e===1?o:i,m=e===1?s:a;return{[c]:p,[u]:m}})??[])}function s0({teamParticipant:t,teamMatchUp:e,participantMap:r,mappedMatchUps:n,homeid:o,uniValues:i}){let{participantId:s,participantName:a}=t,c=o&&(s===o?"H":"V")||"",u=r?.[s]?.matchUps,p=u&&Object.keys(u),m=e?.sides?.find(({participant:E})=>E.participantId===s)?.sideNumber,d=e?.score?.sets?.[0]?.[`side${m}Score`]??0;i[s]={};let l={SINGLES:{w:0,l:0},DOUBLES:{w:0,l:0}},f=[],g=[],I=0;for(let E of p??[]){let P=n?.[E],A=P.sides.find(({participant:N})=>N.participantId===s)?.sideNumber,U=P.score?.sets?.[0]?.[`side${A}Score`]??0;I+=U;for(let N of P.tieMatchUps??[]){let{matchUpType:D,winningSide:M}=N,R=M&&(M===A?"w":"l")||"";R&&(l[D][R]+=1);let b=R==="w"?"1":"0",O=R==="l"?"1":"0";if(D===Lt){let v=g.length+1;g.push({singles_pair:{pair:v,won:b,lost:O,tied:"0"}})}else if(D===vt){let v=f.length+1;f.push({doubles_pair:{pair:v,won:b,lost:O,tied:"0"}})}}}let h=[{singles:{childArray:g,won:l.SINGLES.w,lost:l.SINGLES.l}},{doubles:{childArray:f,won:l.DOUBLES.w,lost:l.DOUBLES.l}}],S=[],T=1;for(let E of t.individualParticipantIds){let P=r?.[E];if(P){let{participant:A,counters:U}=P,N={won:U?.DOUBLES?.wins||0,lost:U?.DOUBLES?.losses||0},D={won:U?.SINGLES?.wins||0,lost:U?.SINGLES?.losses||0},{participantName:M,participantId:R}=A;i[s][R]=T,S.push({player:{name:M,uni:T,singles:D,doubles:N}})}T+=1}return{vh:c,id:s,name:a,score:d||I,totals:h,childArray:S}}function Px({matchUp:t,homeid:e,uniValues:r}){let{collectionPosition:n,orderOfFinish:o,matchUpType:i,sides:s}=t??{},a=s?.map(u=>{let{sideNumber:p,participant:m}=u,d=i0({sets:t.score?.sets,sideNumber:p});return{[i===Lt?"singles_score":"doubles_score"]:{...o0({homeid:e,uniValues:r,participant:m}),...d}}});return{[i===Lt?"singles_match":"doubles_match"]:{match:n,order:o,childArray:a}}}var a0="DESC",Vy="DESC",Nx={ASC:"ASC",ASCENDING:"ASC",DESC:a0,DESCENDING:Vy};function By(t){let{tieFormat:e}=t,{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:o,scaleAccessor:i,singlesOnly:s,attach:a,event:c}=t;if(c?.eventType!==Or)return{error:$n};if(!n)return{error:q};if(!e&&!o)return{error:br};if(e=e??We({drawDefinition:o,event:c})?.tieFormat,ar({tieFormat:e}).error)return{error:Yo};if(typeof i!="object"&&!r)return{error:B,context:{scaleAccessor:i}};let u={},m=(o?.entries??c?.entries??[]).filter(R=>R?.entryStatus===Gr).map(St),{participants:d=[]}=Ft({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),l=d.filter(({participantId:R})=>m.includes(R)),f=R=>R===Ai?"rankings":"ratings",g=c?.category?.categoryName??c?.category?.ageCategoryCode,{scaleName:I=g,scaleType:h=Ai,sortOrder:S,accessor:T}=i||{},y=f(h),E=(R,b)=>{let O=R[y]?.[b];if(!O&&r&&(O=R[y]?.[Ia]),Array.isArray(O)){let v=O.find(x=>x.scaleName===I)?.scaleValue;if(Jt(v))return v;if(T&&typeof v=="object")return v[T]}return 0},P=(R,b,O)=>{let v=S===Vy?b:R,x=S===Vy?R:b;return E(v,O)-E(x,O)},A=(R,b)=>P(R,b,Ia),U=(R,b)=>P(R,b,Gi),N=[],D=e?.collectionDefinitions??[];for(let R of l){let b=R.individualParticipants?.sort(A)??[],O=s?b:R.individualParticipants?.sort(U)??[],v={};for(let F of D){let w=[],{collectionId:L,matchUpCount:k,matchUpType:G,gender:H}=F,K=de(Ia)(G);tt(0,k).forEach(Y=>{let j=K?b:O??[],V=Y+1,$=[];tt(0,K?1:2).forEach(X=>{let W=j?.find(it=>{let z=yr(H),Q=z&&(Dn(H)&&z||en(H)&&[Le,lr][X]);return(!Q||Q===it.person?.sex)&&!w.includes(it.participantId)})?.participantId;W&&($.push(W),w.push(W),v[W]||(v[W]=[]),v[W].push({collectionPosition:V,collectionId:L}))}),K||N.push($)})}let x=Object.keys(v).map(F=>({collectionAssignments:v[F],participantId:F}));u[R.participantId]=x}let M=[];for(let R of N){let{participant:b}=Sn({tournamentParticipants:d,participantIds:R});if(!b){let O={individualParticipantIds:R,participantRole:xe,participantType:ft};M.push(O)}}if(a){for(;M.length;)wn({participant:M.pop(),tournamentRecord:n});At({element:o,extension:{name:wo,value:u}})}return{...C,lineUps:u,participantsToAdd:M}}function uI(t){if(!t)return{error:st};let e=et(t,[{dates:!1,[tr]:s=>Array.isArray(s)&&s.every(Mr)},{uuids:!1,[tr]:s=>Array.isArray(s)&&s.every(kt)},{startTime:!1,endTime:!1,[tr]:sh},{idPrefix:!1,namePrefix:!1,[tr]:kt},{count:!0,[tr]:Jt}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord??{},o=t.dates||r&&n&&js(r,n)||[],i=tt(1,t.count+1).map(s=>nt({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${s}`)??Nt(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${s}`),dateAvailability:o.map(a=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:a}))}));return{...C,courts:i}}var uM={};Xt(uM,{default:()=>c0,garman:()=>Cx});function ja({court:t,date:e}){let r=e&&t.dateAvailability.find(o=>zn(o.date,e)),n=t.dateAvailability.find(o=>!o.date);return r||n}function _s(t){let e=et(t,[{courtDate:!0,_ofType:zr}]);if(e.error)return e;let{includeBookingTypes:r=[],courtDate:n}=t,o=[],i=Ge(n.startTime);(n.bookings||[]).filter(a=>!a.bookingType||!r.includes(a.bookingType)).sort((a,c)=>Nf(a.startTime).localeCompare(Nf(c.startTime))).forEach(a=>{let c={startTime:zt(i.toISOString()),endTime:a.startTime};Ge(a.startTime)>i&&o.push(c),Ge(a.endTime)>i&&(i=Ge(a.endTime))});let s={startTime:zt(i.toISOString()),endTime:n.endTime};return Ge(n.endTime)>i&&o.push(s),{timeSlots:o}}function Mx({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:r,periodEndTime:n}){let o=s=>{let{timeSlots:a}=_s({includeBookingTypes:e,courtDate:s});return!!a?.filter(i)?.length};function i(s){let a=Ge(s.startTime),c=Ge(s.endTime);return a>r||c<n?!1:ya(r,c)>=t}return{enoughTime:o}}function Hy(t){let e=et(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:Be}]);if(e.error)return e;let{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:o,date:i}=t,s=t.courts,a=Ge(o),c=Rf(a,r),{enoughTime:u}=Mx({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:a,periodEndTime:c});return{availableToScheduleCount:(s?.filter(m=>{if(!Array.isArray(m.dateAvailability))return!1;let d=ja({date:i,court:m});return!!(d&&u(d))})||[]).length,...C}}function mm(t){let{remainingScheduleTimes:e=[],clearScheduleDates:r,periodLength:n=30,scheduleDate:o,courts:i=[]}=t,{bookings:s=[]}=t;if(!Array.isArray(i)||!i.length)return{error:B,courts:i};if(!Array.isArray(s))return{error:vm};if(!Mr(o))return{error:Ye};r&&(Array.isArray(r)?r.includes(o)&&(s=[]):s=[]);let{courtBookings:a,unassignedBookings:c}=s.reduce((l,f)=>{let{courtId:g}=f;return g?l.courtBookings[g]?l.courtBookings[g].push(f):l.courtBookings[g]=[f]:l.unassignedBookings.push(f),l},{courtBookings:{},unassignedBookings:[]}),u=i.map((l,f)=>{let{courtId:g,courtName:I}=l,h=a[g]||[],S=ja({date:o,court:l})||{},{bookings:T=[],startTime:y,endTime:E,date:P}=S,U=[e[f]&&{startTime:y,endTime:e[f]},...J(T,!1,!0),...h].filter(Boolean);return{courtId:g,courtName:I,dateAvailability:{bookings:U,startTime:y,endTime:E,date:P}}});c.sort((l,f)=>Yt(l.startTime)-Yt(f.startTime));let p=()=>u.map(l=>{let f=l.dateAvailability,{timeSlots:g=[]}=_s({courtDate:f});return{courtName:l.courtName,courtId:l.courtId,timeSlots:g}}).flat(),m=[];for(let l of c){let{startTime:f,endTime:g,averageMinutes:I,recoveryMinutes:h,matchUpId:S}=l,T=Yt(f),y=Yt(g),P=p().reduce((A,{courtId:U,courtName:N,timeSlots:D})=>{let M;return D.find(({startTime:b,endTime:O})=>{M=Yt(b)-T;let v=T>=Yt(b);return y<=Yt(O)&&A.startDifference!==0&&((M===0||M+n>=0)&&(A.startDifference===void 0||M<A.startDifference)||v)})?{courtName:N,courtId:U,startDifference:M}:A},{});if(P.courtId){let A={averageMinutes:I,recoveryMinutes:h,matchUpId:S,startTime:f,endTime:g};m.push(A),u.find(({courtId:N})=>N===P.courtId)?.dateAvailability.bookings.push(A)}else console.log({unassignedBooking:l})}return{virtualCourts:u.map(({courtId:l,courtName:f,dateAvailability:g})=>({dateAvailability:[g],courtName:f,courtId:l})),assignedBookings:m}}function zu({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:r}){let n=(t||90)+(r||0);return e>n?n:e||30}function Wy(t){let{startTime:e="8:00",endTime:r="20:30",count:n=10,date:o}=t??{};return tt(0,n).map(()=>({dateAvailability:[{date:o,startTime:e,endTime:r}]}))}function Gc({scheduleDate:t,startTime:e,endTime:r,courts:n}){let o=e&&"startTime"||r&&"endTime"||void 0;return n.reduce((i,s)=>{let a=ja({date:t,court:s}),c=o&&(a?.[o]||s[o]);return c&&(!i||e&&Yt(c)<Yt(i)||r&&Yt(c)>Yt(i))?c:i},void 0)}function Rx({averageMinutes:t,startTime:e,endTime:r,courts:n,date:o}){e=e||Gc({courts:n,scheduleDate:o,startTime:!0}),r=r||Gc({courts:n,scheduleDate:o,endTime:!0});let i;if(e&&r){let s=Ge(e),a=Ge(r);for(let c of n||[]){if(!Array.isArray(c.dateAvailability))continue;let u=ja({court:c,date:o}),{timeSlots:p}=_s({courtDate:u});p?.forEach(m=>{let d=Ge(m.startTime),l=Ge(m.endTime);if(d>a||d<s||l<s)return!1;if(ya(d,l)>=t){let I=zt(d.toISOString());(!i||I<i)&&(i=I)}})}}return{firstTimeSlotStartTime:i}}function El(t){let e=et(t,[{courts:!0,_ofType:Be}]);if(e.error)return e;let{date:r=Mf(),startTime:n="08:00",endTime:o="19:00",periodLength:i,courts:s}=t,{calculateStartTimeFromCourts:a=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:p,courtsCount:m,bookings:d}=t;i=i||zu({averageMatchUpMinutes:u}),r=Ut(r),n=zt(n),o=zt(o);let l=0,f=0,g=0,I=0,h=0;!s&&m&&(s=Wy({startTime:n,endTime:o,count:m,date:r}));let{virtualCourts:S}=mm({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:r,periodLength:i,bookings:d,courts:s}),{firstTimeSlotStartTime:T}=Rx({averageMinutes:u,courts:S,startTime:n,endTime:o,date:r});a&&T&&(n=T??n);let y=Yt(n),P=Yt(o)-y,A=Math.floor(P/i),N=tt(0,A+1).map(M=>{let R=y+M*i,b=JC(R),O=Hy({courts:S??[],averageMatchUpMinutes:u,periodStart:b,date:r});if(O.error)return{error:O.error};let{availableToScheduleCount:v=0}=O,x=v>f?v-f:0;h+=M?v:0;let F=M?h/M:v,L=i*F/u,k=M?L*(M-1)+F:F,G=v?f&&k-l||x:0;l=k,f=v,g+=G;let H=dt(g)-I;return I+=H,{periodStart:b,add:H,availableToScheduleCount:v,newCourts:x,totalMatchUps:I}});return{scheduleTimes:N.reduce((M,R)=>{let O=tt(0,R.add).map(()=>({scheduleTime:R.periodStart}));return M.concat(...O)},[]).flat(),timingProfile:N,totalMatchUps:I}}var Cx={getCourtsAvailableAtPeriodStart:Hy,generateTimeSlots:_s,getScheduleTimes:El,courtGenerator:Wy},c0=Cx;var jy={};Xt(jy,{isValid:()=>Nr,isValidMatchUpFormat:()=>Nr,parse:()=>Ne,stringify:()=>gp});var bM={};Xt(bM,{allCompetitionMatchUps:()=>Mn,allDrawMatchUps:()=>nr,allEventMatchUps:()=>to,allTournamentMatchUps:()=>ye,analyzeMatchUp:()=>cm,applyLineUps:()=>RM,assignMatchUpSideParticipant:()=>mM,assignTieMatchUpParticipantId:()=>Pl,bulkMatchUpStatusUpdate:()=>PM,calculateWinCriteria:()=>Os,checkInParticipant:()=>mI,checkMatchUpIsComplete:()=>Ts,checkOutParticipant:()=>pI,competitionScheduleMatchUps:()=>Ku,disableTieAutoCalc:()=>AM,drawMatchUps:()=>Dy,enableTieAutoCalc:()=>TM,eventMatchUps:()=>Il,filterMatchUps:()=>_i,findMatchUp:()=>tI,getAllDrawMatchUps:()=>ie,getAllStructureMatchUps:()=>yt,getCheckedInParticipantIds:()=>Is,getCompetitionMatchUps:()=>am,getEventMatchUpFormatTiming:()=>Iy,getHomeParticipantId:()=>yy,getMatchUpCompetitiveProfile:()=>Du,getMatchUpContextIds:()=>Ey,getMatchUpDailyLimits:()=>Sl,getMatchUpDailyLimitsUpdate:()=>hy,getMatchUpDependencies:()=>an,getMatchUpFormat:()=>Ay,getMatchUpFormatTiming:()=>Nu,getMatchUpFormatTimingUpdate:()=>fy,getMatchUpScheduleDetails:()=>yd,getMatchUpType:()=>Ed,getMatchUpsStats:()=>Uy,getModifiedMatchUpFormatTiming:()=>fl,getParticipantResults:()=>ku,getPredictiveAccuracy:()=>Ty,getRoundMatchUps:()=>Ke,getRounds:()=>Py,isValidMatchUpFormat:()=>Nr,matchUpActions:()=>Bd,mutate:()=>CM,participantScheduledMatchUps:()=>Sy,query:()=>xN,removeDelegatedOutcome:()=>yM,removeMatchUpSideParticipant:()=>lI,removeTieMatchUpParticipantId:()=>lM,replaceTieMatchUpParticipantId:()=>dI,resetAdHocMatchUps:()=>NM,resetMatchUpLineUps:()=>gI,resetScorecard:()=>hI,resetTieFormat:()=>II,setDelegatedOutcome:()=>DM,setMatchUpFormat:()=>UM,setMatchUpStatus:()=>Qu,setOrderOfFinish:()=>MM,substituteParticipant:()=>EM,tallyParticipantResults:()=>Fa,toggleParticipantCheckInState:()=>Al,tournamentMatchUps:()=>hl,updateTieMatchUpScore:()=>go,validMatchUp:()=>pg,validMatchUps:()=>Br});var CM={};Xt(CM,{applyLineUps:()=>RM,assignMatchUpSideParticipant:()=>mM,assignTieMatchUpParticipantId:()=>Pl,bulkMatchUpStatusUpdate:()=>PM,checkInParticipant:()=>mI,checkOutParticipant:()=>pI,disableTieAutoCalc:()=>AM,enableTieAutoCalc:()=>TM,findMatchUp:()=>tI,removeDelegatedOutcome:()=>yM,removeMatchUpSideParticipant:()=>lI,removeTieMatchUpParticipantId:()=>lM,replaceTieMatchUpParticipantId:()=>dI,resetAdHocMatchUps:()=>NM,resetMatchUpLineUps:()=>gI,resetScorecard:()=>hI,resetTieFormat:()=>II,setDelegatedOutcome:()=>DM,setMatchUpFormat:()=>UM,setMatchUpStatus:()=>Qu,setOrderOfFinish:()=>MM,substituteParticipant:()=>EM,toggleParticipantCheckInState:()=>Al,updateTieMatchUpScore:()=>go});function mM({tournamentRecord:t,drawDefinition:e,participantId:r,sideNumber:n,matchUpId:o,event:i}){if(r&&typeof r!="string")return{error:ln};if(!e)return{error:Z};if(!o)return{error:sr};let s=n===void 0;if(s&&(n=1),![1,2].includes(n))return _({result:{error:B,context:{sideNumber:n}}});let{matchUp:a,structure:c}=Vt({drawDefinition:e,matchUpId:o,event:i});if(!a)return{error:we};if(!(!c?.structures&&!(e.drawType&&e.drawType!==Fr)&&!c?.matchUps?.find(({roundPosition:p})=>!!p)))return{error:Om};if(!r&&(a?.score?.scoreStringSide1||ae.includes(a?.matchUpstatus)||a?.matchUpStatus&&[oe,be].includes(a.matchUpStatus)))return{error:ip,info:"matchUp has completed status or score"};if(a){if(a.sides=[1,2].map(p=>{let m=a.sides?.find(d=>d.sideNumber===p)??{sideNumber:p};return n===p?{...m,participantId:r}:m}),s)for(let p of a.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);gt({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a})}return{...C,sidesSwapped:s}}function Zr({removePriorValues:t,tournamentRecord:e,duplicateValues:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:s,event:a}){let{matchUp:c}=Vt({drawDefinition:n,event:a,matchUpId:i});if(!c)return{error:we};let u=ro({removePriorValues:t,element:c,duplicateValues:r,timeItem:s});return o||gt({tournamentId:e?.tournamentId,eventId:a?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function pI(t){let e=[{[ne]:!0},{[Ce]:!0},{[ao]:!0},{[gn]:!0}],r=et(t,e);if(r.error)return r;let n=vs(t,[{[ds]:Gn,attr:{[uu]:!0}}]);if(n.error)return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=n?.matchUp?.matchUp,{matchUpStatus:u,score:p}=c??{};if(u&&id.includes(u)||u&&ae.includes(u)||he({score:p}))return{error:zE};let m=Is({matchUp:c});if(m?.error)return m;let{checkedInParticipantIds:d,allRelevantParticipantIds:l}=m??{};if(!l?.includes(s))return{error:ln};if(!d?.includes(s))return{error:PA};let f=IS({matchUp:c});if(f?.error)return f;let{sideParticipantIds:g,nestedIndividualParticipantIds:I}=f??{},h=g?.indexOf(s);return h!==void 0&&[0,1].includes(h)&&(I?.[h]??[]).forEach(T=>{Zr({drawDefinition:i,matchUpId:a,timeItem:{itemType:hd,itemValue:T}})}),Zr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:hd}}),{...C,checkedOut:!0}}function mI(t){let e=[{[ne]:!0},{[Ce]:!0},{[ao]:!0},{[gn]:!0}],r=et(t,e);if(r[In])return r;let n=vs(t,[{[ds]:Gn,attr:{[uu]:!0}}]);if(n[In])return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=Is({matchUp:n?.matchUp?.matchUp});if(c?.error)return c;let{checkedInParticipantIds:u,allRelevantParticipantIds:p}=c??{};if(!p?.includes(s))return{[In]:ln};let m={...C,checkedIn:!0};return u?.includes(s)||Zr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:Id}}),m}function Al(t){let e=et(t,[{[ao]:!0,[Ce]:!0,[gn]:!0}]);if(e.error)return e;let r=t.tournamentId??t.activeTournamentId,n=t.tournamentRecord??(r&&t.tournamentRecords?.[r]);if(!n)return{error:q};let i=vs(t,[{[ds]:Gn,attr:{[uu]:!0},[In]:we}]).matchUp?.matchUp;if(!i)return{error:we};let{checkedInParticipantIds:s=[]}=Is({matchUp:i}),{participantId:a,matchUpId:c,drawDefinition:u}=t;return a&&s.includes(a)?pI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i}):mI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i})}function Ul({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:n}){if(!t)return{error:q};if(!e)return{error:cn};if(!n)return{error:qr};let o=Pe({drawDefinition:e}),{matchUp:i}=Vt({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!i)return{error:we};let{matchUp:s,structure:a}=Vt({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:n});if(!s)return{error:we};let{collectionPosition:c,drawPositions:u,collectionId:p,matchUpTieId:m,matchUpType:d}=s;if(d&&!Yc([Lt,vt],d))return{error:dr};let{positionAssignments:l}=Ct({structure:a}),f=l?.filter(P=>u?.includes(P.drawPosition)),{matchUp:g}=Vt({matchUpId:m,drawDefinition:e,matchUpsMap:o}),I=g?.sides?.map(St)??[],h=f?.map(St)??[],S=[...I,...h],{participants:T}=Ft({tournamentRecord:t,participantFilters:{participantTypes:[wt],participantIds:S}}),{matchUp:y}=Vt({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),E=We({matchUp:g,drawDefinition:e,structure:a,event:n})?.tieFormat;return{inContextDualMatchUp:y,inContextTieMatchUp:s,relevantAssignments:f,collectionPosition:c,teamParticipants:T,collectionId:p,matchUpType:d,dualMatchUp:g,tieMatchUp:i,tieFormat:E,structure:a,...C}}function dI(t){let e=Ul(t);if(e.error)return e;let r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:o,newParticipantId:i,drawDefinition:s,substitution:a,event:c}=t;if(!n||!i)return _({result:{error:se},stack:r});if(n===i)return{...C};let{inContextDualMatchUp:u,inContextTieMatchUp:p,collectionPosition:m,collectionId:d,dualMatchUp:l,tieMatchUp:f,tieFormat:g}=e,I=p?.matchUpType,h=p?.sides?.find(k=>k.participant?.participantId===n||k.participant?.individualParticipantIds?.includes(n));if(!h)return{error:re};let S=Ft({tournamentRecord:o,participantFilters:{participantIds:[n,i]}})?.participants??[];if(S.length!==2)return _({result:{error:se},stack:r});if(S[0].participantType!==S[1].participantType)return _({result:{error:Pn},stack:r});let{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:s,event:c}),y=t.policyDefinitions?.[er]??T?.[er]??Ps[er],E=S.find(({participantId:k})=>k===i);if((t.enforceGender??y?.participants?.enforceGender)!==!1&&Dn(p?.gender)&&yr(p?.gender)!==yr(E?.person?.sex))return{error:Hi,info:"Gender mismatch"};let A=y?.processCodes?.substitution;ka({tournamentId:o.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:s,dualMatchUp:l});let U=l?.sides?.find(({sideNumber:k})=>k===h.sideNumber);if(!U)return _({result:{sideNumber:h.sideNumber,existingParticipantId:n,error:Oe},stack:r});if(p?.sides?.flatMap(k=>k.participant?.individualParticipantIds||k.participant?.participantId||[])?.includes(i))return _({result:{error:sp},stack:r});let D=u?.sides?.find(({sideNumber:k})=>k===h.sideNumber)?.participantId,M=U.lineUp,R=M?.find(({participantId:k})=>i===k),b=M?.reduce((k,G)=>G.substitutionOrder>k?G.substitutionOrder:k,0),O=M?.map(k=>{let G=J(k,!1,!0);if(![n,i].includes(G.participantId))return G;if(!a&&[n,i].includes(G.participantId)&&(G.collectionAssignments=G.collectionAssignments?.filter(H=>!(H.collectionPosition===m&&H.collectionId===d))),a&&n===G.participantId&&(G.collectionAssignments=G.collectionAssignments.map(H=>H.collectionPosition===m&&H.collectionId===d&&H.substitutionOrder===void 0?{...H,substitutionOrder:b}:H)),G.participantId===i){G.collectionAssignments||(G.collectionAssignments=[]);let H={collectionId:d,collectionPosition:m};a&&(H.previousParticipantId=n,H.substitutionOrder=(b??0)+1),G.collectionAssignments.push(H)}return G})??[];if(!R){let k={collectionId:d,collectionPosition:m};a&&(k.substitutionOrder=(b??0)+1,k.previousParticipantId=n);let G={collectionAssignments:[k],participantId:i};O.push(G)}let v=I===vt,{assignedParticipantIds:x}=Lp({lineUp:M,collectionPosition:m,collectionId:d}),{assignedParticipantIds:F}=Lp({lineUp:O,collectionPosition:m,collectionId:d});if(U.lineUp=O,D&&g){let k=os({participantId:D,lineUp:O,drawDefinition:s,tieFormat:g});if(k.error)return _({result:k,stack:r})}else console.log("team participantId not found");let w,L;if(v){let{tournamentRecord:k}=t,G=Sn({participantIds:F,tournamentRecord:k});if(!G.participant){let Y=wn({returnParticipant:!0,pairOverride:!0,tournamentRecord:k,participant:{participantRole:xe,individualParticipantIds:F,participantType:ft}});if(Y.error)return _({result:Y,stack:r});w=Y.participant?.participantId}G=Sn({participantIds:x,tournamentRecord:k});let H=G.participant?.participantId;H&&ns({participantIds:[H],tournamentRecord:k}).success&&(L=H)}if(a||h.substitutions?.length===1){if(a)A&&f&&(f.processCodes=pt([...f?.processCodes??[],...A]));else for(let k of A||[]){let G=f?.processCodes?.lastIndexOf(k);G!==void 0&&f?.processCodes?.splice(G,1)}f&>({tournamentId:o?.tournamentId,matchUp:f,context:r,drawDefinition:s})}return l&>({tournamentId:o?.tournamentId,matchUp:l,context:r,drawDefinition:s}),{...C,modifiedLineUp:O,participantRemoved:L,participantAdded:w}}function Yy({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:r,drawDefinition:n,participantIds:o,collectionId:i}){if(!i||!t||!Array.isArray(o))return{modifiedLineUp:r?.lineUp||[],error:B};let s=r?.lineUp||Ss({participantId:e,drawDefinition:n})?.lineUp,a=[],c=[];return{modifiedLineUp:s?.map(p=>{if(!o.includes(p.participantId))return p;let m=p.collectionAssignments?.filter(d=>{let l=d.collectionId===i&&d.collectionPosition===t;return l&&(d.previousParticipantId&&a.push(d.previousParticipantId),c.push({participantId:p.participantId,...d})),!l});return{participantId:p.participantId,collectionAssignments:m}}).filter(Boolean)||[],assignmentsRemoved:c,previousParticipantIds:a}}function bx({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n=(r.events||[]).filter(i=>i?.eventType===_e&&i?.entries?.some(s=>s.participantId===e)),o=i=>!t.includes(i.participantId);for(let i of n){i.entries=(i.entries||[]).filter(o);let{flightProfile:s}=Ht({event:i});s?.flights?.forEach(a=>{a.drawEntries=(a.drawEntries||[]).filter(o)}),i?.drawDefinitions?.forEach(a=>{a.entries=(a.entries||[]).filter(o)})}return{...C}}function dm({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:r,tournamentRecord:n}){let o="addIndividualParticipantIds";if(!n)return _({result:{error:q},stack:o});if(!e||!t)return _({result:{error:st},stack:o});let i=n.participants??[],s=i.find(m=>m.participantId===e);if(!s)return _({result:{error:re},stack:o});if(s?.participantType&&![wt,Qr].includes(s.participantType))return _({context:{participantType:s.participantType},result:{error:Pn},stack:o});let a=t.filter(m=>i.find(l=>l.participantId===m)?.participantType!==Et);if(a.length)return _({result:{error:wr,invalidParticipantIds:a},stack:o});s.individualParticipantIds||(s.individualParticipantIds=[]);let c=s.individualParticipantIds,u=t.filter(m=>!c.includes(m));u.length&&(r&&kp({individualParticipantIds:u,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...u));let{topics:p}=Lr();if(p.includes(rr)){let m=i.find(({participantId:d})=>d===e);lt({topic:rr,payload:{participants:[m]}})}return bx({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}),{groupingParticipant:J(s,!1,!0),added:u.length,...C}}function lm(t){let{updateParticipantName:e=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o,pairOverride:i,participant:s}=t;if(!o)return{error:q};if(!s)return{error:Wi};if(!s.participantId)return wn({tournamentRecord:o,participant:s});let{participant:a}=Uo({participantId:s.participantId,tournamentRecord:o});if(!a)return wn({tournamentRecord:o,participant:s});let{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:p,participantName:m,participantRole:d,participantType:l,onlineResources:f,contacts:g,person:I}=s;if(l&&a.participantType!==l)return{error:hA};let h={};if(g&&(h.contacts=g),f&&(h.onlineResources=f),p&&kt(p)&&(h.participantOtherName=p),m&&kt(m)&&(h.participantName=m),Array.isArray(u)){let{participants:S}=Ft({participantFilters:{participantTypes:[Et]},tournamentRecord:o}),T=S?.map(St);if(T){let y=u.filter(E=>kt(E)&&T.includes(E));([Qr,Wt].includes(l||a.participantType)||l===ft&&(y.length===2||i))&&(h.individualParticipantIds=y),a.participantType===yu.PAIR&&e&&(h.participantName=u0({individualParticipants:S,newValues:h}))}}return Object.keys(Dd).includes(d)&&(h.participantRole=d),Object.keys(yu).includes(l)&&(h.participantType=l),Array.isArray(c)&&(h.participantRoleResponsibilties=c),a.participantType===yu.INDIVIDUAL&&I&&p0({updateParticipantName:e,existingParticipant:a,newValues:h,person:I}),Object.assign(a,nt(h)),r&&dm({individualParticipantIds:[a.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o}),lt({topic:rr,payload:{tournamentId:o.tournamentId,participants:[a]}}),{participant:J(a),...C}}function u0({individualParticipants:t,newValues:e}){let r=e.individualParticipantIds,n=t.filter(({participantId:o})=>r.includes(o)).map(({person:o})=>o?.standardFamilyName).filter(Boolean).sort().join("/");return r.length===1&&(n+="/Unknown"),n}function p0({updateParticipantName:t,existingParticipant:e,newValues:r,person:n}){let o={},{standardFamilyName:i,standardGivenName:s,nationalityCode:a,personId:c,birthdate:u,tennisId:p,sex:m}=n;m&&Object.keys(Fm).includes(m)&&(o.sex=m);let d;if(kt(c)&&(o.personId=c),a&&kt(a)&&(m0(a)||a==="")&&(o.nationalityCode=a),i&&typeof kt(i)&&i.length>1&&(o.standardFamilyName=i,d=!0),s&&typeof kt(s)&&s.length>1&&(o.standardGivenName=s,d=!0),d&&t){let l=`${o.standardGivenName} ${o.standardFamilyName}`;r.participantName=l}u&&Mr(u)&&(o.birthdate=u),p&&kt(p)&&(o.tennisId=p),Object.assign(e.person,o)}function m0(t){return ui.flatMap(({iso:e,ioc:r})=>[e,r]).filter(Boolean).includes(t)}function Pl(t){let e=Ul(t);if(e.error)return e;let r="assignTieMatchUpParticipantId",n=t.teamParticipantId,{tournamentRecord:o,drawDefinition:i,participantId:s,event:a}=t;if(!s)return _({result:{error:se},stack:r});if(t.sideNumber&&![1,2].includes(t.sideNumber))return _({result:{error:tf},stack:r});let{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:p,collectionPosition:m,teamParticipants:d,collectionId:l,matchUpType:f,dualMatchUp:g,tieFormat:I}=e;if(u?.sides?.flatMap(V=>V.participant?.individualParticipantIds||V.participant?.participantId||[])?.includes(s))return _({result:{...C},stack:r});n=n??(t.sideNumber?c?.sides?.find(V=>V.sideNumber===t.sideNumber)?.participantId:void 0);let S=Ft({participantFilters:{participantIds:[s]},tournamentRecord:o})?.participants?.[0];if(!S)return _({result:{error:re},stack:r});let{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:i,event:a}),y=t.policyDefinitions?.[er]??T?.[er]??Ps[er];if((t.enforceGender??y?.participants?.enforceGender)!==!1&&Dn(u?.gender)&&yr(u?.gender)!==yr(S.person?.sex))return{error:Hi,info:"Gender mismatch"};let{individualParticipantIds:P,participantType:A}=S;if(de(Lt)(f)&&A!==Et)return{error:Pn};let U=A===Et?[s]:P,N=n&&d?.find(({participantId:V})=>V===n)||d?.find(({individualParticipantIds:V})=>ke(U,V));if(!N)return{error:lf};if(n||(n=N.participantId),!n)return{error:re};let M=p?.find(V=>V.participantId===N?.participantId)?.drawPosition,R=g?.sides?.find(V=>V.participantId===n)?.sideNumber,b=u?.sides?.find(V=>M&&V.drawPosition===M)?.sideNumber,O=R??b??t.sideNumber;if(!I)return{error:ks};if(!I.collectionDefinitions?.find(V=>V.collectionId===l))return{error:cA};ka({tournamentId:o.tournamentId,eventId:a.eventId,inContextDualMatchUp:c,drawDefinition:i,dualMatchUp:g});let x=g?.sides?.find(V=>V.sideNumber===O),F=u?.sides?.find(V=>V.sideNumber===O),k=(x?.lineUp??Ss({participantId:n,drawDefinition:i})?.lineUp)?.filter(V=>V.collectionAssignments?.find($=>$.collectionPosition===m&&$.collectionId===l&&!$.previousParticipantId))?.map(V=>V?.participantId),G=k?.length>1&&k||(A===ft?S.individualParticipantIds:[s]),H=Yy({collectionPosition:m,teamParticipantId:n,dualMatchUpSide:x,drawDefinition:i,participantIds:G,collectionId:l});if(H.error)return _({result:H,stack:r});let{modifiedLineUp:K}=H,Y;if(f===vt){if(A!==ft){let V=dM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:K,participantId:s,collectionId:l,tieFormat:I});if(V?.error)return _({result:V,stack:r});if(V=j({side:F}),V.error)return V;Y=V.deletedParticipantId,x&&(x.lineUp=K),g&>({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i})}else if(A===ft)for(let V of G)dM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:K,participantId:V,collectionId:l,tieFormat:I})}else{let V=dM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:K,participantId:s,collectionId:l,tieFormat:I});if(V?.error)return V}if(x&&(x.lineUp=K),g&>({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i}),Y){let{error:V}=ns({participantIds:[Y],tournamentRecord:o});V&&console.log("cleanup")}return{...C,modifiedLineUp:K};function j({side:V}){let $;if(V.participant){let X=V.participant.individualParticipantIds||[];if(X.filter(Boolean).length===1){let{participant:it}=Sn({participantIds:X,tournamentRecord:o});X.push(s);let{participant:z}=Sn({participantIds:X,tournamentRecord:o});if(!z&&it){it.individualParticipantIds=X;let Q=lm({pairOverride:!0,tournamentRecord:o,participant:it});if(Q.error)return Q}else $=it?.participantId}}else{let W=wn({participant:{individualParticipantIds:[s],participantRole:xe,participantType:ft},pairOverride:!0,tournamentRecord:o});if(W.error)return W}return{...C,deletedParticipantId:$}}}function dM({collectionPosition:t,teamParticipantId:e,drawDefinition:r,modifiedLineUp:n,participantId:o,collectionId:i,tieFormat:s}){let a=Ss({participantId:e,drawDefinition:r})?.lineUp,c=(n||a)?.find(p=>p?.participantId===o),u={collectionId:i,collectionPosition:t};if(c)c.collectionAssignments.push(u);else{let p={collectionAssignments:[u],participantId:o};n.push(p)}return os({participantId:e,lineUp:n,drawDefinition:r,tieFormat:s})}function lM(t){let{tournamentRecord:e,drawDefinition:r,participantId:n,event:o}=t,i="removeTieMatchUpParticiapantId";if(!n)return _({result:{error:se},stack:i});let s=Ul(t);if(s.error)return s;let{appliedPolicies:a}=Tt({tournamentRecord:e,drawDefinition:r,event:o}),u=(t.policyDefinitions?.[er]??a?.[er]??Ps[er])?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:m,relevantAssignments:d,collectionPosition:l,teamParticipants:f,collectionId:g,matchUpType:I,dualMatchUp:h,tieMatchUp:S,tieFormat:T}=s;if(!h)return _({result:{error:mr},stack:i});let y=m?.sides?.find(R=>R.participant?.participantId===n||R.participant?.individualParticipantIds?.includes(n));if(!y)return _({result:{error:re},stack:i});let E=t.policyDefinitions?.[rn]??a?.[rn];if(!y.substitutions?.length&&(he({score:m?.score})||m?.winningSide)&&E?.requireParticipantsForScoring!==!1)return _({result:{error:jA},stack:i});let P=p?.sides?.find(({sideNumber:R})=>R===y.sideNumber)?.participantId;if(!P)return _({result:{error:re},stack:i});let A=Ft({participantFilters:{participantIds:[n]},tournamentRecord:e})?.participants?.[0];if(!A)return _({result:{error:re},stack:i});if(I===Lt&&A.participantType===ft)return _({result:{error:Hi},stack:i});let U=A.participantType===Et?[n]:A.individualParticipantIds;ka({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:h});let N=h.sides?.find(({sideNumber:R})=>R===y.sideNumber);if(!N&&(h.sides?.filter(({lineUp:R})=>!R).length||0)<2){let R=f?.map(({participantId:b})=>({drawPosition:d?.find(O=>O.participantId===b)?.drawPosition,teamParticipantId:b}));N=h.sides?.find(b=>R?.find(({drawPosition:O})=>O===b.drawPosition)?.teamParticipantId===P)}if(!N)return _({result:{error:re,context:{participantId:n}}});let{modifiedLineUp:D,previousParticipantIds:M}=Yy({collectionPosition:l,teamParticipantId:P,dualMatchUpSide:N,participantIds:U,drawDefinition:r,collectionId:g});if(N.lineUp=D,P&&T&&os({participantId:P,lineUp:D,drawDefinition:r,tieFormat:T}),I===vt&&A.participantType===Et){let R=m?.sides?.find(v=>v.sideNumber===N?.sideNumber),{participantId:b}=R??{},O=b&&Ft({participantFilters:{participantIds:[b]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(O){let v=O?.individualParticipantIds?.filter(x=>x!==n)??[];if(M&&v.push(...M),v.length>2)return _({result:{error:wr},stack:i});if(O.draws?.length){if(v.length===1){let{participant:x}=Sn({participantIds:v,tournamentRecord:e});if(!x){let w=wn({participant:{participantRole:xe,individualParticipantIds:v,participantType:ft},pairOverride:!0,tournamentRecord:e});if(w.error)return _({result:w,stack:i})}}}else if(v.length){O.individualParticipantIds=v;let x=lm({participant:O,pairOverride:!0,tournamentRecord:e});if(x.error)return _({result:x,stack:i})}else{let x=ns({participantIds:[b],tournamentRecord:e});x.error&&console.log("cleanup",{result:x})}}else return _({result:{error:re},stack:i})}if(y.substitutions?.length===1&&!m?.sides?.find(b=>b.sideNumber!==y.sideNumber)?.substitutions?.length&&S?.processCodes?.length){for(let b of u||[]){let O=S.processCodes.lastIndexOf(b);S.processCodes.splice(O,1)}gt({tournamentId:e?.tournamentId,matchUp:S,context:i,drawDefinition:r})}return gt({tournamentId:e?.tournamentId,matchUp:h,context:i,drawDefinition:r}),{...C,modifiedLineUp:D}}function lI(t){let e=et(t,[{[ne]:!0,[Ce]:!0,[gn]:!0}]);if(e.error)return e;let{drawDefinition:r,sideNumber:n,matchUpId:o,event:i}=t;if(n&&![1,2].includes(n))return{error:B,sideNumber:n};let{matchUp:s,structure:a}=Vt({drawDefinition:r,matchUpId:o,event:i});return s?cr({structure:a})?(s.sides?.forEach(c=>{(!n||c.sideNumber===n)&&delete c.participantId}),gt({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:r,matchUp:s}),{...C}):{error:Om}:{error:we}}function Ox({matchUpStatuses:t=["BYE",Bt,Gt],drawPositionMatchUps:e,loserDrawPosition:r,sourceMatchUps:n}){let o=e?.reduce((p,m)=>!p||m.roundNumber>p.roundNumber?m:p,void 0),i=o?.drawPositions?.find(p=>p!==r),s=n.filter(p=>p?.drawPositions?.includes(i)).map(p=>p.matchUpStatus),a=n.filter(p=>p?.drawPositions?.includes(r)).map(p=>p.matchUpStatus),c=ke(s||[],t),u=ke(a||[],t);return{sourceMatchUp:o,winnerHadMatchUpStatus:c,winnerMatchUpStatuses:s,loserHadMatchUpStatus:u,loserMatchUpStatuses:a}}function vx({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,structureId:s,dualMatchUp:a,roundNumber:c,matchUpsMap:u,event:p}){let{structure:m}=at({drawDefinition:i,structureId:s});if(m?.structureType===Ve)return{...C};u=u??Pe({drawDefinition:i});let l=(u?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:f}=Es({drawPosition:r,matchUps:l}),g=l?.filter(h=>h.roundNumber>=c&&h.roundNumber!==f&&h.drawPositions?.includes(r)),{positionAssignments:I}=Ct({drawDefinition:i,structureId:s});for(let h of g??[])d0({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:I,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,dualMatchUp:a,matchUpsMap:u,matchUp:h,event:p});return{...C}}function d0({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:r,targetDrawPosition:n,tournamentRecord:o,sourceMatchUpId:i,drawDefinition:s,dualMatchUp:a,matchUpsMap:c,matchUp:u,event:p}){let m="removeSubsequentDrawPosition";if(a){let g=t.find(({matchUpId:h})=>u.matchUpId===h).sides?.find(h=>h.drawPosition===n)?.sideNumber,I=u.sides?.find(h=>h.sideNumber===g);I&&delete I.lineUp}u.drawPositions=(u.drawPositions||[]).map(f=>f===n?void 0:f).filter(Boolean);let l=e.filter(({drawPosition:f})=>u.drawPositions?.includes(f)).filter(f=>f.bye).length;return u.matchUpStatus=l&&"BYE"||pr(u.matchUpStatus)&&u.matchUpStatus||Qt,pr(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&FS({inContextDrawMatchUps:t,sourceMatchUpStatus:r,sourceMatchUpId:i,matchUpsMap:c,matchUp:u}),gt({tournamentId:o?.tournamentId,eventId:p?.eventId,context:`${m}-${n}`,drawDefinition:s,matchUp:u}),{...C}}function Vc(t){let{dualWinningSideChange:e,inContextDrawMatchUps:r,tournamentRecord:n,drawDefinition:o,matchUpStatus:i,matchUpsMap:s,dualMatchUp:a,targetData:c,matchUpId:u,structure:p,event:m}=t,d=!!t.matchUp.collectionId,l=cr({structure:p}),{drawPositions:f,winningSide:g}=c.matchUp||{};if(!l&&!f)return{error:Ja};let{targetLinks:{loserTargetLink:I,winnerTargetLink:h,byeTargetLink:S},targetMatchUps:{loserMatchUp:T,winnerMatchUp:y,byeMatchUp:E}}=c,P=Yn({...t,matchUpStatus:i||Qt,removeWinningSide:!0});if(P.error)return P;let A;if(d){let{matchUpTieId:w,matchUpsMap:L}=t;if(A=go({appliedPolicies:t.appliedPolicies,matchUpId:w,tournamentRecord:n,drawDefinition:o,matchUpsMap:L,event:m}),!e&&!A.removeWinningSide)return{...C}}if(l)return{...C};let{matchUps:U}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:o,matchUpsMap:s,structure:p}),{positionAssignments:N}=Ie({structure:p}),D=g-1,M=1-D,R=f[D],b=f[M],{winnerParticipantId:O,loserParticipantId:v}=N?.reduce((w,L)=>(L.drawPosition===b&&(w.loserParticipantId=L.participantId),L.drawPosition===R&&(w.winnerParticipantId=L.participantId),w),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},x=U.filter(w=>w.drawPositions?.includes(b));if(y&&fM({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:r,winningDrawPosition:R,winnerParticipantId:O,tournamentRecord:n,winnerTargetLink:h,drawDefinition:o,winnerMatchUp:y,dualMatchUp:a,matchUpsMap:s}),T){let{winnerHadMatchUpStatus:w}=Ox({drawPositionMatchUps:x,loserDrawPosition:b,sourceMatchUps:U}),k=I.linkCondition===kn;if(w&&k){let H=Math.min(...T.drawPositions);qy({targetLink:I,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:H,matchUpsMap:s,event:m})}let G=l0({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:v,tournamentRecord:n,loserTargetLink:I,drawDefinition:o,loserMatchUp:T,dualMatchUp:a,matchUpsMap:s,event:m});if(G.error)return G}if(E){let w=Math.min(...E.drawPositions);qy({sourceMatchUpId:u,targetLink:S,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:w,matchUpsMap:s,event:m})}return{...C,...A&&{tieMatchUpResult:A}}}function fM({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:r,winnerParticipantId:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:p,event:m}){let{structureId:d,roundNumber:l}=c,f="removeDirectedWinner";if(i){let g=i.target.structureId,{structure:I}=at({drawDefinition:a,structureId:g});if(!I)return{error:_t};let{positionAssignments:h}=Ie({structure:I});I.seedAssignments=(I.seedAssignments??[]).filter(N=>N.participantId!==n);let T=h?.find(N=>N.participantId===n)?.drawPosition,{matchUps:y}=yt({drawDefinition:a,structure:I,event:m}),E=y.map(N=>N.drawPositions).flat(1/0).filter(Boolean),P=Er(E);if((T?P[T]:void 0)===1)h?.forEach(N=>{N.participantId===n&&delete N.participantId});else{let N=y.filter(({drawPositions:D})=>D.includes(T));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:N,winnerTargetLink:i})}let U=u?.drawMatchUps?.find(({matchUpId:N})=>N===c.matchUpId);U&>({tournamentId:o?.tournamentId,eventId:m?.eventId,matchUp:U,context:f,drawDefinition:a})}return l&&vx({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,dualMatchUp:p,matchUpsMap:u,roundNumber:l,structureId:d}),{...C}}function l0({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:r,loserTargetLink:n,sourceMatchUpId:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,dualMatchUp:c,event:u}){let p="removeDirectedLoser",m=n.target.structureId,{structure:d}=at({drawDefinition:i,structureId:m});if(!d)return{error:_t};let{positionAssignments:l}=Ie({structure:d}),f=l?.find(g=>g.participantId===e)?.drawPosition;if(l?.forEach(g=>{g.participantId===e&&delete g.participantId}),o&&t){let g=a?.drawMatchUps?.find(({matchUpId:I})=>I===s.matchUpId);g.matchUpStatusCodes=t===oe?["WO","WO"]:[]}if(d.seedAssignments=(d.seedAssignments??[]).filter(g=>g.participantId!==e),c){let g=s?.sides.reduce((S,T,y)=>T.drawPosition===f?y:S,void 0),I=a?.drawMatchUps?.find(({matchUpId:S})=>S===s.matchUpId),h=I?.sides?.[g];h&&(delete h.lineUp,gt({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:I,context:p,drawDefinition:i}))}return{...C}}function qy({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,targetLink:i,event:s}){let a=i.target.structureId,c="removeDirectedBye";Tn({color:"brightyellow",method:c,drawPosition:n});let u=Uc({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:a,event:s});return _({result:u,stack:c})}function _x(t){let{matchUpFormat:e,score:r}=t,n=r?.sets?.length,o=e&&Ne(e),{setFormat:i,finalSetFormat:s,bestOf:a}=o??{};return(a&&n===a&&s||i)?.timed||!1}function xx({tournamentRecord:t,drawDefinition:e,structure:r,matchUp:n}){let o="attemptToSetMatchUpStatusBYE";if(n?.winningSide)return _({result:{error:Ta},context:{matchUpStatus:"BYE"},stack:o});let{positionAssignments:i}=Ie({structure:r}),s=i?.filter(c=>c.bye).map(c=>c.drawPosition);return n.drawPositions?.some(c=>s?.includes(c))?(n.matchUpStatus="BYE",n.matchUpStatusCodes=[],gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:n}),{...C}):_({result:{error:aA},info:"matchUp does not include BYE",stack:o})}function Dl(t){let{tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,structure:s,event:a}=t,c="doubleExitAdvancement";if(s.structureType===Ve)return _({result:{...C},stack:c});let{matchUp:u,targetMatchUps:p,targetLinks:m}=i,{loserMatchUp:d,winnerMatchUp:l,loserTargetDrawPosition:f}=p,g=pr(d?.matchUpStatus)&&!d.sides?.map(h=>h.participantId??h.participant).filter(Boolean).length,I=d?.matchUpStatus===oe;if(d&&d.matchUpStatus!=="BYE"){let{loserTargetLink:h}=m;if(r?.progression?.doubleExitPropagateBye||d.feedRound&&d.sides?.[0]?.participantFed){let S=Lx({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:h,drawDefinition:n,loserMatchUp:d,matchUpsMap:o,event:a});if(S.error)return _({result:S,stack:c})}else if(!I){let{feedRound:S,drawPositions:T,matchUpId:y}=d,E=S?2:2-T.indexOf(f);E=g?d.winningSide:E;let P=wx({...t,targetMatchUp:d,walkoverWinningSide:E,tournamentRecord:e,sourceMatchUp:u,matchUpId:y});if(P.error)return _({result:P,stack:c})}}if(l){let h=wx({...t,matchUpId:l.matchUpId,targetMatchUp:l,tournamentRecord:e,sourceMatchUp:u});if(h.error)return _({result:h,stack:c})}return _({result:{...C},stack:c})}function wx(t){let{inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s}=t,a=n.structures.find(({structureId:j})=>j===i.structureId),c=t.matchUpStatus===be?be:oe,u=t.matchUpStatus===be?Gt:Bt,p="conditionallyAdvanceDrawPosition",m=s.drawMatchUps.find(j=>j.matchUpId===i.matchUpId);if(!m)return{error:mr};let d=o?.drawPositions||[],l=m.drawPositions?.filter(Boolean),f=o?.structureId===i.structureId;if(f&&ke(d,l)&&(l=l.filter(j=>!d.includes(j))),f&&l.length>1)return _({result:{error:Xa},stack:p});let{pairedPreviousMatchUpIsDoubleExit:g,pairedPreviousMatchUp:I}=wS(t),h=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:S,targetLinks:T}=h,{loserTargetDrawPosition:y,winnerMatchUp:E,loserMatchUp:P}=S;if(P){let{loserTargetLink:j}=T,V=Lx({loserTargetDrawPosition:y,loserMatchUp:P,tournamentRecord:r,loserTargetLink:j,drawDefinition:n,matchUpsMap:s});if(V.error)return _({result:V,stack:p})}let A=m.drawPositions?.filter(Boolean)||[],U=A.length===1,N=t.walkoverWinningSide||U&&Md({drawPosition:A[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,D=pr(m.matchUpStatus)&&!A.length,M=m.finishingRound===1,R=D&&!M?c:u,b=e.find(j=>j.matchUpId===I.matchUpId),O=[],v;o&&(o?.structureId===b?.structureId?o.roundPosition<I?.roundPosition?v=1:v=2:i.feedRound?o.structureId===i.structureId?v=2:v=1:N&&(v=3-N));let x=t.matchUpStatus,F=I?.matchUpStatus;v===1?O=[{matchUpStatus:$y(x),previousMatchUpStatus:x,sideNumber:1},{matchUpStatus:$y(F),previousMatchUpStatus:F,sideNumber:2}]:v===2&&(O=[{matchUpStatus:$y(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:$y(x),previousMatchUpStatus:x,sideNumber:2}]),O.length&&(O=O.map(j=>nt(j)));let w=Yn({...t,winningSide:N,matchUp:m,matchUpStatusCodes:O,context:p,matchUpStatus:R});if(w.error)return _({result:w,stack:p});if(D)return Dl({...t,matchUpStatus:R,targetData:h});if(!E)return _({result:{...C},stack:p});let L=l.length===2?l[N-1]:l[0],{positionAssignments:k}=Ct({structure:a}),G=k?.find(j=>j.drawPosition===L),H=s.drawMatchUps.find(j=>j.matchUpId===E.matchUpId),K=H?.drawPositions?.filter(Boolean),Y=K.length===1;if(L){if(G?.bye){let j=ur({matchUpId:H.matchUpId,inContextDrawMatchUps:e,drawDefinition:n});if(Y){let V=K.filter(Boolean)[0],$=Md({drawPosition:V,matchUpId:H.matchUpId,inContextDrawMatchUps:e}),X=Yn({appliedPolicies:t.appliedPolicies,matchUpId:H.matchUpId,matchUp:H,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,winningSide:$});return X.error?_({result:X,stack:p}):RS({drawPositionToAdvance:V,matchUpId:H.matchUpId,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}else if(pr(E.matchUpStatus)){let V=Dl({...t,matchUpId:H.matchUpId,matchUpStatus:R,targetData:j});if(V.error)return _({result:V,stack:p})}return _({result:{...C},stack:p})}return wa({matchUpId:E.matchUpId,drawPosition:L,inContextDrawMatchUps:e,drawDefinition:n})}else if(g){if(!H)return{error:mr};if(Y){let $=K[0],X=Md({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawPosition:$});console.log("existing drawPosition is winningSide",{walkoverWinningSide:X})}let j=pr(H.matchUpStatus)?u:c,V=Yn({matchUpId:H.matchUpId,appliedPolicies:t.appliedPolicies,matchUp:H,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,matchUpStatus:j});if(V.error)return _({result:V,stack:p});if(j===c){let $=Dl({...t,matchUpId:i.matchUpId,matchUpStatus:j,targetData:h});if($.error)return $}}return _({result:{...C},stack:p})}function Lx(t){let{loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,matchUpsMap:i,event:s,loserMatchUp:a}=t,c=n?.target?.structureId,{structure:u}=at({drawDefinition:o,structureId:c});return u?Wr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:c,matchUpsMap:i,loserMatchUp:a,event:s}):{error:Si}}function $y(t){return t===oe?Bt:t===be?Gt:t}function Fx(t){let{tournamentRecord:e,drawDefinition:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(h=>h.matchUpId===i.matchUpId).containerStructureId),a="attemptToSetMatchUpStatus",c=n==="BYE",u=i.winningSide,p=[oe,be].includes(n),m=Oa({matchUpStatus:n}),d=gg({matchUpStatus:n}),l=!m&&!d,f=t.matchUpTieId||u&&m&&!p,g=u&&p,I=()=>Yn({...t,removeScore:[po,Bt].includes(n),matchUpStatus:n||Qt});return l&&{error:jI}||f&&Ky(t)||g&&f0(t)||u&&Vc(t)||d&&I()||c&&xx({tournamentRecord:e,drawDefinition:r,structure:o,matchUp:i})||!m&&{error:jI}||p&&g0(t)||s&&Ky(t)||t.propagateExitStatus&&Ky(t)||_({result:{error:Ta,info:"matchUpStatus: "+n},stack:a})}function f0(t){let e=Vc(t);return e.error?e:Dl(t)}function g0(t){let e=Ky({...t,removeScore:!0});return e.error?e:Dl(t)}function Ky(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let i=Vc(t);if(i.error)return _({result:i,stack:e})}let n=!!t.matchUp.collectionId,o=Yn({...t,context:e});if(n){let{matchUpTieId:i,drawDefinition:s,matchUpsMap:a}=t,c=go({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:i,event:t.event,drawDefinition:s,matchUpsMap:a});if(c.error)return _({result:c,stack:e});Object.assign(o,{tieMatchUpResult:c})}return _({result:o,stack:e})}function kx({drawDefinition:t,structure:e,matchUp:r}){let{drawPositions:n}=r,{positionAssignments:o}=Ct({drawDefinition:t,structure:e}),s=o?.filter(({drawPosition:m})=>n?.includes(m))?.map(m=>{let{extension:d}=mt({element:m,name:Lo});return d?.value?.groupOrder}),{containerStructures:a}=fs({drawDefinition:t}),c=a[e.structureId];return{structureIds:Js({drawDefinition:t,structureId:c})?.links?.source?.filter(m=>ke(s,m.source?.finishingPositions||[])).map(m=>m.source.structureId)}}function zy({drawDefinition:t,structure:e,matchUp:r}){let n=[];if(e.finishingPosition===Ei&&Do({drawDefinition:t,structure:e})){let{structureIds:i}=kx({drawDefinition:t,structure:e,matchUp:r});i?.length&&n.push(...i)}return{connectedStructureIds:n}}function Gx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===fn){let a=n.sides.find(({sideNumber:u})=>u!==i).participantId,c=r.find(u=>u.structureId===s.target.structureId&&u.roundNumber===s.target.roundNumber&&u.sides.some(({participantId:p})=>p===a));if(c?.matchUpStatus===Qt){let u=ur({matchUpId:c.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Fi({inContextDrawMatchUps:r,drawDefinition:o,targetData:u})){let{structure:m}=at({structureId:c.structureId,drawDefinition:o}),d=Ct({structure:m}).positionAssignments;for(let l of d||[])if(l.participantId===a){let f=n.sides.find(({sideNumber:g})=>g===i).participantId;if(l.participantId=f,m?.positionAssignments)m.positionAssignments=d;else if(m?.structures){let g=Object.assign({},...(d||[]).map(I=>({[I.drawPosition]:I.participantId})));for(let I of m.structures)I.positionAssignments?.forEach(h=>h.participantId=g[h.drawPosition])}ko({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:m}),e=!0}}}}return{...C,qualifierReplaced:e}}function Vx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===fn){let a=n.sides.find(({sideNumber:p})=>p===i)?.participantId,c=r.filter(p=>p.structureId===s.target.structureId&&p.roundNumber===s.target.roundNumber&&p.sides.some(({participantId:m,qualifier:d})=>d&&!m)),u=Un(c);if(u?.matchUpStatus===Qt){let p=ur({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Fi({inContextDrawMatchUps:r,drawDefinition:o,targetData:p})){let d=u.sides.find(g=>g.qualifier&&!g.participantId)?.drawPosition,{structure:l}=at({structureId:u.structureId,drawDefinition:o});if(!l)return{error:_t};let f=Ct({structure:l}).positionAssignments;for(let g of f||[])if(g.drawPosition===d&&!g.participantId){if(g.participantId=a,l.positionAssignments)l.positionAssignments=f;else if(l.structures){let I=Object.assign({},...(f||[]).map(h=>({[h.drawPosition]:h.participantId})));for(let h of l.structures)h.positionAssignments?.forEach(S=>S.participantId=I[S.drawPosition])}ko({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:l}),e=!0}}}}return{...C,qualifierPlaced:e}}function Bx(t){let e="attemptToSetWinningSide",r,n={},{appliedPolicies:o,disableAutoCalc:i,drawDefinition:s,dualMatchUp:a,winningSide:c,structure:u,matchUp:p}=t;if(a?._disableAutoCalc&&i!==!1)return Fd(t);if(p.winningSide&&p.winningSide!==c){let{connectedStructureIds:f}=zy({drawDefinition:s,structure:u,matchUp:p});f.length&&(console.log({connectedStructureIds:f}),r=!0);let g=Vc(t);if(g.error)return g}let m=uT(t);if(m.context?.progressExitStatus&&Object.assign(n,m.context),m.error)return _({result:m,stack:e});let d,l;return t.qualifierChanging&&o?.[pu]?.autoReplaceQualifiers&&(d=Gx(t).qualifierReplaced),t.qualifierAdvancing&&o?.[pu]?.autoPlaceQualifiers&&(l=Vx(t).qualifierPlaced),_({result:nt({...C,...m,connectedStructures:r,qualifierReplaced:d,qualifierPlaced:l,context:n}),stack:e})}var Qy={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function gM(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,matchUp:s}=t,{matchUpId:a}=s,{iteration:c=0}=t;c+=1;let u="removeDoubleExit";Tn({color:"brightyellow",method:u,matchUpId:a,iteration:c,keyColors:Qy});let{targetMatchUps:{loserMatchUp:p,winnerMatchUp:m,loserTargetDrawPosition:d},targetLinks:{loserTargetLink:l}}=i;if(m&&m.matchUpStatus!=="BYE"){let{stage:I,roundNumber:h,roundPosition:S,structureName:T}=m;Tn({winner:"winner",roundPosition:S,structureName:T,roundNumber:h,keyColors:Qy,stage:I}),Hx({...t,targetMatchUp:m,sourceMatchUp:s,iteration:c})}let f=p?.matchUpStatus==="BYE"&&(p?.feedRound||p?.roundNumber===1),g=i?.targetLinks?.loserTargetLink?.linkCondition===kn;if(f&&g){let I=e.filter(({roundNumber:E,structureId:P})=>P===s.structureId&&E===1),h=I.map(({roundPosition:E})=>E),S=Ae(h.sort(),2).find(E=>E.includes(s.roundPosition));if((I.filter(({roundPosition:E})=>S.includes(E))?.map(({matchUpStatus:E})=>E)).every(E=>[be,oe].includes(E)))return _({result:{...C},stack:u})}if(p&&(p.matchUpStatus!=="BYE"||f)){let I=e.find(({matchUpId:A})=>A===p.matchUpId),{structure:h}=at({drawDefinition:n,structureId:I.structureId}),{stage:S,roundNumber:T,roundPosition:y,feedRound:E,structureName:P}=p;if(Tn({loser:"loser",roundPosition:y,structureName:P,roundNumber:T,keyColors:Qy,feedRound:E,stage:S}),r?.progression?.doubleExitPropagateBye||f)qy({drawPosition:d,targetLink:l,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:o});else{let A=Hx({...t,targetMatchUp:p,structure:h,iteration:c});if(A.error)return _({result:A,stack:u})}}return _({result:{...C},stack:u})}function Hx(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s,structure:a,iteration:c}=t,u="conditionallyRemoveDrawPosition";Tn({method:u,structureName:a?.structureName,iteration:c});let p=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:{winnerMatchUp:m}}=p,d=s?.drawMatchUps.find(y=>y.matchUpId===i.matchUpId),l=[],f,g,I;if(i.feedRound)I=m?.drawPositions?.filter(Boolean)?.find(E=>i.drawPositions.includes(E));else if(!o)I=jt(i?.drawPositions||[],m?.drawPositions||[])?.[0];else if(g=LS({structureId:a.structureId,matchUp:o,matchUpsMap:s})?.pairedPreviousMatchUp,f=[oe,be].includes(g?.matchUpStatus),l=g?.drawPositions?.filter(Boolean)||[],[...ae,"BYE"].includes(g?.matchUpStatus)||g?.winningSide){let E=o.drawPositions||[],P=i.drawPositions?.filter(Boolean);ke(E,P)&&(P=P?.filter(U=>!E.includes(U))),I=E.concat(l).find(U=>P?.includes(U))}if(m&&I){let{stage:y,roundNumber:E,roundPosition:P,structureName:A}=m;Tn({method:"removeDirectedWinner",drawPositionToRemove:I,color:"brightgreen",roundPosition:P,structureName:A,roundNumber:E,keyColors:Qy,stage:y}),fM({winningDrawPosition:I,winnerMatchUp:m,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}let h=gM({targetData:p,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:s,structure:a,iteration:c});if(h.error)return _({result:h,stack:u});let S=I0({pairedPreviousDoubleExit:f,noContextTargetMatchUp:d}),T=!f;return h=Yn({...t,matchUpId:i.matchUpId,matchUp:d,removeWinningSide:!0,matchUpStatusCodes:[],context:u,matchUpStatus:S,removeScore:T,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),h.error?_({result:h,stack:u}):{...C}}function I0({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus==="BYE"?"BYE":t?[be,Gt].includes(e?.matchUpStatus)?Gt:Bt:Qt}function Wx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o}=t,i=t.targetData.targetLinks?.winnerTargetLink;if(i.target.feedProfile===fn){let s=n.sides?.find(({sideNumber:c})=>c===n.winningSide)?.participantId,a=r.find(c=>c.structureId===i.target.structureId&&c.roundNumber===i.target.roundNumber&&c.sides?.some(({participantId:u})=>u===s));if(a&&a.matchUpStatus===Qt){let c=ur({matchUpId:a.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Fi({inContextDrawMatchUps:r,drawDefinition:o,targetData:c})){let{structure:p}=at({structureId:a.structureId,drawDefinition:o}),m=Ct({structure:p}).positionAssignments;for(let d of m||[])if(d.participantId===s){if(d.participantId=void 0,p?.positionAssignments)p.positionAssignments=m;else if(p?.structures){let l=Object.assign({},...(m||[]).map(f=>({[f.drawPosition]:f.participantId})));for(let f of p?.structures||[])f.positionAssignments?.forEach(g=>g.participantId=l[g.drawPosition])}ko({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:p}),e=!0}}}}return{qualifierRemoved:e}}function Yx(t){let{matchUp:e,matchUpStatus:r,score:n,winningSide:o}=t,i="noDownStreamDependencies";if([oe,be].includes(e?.matchUpStatus)&&![oe,be].includes(r)){let h=gM(t);if(h.error)return _({result:h,stack:i})}let a=r===oe,c=he({score:n})&&!a&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!o),u=t?.inContextMatchUp?.collectionId&&_x(t.inContextMatchUp),p=t.removeScore||!u&&![mn,vr].includes(r||mn),m=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!o&&!he({score:n}),d=h=>{let S,{structure:T,drawDefinition:y,dualMatchUp:E,disableAutoCalc:P}=t;if(E?._disableAutoCalc&&P!==!1)return Fd({...t,removeWinningSide:m});let{connectedStructureIds:A}=zy({drawDefinition:y,structure:T,matchUp:e});A.length&&(console.log({connectedStructureIds:A}),S=!0),Object.assign(t,{removeScore:h});let U=Vc(t);if(U.error)return U;if(t.removingQualifier&&t.appliedPolicies?.[pu]?.autoRemoveQualifiers){let N=Wx(t);return{...C,connectedStructures:S,...N}}return{...C,connectedStructures:S}};if(m&&o&&t.isCollectionMatchUp)return jx(t);let l=[po,vr].includes(r)&&t.dualWinningSideChange,f=r&&r!==Qt,g=t.propagateExitStatus&&pr(r),I=(o||l||g)&&Bx(t)||c&&d(p)||f&&Fx(t)||m&&d(p)||e&&jx({...t,removeScore:!0})||{...C};return _({result:I,stack:i})}function jx(t){let e="ndd:scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide&&!t.autoCalcDisabled){let o=Vc(t);if(o.error)return o}let n=Yn({...t,context:e});if(t.isCollectionMatchUp){let{matchUpTieId:o,drawDefinition:i,event:s,matchUpsMap:a}=t,{removeWinningSide:c}=go({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:o,drawDefinition:i,matchUpsMap:a,event:s});c&&console.log("REMOVE WINNING SIDE")}return _({result:n,stack:e})}function fI(t){let e=et(t,[{[ne]:!0,[Ce]:!0,[gn]:!0},{homeParticipantId:!0,[In]:se}]);if(e.error)return e;let r=vs(t,[{[ds]:Gn,attr:{[uu]:!0}}]);if(r.error)return r;let n=r?.matchUp?.matchUp?.sides?.map(m=>m?.participantId);if(t.homeParticipantId&&!n?.includes(t.homeParticipantId))return{error:ln};let{disableNotice:o,homeParticipantId:i,removePriorValues:s,tournamentRecord:a,drawDefinition:c,matchUpId:u}=t;return Zr({duplicateValues:!1,removePriorValues:s,tournamentRecord:a,drawDefinition:c,disableNotice:o,matchUpId:u,timeItem:{itemType:Sd,itemValue:i}})}function IM({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Op});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{timeModifiers:n}:e}function ii(t){let e="addMatchUpScheduledTime",r=t.matchUp,{removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,scheduledTime:a,matchUpId:c}=t;if(!c)return _({result:{error:sr},stack:e});if(!Jc(a))return _({result:{error:Co},stack:e});if(!r){let I=Vt({drawDefinition:i,matchUpId:c});if(I.error)return _({result:I,stack:e});r=I.matchUp}let u=Ut(a),p=Xs({matchUp:r}).scheduledDate,m=u&&!p;if((IM({matchUp:r}).timeModifiers||[])?.length){let I=hM({disableNotice:!0,removePriorValues:n,tournamentRecord:o,timeModifiers:[],drawDefinition:i,matchUpId:c,matchUp:r});if(I?.error)return _({result:I,stack:e})}let f=ac(a,!0,m);return Zr({duplicateValues:!1,removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,matchUpId:c,timeItem:{itemType:ts,itemValue:f}})}function hM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,timeModifiers:o,matchUpId:i,matchUp:s}){let a="addMatchUpTimeModifiers";if(!i)return _({result:{error:sr},stack:a});if(o!==void 0&&!Array.isArray(o))return _({info:li("timeModifiers"),result:{error:B},stack:a});if(!s){let l=Vt({drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a});s=l.matchUp}let c=IM({matchUp:s}).timeModifiers||[],u=o.filter(l=>!c.includes(l));if(o.length&&!u.length)return{...C};if(u.some(l=>hS.includes(l))){c=c.filter(f=>!hS.includes(f));let l=ii({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a})}let m=o?.length?[...u,...c]:void 0;return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:Op,itemValue:m}})}function fm({scheduledDate:t,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i}){if(!i)return{error:sr};let s=t&&Oo.test(t);if(t&&!s)return{error:Ye};let c={itemValue:Ut(t),itemType:Zi};return Zr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:c})}function gm({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtIds:a}){if(!r&&!e)return{error:q};if(!s)return{error:sr};let c=Vt({drawDefinition:n,matchUpId:s});if(c.error)return c;if(c?.matchUp?.matchUpType!==xr)return{error:dr};if(!(a===void 0||Array.isArray(a)&&a.length&&a.every(d=>typeof d=="string")))return{error:B,context:{courtIds:a}};let p;if(a){let d=e||r&&{[r.tournamentId]:r},l=Ro({tournamentRecords:d});if(l.error)return l;let f=l.courts?.filter(g=>a.includes(g.courtId));if(f?.length!==a.length)return{error:B,context:{courtIds:a}};p=f?.map(g=>({venueId:g.venueId,courtId:g.courtId}))}return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:lo,itemDate:i,itemValue:p}})}function la({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,venueId:s}){if(!r)return{error:q};if(!i)return{error:sr};if(s){let c=ti({tournamentRecords:e,tournamentRecord:r,venueId:s});if(c.error)return c}return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:Ji,itemValue:s}})}function as({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtId:a}){if(!r&&!e)return{error:q};if(!s)return{error:sr};if(a){let u=hs({tournamentRecords:e,tournamentRecord:r,courtId:a});if(u.error)return u;let p=u.venue?.venueId;la({tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,venueId:p})}return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:Jo,itemDate:i,itemValue:a}})}function xs(t,e){let r=nh.test(t)?t:zt(t),n=Ut(t)||Ut(e)||Kn(new Date);return new Date(`${n}T${r}`).getTime()}function Im(t){let e="addMatchUpScheduleItems",r=et(t,[{drawDefinition:!0,matchUpId:!0},{schedule:!0,[He]:zr}],e);if(r.error)return r;let{matchUpDependencies:n,inContextMatchUps:o}=t,{errorOnAnachronism:i=!1,checkChronology:s=!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,disableNotice:m,drawMatchUps:d,matchUpId:l,schedule:f,event:g}=t,I,h;if(d)I=d.find(v=>v.matchUpId===l);else{let v=Vt({drawDefinition:p,event:g,matchUpId:l});if(v.error)return v;I=v.matchUp}let{endTime:S,courtId:T,courtIds:y,courtOrder:E,resumeTime:P,homeParticipantId:A,scheduledDate:U,scheduledTime:N,startTime:D,stopTime:M,timeModifiers:R,venueId:b}=f;s&&(!n||!o)&&({matchUpDependencies:n,matchUps:o}=an({drawDefinition:p}));let O=n?.[l]?.matchUpIds;if(f.scheduledDate&&s&&O){let v=o?.filter(x=>(x.schedule?.scheduledDate||Ut(x.schedule?.scheduledTime))&&O.includes(x.matchUpId)).map(({schedule:x})=>{let F=Bm(x);return new Date(F).getTime()});if(v?.length){let x=Bm(f),F=new Date(x).getTime();if(Math.max(...v)>=F){if(i)return _({result:{error:VI},stack:e});h=VI}}}if(U!==void 0){let v=fm({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledDate:U,matchUpId:l});if(v?.error)return _({result:v,stack:e,context:{scheduledDate:U}})}if(N!==void 0){let v=ii({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledTime:N,matchUpId:l,matchUp:I});if(v?.error)return _({result:v,stack:e,context:{scheduledTime:N}})}if(D!==void 0){let v=Jy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,startTime:D,event:g});if(v?.error)return _({result:v,stack:e,context:{startTime:D}})}if(M!==void 0){let v=tE({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,stopTime:M,event:g});if(v?.error)return _({result:v,stack:e,context:{stopTime:M}})}if(P!==void 0){let v=eE({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,resumeTime:P,matchUpId:l,event:g});if(v?.error)return _({result:v,stack:e,context:{resumeTime:P}})}if(S!==void 0){let v=Zy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,endTime:S,event:g});if(v?.error)return _({result:v,stack:e,context:{endTime:S}})}if(y!==void 0){let v=gm({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtIds:y});if(v?.error)return _({result:v,stack:e,context:{courtIds:y}})}if(T!==void 0&&U!==void 0){let v=as({courtDayDate:U,disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtId:T});if(v?.error)return _({result:v,stack:e,context:{courtId:T}})}if(b!==void 0){let v=la({disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,venueId:b});if(v?.error)return _({result:v,stack:e,context:{venueId:b}})}if(E!==void 0&&It(E)){let v=Xy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,courtOrder:E,matchUpId:l});if(v?.error)return _({result:v,stack:e,context:{courtOrder:E}})}if(R!==void 0){let v=hM({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,timeModifiers:R,matchUpId:l,matchUp:I});if(v?.error)return _({result:v,stack:e,context:{timeModifiers:R}})}return kt(A)&&fI({disableNotice:!0,homeParticipantId:A,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l}),m||gt({tournamentId:u?.tournamentId,eventId:g?.eventId,context:e,drawDefinition:p,matchUp:I}),h?{...C,warnings:[h]}:{...C}}function Xy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,courtOrder:o,matchUpId:i}){if(!i)return{error:sr};if(o&&!It(o))return{error:B,info:"courtOrder must be numeric"};let s=o&&dt(o);return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:bp,itemValue:s}})}function SM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,participantId:o,officialType:i,matchUpId:s}){if(!s)return{error:sr};if(!o)return{error:se};if(e){let c=Ft({tournamentRecord:e,participantFilters:{participantTypes:[Et],participantRoles:[Sg]}}).participants??[];if(!zo({tournamentParticipants:c,participantId:o}))return{error:re}}let a={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:o};return i&&(a.itemSubTypes=[i]),Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:s,timeItem:a})}function Jy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,startTime:i,event:s}){if(!o)return{error:sr};if(!Jc(i))return{error:Co};let{matchUp:a}=Vt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Xs({matchUp:a}),p=(a?.timeItems??[]).filter(m=>[es,Oi,vi].includes(m?.itemType)).map(m=>xs(m.itemValue,c)).reduce((m,d)=>!m||d<m?d:m,void 0);if(!p||xs(i,c)<p){a?.timeItems&&(a.timeItems=a.timeItems.filter(l=>l.itemType!==Bo));let m=ac(i,!0,!0);return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:{itemType:Bo,itemValue:m}})}else return{error:xA}}function Zy({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,endTime:s,event:a}){if(!i)return{error:sr};if(!Jc(s))return{error:Co};let{matchUp:c}=Vt({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:u}=Xs({matchUp:c}),m=(c?.timeItems??[]).filter(d=>[Bo,Oi,es].includes(d?.itemType)).map(d=>xs(d.itemValue,u)).reduce((d,l)=>!d||l>d?l:d,void 0);if(!t||!m||xs(s,u)>m){c?.timeItems&&(c.timeItems=c.timeItems.filter(f=>f.itemType!==vi));let d=ac(s,!0,!0);return Zr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:vi,itemValue:d}})}else return{error:vA}}function tE({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,stopTime:i,event:s}){if(!o)return{error:sr};if(!Jc(i))return{error:Co};let{matchUp:a}=Vt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Xs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===vi||g,void 0))return{error:JI};let m=u.filter(g=>[Bo,Oi,es].includes(g?.itemType)).sort((g,I)=>xs(g.itemValue,c)-xs(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===es,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>xs(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(xs(i,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:ac(i,!0,!0),itemType:es};return Zr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:I})}else return{error:_A}}function eE({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,resumeTime:o,matchUpId:i,event:s}){if(!i)return{error:sr};if(!Jc(o))return{error:Co};let{matchUp:a}=Vt({drawDefinition:r,event:s,matchUpId:i}),{scheduledDate:c}=Xs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===vi||g,void 0))return{error:JI};let m=u.filter(g=>[Bo,Oi,es].includes(g?.itemType)).sort((g,I)=>xs(g.itemValue,c)-xs(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===Oi,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>xs(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(xs(o,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:ac(o,!0,!0),itemType:Oi};return Zr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:I})}else return{error:xC}}function qx(t){let{targetData:e,matchUpsMap:r}=t,{targetMatchUps:{loserMatchUp:n}}=e,o=pr(n?.matchUpStatus),i=!!r?.drawMatchUps.find(s=>s.loserMatchUpId===n?.matchUpId&&pr(s.matchUpStatus));return i&&n?.matchUpStatus===oe||i&&o}function $x({drawDefinition:t,matchUpStatus:e,matchUpsMap:r,winningSide:n,dualMatchUp:o,tieFormat:i,structure:s,matchUp:a,event:c,score:u}){let p=J(o,void 0,!0);for(let d of p?.tieMatchUps||[])d.matchUpId===a.matchUpId&&(d.winningSide=n,d.score=u,!he({score:u})&&!e?Object.assign(d,{...Gu}):e&&(d.matchUpStatus=e));i=i??We({matchUp:a,structure:s,drawDefinition:t,event:c})?.tieFormat;let{winningSide:m}=vc({matchUp:p,drawDefinition:t,matchUpsMap:r,structure:s,tieFormat:i,event:c});return{projectedWinningSide:m}}function Kx(t){let{tournamentRecord:e,inContextMatchUp:r,structure:n,drawDefinition:o}=t,i=r.roundNumber,s=r.sides.find(P=>P.sideNumber===r.winningSide),a=r.sides.find(P=>P.sideNumber!==r.winningSide),{drawPosition:c,participantId:u}=s,{drawPosition:p,participantId:m}=a,d="swapWinnerLoser",{matchUps:l}=yt(t),f=l.filter(({drawPositions:P,roundNumber:A})=>P?.includes(c)&&A>i);Dr({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:f}),f.forEach(P=>{P.drawPositions=P.drawPositions?.map(A=>A===c?p:A)||[],gt({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:d,drawDefinition:o,matchUp:P})});let{stage:g,stageSequence:I}=n,h=o.structures.filter(({stage:P,stageSequence:A})=>P===g&&A>I).map(({structureId:P})=>P),{targetLinks:{loserTargetLink:S,winnerTargetLink:T}}=t.targetData,y=[S?.target.structureId,T?.target?.structureId].filter(Boolean);return o.structures.filter(({stage:P,structureId:A})=>P!==g&&y.includes(A)).forEach(({stage:P,stageSequence:A,structureId:U})=>{h.includes(U)||h.push(U),o.structures.filter(({stage:N,stageSequence:D})=>N===P&&D>A).forEach(({structureId:N})=>{h.includes(N)||h.push(N)})}),o.structures.filter(({structureId:P})=>h.includes(P)).forEach(P=>{let{positionAssignments:A}=Ct({structure:P}),U=A?.find(({participantId:D})=>D===u),N=A?.find(({participantId:D})=>D===m);U&&(U.participantId=m),N&&(N.participantId=u)}),Yn({...t,context:d})}function ws(t){let e="setMatchUpStatus";t.matchUpStatus&&[Bt,oe].includes(t.matchUpStatus)&&(t.score=void 0);let{allowChangePropagation:r,disableScoreValidation:n,propagateExitStatus:o,tournamentRecords:i,tournamentRecord:s,disableAutoCalc:a,enableAutoCalc:c,drawDefinition:u,matchUpStatus:p,winningSide:m,matchUpId:d,event:l,score:f}=t;if(!u)return{error:Z};if(p&&[po,mn,vr,Qt].includes(p)&&m)return{error:B,winningSide:m,matchUpStatus:p};if(![void 0,...qh].includes(p))return _({result:{error:Ta},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});let g=Pe({drawDefinition:u}),{matchUps:I}=ie({nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:u,matchUpsMap:g,event:l}),h=g.drawMatchUps.find(Y=>Y.matchUpId===d),S=I?.find(Y=>Y.matchUpId===d);if(!h||!I)return{error:we};if((h.winningSide||m)&&p==="BYE")return{context:"Cannot have Bye with winningSide",error:Xl,matchUpStatus:p};let T=S?.structureId,{structure:y}=at({drawDefinition:u,structureId:T}),E=de(Wt)(h.matchUpType),P=S?.drawPositions?.filter(Boolean),A=S?.matchUpTieId,U=ur({matchUpId:A||d,inContextDrawMatchUps:I,drawDefinition:u});Object.assign(t,{inContextDrawMatchUps:I,inContextMatchUp:S,matchUpTieId:A,matchUpsMap:g,targetData:U,structure:y,matchUp:h});let N=p===Qt&&f?.scoreStringSide1===""&&f?.scoreStringSide2===""&&!m;if(qx(t)&&N)return{error:bC};let M=Fi(t),R;if(E){if(a)At({extension:{name:Ua,value:!0},element:h});else if(c){let Y=h.winningSide,{winningSide:j,scoreStringSide1:V,scoreStringSide2:$,set:X}=vc({drawDefinition:u,matchUpsMap:g,structure:y,matchUp:h,event:l}),W={scoreStringSide1:V,scoreStringSide2:$,sets:X?[X]:[]};if(R=j!==Y,M&&R)return _({stack:"winningSideWithDownstreamDependencies",result:{error:xm},context:{winningSide:m,matchUp:h}});Ir({name:Ua,element:h}),Object.assign(t,{winningSide:j,dualWinningSideChange:R,projectedWinningSide:j,score:W})}ka({tournamentId:s?.tournamentId,inContextDualMatchUp:S,eventId:l?.eventId,dualMatchUp:h,drawDefinition:u})}if(E&&p&&[gc].includes(p))return{info:"Not supported for matchUpType: TEAM",error:B};if(f&&!E&&!n){let Y=h.matchUpFormat??y?.matchUpFormat??u?.matchUpFormat??l?.matchUpFormat,j=Qg({existingMatchUpStatus:h.matchUpStatus,matchUpFormat:Y,matchUpStatus:p,winningSide:m,score:f});if(j.error)return j}let b=Tt({policyTypes:[pu,rn],tournamentRecord:s,drawDefinition:u,event:l})?.appliedPolicies??{};ht(t.policyDefinitions)&&Object.assign(b,t.policyDefinitions);let O=S0({assignedDrawPositions:P,propagateExitStatus:o,inContextMatchUp:S,appliedPolicies:b,drawDefinition:u,matchUpStatus:p,structure:y,matchUp:h});if(O?.error)return O;let v=S?.stage===ct&&S.finishingRound===1,x=v&&m,F=v&&h.winningSide&&!m&&(!t.matchUpStatus||t.matchUpStatus&&gg({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!he({outcome:t.outcome})),w=x&&m!==h.winningSide&&h.winningSide;if(Object.assign(t,{qualifierAdvancing:x,qualifierChanging:w,removingQualifier:F,appliedPolicies:b}),A){let{matchUp:Y}=Vt({matchUpId:A,inContext:!0,drawDefinition:u,matchUpsMap:g,event:l});if(Y){let j=We({matchUp:Y,drawDefinition:u,structure:y,event:l})?.tieFormat,{projectedWinningSide:V}=$x({drawDefinition:u,matchUpStatus:p,dualMatchUp:Y,matchUpsMap:g,winningSide:m,tieFormat:j,structure:y,matchUp:h,event:l,score:f}),$=Y.winningSide;R=V!==$;let X=Y._disableAutoCalc;Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:R,projectedWinningSide:V,autoCalcDisabled:X,matchUpTieId:A,dualMatchUp:Y,tieFormat:j})}}let L=Oa({matchUpStatus:p});if(!A){if(M&&!m&&(p&&gg({matchUpStatus:p})||p&&[oe,be].includes(p)))return{error:Xl,activeDownstream:M,winningSide:m};if(m&&m===h.winningSide&&p&&!L)return{context:"winningSide must include directing matchUpStatus",error:Xl,directingMatchUpStatus:L,matchUpStatus:p}}let{schedule:k}=t;if(k){let Y=Im({disableNotice:!0,tournamentRecords:i,tournamentRecord:s,drawDefinition:u,matchUpId:d,schedule:k});if(Y.error)return Y}let G=!E&&!R&&m&&h.winningSide&&h.winningSide!==m;if(r&&G&&h.roundPosition)return Kx(t);let H=m&&!A||t.projectedWinningSide;Tn({activeDownstream:M,matchUpWinner:H,method:e,winningSide:m});let K=!M&&Yx(t)||H&&h0(t)||(L||t.autoCalcDisabled)&&zx(t)||{error:HA};return _({result:K,stack:e})}function h0(t){let{matchUp:e,winningSide:r,matchUpTieId:n,dualWinningSideChange:o}=t;return r===e.winningSide||n&&!o?zx(t):_({stack:"winningSideWithDownstreamDependencies",result:{error:xm},context:{winningSide:r,matchUp:e}})}function zx(t){let{tournamentRecord:e,matchUp:r,event:n}=t,o=t.isCollectionMatchUp&&r.winningSide&&!t.winningSide&&!he({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||o&&Qt||t.winningSide&&ge||mn:t.matchUpStatus||ge,s=t.removeScore||[po,Bt].includes(i)&&![mn,vr].includes(i),a=Yn({...t,matchUpStatus:i,removeWinningSide:o,context:"sms",removeScore:s});if(a.error)return a;if(t.isCollectionMatchUp){let{matchUpTieId:c,drawDefinition:u,matchUpsMap:p}=t,m=go({appliedPolicies:t.appliedPolicies,matchUpId:c,tournamentRecord:e,drawDefinition:u,matchUpsMap:p,event:n});if(m.error)return m;Object.assign(a,{tieMatchUpResult:m})}return a}function S0({assignedDrawPositions:t,propagateExitStatus:e,inContextMatchUp:r,appliedPolicies:n,drawDefinition:o,matchUpStatus:i,structure:s,matchUp:a}){if(n?.[rn]?.requireParticipantsForScoring===!1)return{...C};let c=r?.sides?.map(m=>m.participantId).filter(Boolean).length,u=a?.sides?[]:Ct({structureId:s?.structureId,drawDefinition:o}).positionAssignments,p=c&&c===2||a.collectionId&&cr({structure:s})&&c&&c>=1||t?.length===2&&u?.filter(m=>t.includes(m.drawPosition)).every(m=>m.participantId);return i&&[Bt,Gt,oe].includes(i)&&c===1&&e?{...C}:i&&Yh.includes(i)&&!p?_({info:"matchUpStatus requires assigned participants",context:{matchUpStatus:i,requiredParticipants:p},result:{error:Ta}}):{...C}}function TM({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n}){if(!e)return{error:Z};let{matchUp:o}=Vt({drawDefinition:e,matchUpId:r,event:n});return o?.matchUpType!==xr?{error:dr}:ws({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n})}function yM({drawDefinition:t,event:e,matchUpId:r}){if(!t)return{error:Z};if(!r)return{error:sr};let{matchUp:n}=Vt({drawDefinition:t,event:e,matchUpId:r});return n?Ir({name:Jm,element:n}):{error:we}}function Qx({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:r,drawDefinition:n,sideNumber:o,matchUpId:i,event:s}){let a="substituteParticipant";if(!n)return{error:Z};if(!i)return{error:sr};if(!e||!t)return _({result:{error:se},stack:a});let{matchUp:c}=Vt({drawDefinition:n,matchUpId:i,event:s});if(!c)return{error:we};if(!c.collectionId)return _({result:{error:dr},stack:a});let u=Pe({drawDefinition:n}),{matchUps:p}=ie({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),m=p?.find(g=>g.matchUpId===i),l=p?.find(g=>g.matchUpId===m?.matchUpTieId)?.sides?.find(g=>g.participant.individualParticipants.some(({participantId:I})=>I===e));return!l||o&&l.sideNumber!==o?{error:ln}:l.participant?.individualParticipants?.map(St).filter(g=>g!==e)?.includes(t)?dI({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:r,drawDefinition:n,event:s}):_({result:{error:ln},stack:a})}function EM(t){return Qx(t)}function AM({drawDefinition:t,matchUpId:e,event:r}){if(!t)return{error:Z};let{matchUp:n}=Vt({drawDefinition:t,matchUpId:e,event:r});return At({extension:{name:Ua,value:!0},element:n})}function UM(t){let e="setMatchUpFormat",r=et(t,[{tournamentRecord:!0},{[tr]:E=>Nr({matchUpFormat:E}),[kr]:tc,matchUpFormat:!0}]);if(r.error)return _({result:r,stack:e});let{tournamentRecord:n,drawDefinition:o,scheduledDates:i,stageSequences:s,matchUpFormat:a,structureId:c,eventType:u,matchUpId:p,eventId:m,stages:d,drawId:l,event:f,force:g}=t;if(i&&!Array.isArray(i))return _({result:{error:B,scheduledDates:i},stack:e});if(u&&!Yc([Qn,Kr],u))return _({result:{error:$n},stack:e});let I=0,h=t.structureIds||c&&[c].filter(Boolean)||[],S=t.eventIds||m&&[m].filter(Boolean)||[],T=t.drawIds||l&&[l].filter(Boolean)||[];if((c||h?.length)&&!o)return _({result:{error:Z},stack:e});if(l&&p&&o){let E=el({tournamentRecord:n,drawDefinition:o,matchUpFormat:a,structureIds:h,structureId:c,matchUpId:p});if(E.error)return E;I+=1}let y=E=>{let P=[];for(let A of E.structures||[]){if(Array.isArray(d)&&!d.includes(A.stage)||Array.isArray(s)&&!s.includes(A.stageSequence)||h?.length&&!h.includes(A.structureId))continue;h?.length&&A.matchUpFormat!==a&&(A.matchUpFormat=a,P.push(A.structureId),I+=1);let U=((g||i)&&yt({matchUpFilters:{matchUpStatuses:[Qt]},structure:A}).matchUps)??[],N=(i&&yt({matchUpFilters:{matchUpStatuses:[Qt]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:A}).matchUps)??[];if(U?.length){let D=N?N.map(Ue):U.map(Ue);for(let M of U)D.includes(M.matchUpId)&&(M.matchUpFormat=i?.length?a:void 0,gt({tournamentId:n?.tournamentId,eventId:f?.eventId,context:e,drawDefinition:E,matchUp:M}))}}return!P.length&&E.matchUpFormat!==a&&(E.matchUpFormat=a,I+=1),P};for(let E of n?.events||[])if(!(S?.length&&!S.includes(E.eventId)||u&&u!==E.eventType||u===_e))if(Array.isArray(s)||Array.isArray(d)||h?.length||T?.length)for(let P of E.drawDefinitions||[]){if(Array.isArray(T)&&!T.includes(P.drawId))continue;let A=y(P);bt({structureIds:A,drawDefinition:P})}else E.matchUpFormat!==a&&(E.matchUpFormat=a,I+=1);return I?{...C,modificationsCount:I}:{...C,info:Bs}}function gI({inheritance:t=!0,tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}){if(!r)return{error:Z};let i=Vt({drawDefinition:r,matchUpId:n})?.matchUp;if(!i?.tieMatchUps)return{error:dr};let s=Vt({inContext:!0,drawDefinition:r,matchUpId:n,event:o})?.matchUp,a=0;return(i?.sides||[]).forEach(c=>{c.lineUp&&delete c.lineUp}),(s?.sides||[]).forEach(c=>{if(a+=1,t===!1){let u=s?.tieFormat,p=c.participantId;u&&p&&os({drawDefinition:r,participantId:p,lineUp:[],tieFormat:u})}gt({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:o?.eventId,drawDefinition:r,matchUp:i})}),{...C,modificationsCount:a}}function rE(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o,setTBlast:i}=t;if(!o)return{sets:[]};let s=o.sets||[],a=Mo({winnerFirst:!1,matchUpFormat:e,matchUpStatus:r,setTBlast:i,sets:s}),c=Mo({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:r,setTBlast:i,sets:s}),u=Mo({matchUpFormat:e,matchUpStatus:r,winningSide:n,setTBlast:i,sets:s}),p=a===u?c:a;return n&&(a=n===1?u:p,c=n===2?u:p),{score:{sets:s,scoreStringSide1:a,scoreStringSide2:c}}}function Xx({sourceMatchUpStatusCodes:t,propagateExitStatus:e,sourceMatchUpStatus:r,loserParticipantId:n,tournamentRecord:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,event:c}){let u="progressExitStatus";Tn({matchUpId:s?.matchUpId,matchUpStatus:r,color:"magenta",method:u});let p=pr(r)&&r!==Me&&r||Bt,m=ie({inContext:!0,drawDefinition:i,matchUpsMap:a})?.matchUps,d=p,l=m?.find(f=>f.matchUpId===s?.matchUpId);if(l?.matchUpId&&d){let f,g=l.matchUpStatusCodes?.map(S=>typeof S=="string"?S:"WO")??[],I=l.sides?.find(S=>S.participantId===n);if(I?.sideNumber)if(l?.sides?.reduce((T,y)=>y?.participantId?T+1:T,0)===1&&g.length===0)f=I.sideNumber===1?2:1,g[0]=t[0];else if(!pr(s.matchUpStatus))f=I.sideNumber===1?2:1,g[0]=t[0];else{let T=g[0];g[I.sideNumber-1]=t[0];let y=I.sideNumber===1?2:1;g[y-1]=T,d=oe,f=void 0}let h=ws({matchUpStatus:d,matchUpId:s.matchUpId,matchUpStatusCodes:g,allowChangePropagation:!0,propagateExitStatus:e,tournamentRecord:o,drawDefinition:i,winningSide:f,event:c});return _({result:h,stack:u,context:{progressExitStatus:!0}})}return _({result:{error:mr},stack:u})}function Qu(t){let e=et(t,[{[gn]:!0,[Ce]:!0}]);if(e.error)return e;let r="setMatchUpStatus",n=Rr(t);if(!t.drawDefinition){let E=t.tournamentRecord??(t.tournamentId&&n[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=E);let P=ze({eventId:t.eventId,drawId:t.drawId,tournamentRecord:E});if(P.error)return P;P.drawDefinition&&(t.drawDefinition=P.drawDefinition),t.event=P.event}let{disableScoreValidation:o,propagateExitStatus:i,policyDefinitions:s,tournamentRecord:a,disableAutoCalc:c,enableAutoCalc:u,drawDefinition:p,matchUpId:m,schedule:d,event:l,notes:f}=t,g=t.matchUpFormat||t.outcome?.matchUpFormat,{policy:I}=pi({policyType:rn,tournamentRecord:a,event:l}),h=t.allowChangePropagation!==void 0&&t.allowChangePropagation||I?.allowChangePropagation!==void 0&&I.allowChangePropagation||void 0,{outcome:S,setTBlast:T}=t;if(S?.winningSide&&![1,2].includes(S.winningSide))return{error:_m};if(g){let E=el({tournamentRecord:a,drawDefinition:p,matchUpFormat:g,matchUpId:m,event:l});if(E.error)return E}if(S?.score?.sets&&!S.score.scoreStringSide1){let{score:E}=rE({...S,setTBlast:T});S.score=E,S.score.sets=S.score.sets.filter(P=>P.side1Score||P.side2Score||P.side1TiebreakScore||P.side2TiebreakScore)}let y=ws({matchUpStatusCodes:S?.matchUpStatusCodes,matchUpStatus:S?.matchUpStatus,winningSide:S?.winningSide,allowChangePropagation:h,disableScoreValidation:o,score:S?.score,propagateExitStatus:i,tournamentRecords:n,policyDefinitions:s,tournamentRecord:a,disableAutoCalc:c,enableAutoCalc:u,drawDefinition:p,matchUpFormat:g,matchUpId:m,schedule:d,event:l,notes:f});if(y.context?.progressExitStatus){let E=!0,P=0;for(;E&&P<10;){E=!1,P+=1;let A=Xx({sourceMatchUpStatusCodes:y.context.sourceMatchUpStatusCodes,sourceMatchUpStatus:y.context.sourceMatchUpStatus,loserParticipantId:y.context.loserParticipantId,propagateExitStatus:t.propagateExitStatus,tournamentRecord:t.tournamentRecord,loserMatchUp:y.context.loserMatchUp,matchUpsMap:y.context.matchUpsMap,drawDefinition:t.drawDefinition,event:t.event});A.context?.loserMatchUp&&(Object.assign(y.context,A.context),E=!0)}}return _({result:y,stack:r})}function PM(t){if(!t?.outcomes)return{error:st};if(!Array.isArray(t.outcomes))return{error:st,info:{outcomes:t.outcomes}};let e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},r=t.outcomes??[],n=r.reduce((o,i)=>o.includes(i.tournamentId)?o:o.concat(i.tournamentId),[]);for(let o of n){let i=e[o];if(!i)return{error:q};let s=r.filter(a=>a.tournamentId===o);if(s.length){let a=T0({outcomes:s,tournamentRecord:i});if(a.error)return a}}return{...C}}function T0(t){let{tournamentRecords:e,tournamentRecord:r,outcomes:n,policyDefinitions:o}=t,i={};n.forEach(s=>{let{eventId:a}=s;i[a]||(i[a]=[]),i[a].push(s)});for(let s of Object.keys(i)){let{event:a}=ze({tournamentRecord:r,eventId:s});for(let c of i[s]){let{drawId:u}=c,p=a?.drawDefinitions?.find(m=>m.drawId===u);if(p&&u){let{matchUpFormat:m,matchUpId:d}=c,l=Qu({schedule:c?.schedule,tournamentRecords:e,policyDefinitions:o,tournamentRecord:r,drawDefinition:p,matchUpFormat:m,matchUpId:d,outcome:c,drawId:u,event:a});if(l.error)return l}}}return{...C}}function Jx({drawDefinition:t,matchUpId:e,outcome:r,matchUp:n}){if(!n&&!t)return{error:Z};if(!r)return{error:st,info:"missing outcome"};if(!n&&!e)return{error:mr};if(!n){let i=Vt({drawDefinition:t,matchUpId:e});if(i.error)return i;n=i.matchUp}return typeof r!="object"||!r.score?.scoreStringSide1||!r.score?.scoreStringSide2?{error:B}:At({element:n,extension:{name:Jm,value:r}})}function DM(t){return Jx(t)}function II(t){let e="resetTieFormat",{drawDefinition:r,event:n,uuids:o}=t,i=et(t,[{[ne]:!0,[gn]:!0}],e);if(i.error)return i;let s=vs(t,[{[ds]:Gn}]);if(s[In])return s;let a=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=s?.matchUp??{};if(!c?.tieMatchUps)return _({result:{error:dr},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...C};let p=We({structure:u,drawDefinition:r,event:n})?.tieFormat;if(!p)return _({result:{error:Oe},info:"No inherited tieFormat",stack:e});let m=[],d=[],l=[],f=[];for(let g of p.collectionDefinitions){let{matchUpCount:I,collectionId:h}=g;d.push(h);let S=(c.tieMatchUps||[]).filter(T=>T.collectionId===h);if(S.length>I)S.sort((T,y)=>(T.matchUpStatus===Qt?1:0)-(y.matchUpStatus===Qt?1:0)),l.push(...S.slice(0,I)),m.push(...S.slice(3).map(Ue));else if(l.push(...S),S.length<I){let T=I-S.length,y=wu({collectionDefinition:g,matchUpsLimit:T,matchUp:c,uuids:o});f.push(...y)}}for(let g of c?.tieMatchUps||[])g.collectionId&&!d.includes(g.collectionId)&&m.push(g.matchUpId);return f.length&&(l.push(...f),Fo({eventId:n?.eventId,matchUps:f,drawDefinition:r,tournamentId:a})),m.length&&_n({matchUpIds:m,eventId:n?.eventId,drawDefinition:r,tournamentId:a}),c&&(c.tieMatchUps=l,c.tieFormatId=void 0,c.tieFormat=void 0,gt({structureId:u?.structureId,eventId:n?.eventId,context:e,drawDefinition:r,tournamentId:a,matchUp:c})),{...C,newMatchUps:f,deletedMatchUpIds:m}}function hI(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}=t,i="resetScorecard";if(!r)return _({result:{error:Z},stack:i});if(!n)return _({result:{error:sr},stack:i});if(!kt(n))return _({result:{error:B,matchUpId:n},stack:i});let s=Pe({drawDefinition:r}),{matchUps:a}=ie({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),c=s.drawMatchUps.find(I=>I.matchUpId===n),u=a?.find(I=>I.matchUpId===n);if(!c||!a)return{error:we};if(c.matchUpType!==Or)return{error:dr};let p=ur({inContextDrawMatchUps:a,drawDefinition:r,matchUpId:n}),m=u?.structureId,{structure:d}=at({drawDefinition:r,structureId:m});if(Object.assign(t,{inContextDrawMatchUps:a,inContextMatchUp:u,matchUpsMap:s,targetData:p,structure:d,matchUp:c}),Fi(t))return{error:xm};if(c.tieMatchUps?.length)for(let I of c.tieMatchUps){let h=ws({matchUpId:I.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:r,event:o});if(h.error)return _({result:h,stack:i})}let f=Tt({tournamentRecord:e,drawDefinition:r,event:o})?.appliedPolicies,g=go({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(g.error)return _({result:g,stack:i});if(t.tiebreakReset&&!g.tieFormatRemoved){let I=We({drawDefinition:r,structure:d,event:o})?.tieFormat;if(c.tieFormat&&I){let{matchUpCountDifference:h,descendantDifferences:S,ancestorDifferences:T,valueDifference:y}=ni({descendant:c.tieFormat,ancestor:I});if(S.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&h===1&&y===1){let E=II({tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o});if(E.error)return E}}}return{...C}}function NM(t){let e=et(t,[{[Ce]:!0,[co]:!0},{[Ks]:{[mc]:!1,roundNumbers:!1},[Vh]:"At least one must be provided",[He]:Be}]);if(e.error)return e;let r=mT(t);if(r.error)return r;let{matchUpIds:n}=r,o=de(Or)(t.event.eventType),{tournamentRecord:i,drawDefinition:s,event:a}=t;for(let c of n){if(o){let p=hI({tiebreakReset:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(p.error||t.removeAssignments&&gI({inheritance:!1,drawDefinition:s,matchUpId:c}).error)return p}let u=ws({winningSide:void 0,removeScore:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(u.error)return u;if(t.removeAssignments){let p=lI({...t,matchUpId:c});if(p.error)return p}}return{...C}}function Zx({tournamentRecord:t,drawDefinition:e,finishingOrder:r}){if(!e)return{error:Z};let n="setOrderOfFinish";if(!Array.isArray(r))return _({info:li("finishingOrder"),result:{error:B},stack:n});let{completedMatchUps:o,matchUpsMap:i}=Zs({inContext:!0,drawDefinition:e}),s=o?.map(Ue)??[],a=r.map(Ue),{matchUpTypes:c,roundNumbers:u,structureIds:p,matchUpTieIds:m}=(o??[]).filter(({matchUpId:T})=>a.includes(T)).reduce((T,y)=>{let{matchUpTieId:E,matchUpType:P,roundNumber:A,structureId:U}=y;return T.matchUpTypes.includes(P)||T.matchUpTypes.push(P),T.roundNumbers.includes(A)||T.roundNumbers.push(A),T.structureIds.includes(U)||T.structureIds.push(U),T.matchUpTieIds.includes(E)||T.matchUpTieIds.push(E),T},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||m.length>1||u.length>1||p.length>1)return _({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:B},stack:n});let d,l,f={},g=[],I=[];if(!r.every(({orderOfFinish:T,matchUpId:y})=>(g.push(y),T&&I.push(T),f[y]=T,d=s.includes(y),l=T===void 0||It(T)&&Math.floor(T)>0,d&&l)))return _({result:{error:d?B:Ta},info:!d&&"matchUps must be completed"||!l&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:n});let S=o?.filter(T=>T.structureId===p[0]&&T.roundNumber===u[0]&&T.matchUpType===c[0]&&T.matchUpTieId===m[0]&&!g.includes(T.matchUpId));for(let T of S??[]){let{orderOfFinish:y}=T||{};if(y){if(!It(y))return _({context:{orderOfFinish:y,matchUp:T},result:{error:B},stack:n});I.push(y)}}if(xI(I).length!==I.length||Math.max(...I)>I.length)return _({info:"Values not unique or greater than expected number of values",result:{error:B},stack:n});if(p.length){let T=Mu({matchUpFilters:{matchUpIds:a},structureId:p[0],drawDefinition:e,matchUpsMap:i});if(T.error)return _({result:T,stack:n});T.completedMatchUps?.forEach(y=>{y.orderOfFinish=f[y.matchUpId],gt({tournamentId:t.tournamentId,context:"setOrderOfFinish",drawDefinition:e,matchUp:y})})}return{...C}}function MM(t){return Zx(t)}function RM(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,lineUps:o,event:i}=t,s="applyLineUps",a=et(t,[{[ne]:!0,[Ce]:!0,[gn]:!0},{lineUps:!0,[He]:Be}],s);if(a.error)return a;let c=e.participants||[],u=Vt({tournamentParticipants:c,inContext:!0,drawDefinition:r,matchUpId:n});if(u.error)return u;if(!u.matchUp)return{error:we};let{matchUp:p,structure:m}=u,{drawPositions:d,matchUpType:l}=p;if(l!==Wt)return{error:dr};if(!d?.length)return{error:Ja};let f=We({matchUp:p,drawDefinition:r,structure:m,event:i})?.tieFormat,g={};for(let h of o){if(!Array.isArray(h))return{error:B,lineUp:h};let S={},T=[];for(let U of h){if(typeof U!="object")return{error:B,lineUpAssignment:U};let{participantId:N,collectionAssignments:D=[]}=U;if(!Array.isArray(D))return{error:B,collectionAssignments:D};let M=c.find(b=>b.participantId===N);if(!M)return{error:re};if(M.participantType!==Et)return{error:Pn};let R=p.sides?.find(b=>b.participant?.individualParticipantIds?.includes(N))?.sideNumber;R&&T.push(R);for(let b of D){if(typeof b!="object")return{error:B,collectionAssignment:b};let{collectionId:O,collectionPosition:v}=b,x=f?.collectionDefinitions?.find(L=>L.collectionId===O);if(!x)return{error:B,collectionId:O};let F=`${O}-${v}`;S[F]||(S[F]=[]);let w=S[F].length;if(de(Lt)(x.matchUpType)&&w||x.matchUpType===vt&&w>1)return{info:"Excessive collectionPosition assignments",error:B};S[F].push(N)}}let y=Object.values(S);for(let U of y)if(U.length===2){let{participant:N}=Sn({tournamentParticipants:c,participantIds:U});if(!N){let M=wn({participant:{participantType:ft,participantRole:xe,individualParticipantIds:U},pairOverride:!0,tournamentRecord:e});if(M.error)return M}}let E=Er(T),P=(E[1]||0)>(E[2]||0)&&1||(E[2]||0)>(E[1]||0)&&2||void 0,A=Object.keys(g).map(U=>parseInt(U));P&&!A.includes(P)&&(g[P]=h)}if(!Object.keys(g).length)return{error:ff};if(u=Vt({drawDefinition:r,matchUpId:n}),u.error)return u;if(!u.matchUp)return{error:we};let{matchUp:I}=u;I.sides||(I.sides=[]);for(let h of[1,2]){let S=I.sides.find(y=>y.sideNumber===h),T=g[h];if(T)S?S.lineUp=T:I.sides.push({lineUp:T,sideNumber:h});else continue}return gt({tournamentId:e?.tournamentId,context:s,drawDefinition:r,matchUp:I}),{...C}}var PI={};Xt(PI,{anonymizeTournamentRecord:()=>FM,generate:()=>LM,generateEventWithDraw:()=>Um,generateOutcome:()=>EI,generateOutcomeFromScoreString:()=>SI,generateParticipants:()=>fa,generateTournamentRecord:()=>wM,modifyTournamentRecord:()=>kM,mutate:()=>GM});var LM={};Xt(LM,{generateEventWithDraw:()=>Um,generateOutcome:()=>EI,generateOutcomeFromScoreString:()=>SI,generateParticipants:()=>fa,generateTournamentRecord:()=>wM});function y0(t){let e=t.reduce((n,o)=>((o.side1Score!==void 0||o.side2Score!==void 0)&&(n.side1+=o.side1Score??0,n.side2+=o.side2Score??0),n),{side1:0,side2:0});return e.side1>e.side2?1:e.side2>e.side1?2:t.find(n=>n.side1TiebreakScore!==void 0||n.side2TiebreakScore!==void 0)?.winningSide}function E0(t){let e={side1:0,side2:0};if(t.forEach(r=>{r.winningSide===1?e.side1++:r.winningSide===2&&e.side2++}),e.side1>e.side2)return 1;if(e.side2>e.side1)return 2}function A0(t,e,r){if(t||!e||!r)return t;let n=Ne(e);return n?.setFormat?.based==="A"||n?.finalSetFormat?.based==="A"?y0(r):E0(r)}function U0(t,e,r){let n=nm({scoreString:t,matchUpFormat:e});return{sets:n,scoreStringSide1:Mo({sets:n,matchUpFormat:e,setTBlast:r}),scoreStringSide2:Mo({sets:n,reversed:!0,matchUpFormat:e,setTBlast:r})}}function P0(t,e,r,n){let o=Mo({sets:t,matchUpFormat:r,setTBlast:n}),i=Mo({sets:t,reversed:!0,matchUpFormat:r,setTBlast:n});if(typeof o!="string")return o;if(typeof i!="string")return i;let s=e===2?i:o,a=e===2?o:i;return{sets:nm({scoreString:s,matchUpFormat:r}),scoreStringSide1:s,scoreStringSide2:a}}function SI(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,scoreString:o,setTBlast:i}=t;if(!o)return{outcome:{...Gu,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:B,winningSide:n};let s=o&&nm({scoreString:o,matchUpFormat:e}),a=o?.trim().startsWith("["),c=A0(n,e,s),u=Ne(e),p=u?.setFormat?.based==="A"||u?.finalSetFormat?.based==="A",m=a||p?U0(o,e,i):P0(s,c,e,i);return nt({outcome:{matchUpStatus:r,winningSide:c,score:m}})}function Nl({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:r,matchUp:n}){let i=(e?.[n.matchUpId]?.matchUpIds||[]).filter(a=>r.includes(a)).filter(a=>!t[a]);return{dependenciesScheduled:!i?.length,remainingDependencies:i}}function Ya({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function tw({individualParticipantProfiles:t,recoveryValue:e,participantId:r,scheduleTime:n,drawId:o}){t[r].potentialRecovery[o]||(t[r].potentialRecovery[o]=[]),t[r].potentialRecovery[o].push(e),t[r].potentialBookings[o]||(t[r].potentialBookings[o]=[]),t[r].potentialBookings[o].push({timeAfterRecovery:e,scheduleTime:n})}function Bc({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:o,matchUpDependencies:i,recoveryMinutes:s=0,scheduleTime:a,matchUp:c}){let u=zt(c?.schedule?.endTime),p=u?$r(u,dt(s)):$r(a,dt(n)+dt(s)),m=r&&(u?$r(zt(u),r):$r(a,dt(n)+dt(r))),d=i?.[c.matchUpId]?.participantIds||[],l=(c.roundPosition&&t[c.matchUpId]||[]).flat();d.forEach(f=>{Ya({individualParticipantProfiles:e,participantId:f});let I=e[f].priorMatchUpType!==c.matchUpType&&m||p;l.includes(f)?tw({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:I,participantId:f,scheduleTime:a}):(e[f].timeAfterRecovery=I,e[f].bookings.push({scheduleTime:a,timeAfterRecovery:I}))}),ua({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:o,timeAfterRecovery:p,matchUp:c})}function nE({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:r,matchUpId:n,details:o}){let i,s=o.minutesMap?.[n]?.recoveryMinutes,c=(o.minutesMap?.[n]?.averageMinutes||0)+(s||0),u=$r(r,c),p=e?.[n]?.dependentMatchUpIds||[];if(p.length){let m=p.reduce((d,l)=>{let f=t[l];if(!f)return d;let g={scheduleTime:f,matchUpId:l};return f&&!d.matchUpId||Yt(f)<Yt(d.scheduleTime)?g:d},{});m.scheduleTime&&Yt(u)>Yt(m.scheduleTime)&&(i=m)}return{scheduledDependent:i}}function ew(t){let{sides:e,matchUpType:r}=t||{};return(e||[]).map(n=>r===vt&&(n?.participant?.individualParticipants||[])||n?.participant&&[n.participant]||[]).flat()}var Hc="DO_NOT_SCHEDULE",rw={DO_NOT_SCHEDULE:Hc};function Ml({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:r=!0,personRequests:n,scheduleTime:o,scheduleDate:i,matchUp:s}){let a=ew(s).map(({person:l})=>l?.personId);if(r){let l=(s?.potentialParticipants||[]).flat().map(({person:f})=>f?.personId);a.push(...l)}let c=a.map(l=>n[l]?.map(f=>({...f,personId:l}))).filter(Boolean).flat().filter(l=>l.requestType===Hc&&zn(i,l.date)),u=[],p=s?.matchUpId,m=Ge(zt(o),Ut(i)),d=zt(Rf(m,t).toISOString());for(let l of c){let{requestId:f,startTime:g,endTime:I}=l;(o>g&&o<I||d>g&&d<I)&&(u.push({matchUpId:p,request:l,scheduleTime:o}),e[f]?(e[f].scheduleTimes.includes(o)||e[f].scheduleTimes.push(o),e[f].matchUpIds.includes(p)||e[f].matchUpIds.push(p)):e[f]={request:l,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:u}}function TI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:r,value:n}){let{matchUpType:o}=r,{individualParticipantIds:i}=Su(r),a=(t[r.matchUpId]||[]).filter(u=>!ke(u,i)).flat();[...i,...a].forEach(u=>{if(Ya({individualParticipantProfiles:e,participantId:u}),!e[u].potentialCounted[r.drawId]){let p=e[u].counters;p[o]?p[o]+=n:n>0&&(p[o]=n),p[fo]?p[fo]+=n:n>0&&(p[fo]=n),a.includes(u)&&(e[u].potentialCounted[r.drawId]=!0)}})}function nw({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,matchUpDependencies:a,clearScheduleDates:c,scheduleDate:u,minutesMap:p,matchUps:m}){let d=[];r||(o=m?.filter(g=>{let I=g.schedule||{},h=g.matchUpStatus==="BYE";return h&&d.push({tournamentId:g.tournamentId,matchUpId:g.matchUpId}),!h&&Ha({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),r=o.map(Ue));let l=Array.isArray(c)?c.includes(u):c,f=l?[]:m.filter(({matchUpId:g})=>r.includes(g));for(let g of f){TI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});let I=g.schedule?.scheduledTime;if(I){s[g.matchUpId]=I;let h=p?.[g.matchUpId]?.recoveryMinutes;Bc({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:a,averageMatchUpMinutes:n,recoveryMinutes:h,scheduleTime:I,matchUp:g})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:d,dateScheduledMatchUps:o,clearDate:l}}function hm({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:o=[],periodLength:i,scheduleDate:s,matchUps:a}){if(typeof n!="object")return{error:xt};if(!Br(a)&&!Array.isArray(r))return{error:no};i=i??zu({recoveryMinutes:t,averageMatchUpMinutes:e});let c=Object.assign({},...Object.values(n).map(d=>(d.events??[]).map(l=>{let{scheduleTiming:f}=Ra({tournamentRecord:d,event:l});return{[l.eventId]:{event:l,scheduleTiming:f}}})).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};r||(r=a?.filter(d=>{let l=d.schedule;return Ha({schedule:l})&&(!s||d.schedule.scheduledDate===s)}));let p=r?.filter(d=>(!o.length||o.includes(d.schedule.venueId))&&d.matchUpStatus!=="BYE");return{bookings:p?.map(({eventId:d,schedule:l,matchUpFormat:f})=>{let{event:g,scheduleTiming:I}=c[d],h=g?.eventType,S={...I,defaultTiming:u,matchUpFormat:f},{averageMinutes:T,recoveryMinutes:y}=xp({timingDetails:S,eventType:h}),{courtId:E,venueId:P}=l,A=zt(l.scheduledTime),U=$r(A,T);return{recoveryMinutes:y,averageMinutes:T,periodLength:i,startTime:A,courtId:E,endTime:U,venueId:P}}).filter(Boolean),relevantMatchUps:p,dateScheduledMatchUps:r}}function ow({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:r,averageMatchUpMinutes:n,clearScheduleDates:o,tournamentRecords:i,tournamentRecord:s,periodLength:a,scheduleDate:c,startTime:u,venueIds:p,matchUps:m,endTime:d}){if(s&&!i&&(i={[s.tournamentId]:s}),typeof i!="object"||!Object.keys(i).length)return{error:xt};a=a??zu({recoveryMinutes:r,averageMatchUpMinutes:n});let{courts:l,venues:f}=Ro({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),g=l?.filter(P=>!p||p.includes(P.venueId))??[];u=u??Gc({courts:g,scheduleDate:c,startTime:!0}),d=d??Gc({courts:g,scheduleDate:c,endTime:!0});let{bookings:I,dateScheduledMatchUps:h}=hm({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:i,scheduleDate:c,periodLength:a,venueIds:p,matchUps:m}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:n,clearScheduleDates:o,date:c,periodLength:a,startTime:u,bookings:I,endTime:d,courts:g},{scheduleTimes:T}=El(S),y=p?.length===1&&p[0]||f?.length===1&&f[0].venueId||void 0;return{dateScheduledMatchUpIds:h?.map(Hr("matchUpId")),dateScheduledMatchUps:h,scheduleTimes:T,venueId:y}}function iw({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:r}){let n=[],o=[],i,s,a,c;for(let u of t.filter(Boolean))c||(c=u.hash),(u.hash===c||r)&&(o=o.concat(u.matchUpIds)),u.hash!==c&&!r&&(c=u.hash,n.push({averageMinutes:a,recoveryMinutes:s,roundPeriodLength:i,matchUpIds:o}),o=u.matchUpIds),a=r?e:u.averageMinutes,s=u.recoveryMinutes,i=u.roundPeriodLength;return o.length&&n.push({matchUpIds:o,roundPeriodLength:i,recoveryMinutes:s,averageMinutes:a}),{groupedRounds:n}}function oE({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,tournamentRecords:c,periodLength:u,scheduleDate:p,useGarman:m,matchUps:d,courts:l,venues:f}){let g={},I=[],h=[],S=[];for(let T of f){let{rounds:y=[],venueId:E}=T,{scheduledRoundsDetails:P,greatestAverageMinutes:A,orderedMatchUpIds:U,minutesMap:N}=$u({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:d,rounds:y});S.push(...U??[]);let{groupedRounds:D}=iw({scheduledRoundsDetails:P,greatestAverageMinutes:A,garmanSinglePass:!0}),M,R=[];m&&({scheduleTimes:R,dateScheduledMatchUpIds:M}=ow({averageMatchUpMinutes:D[0]?.averageMinutes,scheduleDate:Ut(p),venueIds:[T.venueId],clearScheduleDates:a,tournamentRecords:c,periodLength:u,matchUps:d}));let b=nw({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:M,greatestAverageMinutes:A,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,scheduleDate:p,minutesMap:N,matchUps:d});({dateScheduledMatchUpIds:M}=b);let O=b,{byeScheduledMatchUpDetails:v,clearDate:x}=b;v?.length&&h.push(...v);let{matchUpsToSchedule:F,matchUpMap:w}=pl({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:M,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,orderedMatchUpIds:U,clearDate:x,matchUps:d}),L=l.filter(k=>k.venueId===E);g[E]={previousRemainingScheduleTimes:[],courtsCount:L.length,greatestAverageMinutes:A,scheduledRoundsDetails:P,dateScheduledMatchUps:O,matchUpsToSchedule:F,scheduleTimes:R,groupedRounds:D,venueCourts:L,minutesMap:N,matchUpMap:w},a||I.push(...M)}return{allDateScheduledByeMatchUpDetails:h,allDateScheduledMatchUpIds:I,venueScheduledRoundDetails:g,allDateMatchUpIds:S}}function sw(t,e){let r=Yt(t.scheduleTime),n=Yt(t.timeAfterRecovery),o=Yt(e.scheduleTime),i=Yt(e.timeAfterRecovery),s=r===o||n===i,a=r>o&&r<i,c=o>r&&o<n,u=n>o&&n<i,p=i>r&&i<n;return nt({hasOverlap:s||a||u||c||p,startAisContained:a,endAisContained:u,startBisContained:c,endBisContained:p},!0)}function Rl({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:r,scheduleTime:n,matchUp:o,details:i}){let s=(r?.[o.matchUpId]?.participantIds||[]).flat(),a=i?.minutesMap?.[o.matchUpId]?.averageMinutes||0,c=i?.minutesMap?.[o.matchUpId]?.recoveryMinutes||0,u=s.every(f=>{Ya({individualParticipantProfiles:t,participantId:f});let g=t[f];if(!g.timeAfterRecovery)return!0;let I=zt(o?.schedule?.endTime),h=I?$r(I,dt(c)):$r(n,dt(a)+dt(c));return!!![...Object.keys(g.potentialBookings).filter(E=>E!==o.drawId).map(E=>g.potentialBookings[E]).flat(),...g.bookings].find(E=>sw({scheduleTime:n,timeAfterRecovery:h},E).hasOverlap)}),p=e[o.matchUpId],d=(p?ya(Ge(p),Ge(n),!1):0)>=0;return{enoughTime:u&&d}}function iE({autoSchedulingAudit:t,tournamentRecords:e}){lt({topic:Mi,payload:t});let r=s=>s?Object.values(s).reduce((c,u)=>c+u.length||0,0):0,n=(t?.schedulingProfile||[]).reduce((s,a)=>s+a.venues.reduce((c,u)=>c+u.rounds.length,0),0),o={scheduledDatesCount:t.scheduledDates?.length,noTimeMatchUpIdsCount:r(t?.noTimeMatchUpIds),scheduledMatchUpIdsCount:r(t?.scheduledMatchUpIds),overLimitMatchUpIdsCount:r(t?.overLimitMatchUpIds),requestConflictsCount:r(t?.requestConflicts),profileRoundsCount:n},i={itemType:wy,itemValue:o};for(let s of Object.values(e)){let a=s.tournamentId;dp(Mi)?lt({payload:{type:wy,tournamentId:a,detail:o},topic:Mi}):_c({tournamentRecord:s,timeItem:i})}}function Cl({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUpDailyLimits:r={},matchUp:n}){let{enteredIndividualParticipantIds:o}=Su(n),{matchUpId:i,matchUpType:s}=n,a=(n.roundPosition&&t[i]||[]).flat(),c=pt(o.concat(...a));return c.forEach(p=>{Ya({individualParticipantProfiles:e,participantId:p})}),{participantIdsAtLimit:c.filter(p=>{let m=e[p];if(m)return[s,fo].find(d=>{let l=m.counters?.[d]||0,f=r[d]||0;return l&&f&&l>=f})}),relevantParticipantIds:c}}function Xu({scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:e=!1,errorOnAnachronism:r=!1,checkChronology:n=!0,matchUpDependencies:o,removePriorValues:i,tournamentRecords:s,tournamentRecord:a,matchUpDetails:c,matchUpIds:u,schedule:p}){if(!a)return{error:q};if(!c&&(!u||!Array.isArray(u)))return{error:ps};if(!c&&(!p||typeof p!="object"))return{error:LA};let m,d=[],l=0;if(n&&!o){let I=an({tournamentRecords:s,tournamentRecord:a});o=I.matchUpDependencies,m=I.matchUps}m||(m=ye({tournamentRecord:a})?.matchUps??[]);let f=m.reduce((I,h)=>{let{matchUpId:S,drawId:T,matchUpStatus:y}=h;return(e||y!=="BYE")&&(t||!ae.includes(y))&&(I[T]?I[T].push(S):I[T]=[S]),I},{}),g=c?.map(I=>I.matchUpId);for(let I of Object.keys(f)){let{drawDefinition:h}=jo({tournamentRecord:a,drawId:I});if(!h)continue;let S=f[I].filter(y=>u?.includes(y)??g?.includes(y)),T=nr({inContext:!1,drawDefinition:h}).matchUps;for(let y of S){let E=c?.find(A=>A.matchUpId===y)?.schedule||p,P=Im({schedule:E,matchUpDependencies:o,errorOnAnachronism:r,removePriorValues:i,inContextMatchUps:m,tournamentRecords:s,tournamentRecord:a,checkChronology:n,drawDefinition:h,drawMatchUps:T,matchUpId:y});if(P?.warnings?.length&&d.push(...P.warnings),P?.success&&(l+=1),P.error)return P}}return d.length?{...C,scheduled:l,warnings:d}:{...C,scheduled:l}}function Wc(t){let{scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:r=!1,errorOnAnachronism:n,matchUpContextIds:o,removePriorValues:i,tournamentRecords:s,checkChronology:a,matchUpDetails:c,schedule:u}=t;if(t.matchUpIds&&!o)return Xu(t);let p=et(t,[{[Re]:!0},{[Ks]:{matchUpContextIds:!1,matchUpDetails:!1},[kr]:B,[He]:Be}]);if(p.error)return p;if((!c||o)&&!u)return{error:st,info:"schedule is required"};let m=[],d=0,{matchUpDependencies:l}=an({tournamentRecords:s});for(let f of Object.values(s)){let{tournamentId:g}=f,I=o?.filter(S=>S.tournamentId===g).map(Ue),h=c?.filter(S=>S?.tournamentId===g);if(I?.length||h?.length){let S=Xu({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:r,matchUpDependencies:l,errorOnAnachronism:n,removePriorValues:i,tournamentRecords:s,tournamentRecord:f,checkChronology:a,matchUpIds:I,schedule:u});if(S.warnings?.length&&m.push(...S.warnings),S.scheduled&&(d+=S.scheduled),S.error)return S}}return m.length?{...C,scheduled:d,warnings:m}:{...C,scheduled:d}}function aw({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:p,personRequests:m,periodLength:d,matchUps:l,courts:f,dryRun:g}){let I={},h={},S={},T={},y={},E={},P={},A={},U={},N={};for(let R of o){let b=Ut(R?.scheduleDate),O=R?.venues||[],v={},x={},F=(V,$)=>{V.forEach(X=>{let W=x[X].counters;W[$]?W[$]+=1:W[$]=1,W[fo]?W[fo]+=1:W[fo]=1})};S[b]={},T[b]={},I[b]={},h[b]={},P[b]=[],A[b]=[],U[b]=[],N[b]=[];let w={};l.forEach(V=>{V.schedule?.scheduledDate&&zn(b,Ut(V.schedule.scheduledDate))&&ua({matchUpPotentialParticipantIds:v,matchUpNotBeforeTimes:w,matchUp:V})});let{allDateScheduledByeMatchUpDetails:L,venueScheduledRoundDetails:k,allDateMatchUpIds:G}=oE({matchUpPotentialParticipantIds:v,individualParticipantProfiles:x,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:w,matchUpScheduleTimes:E,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:d,scheduleDate:b,matchUps:l,courts:f,venues:O}),H=10,K=0,Y,j=10;for(;!Y;){for(let{venueId:V}of O){let $=0,X=k[V];for(;X.courtsCount&&X.scheduleTimes?.length&&X.matchUpsToSchedule?.length&&$<=X.courtsCount;){let{scheduleTime:W,attempts:it=0}=X.scheduleTimes.shift(),z=X.matchUpsToSchedule.find(Q=>{let{matchUpId:ut,matchUpType:ot}=Q,{participantIdsAtLimit:Dt,relevantParticipantIds:Rt}=Cl({matchUpPotentialParticipantIds:v,individualParticipantProfiles:x,matchUpDailyLimits:a,matchUp:Q});if(Dt.length)return A[b].includes(ut)||A[b].push(ut),!1;let{scheduledDependent:De}=nE({matchUpScheduleTimes:E,matchUpDependencies:s,scheduleTime:W,matchUpId:ut,details:X});if(De)return!1;let{dependenciesScheduled:qt,remainingDependencies:Se}=Nl({matchUpScheduleTimes:E,matchUpDependencies:s,allDateMatchUpIds:G,matchUp:Q});if(!qt)return T[b][ut]||(T[b][ut]=[]),T[b][ut].push({scheduleTime:W,remainingDependencies:Se}),!1;let{enoughTime:_r}=Rl({individualParticipantProfiles:x,matchUpNotBeforeTimes:w,matchUpDependencies:s,scheduleTime:W,details:X,matchUp:Q});if(!_r)return S[b][ut]||(S[b][ut]=[]),S[b][ut].push({scheduleTime:W}),!1;let dn=X.greatestAverageMinutes,{conflicts:hr}=Ml({potentials:e,averageMatchUpMinutes:dn,requestConflicts:N,personRequests:m,scheduleTime:W,scheduleDate:b,matchUp:Q});if(hr?.length)return y[b]||(y[b]=[]),y[b].push(...hr),!1;F(Rt,ot);let Xe=X.minutesMap?.[ut]?.recoveryMinutes;return Bc({matchUpPotentialParticipantIds:v,individualParticipantProfiles:x,matchUpNotBeforeTimes:w,averageMatchUpMinutes:dn,matchUpDependencies:s,recoveryMinutes:Xe,scheduleTime:W,matchUp:Q}),E[ut]=W,!0});X.matchUpsToSchedule=X.matchUpsToSchedule.filter(({matchUpId:Q})=>Q!==z?.matchUpId),z?$+=1:(h[b][V]||(h[b][V]=[]),h[b][V].push({scheduleTime:W,attempts:it+1}))}X.matchUpsToSchedule?.length&&(h[b][V]=h[b][V]?.filter(W=>{let it=W.attempts<H;return it&&X.scheduleTimes.push(W),!it})),(!X.scheduleTimes?.length||!X.matchUpsToSchedule?.length)&&(X.complete=!0)}K+=1,Y=O.every(({venueId:V})=>k[V].complete)||K===j}for(let{venueId:V}of O){let $=k[V].matchUpMap;Object.keys($).forEach(X=>{let W=u[X];W&&Object.keys($[X]).forEach(it=>{let{drawDefinition:z}=jo({tournamentRecord:W,drawId:it});z&&$[X][it].forEach(({matchUpId:ut})=>{let ot=E[ut];if(ot){let Dt=ot.split(":").map(oo).join(":"),Rt=`${Ut(b)}T${Dt}`;g?P[b].push(ut):(ii({drawDefinition:z,scheduledTime:Rt,matchUpId:ut}).success&&P[b].push(ut),V&&la({tournamentRecord:W,drawDefinition:z,matchUpId:ut,venueId:V}))}})})}),U[b]=k[V].matchUpsToSchedule.map(Ue),I[b][V]=k[V].scheduleTimes.sort((X,W)=>Yt(X.scheduleTime)-Yt(W.scheduleTime))}!g&&L?.length&&Wc({matchUpDetails:L,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let V of R.venues)for(let $ of V.rounds){let W=($.matchUps?.map(({matchUpId:z})=>z)||[]).filter(z=>P[b].includes(z));$.canScheduledMatchUpIds=W;let it=Math.round(W.length/$.matchUpsCount*1e4)/100;(it===1/0||isNaN(it))&&(it=0),$.possibleToSchedulePct=it,$.matchUpsCount===W.length&&($.possibleToSchedule=!0)}}let D=o.map(({scheduleDate:R})=>R),M={timeStamp:Date.now(),overLimitMatchUpIds:A,scheduledMatchUpIds:P,schedulingProfile:p,noTimeMatchUpIds:U,requestConflicts:N,scheduledDates:D};return iE({tournamentRecords:u,autoSchedulingAudit:M}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,scheduleTimesRemaining:I,dateSchedulingProfiles:o,skippedScheduleTimes:h,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:E,overLimitMatchUpIds:A,scheduledMatchUpIds:P,noTimeMatchUpIds:U,requestConflicts:N,scheduledDates:D}}function OM({averageMinutes:t,startTime:e,endTime:r,court:n,date:o}){if(!Array.isArray(n.dateAvailability))return{error:st,stack:"getEarliestCourtTime"};let i=Gc({scheduleDate:o,courts:[n],startTime:!0}),s=Gc({scheduleDate:o,courts:[n],endTime:!0});e=e||i,r=r||s;let a=ja({court:n,date:o}),{timeSlots:c}=_s({courtDate:a}),u=Ge(e),p=Ge(r);return{earliestCourtTime:c?.reduce((d,l)=>{let f=Ge(l.startTime),g=Ge(l.endTime);if(f>p||g<u)return d;let I=u>f?u:f;if(ya(I,g)>=t){let T=zt(I.toISOString());(!d||T<d)&&(d=T)}return d},void 0),courtStartTime:i,courtEndTime:s}}function cw({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,periodLength:p=30,schedulingProfile:m,personRequests:d,matchUps:l=[],courts:f,dryRun:g}){let I={},h={},S={},T={},y={},E={},P={},A={},U={};for(let M of o??[]){let R=Ut(M?.scheduleDate),b=M?.venues||[],O={},v={},x=(z,Q)=>{z.forEach(ut=>{let ot=v[ut].counters;ot[Q]?ot[Q]+=1:ot[Q]=1,ot[fo]?ot[fo]+=1:ot[fo]=1})};I[R]={},h[R]={},E[R]=[],P[R]=[],A[R]=[],U[R]=[];let F={};l?.forEach(z=>{z.schedule?.scheduledDate&&zn(R,Ut(z.schedule.scheduledDate))&&ua({matchUpPotentialParticipantIds:O,matchUpNotBeforeTimes:F,matchUp:z})});let{allDateScheduledByeMatchUpDetails:w,allDateScheduledMatchUpIds:L,venueScheduledRoundDetails:k,allDateMatchUpIds:G}=oE({matchUpPotentialParticipantIds:O,individualParticipantProfiles:v,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:y,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,periodLength:p,scheduleDate:R,matchUps:l,courts:f,venues:b}),H=l?.filter(({matchUpId:z})=>L.includes(z)),{bookings:K}=hm({dateScheduledMatchUps:H,tournamentRecords:u,scheduleDate:R,periodLength:p}),{virtualCourts:Y}=mm({scheduleDate:R,periodLength:p,bookings:K,courts:f}),j=Y?.reduce((z,Q)=>{let{earliestCourtTime:ut,courtEndTime:ot}=OM({date:R,averageMinutes:0,court:Q});return(!z.startTime||Ge(ut)<Ge(z.startTime))&&(z.startTime=ut),(!z.endTime||Ge(ot)>Ge(z.endTime))&&(z.endTime=ot),z},{}),V=j.startTime,$=({courtId:z,booking:Q})=>Y?.find(ut=>ut.courtId===z)?.dateAvailability[0].bookings.push(Q),X=10,W=0,it;for(;!it;){for(let{venueId:z}of b){let Q=k[z],ut=Q.matchUpsToSchedule.length,ot=[],Dt=[],Rt,De=0;for(;!Rt;){for(let qt of Q.matchUpsToSchedule){if(Dt.length===Q.courtsCount||ot.length===Q.courtsCount){Rt=!0;break}let{matchUpId:Se,matchUpType:_r}=qt,{participantIdsAtLimit:dn,relevantParticipantIds:hr}=Cl({matchUpPotentialParticipantIds:O,individualParticipantProfiles:v,matchUpDailyLimits:a,matchUp:qt});if(dn.length){P[R].includes(Se)||P[R].push(Se);continue}let{dependenciesScheduled:Xe,remainingDependencies:Zt}=Nl({matchUpScheduleTimes:y,matchUpDependencies:s,allDateMatchUpIds:G,matchUp:qt});if(!Xe){h[R][Se]||(h[R][Se]=[]),h[R][Se].push({remainingDependencies:Zt});continue}let Pt=[],ce=Y?.reduce((ue,Fe)=>{if(Dt.includes(Fe.courtId))return ue;let{earliestCourtTime:te}=OM({averageMinutes:Q.greatestAverageMinutes,startTime:V,date:R,court:Fe});if(ue.scheduleTime&&Yt(te)>=Yt(ue.scheduleTime))return ue;let{scheduledDependent:Je}=nE({matchUpScheduleTimes:y,matchUpDependencies:s,scheduleTime:te,matchUpId:Se,details:Q});if(Je)return ue;let{enoughTime:$t}=Rl({individualParticipantProfiles:v,matchUpNotBeforeTimes:F,matchUpDependencies:s,scheduleTime:te,details:Q,matchUp:qt});if(!$t)return I[R][Se]||(I[R][Se]=[]),I[R][Se].includes(te)||I[R][Se].push(te),ue;let ir=Q.minutesMap?.[Se]?.averageMinutes||Q.greatestAverageMinutes,{conflicts:fr}=Ml({potentials:e,averageMatchUpMinutes:ir,requestConflicts:U,personRequests:d,scheduleTime:te,scheduleDate:R,matchUp:qt});if(fr?.length)return Pt.push(...fr),!1;x(hr,_r);let pe=Q.minutesMap?.[Se]?.recoveryMinutes;return Bc({matchUpPotentialParticipantIds:O,individualParticipantProfiles:v,matchUpNotBeforeTimes:F,averageMatchUpMinutes:ir,matchUpDependencies:s,recoveryMinutes:pe,scheduleTime:te,matchUp:qt}),(!ue.scheduleTime||Yt(te)<Yt(ue.scheduleTime))&&(ue.averageMatchUpMinutes=ir,ue.recoveryMinutes=pe,ue.scheduleTime=te,ue.courtName=Fe.courtName,ue.courtId=Fe.courtId),ue},{});if(ce.scheduleTime){let{averageMatchUpMinutes:ue,recoveryMinutes:Fe,scheduleTime:te,courtId:Je}=ce;y[Se]=te,T[Se]=Je,ot.push(Se),Dt.push(Je);let $t=te,ir=$r($t,ue);$({courtId:Je,booking:{averageMatchUpMinutes:ue,recoveryMinutes:Fe,periodLength:p,matchUpId:Se,startTime:$t,courtId:Je,endTime:ir,venueId:z}}),Q.matchUpsToSchedule=Q.matchUpsToSchedule.filter(pe=>pe.matchUpId!==Se)}else Pt?.length&&(S[R]||(S[R]=[]),S[R].push(...Pt))}(Dt.length===Q.courtsCount||ot.length===Q.courtsCount||!Q.matchUpsToSchedule.length)&&(Rt=!0),Q.matchUpsToSchedule.length&&ot<Q.courtsCount&&(Ge(V)<Ge(j.endTime)?V=$r(V,p):(Rt=!0,Q.complete=!0)),De+=1,!Rt&&De>=ut&&(Rt=!0)}Q.matchUpsToSchedule?.length||(Q.complete=!0)}W+=1,it=b.every(({venueId:z})=>k[z].complete)||W===X}for(let{venueId:z}of b){let Q=k[z].matchUpMap;Object.keys(Q).forEach(ut=>{let ot=u[ut];ot&&Object.keys(Q[ut]).forEach(Dt=>{let{drawDefinition:Rt}=jo({tournamentRecord:ot,drawId:Dt});Rt&&Q[ut][Dt].forEach(({matchUpId:qt})=>{let Se=y[qt],_r=T[qt];if(Se){let dn=Se.split(":").map(oo).join(":"),hr=`${Ut(R)}T${dn}`;g||(ii({drawDefinition:Rt,scheduledTime:hr,matchUpId:qt}),as({courtDayDate:R,tournamentRecords:u,tournamentRecord:ot,drawDefinition:Rt,matchUpId:qt,courtId:_r})),E[R].push(qt)}})})}),A[R]=k[z].matchUpsToSchedule.map(Ue)}!g&&w?.length&&Wc({matchUpDetails:w,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let z of M.venues)for(let Q of z.rounds){let ot=(Q.matchUps??[]).map(({matchUpId:Rt})=>Rt)?.filter(Rt=>E[R].includes(Rt));Q.canScheduledMatchUpIds=ot;let Dt=Math.round((ot?.length||0)/Q.matchUpsCount*1e4)/100;(Dt===1/0||isNaN(Dt))&&(Dt=void 0),Q.possibleToSchedulePct=Dt,Q.matchUpsCount===ot?.length&&(Q.possibleToSchedule=!0)}}let N=(o??[]).map(({scheduleDate:M})=>M),D={timeStamp:Date.now(),overLimitMatchUpIds:P,scheduledMatchUpIds:E,schedulingProfile:m,noTimeMatchUpIds:A,requestConflicts:U,scheduledDates:N};return iE({tournamentRecords:u,autoSchedulingAudit:D}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:I,dependencyDeferredMatchUpIds:h,matchUpScheduleTimes:y,overLimitMatchUpIds:P,scheduledMatchUpIds:E,noTimeMatchUpIds:A,requestConflicts:U,scheduledDates:N}}function Sm(t){let{scheduleAttributes:e=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:r=ae,scheduledDates:n,venueIds:o}=t,i=Rr(t),s=ht(i)?Object.values(i).map(({tournamentId:c})=>c).filter(Boolean):[];if(!s?.length)return{error:xt};let a=0;for(let c of s){let u=i[c],p=D0({ignoreMatchUpStatuses:r,scheduleAttributes:e,tournamentRecord:u,scheduledDates:n,venueIds:o});if(p.error)return p;a+=p.clearedScheduleCount??0}return{...C,clearedScheduleCount:a}}function D0({scheduleAttributes:t=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:e=ae,tournamentRecord:r,scheduledDates:n,venueIds:o=[]}){if(typeof r!="object")return{error:q};if(!Array.isArray(e)||!Array.isArray(o))return{error:B};o.length&&t.push("venueId");let i=ye({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[],s={};i.forEach(({matchUpStatus:u,schedule:p,drawId:m,matchUpId:d})=>{(!u||!e.includes(u))&&Ha({schedule:p,scheduleAttributes:t})&&(!o?.length||o.includes(p.venueId))&&(s[m]||(s[m]=[]),s[m].push(d))});let a=r.tournamentId,c=0;for(let u in s){let{event:p,drawDefinition:m}=ze({tournamentRecord:r,drawId:u}),d=nr({drawDefinition:m,matchUpFilters:{matchUpIds:s[u]}}).matchUps??[];for(let l of d){let f=!1;l.timeItems=(l.timeItems??[]).filter(g=>{let I=g?.itemType&&![lo,Jo,Ji,bp,Zi,ts].includes(g?.itemType);return I||(f=!0),I}),f&&(gt({context:"clear schedules",eventId:p?.eventId,drawDefinition:m,tournamentId:a,matchUp:l}),c+=1)}}return{...C,clearedScheduleCount:c}}function Tm(t){let{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,periodLength:s,useGarman:a,dryRun:c,pro:u}=t,p=et(t,[{[Re]:!0},{[tr]:N=>!N||Array.isArray(N)&&N.every(Mr),[wh]:!1,[He]:Be}]);if(p.error)return p;let m=oi({tournamentRecords:i});if(m.error)return m;if(!m.schedulingProfile.length)return{...C};let{modifications:d,issues:l=[],schedulingProfile:f=[]}=m,g=Object.assign({},...Object.values(i).map(N=>fs({tournamentRecord:N}).containedStructures)),I=o.map(N=>{if(Mr(N))return Ut(N)}).filter(Boolean),h=f.map(N=>N.scheduleDate).map(N=>Mr(N)&&Ut(N)).filter(N=>N&&(!o.length||I.includes(N)));if(!h.length)return{error:lA};if(n&&!c){let N=Array.isArray(n)?n:[];Sm({tournamentRecords:i,scheduledDates:N})}let S=Ro({ignoreDisabled:!1,tournamentRecords:i}).courts,{matchUps:T}=Mn({matchUpFilters:{matchUpTypes:[Lt,vt]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:i}),{matchUpDependencies:y}=an({includeParticipantDependencies:!0,tournamentRecords:i,matchUps:T}),{matchUpDailyLimits:E}=Sl({tournamentRecords:i}),{personRequests:P}=ki({requestType:Hc,tournamentRecords:i}),A=f.filter(N=>{let D=Ut(N?.scheduleDate);return h.includes(D)}).sort((N,D)=>new Date(N.scheduleDate).getTime()-new Date(D.scheduleDate).getTime()),U={schedulingProfileModifications:d,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:l,dateSchedulingProfiles:A,containedStructureIds:g,matchUpDependencies:y,matchUpDailyLimits:E,clearScheduleDates:n,tournamentRecords:i,schedulingProfile:f,personRequests:P,periodLength:s,useGarman:a,matchUps:T,dryRun:c,courts:S};return u?cw(U):aw(U)}function ym(t){let{tournamentRecord:e,tournamentRecords:r,activeTournamentId:n,...o}=t||{};return o.tournamentId||(o.tournamentId=Nt()),o.startDate&&!sc(o.startDate)&&!Vm.test(o.startDate)?{error:Ye}:o.endDate&&!sc(o.endDate)&&!Vm.test(o.endDate)?{error:Ye}:(o.extensions&&(o.extensions=o.extensions.filter(Bn)),{...o})}function yI({addParticipants:t=!0,participantAttribute:e,tournamentRecord:r,personAttribute:n,teamNames:o,accessor:i,uuids:s}){if(!r)return{error:q};let a={},c=(r.participants??[]).filter(({participantType:f,participantRole:g})=>f===Et&&g===xe),u=0;for(let f of c){let I=i&&ys({element:f,accessor:i})?.value||n&&f.person?.[n]||e&&f[e];if(I){if(!Object.keys(a).includes(I)){a[I]={participantName:o?.[u]??I,participantId:s?.pop()??Nt(),individualParticipantIds:[],participantRole:xe,participantType:wt};let h={value:n??e,name:Hh};At({element:a[I],extension:h}),u+=1}a[I].individualParticipantIds.push(f.participantId)}}let p=Object.keys(a),m=(r.participants??[]).map(f=>{if(f.participantType!==wt||f.participantRole!==xe)return;let{extension:g}=mt({name:Hh,element:f}),I=g?.value;if(p.includes(I))return f.participantId}).filter(Boolean),d=0,l=[];return Object.keys(a).forEach(f=>{let g=a[f],{participantId:I}=g;m.includes(I)||(r.participants||(r.participants=[]),t&&r.participants.push(g),l.push(g),d++)}),t&&d?(lt({payload:{tournamentId:r.tournamentId,participants:l},topic:ci}),{...C,participantsAdded:d}):l.length?{...C,newParticipants:l}:{error:OC}}var uw=[{AA:"Annexia"},{BA:"Bacteria"},{BO:"Borduria"},{BM:"Bensalem"},{BS:"Basenji"},{BI:"Balnibarbi"},{BV:"Bartovia"},{BZ:"Berzerkistan"},{CA:"Caldonia"},{CC:"Concordia"},{CH:"Chula"},{DA:"Deltora"},{DW:"Discworld"},{EA:"Eastasia"},{EP:"Ecotopia"},{ER:"Erewhon"},{FA:"Freedonia"},{FN:"Florin"},{FG:"Fogg"},{FK:"Fourecks"},{GA:"Genovia"},{GL:"Gilead"},{GD:"Gilead"},{GL:"Gondal"},{GO:"Gondor"},{GR:"Gruzinia"},{GT:"Goritania"},{GU:"Guilder"},{HA:"Heldscalla"},{HO:"Hidalgo"},{IL:"Illyria"},{KA:"Kinakuta"},{KG:"Kangan"},{KN:"Kreplachistan"},{KS:"Kallipolis"},{LH:"Lugash"},{LI:"Listenbourg"},{LT:"Lilliput"},{LU:"Luggnagg"},{LV:"Lichtenslava"},{MR:"Moher"},{NA:"Narnia"},{NV:"Novaria"},{OA:"Oceania"},{OS:"Orsinia"},{OV:"Octavia"},{PA:"Palombia"},{PG:"Penguina"},{QA:"Qasha"},{PM:"Panem"},{SA:"Solymbria"},{SD:"Syldavia"},{SG:"San Glucose"},{SL:"San Lorenzo"},{SR:"Sontar"},{SY:"Sylvania"},{TF:"Tralfamadore"},{TH:"Themyscira"},{UA:"Utopia"},{VA:"Vespugia"},{WA:"Wakanda"},{WX:"Wessex"},{ZA:"Zamunda"},{ZK:"Zubrowka"}];var pw=["Amber","Ansul","Atlantis","Braavos","Busytown","Castle Rock","Centralia","Coober Pedy","Chefchaouen","Chronopolis","Damanhur","Diaspar","Dictionopolis","Diomira","El Dorado","Elista","Ephesus","Gotham","Hadleyburg","Hallstatt","Hierusalem","Ilium","Inverness","Kowloon","Laputa","Longyearbyen","Lys","Matmata","Maycomb","Metropolis","Miyake-jima","Monowi","Nagoro","Navarre","New New York","Nimbin","Pemberley","Pseudopolis","Rivendell","Roswell","Shangri-La","Springfield","Supilinn","Thneedville","Trantor","Wobegon","Yonwood","Xanadu","Xylar","Zion"];function sE({count:t=1,participantsCount:e=32}={}){let r=Tr(pw),n=r.slice(0,t);return{cities:tt(0,e).map(i=>i<Math.min(t,r.length)?n[i]:Un(n))}}function aE({count:t=1,participantsCount:e=32}={}){let r=Tr(uw),n=r.slice(0,t).map(i=>Object.keys(i)).flat();return{states:tt(0,e).map(i=>i<Math.min(t,r.length)?n[i]:Un(n))}}function cE({count:t=1,participantsCount:e=32}={}){let r=tt(0,t).map(()=>tt(0,5).map(()=>Io(0,9)).join(""));return{postalCodes:tt(0,e).map(o=>o<t?r[o]:Un(r))}}function Em({idPrefix:t,participantType:e,index:r,uuids:n}){let o=kt(e)?e[0]:"X";return t?`${t}-${o}-${r}`:n?.pop()||Nt()}function uE(t){let{cities:e,states:r,postalCodes:n,nationalityCode:o,participantIndex:i}=t;return{postalCode:n?.[i],state:r?.[i],city:e?.[i],countryCode:o}}var mw={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brewer","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carlin","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Ellul","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","McLuhan","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood","Zecic"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","Jacques","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Marhsall","Masanobu","Maurits","Michael","Miro","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function pE(t){let{count:e=100,sex:r}=t||{};if(!e||r&&!Dn(r))return{personData:[],error:B};let n=Math.ceil(e*1.3),{lastNames:o,firstFemale:i,firstMale:s}=mw,a=ui.map(({iso:I})=>I).filter(Boolean),c=Math.ceil(n/o.length),u=Math.ceil(n/i.length),p=Math.ceil(n/s.length),m=tt(0,c).flatMap(()=>{let I=J(o,!1,!0);return tt(0,o.length).map(()=>tn(I))}),d=tt(0,u).flatMap(()=>{let I=J(i,!1,!0);return tt(0,i.length).map(()=>tn(I))}),l=tt(0,p).flatMap(()=>{let I=J(s,!1,!0);return tt(0,s.length).map(()=>tn(I))}),f={};for(let I=0;I<n;I++){let h=m.pop(),S=r||Un([Le,lr]),T=S===Le?l.pop():d.pop(),y=Un(a);f[`${T}${h}`]={nationalityCode:y,sex:S,firstName:T,lastName:h}}return{personData:Object.values(f).slice(0,e)}}function mE(t){let e=t?.count||1,{personExtensions:r,consideredDate:n,isMock:o=!0,gendersCount:i,personData:s,category:a,sex:c}=t||{};if(isNaN(e))return{error:B};let u=i?.[Le]||Hs(c)&&e||0,p=i?.[lr]||$i(c)&&e||0;e=Math.max(e,u+p);let m=e-(u+p),d=u&&pE({count:u,sex:Le}).personData||[],l=p&&pE({count:p,sex:lr}).personData||[],f=[...d,...l,...m&&pE({count:m}).personData||[]],g=f.filter(U=>!c||u&&p||U.sex===c),I=[];if(Array.isArray(s)){let U=s.filter(N=>typeof N.firstName!="string"||typeof N.lastName!="string"||N.sex&&![Le,lr].includes(N.sex)||N.nationalityCode&&(typeof N.nationalityCode!="string"||N.nationalityCode.length>3||!ui.find(({iso:D,ioc:M})=>[D,M].includes(N.nationalityCode)))?!1:(N.nationalityCode&&I.push(N.nationalityCode),!0));if(U.length)g=U;else return{error:B}}let h=s?g:Tr(g);if(h.length<e){let{maleFirstNames:U,maleLastNames:N,femaleFirstNames:D,femaleLastNames:M,nationalityCodes:R}=f.reduce((b,O)=>{let{firstName:v,lastName:x,nationalityCode:F}=O;return O.sex===Le?(b.maleFirstNames.includes(v)||b.maleFirstNames.push(v),b.maleLastNames.includes(x)||b.maleLastNames.push(x)):(b.femaleFirstNames.includes(v)||b.femaleFirstNames.push(v),b.femaleLastNames.includes(x)||b.femaleLastNames.push(x)),b.nationalityCodes.includes(F)||b.nationalityCodes.push(F),b},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});tt(0,e-h.length).forEach(()=>{let b=c||Un([Le,lr]),O=Un(R),v=b===Le?Un(U):Un(D),x=b===Le?Un(N):Un(M),F={firstName:v,lastName:x,sex:b,nationalityCode:O};h.push(F)})}let{ageMinDate:S,ageMaxDate:T}=Ys({consideredDate:n,category:a}),y=dt(S?.slice(0,4)||0)||dt(T?.slice(0,4)||0)-3,E=dt(T?.slice(0,4)||0)||dt(S?.slice(0,4)||0)+3,P=(S||T)&&[y,E],A=h.slice(0,e).map((U,N)=>{let[D,M]=P||[],R=P&&tn(tt(D,M)),b=tn(tt(0,365)),O=R&&ZC(R,b);return Object.assign(nt({extensions:r||[{name:"regionCode",value:N+1}],birthDate:O,isMock:o}),U)});return{persons:A.length&&A||h[0],nationalityCodes:I}}var dw=["Ace Academy","Avengers","Ball Bouncers","Baseliners","Captivators","Civil Disobedients","Continentals","Court Royal","Court Sharks","Diamond Dogs","Danger Zone","Doubles Dominators","Double Faults","Tricksters","Eliminators","Court Crusaders","Fuzz Busters","Game Changers","Goal Gurus","Good Volley","Green Machine","Hawk Eyes","Inside Outers","Killer Instinct","Line Toers","Masters of Mayhem","Matter Catchers","Cheap Shot","Mean Machines","Mindspace Invaders","Net Centric","Net Positive","Smash Mullet","Over Your Head","Spin Meisters","Aggressors","Racket Machine","Slice Happy","Refs Nightmare","Sandeaters","Sun Seekers","Slicer Dicers","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Unreturnables","Upside Downers","Vertically Challenged","Visual Spectacle"];function Am({nameRoot:t="TEAM",count:e=1}={}){let n=Tr(dw).slice(0,e);return n.length<e&&tt(0,e-n.length).forEach(o=>n.push(`${t} ${o+1}`)),{names:n}}function fa(t){let{scaledParticipantsCount:e,rankingRange:r}=t,{ratingsParameters:n=je,valuesInstanceLimit:o,ratingsValues:i=[],consideredDate:s,categories:a,category:c,nationalityCodesCount:u,nationalityCodeType:p,nationalityCodes:m,participantsCount:d=32,participantType:l,teamSize:f=8,personIds:g,idPrefix:I,uuids:h,personExtensions:S,addressProps:T,gendersCount:y,matchUpType:E,personData:P,sex:A,inContext:U,withISO2:N,withIOC:D,scaleAllParticipants:M}=t,R=l===ft||E===Gi,b=l===wt||E===wt;r&&(!Array.isArray(r)||!r.every(Zt=>Jt(Zt))||r.length!==2)&&(r=void 0),e=M?d:e;let O=1e3,v=e&&e>O?e:O;r=r||[1,v],r[1]+=1;let x=d*(R&&2||b&&(f??8)||1),F=mE({count:x,personExtensions:S,consideredDate:s,gendersCount:y,personData:P,category:c,sex:A});if(F.error)return F;let{nationalityCodes:w,persons:L}=F,k={},G={},H={},K={},Y=Zt=>{Object.assign(k,Zt.doublesRankings),Object.assign(G,Zt.singlesRankings),Object.assign(K,Zt.doublesRatings),Object.assign(H,Zt.singlesRatings)};if(ht(c)){let Zt=lw({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:c});Y(Zt)}Array.isArray(a)&&a.forEach(Zt=>{let Pt=lw({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:Zt});Y(Pt)});let j=ui.filter(Zt=>p==="IOC"&&Zt.ioc||Zt.iso);function V(Zt){let Pt=Math.ceil(x/Zt);return o&&Pt>o?Math.ceil(x/o):Zt}let{postalCodesProfile:$,postalCodesCount:X,statesProfile:W,citiesProfile:it,citiesCount:z,statesCount:Q}=T||{},ut=Zt=>Object.keys(Zt).map(Pt=>tt(0,W[Pt]).map(()=>Pt)).flat(),ot=it&&ut(it)||T?.cities||sE({count:z||x,participantsCount:x}).cities,Dt=W&&ut(W)||T?.states||aE({count:Q||x,participantsCount:x}).states,Rt=$&&ut($)||T?.postalCodes||cE({count:X||x,participantsCount:x}).postalCodes,De={cities:ot,states:Dt,postalCodes:Rt},qt=V(u),Se=qt?Tr(j).slice(0,u):m&&j.filter(Zt=>m.includes(Zt.iso))||j,_r=Tr(tt(0,Math.ceil(x/(qt||1))).map(()=>Se).flat(1/0)),dn=Am({count:d}).names;return{participants:tt(0,d).map(Zt=>{let Pt=R&&2||b&&(f??8)||1,ce=tt(0,Pt).map($t=>{let ir=Zt*Pt+$t;return Xe(ir)}),ue=ce.map($t=>$t.participantId),Fe=ce.map($t=>$t.person.standardFamilyName).join("/"),te=R?ft:wt,Je={participantId:Em({participantType:te,index:Zt,idPrefix:I,uuids:h}),participantName:R?Fe:dn[Zt],participantRole:xe,individualParticipantIds:ue,participantType:te};return U&&(Je.individualParticipants=ce),R||b?[Je,...ce]:ce}).flat(),...C};function Xe(Zt){let Pt=L[Zt],{nationalityCode:ce,participantExtensions:ue,participantTimeItems:Fe,extensions:te,firstName:Je,birthDate:$t,lastName:ir,personId:fr,sex:pe}=Pt||{},me=Je||"GivenName",Sr=ir||"FamilyName",jr=`${me} ${Sr}`,Kt=_r[Zt],Te=w?.length&&ce||Kt&&(p==="IOC"?Kt.ioc||Kt.iso:Kt.iso||Kt.ioc)||ce;_r?.length&&!Te&&!ce&&console.log("%c Invalid Nationality Code",{participantIndex:Zt,country:Kt});let gr=uE({...De,participantIndex:Zt,nationalityCode:Te}),Ee=nt({participantId:Em({participantType:Et,index:Zt,idPrefix:I,uuids:h}),extensions:ue,timeItems:Fe,participantRole:xe,participantType:Et,participantName:jr,person:{personId:fr||g?.length&&g[Zt]||Nt(),birthDate:Mr($t)?$t:void 0,addresses:[gr],standardFamilyName:Sr,standardGivenName:me,nationalityCode:Te,extensions:te,sex:pe}});if(D&&Te){let ee=ui.find(({iso:Ur})=>Ur===Te);ee?.ioc&&(Ee.person.iocNationalityCode=ee.ioc),ee?.label&&(Ee.person.countryName=ee.label)}if(N&&Te){let ee=ui.find(({iso:Ur})=>Ur===Te);ee?.iso2&&(Ee.person.iso2NationalityCode=ee.iso2),ee?.label&&(Ee.person.countryName=ee.label)}let Rn=ee=>{let Ur=ee.categoryName||ee.ratingType||ee.ageCategoryCode,Cn=G[Ur]?.[Zt],An=k[Ur]?.[Zt];dE({scaleValue:Cn,eventType:qs,scaleType:Ai,participant:Ee,category:ee}),dE({scaleValue:An,eventType:Ko,scaleType:Ai,participant:Ee,category:ee});let hi=H[Ur]?.[Zt],ga=K[Ur]?.[Zt];dE({scaleValue:hi,eventType:qs,scaleType:Ui,participant:Ee,category:ee}),dE({scaleValue:ga,eventType:Ko,scaleType:Ui,participant:Ee,category:ee})};return Array.isArray(a)?a.forEach(ee=>Rn(ee)):c&&Rn(c),Ee}}function dE({scaleValue:t,participant:e,eventType:r,scaleType:n,category:o}){let i=o.categoryName||o.ratingType||o.ageCategoryCode,s=[Pi,n,r,i].join("."),a={itemValue:t,itemType:s};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(a))}function lw(t){let{category:e,scaledParticipantsCount:r,ratingsParameters:n,participantType:o,ratingsValues:i=[]}=t,s=e.rankingRange||t.rankingRange||[1,1e3],a={},c={},u={},p={},{categoryName:m,ageCategoryCode:d,ratingType:l}=e,f=e.categoryName||e.ratingType||e.ageCategoryCode;if((m||d)&&!l){let[g,I]=s||[];if(c[f]=Tr(tt(g,I)).slice(0,r||Io(20,30)),[ft,wt].includes(o)){let[h,S]=s||[];a[f]=Tr(tt(h,S)).slice(0,r||Io(20,30))}}if(l&&n[l]){let{ratingMax:g,ratingMin:I,ratingAttributes:h}=e,S={...n[l],...h||{}},{attributes:T={},decimalsCount:y,accessors:E,range:P,step:A}=S,U=v=>{let x={},F=Object.keys(v||{});for(let w of F){let L=v[w];if(typeof L=="object"&&L.generator){let{range:k}=L,[G,H]=k.slice().sort();x[w]=Io(G,H)}else x[w]=L}return x},D=P[0]>P[1]?2:.7,[M,R]=P.slice().sort(),O=tt(0,2e3).map(()=>wE(M,R,D,A,y)).filter(x=>(!g||x<=g)&&(!I||x>=I)).slice(0,r||Io(20,30)).map(x=>E?Object.assign({},...E.map(F=>({[F]:x})),U(T)):x);u[f]=[...i,...O],[ft,wt].includes(o)&&(p[f]=[...i,...O])}return{singlesRankings:c,doublesRankings:a,singlesRatings:u,doublesRatings:p}}function bl(t){let{alternatesCount:e=0,tieFormatName:r,drawSize:n}=t,o=0,i=0,s=0,a=0,c={},u={[Le]:0,[lr]:0,[qi]:0,[$o]:0,ANY:0};(ht(t.tieFormat)?t.tieFormat:io({namedFormat:r}))?.collectionDefinitions?.filter(Boolean).forEach(f=>{let{category:g,collectionId:I,matchUpType:h,matchUpCount:S,gender:T}=f;if(Dn(T)){let y=yr(T),E=S*(h===vt?2:1);y&&u[y]<E&&(u[y]=E)}else en(T)&&(u[Le]<S&&(u[Le]=S),u[lr]<S&&(u[lr]=S));if(g){let y=JSON.stringify(g);c[y]=g}if(I||(f.collectionId=Nt()),de(vt)(h)){let y=S;a+=S,o=Math.max(o,y)}if(de(Lt)(h)){let y=S;s+=S,i=Math.max(i,y)}});let m=Object.keys(c).length?Math.max(s,a*2):Math.max(i,o*2),d=o*(n+e),l=i*(n+e);return{maxDoublesDraw:d,maxSinglesDraw:l,teamSize:m,genders:u}}function fw({participantsProfile:t,eventProfiles:e,drawProfiles:r}){let{participantsCount:n,participantType:o=Et}=t||{},i=n||0,s={[lr]:0,[qi]:0,[$o]:0,[Le]:0,ANY:0},a=0,c=0,u=0,p=0,m=0,d=({alternatesCount:f=0,uniqueParticipants:g,tieFormatName:I,drawSize:h=0,eventType:S,tieFormat:T,category:y,gender:E,stage:P})=>{let A=S===Kr,U=S===_e,N=!!(g||P===ct||y||E);if(U){p=Math.max(p,h+f),T=typeof T=="object"?T:io({namedFormat:I});let{teamSize:D,maxDoublesDraw:M,maxSinglesDraw:R,genders:b}=bl({alternatesCount:f,tieFormatName:I,tieFormat:T,drawSize:h});u=Math.max(u,D),c=Math.max(c,R),N||(a=Math.max(a,M)),Object.keys(b).forEach(O=>s[O]+=b[O])}else if(A)if(N){let D=(h+f)*2;m+=D,E&&(s[E]+=D)}else h+f&&h+f>a&&(a=h+f);else if(N){let D=h+f;E&&(s[E]+=D),m+=D}else h&&h>c&&(c=h+f)};if(e?.forEach(f=>{let{tieFormatName:g,tieFormat:I,drawProfiles:h,eventType:S,category:T,gender:y}=f;if(h)for(let E of h){let{tieFormatName:P,tieFormat:A}=E;d({...E,tieFormatName:P||g,tieFormat:A||I,eventType:S,category:T,gender:y})}}),Array.isArray(r))for(let f of r)d(f);let l=Math.max(p*u,a*2,c);return a&&(o=ft),(n||i)<l&&(n=l),n&&a&&[ft,_e].includes(o)&&(c&&Math.floor(c/2)>a?n=Math.floor(c/2):(!c||a*2>=c)&&(n=Math.ceil(n/2))),n===void 0&&(n=!e?.length&&!r?.length?32:0),n<i&&(n=i),{uniqueParticipantsCount:m,participantsCount:n,largestTeamDraw:p,largestTeamSize:u,participantType:o,gendersCount:s}}function lE({participantsProfile:t,tournamentRecord:e,eventProfiles:r,drawProfiles:n,startDate:o,uuids:i}){if(t?.participantsCount===0)return{addedCount:0,...C};let{participantsCount:s,participantType:a,largestTeamDraw:c,largestTeamSize:u,gendersCount:p}=fw({participantsProfile:t,eventProfiles:r,drawProfiles:n}),m=t?.teamKey,d=fa({consideredDate:o,...t,participantsCount:s,participantType:a,gendersCount:p,uuids:i}).participants,l=0,f=En({tournamentRecord:e,participants:d});if(f.error)return f;if(l+=f.addedCount,m){let S=yI({tournamentRecord:e,...m});if(S.error)return S}let g=d.filter(({participantType:S})=>S===Et).map(St),I=t?.idPrefix?`${wt}-${t.idPrefix}`:void 0,h=tt(0,c).map(S=>{let T=g.slice(S*u,(S+1)*u),y=Em({index:S,participantType:a,idPrefix:I,uuids:i});return{participantName:`Team ${S+1}`,participantRole:xe,individualParticipantIds:T,participantType:wt,participantId:y}});return f=En({participants:h,tournamentRecord:e}),f.error?f:(l+=f.addedCount,{addedCount:l,...C})}function fE({drawProfiles:t,category:e,gender:r}){let n={},o=t?.reduce((s,a)=>{let{qualifyingPositions:c=0,participantsCount:u=0,uniqueParticipants:p,stage:m=rt,drawSize:d=0}=a||{};Object.keys(s).includes(m)||(s[m]=0);let l=(u||d)-c;return p||r||e||m===ct?(Object.keys(n).includes(m)||(n[m]=0),n[m]+=l):s[m]=Math.max(s[m],l),s},{}),i=Object.keys(n);return i.forEach(s=>o[s]+=n[s]),{stageParticipantsCount:o,uniqueParticipantsCount:n,uniqueParticipantStages:i}}function gE({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:r,targetParticipants:n}){let o=e[rt]||0,i=e[ct]||0;return{stageParticipants:{QUALIFYING:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(0,i),MAIN:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(i,i+o)}}}var b0={[Bt]:2,[oe]:1,[be]:1,[Me]:1,[Gt]:4};function EI(t){let{defaultWithScorePercent:e=2,winningSide:r}=t,{matchUpStatusProfile:n=b0,matchUpFormat:o=bn,pointsPerMinute:i=1,sideWeight:s=4}=t;if(!Nr({matchUpFormat:o}))return{error:Jl};if(typeof n!="object")return{error:B};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(s))return{error:B};let a=Object.keys(n).filter(b=>Object.keys(Qh).includes(b)&&b!==ge);if(Object.keys(a).reduce((b,O)=>b+n[O],0)>100)return{error:B,matchUpStatusProfile:n};let u=a.reduce((b,O)=>(b.pointer=b.pointer+n[O],b.valueMap.push([b.pointer,O]),b),{pointer:0,valueMap:[]}),p=Io(1,100),m=(u.valueMap.find(b=>p<=b[0])??[100,ge])[1],d={sets:[],scoreStringSide1:"",side2ScoreString:""};if(pr(m)){r=r||Io(1,2);let b={score:d,matchUpStatus:m,winningSide:r};if(!(m===Gt&&Io(1,100)>100-e))return{outcome:b}}else if([oe,be].includes(m))return{outcome:{score:d,matchUpStatus:m}};let l=Ne(o),{bestOf:f=1,exactly:g,setFormat:I,finalSetFormat:h}=l??{},S=[],T=Io(0,1),y=r?[r-1]:[...tt(0,s).map(()=>T),1-T],P=[Me,Gt,mn,ls].includes(m)&&(tn(tt(1,g||f))||1),A,U=tt(1,(g??f)+1);for(let b of U){let O=b===(g??f),{set:v,incomplete:x,winningSideNumber:F}=O0({setFormat:O&&h||I,incomplete:P===b,pointsPerMinute:i,matchUpStatus:m,weightedRange:y,setNumber:b});if(S.push(v),x){A=F;break}if(cm({matchUp:{score:{sets:S},matchUpFormat:o}}).calculatedWinningSide)break}let N=cm({matchUp:{score:{sets:S},matchUpFormat:o,winningSide:r}}),D=A?r||A:N.calculatedWinningSide,{score:M}=rE({winningSide:D,score:{sets:S},matchUpStatus:m});return{outcome:{winningSide:D,matchUpStatus:m,score:M}}}function O0({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:r,incomplete:n,setFormat:o,setNumber:i}){let s={setNumber:i},{setTo:a,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:p,timed:m,minutes:d}=o,l=Io(0,t.length-1),f=t[l],g;if(m){let I=d*e,h=Math.round(I*.2),S=I+tn([1,-1])*h,T=SC(S,2),y=[T,S-T];f&&y.reverse(),g=t[l]+1;let E=y[0]>y[1]&&1||y[1]>y[0]&&2||0;if(n){let[U,N]=y;return Object.assign(s,{side1Score:U,side2Score:N}),ae.includes(r)?{set:s,incomplete:n,winningSideNumber:g}:{set:s,incomplete:n}}E||(y[Io(0,1)]+=1),E=y[0]>y[1]?1:2,E!==g&&y.reverse();let[P,A]=y;return Object.assign(s,{side1Score:P,side2Score:A,winningSide:g}),{set:s}}else{if(n)return s.side1Score=Io(0,u),s.side2Score=Io(0,u),ae.includes(r)&&(g=t[l]+1),{set:s,incomplete:n,winningSideNumber:g};{let I=tt(1,a+1).map(A=>tt(0,a+2-A).map(()=>A)).flat(),h=I[Io(0,I.length-1)],S=a&&Xg({isSide1:!0,tiebreakAt:u,lowValue:h,setTo:a}),T=!S,y=t.length===1&&t[l]+1;if(!T){y?(S[0]>S[1]?1:2)!==y&&S.reverse():f&&S.reverse();let[A,U]=S;Object.assign(s,{side1Score:A,side2Score:U})}let E=qu({matchUpScoringFormat:{setFormat:o},setObject:s}),P;if(E.hasTiebreakCondition||T){let{NoAD:A,tiebreakTo:U}=c||p||{},N=tt(1,U+1).map(R=>tt(0,U+2-R).map(()=>R)).flat(),D=N[Io(0,N.length-1)],M=rm({isSide1:!0,tiebreakNoAd:A,tiebreakTo:U,lowValue:D});if(M)if(T){let R=M[0]>M[1]?1:2;y?R!==y&&M.reverse():f&&M.reverse(),[s.side1TiebreakScore,s.side2TiebreakScore]=M,P=M[0]>M[1]&&1||M[1]>M[0]&&2||void 0}else E.leadingSide===2?[s.side1TiebreakScore,s.side2TiebreakScore]=M:[s.side2TiebreakScore,s.side1TiebreakScore]=M}s.winningSide=E.winningSide||E.leadingSide||y||P}}return{set:s}}function Ol(t){let{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:o,completionGoal:i,drawDefinition:s,event:a}=t;if(!s)return{error:Z};let c=t.matchUpFormat||s.matchUpFormat||a?.matchUpFormat,u=s.structures.slice().sort(Ni),p=0,{matchUps:m,matchUpsMap:d}=ie({matchUpFilters:{matchUpTypes:[Wt],roundNumbers:[1]},contextFilters:{stages:[rt,ct]},inContext:!0,drawDefinition:s});if(m?.length){let h=a?.category?.ageCategoryCode||a?.category?.categoryName;if(h){let T=By({singlesOnly:!0,tournamentRecord:o,drawDefinition:s,scaleAccessor:{scaleName:h,sortOrder:"ASC",scaleType:Ai},event:a});if(T.error)return T;let{lineUps:y,participantsToAdd:E}=T;En({tournamentRecord:o,participants:E}),At({element:s,extension:{name:wo,value:y}})}else{let S=m[0]?.structureId,{positionAssignments:T}=Ct({drawDefinition:s,structureId:S});if(T?.length){let{participants:y}=Ft({participantFilters:{participantTypes:[Wt]},tournamentRecord:o}),E=P=>{let A=P.tieMatchUps.filter(de(Lt)),U=P.tieMatchUps.filter(de(vt));A.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,O=y?.find(v=>{let{participantId:x}=v;return T.find(w=>w.participantId===x)?.drawPosition===b});if(O){let v=O.individualParticipantIds?.[D];v&&Pl({teamParticipantId:O.participantId,participantId:v,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})}})}),U.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,O=y?.find(v=>{let{participantId:x}=v;return T.find(w=>w.participantId===x)?.drawPosition===b});O&&O.individualParticipantIds?.slice(D*2,D*2+2)?.forEach(x=>{Pl({teamParticipantId:O.participantId,participantId:x,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})})})})};m.forEach(E)}}}let l=typeof r=="string"&&r,f=l&&ge,g=u.length===2&&u[0].finishingPosition===Ei&&jt(u.map(({stage:h})=>h),[rt,fe]).length===2,I=u.map(({structureId:h})=>h);for(let h of I){if(p>=i)break;let S=s.structures.find(E=>E.structureId===h),T=yt({contextFilters:{matchUpTypes:[vt,Lt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}).matchUps;T.length;let y=T.filter(({winningSide:E})=>!E).sort(xi).map(Ue);for(let E of y){if(!isNaN(i)&&p>=i)break;let{matchUps:P}=yt({matchUpFilters:{matchUpTypes:[vt,Lt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}),A=P.find(N=>N.matchUpId===E),U=[oe,be].includes(A.matchUpStatus);if(A?.readyToScore&&!U){let D=_0({matchUpStatusProfile:e,tournamentRecord:o,drawDefinition:s,targetMatchUp:A,matchUpFormat:c,matchUpStatus:f,scoreString:l,winningSide:!n&&1,event:a});if(D?.error)return D;p+=1}}g&&S.finishingPosition===Ei&&t.completeRoundRobinPlayoffs&&na({structureId:S.structureId,applyPositioning:!0,drawDefinition:s})}return{...C,completedCount:p}}function vM(t){let{matchUpStatusCodes:e,policyDefinitions:r,tournamentRecord:n,drawDefinition:o,targetMatchUp:i,matchUpStatus:s,matchUpFormat:a,scoreString:c,winningSide:u,event:p}=t;if(!i||i.matchUpStatus==="BYE")return;let{matchUpId:m}=i||{},{outcome:d}=SI({matchUpFormat:a,matchUpStatus:s,scoreString:c,winningSide:u});return e&&(d.matchUpStatusCodes=e),Qu({tournamentRecord:n,policyDefinitions:r,drawDefinition:o,matchUpFormat:a,matchUpId:m,outcome:d,event:p})}function _0(t){let{matchUpStatusProfile:e={},tournamentRecord:r,policyDefinitions:n,drawDefinition:o,matchUpStatus:i,matchUpFormat:s,targetMatchUp:a,scoreString:c,winningSide:u,event:p}=t;if(c||i)return vM(t);let{matchUpId:m}=a||{},{outcome:d}=EI({matchUpStatusProfile:e,matchUpFormat:s,winningSide:u});return Qu({policyDefinitions:n,tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:m,outcome:d,event:p})}function IE({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfiles:o,isMock:i,event:s}){let a=Ht({event:s}).flightProfile,{eventName:c,eventType:u,category:p}=s,{startDate:m}=n,d=[],l=p?.categoryName||p?.ageCategoryCode||p?.ratingType,f=s.drawDefinitions?.map(({drawId:g})=>g);if(Array.isArray(a?.flights))for(let[g,I]of a.flights.entries()){let{drawId:h,stage:S,drawName:T,drawEntries:y}=I;d.push(I.drawId);let E=o[g],{seedsCount:P,generate:A=!0}=E||{};if(A){let U=y.filter(Hr(ao)).map(Hr(ao)),N=l||c;if(n&&P&&P<=U.length&&tt(1,P+1).forEach((x,F)=>{let w={scaleValue:x,scaleName:N,scaleType:Ao,eventType:u,scaleDate:m},L=U[F];xc({tournamentRecord:n,participantId:L,scaleItem:w})}),f?.includes(h))break;let D=Wa({...E,matchUpType:u,seedingScaleName:N,tournamentRecord:n,drawEntries:y,drawName:T,drawId:h,isMock:i,event:s,stage:S});if(D.error)return{error:D.error,drawIds:[]};let{drawDefinition:M}=D;if(!M)return{error:br};let R=o[g]?.drawExtensions;if(Array.isArray(R)&&R.filter(Bn).forEach(v=>At({element:M,extension:v})),D=kc({suppressNotifications:!0,tournamentRecord:n,drawDefinition:M,event:s}),D.error)return{error:D.error,drawIds:[]};if(E?.withPlayoffs){let v=M.structures?.[0].structureId,x=Kp({idPrefix:E.idPrefix,...E.withPlayoffs,tournamentRecord:n,drawDefinition:M,structureId:v,isMock:i,event:s});if(x?.error)return x}let b=E?.completionGoal;if(!(E?.automated===!1)&&(e||b)){let v=E?.matchUpFormat,x=Ol({completeAllMatchUps:!b&&e,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,completionGoal:b,drawDefinition:M,matchUpFormat:v,event:s});if(x.error)return{error:x.error,drawIds:[]};let F=x.completedCount;if(E?.drawType===Eo){let w=M.structures?.find(G=>G.stage===rt);if(!w)return{error:_t};let L=na({structureId:w.structureId,tournamentRecord:n,drawDefinition:M,event:s});if(L.error)return{error:L.error,drawIds:[]};let k=b?b-(F??0):void 0;if(L=Ol({completeAllMatchUps:!b&&e,completionGoal:b?k:void 0,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:M,matchUpFormat:v,event:s}),L.error)return{error:L.error,drawIds:[]}}}}}return{...C,drawIds:d}}function hE(t){let{participantsProfile:e={},uniqueParticipantsCount:r,ratingsParameters:n,tournamentRecord:o,eventProfile:i,eventIndex:s,event:a,uuids:c}=t,{category:u,gender:p,eventType:m}=a,d=de(Qn)(m)&&Et||de(Kr)(m)&&ft||m,l=r[rt]||0,f=r[ct]||0,g=i.drawProfiles?.length?l+f:i.participantsProfile?.participantsCount??0,I=Dn(p)?p:void 0,h=e?.idPrefix?`E-${s}-${e?.idPrefix}`:void 0,{participants:S}=fa({uuids:i.uuids||c,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:o?.startDate,rankingRange:i.rankingRange,participantType:d,participantsCount:g,ratingsParameters:n,category:u,idPrefix:h,sex:I}),y=En({tournamentRecord:o,participants:S});if(y.error)return y;let E=S?.filter(({participantType:A})=>A===d),P=S?.map(St);return{uniqueDrawParticipants:E,uniqueParticipantIds:P}}function gw({autoEntryPositions:t,tournamentRecord:e,drawParticipants:r,drawProfile:n,event:o}){let{drawType:i=yo,qualifyingPositions:s=0,stage:a=rt,drawSize:c=0,drawName:u,drawId:p}=n,m=c-s,d=r.slice(0,m).map(St);if(d.length){let g=Wn({participantIds:d,autoEntryPositions:t,entryStage:a,tournamentRecord:e,event:o});if(g.error)return g}let l=d.map(g=>({entryStatus:Gr,entryStage:a,participantId:g})),f=pm({drawName:u||i,qualifyingPositions:s,drawEntries:l,drawId:p,event:o,stage:a});return f.error?f:{...C}}function SE({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:r,tournamentRecord:n,drawProfiles:o,category:i,gender:s,event:a}){let c=0;for(let u of o){let{qualifyingPositions:p=0,uniqueParticipants:m,stage:d=rt,drawSize:l=0}=u,f=l-p,g=m||s||i||d===ct,I=g?t.slice(c,c+f):r[d||rt]||[];g&&(c+=f);let h=gw({autoEntryPositions:e,drawParticipants:I,tournamentRecord:n,drawProfile:u,event:a});if(h.error)return h}return{...C}}function TE(t){let{allUniqueParticipantIds:e,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,publish:d,isMock:l,uuids:f}=t,g=p.gender,I=p.eventName,{eventType:h=Qn,policyDefinitions:S,drawProfiles:T=[],eventExtensions:y,surfaceCategory:E,tieFormatName:P,processCodes:A,discipline:U,eventLevel:N,timeItems:D,ballType:M,category:R}=p,b=p.eventId||Nt(),O=p.tieFormat||(h===_e?io({namedFormat:P,event:{eventId:b,category:R,gender:g},hydrateCollections:s,isMock:l}):void 0),v=u.participants;for(let W of T)!g&&W.gender&&(g=W?.gender);let{stageParticipantsCount:x,uniqueParticipantsCount:F,uniqueParticipantStages:w}=fE({drawProfiles:T,category:R,gender:g}),L=de(Qn)(h)&&Et||de(Kr)(h)&&ft||h,{uniqueDrawParticipants:k=[],uniqueParticipantIds:G=[]}=w?hE({event:{eventType:h,category:R,gender:g},uniqueParticipantsCount:F,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,uuids:f}):{},{eventAttributes:H}=p;typeof H!="object"&&(H={});let K=R?.categoryName||R?.ageCategoryCode||R?.ratingType;I=I||K||"Generated Event";let Y={...H,surfaceCategory:E,processCodes:A,discipline:U,eventLevel:N,eventName:I,eventType:h,tieFormat:O,ballType:M,category:R,eventId:b,gender:g};if(y?.length&&Array.isArray(y)){let W=y.filter(Bn);W?.length&&Object.assign(Y,{extensions:W})}if(Array.isArray(D)&&D.forEach(W=>is({event:$,timeItem:W})),typeof S=="object")for(let W of Object.keys(S))ss({policyDefinitions:{[W]:S[W]},event:Y});Y.category&&(Y.category.categoryName=K);let j,V=pa({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:Y});if(V.error)return V;let $=V?.event,{stageParticipants:X}=gE({allUniqueParticipantIds:e,stageParticipantsCount:x,eventParticipantType:L,targetParticipants:v});if(T?.length){let W=SE({uniqueDrawParticipants:k,autoEntryPositions:i,stageParticipants:X,tournamentRecord:u,drawProfiles:T,category:R,gender:g,event:$});if(W.error)return W;let it=IE({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:T,isMock:l,event:$});if(it.error)return it;j=it.drawIds}else if(p?.participantsProfile?.participantsCount){let W=k.map(St);if(W.length){let it=Wn({participantIds:W,autoEntryPositions:i,tournamentRecord:u,entryStage:rt,event:$});if(it.error)return it}}return d&&da({tournamentRecord:u,event:$}),{drawIds:j,eventId:b,uniqueParticipantIds:G}}function AI({tournamentRecords:t,scheduleDate:e,venueId:r,round:n}){if(!Mr(e))return{error:Ye};let o="addSchedulingProfileRound",{extension:i}=mt({name:Na,tournamentRecords:t,discover:!0}),s=i?.value||[],a=s.find(l=>zn(e,l.scheduleDate));if(!a){let{startDate:l,endDate:f}=ol({tournamentRecords:t}),g=new Date(e);if(l&&g<new Date(l)||f&&g>new Date(f))return{error:Ye};a={scheduleDate:e,venues:[]},s.push(a)}let c=a.venues.find(l=>l.venueId===r);c||(c={venueId:r,rounds:[]},a.venues.push(c));let u=["notBeforeTime"],p=l=>Object.keys(l).filter(f=>!u.includes(f)).sort().map(f=>ht(l[f])?p(l[f]):l[f]).flat().join("|");if(c.rounds.find(l=>p(l)===p(n)))return _({result:{error:ZE},stack:o});c.rounds.push(n);let d=Lc({tournamentRecords:t,schedulingProfile:s});return d.error?d:{...C}}function Iw({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:B};let r=fs({tournamentRecord:e}).containedStructures,n=ye({tournamentRecord:e}).matchUps??[],{tournamentId:o}=e,i=[];for(let s of t){let{scheduleDate:a,venues:c=[]}=s;for(let u of c){let{rounds:p,venueId:m}=u;for(let d of p){let{drawId:l,winnerFinishingPositionRange:f,roundSegment:g}=d,h=n.filter(S=>{let T=f?.indexOf("-")>0&&f.split("-").map(E=>+E),y=S.finishingPositionRange?.winner;return S.drawId===l&&(!d.roundNumber||S.roundNumber===d.roundNumber)&&(!y||!T||jt(y,T).length===2||pt(y).length===pt(T).length&&jt(y,T).length===pt(y).length)})[0];if(h){let{eventId:S,roundNumber:T,drawName:y,structureName:E,roundName:P}=h,A=h.structureId;T&&!f&&(A=Object.keys(r).find(D=>r[D].includes(A))??A);let U={tournamentId:o,structureId:A,roundNumber:T,roundSegment:g,eventId:S,drawId:l},N=AI({tournamentRecords:{[o]:e},round:U,scheduleDate:a,venueId:m});if(N.error)return N;i.push({structureName:E,roundName:P,drawName:y,...U})}}}}return{scheduledRounds:i}}function Um(t){let e=et(t,[{drawProfile:!0,_ofType:zr}]);if(e.error)return e;let{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:o,completeAllMatchUps:i,autoEntryPositions:s,hydrateCollections:a,randomWinningSide:c,ratingsParameters:u,tournamentRecord:p,isMock:m=!0,drawProfile:d,startDate:l,drawIndex:f,uuids:g}=t,I=J(d,!1,!0),{excessParticipantAlternates:h=!0,matchUpFormat:S=bn,drawType:T=yo,tournamentAlternates:y=0,alternatesCount:E=0,qualifyingPositions:P,qualifyingProfiles:A,generate:U=!0,eventExtensions:N,drawExtensions:D,completionGoal:M,tieFormatName:R,buildTeams:b,seedsCount:O,timeItems:v,drawName:x,category:F,idPrefix:w,publish:L,gender:k,stage:G}=I,H=I.drawSize||(I.ignoreDefaults?void 0:32),K=I.eventId||Nt(),Y=d.eventType||d.matchUpType||Qn,j=Y===Kr?ft:Et,V=ht(d.tieFormat)&&d.tieFormat||Y===wt&&io({event:{eventId:K,category:F,gender:k},namedFormat:R,hydrateCollections:a,isMock:m})||void 0,$=F?.categoryName||F?.ageCategoryCode||F?.ratingType,X=d.eventName||$||`Generated ${Y}`,W=p?.participants||[],it=(A?.map(Pt=>Pt.structureProfiles||[]).flat().reduce((Pt,ce)=>{let ue=!ce.participantsCount||ce.participantsCount>ce.drawSize?ce.drawSize:ce.participantsCount||0;return Pt+ue},0)||0)*(j===ft?2:1),z=(!d.participantsCount||d.participantsCount>H?H:d.participantsCount)||0,Q={eventName:X,eventType:Y,tieFormat:V,category:F,eventId:K,gender:k};Array.isArray(v)&&v.forEach(Pt=>is({event:Q,timeItem:Pt}));let{eventAttributes:ut}=d;if(typeof ut!="object"&&(ut={}),Object.assign(Q,ut),N?.length&&Array.isArray(N)){let Pt=N.filter(Bn);Pt?.length&&Object.assign(Q,{extensions:Pt})}let ot=[];if(n?.participantsCount===0||d.uniqueParticipants||it||!p||k||F){let Pt=(z||0)+E+it,ce=Pt,ue={[Le]:0,[lr]:0},Fe,te;Y===wt&&({teamSize:Fe,genders:te}=bl({alternatesCount:E,tieFormatName:R,tieFormat:V,drawSize:H}),Object.keys(te).forEach(fr=>{let pe=yr(fr);pe&&Dn(fr)&&te[pe]&&(ue[pe]=H*te[pe])}),ce=Fe*((H||0)+it));let Je=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,ir=fa({...n,scaledParticipantsCount:d.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:ce,consideredDate:p?.startDate,sex:k||n?.sex,rankingRange:d.rankingRange,uuids:d.uuids||g,ratingsParameters:u,participantType:j,gendersCount:ue,idPrefix:Je,category:F}).participants;if(Q.category&&(Q.category.categoryName=$),p){let fr=En({participants:ir,tournamentRecord:p});if(fr.error)return fr}if(ir.forEach(({participantId:fr})=>ot.push(fr)),W=ir,Y===wt){let fr=te[Le]?ir.filter(({participantType:ee,person:Ur})=>ee===Et&&Ur?.sex===Le).map(St):[],pe=te[lr]?ir.filter(({participantType:ee,person:Ur})=>ee===Et&&$i(Ur?.sex)).map(St):[],me=ir.filter(({participantType:ee})=>ee===Et).map(St).filter(ee=>!fr.includes(ee)&&!pe.includes(ee)),Sr=[...I.teamNames??[],...Am({count:Pt}).names],jr=Fe-(te[Le]+te[lr]),Kt=0,Te=0,gr=0,Ee=tt(0,Pt).map(ee=>{let Ur=pe.slice(Kt,Kt+te[lr]),Cn=fr.slice(Te,Te+te[Le]),An=me.slice(gr,gr+jr);Kt+=te[lr],Te+=te[Le],gr+=jr;let hi=b!==!1?[...Ur,...Cn,...An]:[];return{participantName:Sr[ee]||`Team ${ee+1}`,participantOtherName:`TM${ee+1}`,participantRole:xe,individualParticipantIds:hi,participantType:wt,participantId:Nt()}}),Rn=En({participants:Ee,tournamentRecord:p});if(!Rn.success)return Rn;W=Ee}}let Dt=Pt=>{let{participantType:ce}=Pt;return de(Qn)(Y)&&ce===Et||de(Kr)(Y)&&ce===ft?!0:Y===wt&&ce===wt},Rt=Pt=>!d.gender||Pt.person?.sex===d.gender?!0:Pt.individualParticipantIds?.some(ce=>{let ue=W.find(Fe=>Fe.participantId===ce);return ue&&Rt(ue)}),De=W.filter(Dt).filter(Rt).filter(({participantId:Pt})=>!r.includes(Pt)),qt=De.slice(0,z).map(Pt=>Pt.participantId);if(m&&qt?.length){let Pt=Wn({autoEntryPositions:s,entryStage:G,tournamentRecord:p,participantIds:qt,event:Q});if(Pt.error)return Pt}let Se=it?De.slice(z,z+it).map(Pt=>Pt.participantId):0;if(m&&Se?.length){let Pt=0,ce=1,ue=(te,Je)=>te.stageSequence-Je.stageSequence,Fe=(te,Je)=>te.roundTarget-Je.roundTarget;for(let te of A.sort(Fe)){ce=te.roundTarget||ce;let Je=1,$t;for(let ir of te.structureProfiles.sort(ue)){let pe=(ir.drawSize||Rm(ir.participantsCount))-($t||0),me=Se.slice(Pt,Pt+pe),Sr=Wn({entryStage:ct,entryStageSequence:Je,autoEntryPositions:s,tournamentRecord:p,participantIds:me,roundTarget:ce,event:Q});if(Sr.error)return Sr;$t=ir.qualifyingPositions,Pt+=pe,Je+=1}ce+=1}}let _r=h&&p?.participants?.filter(({participantId:Pt})=>!qt.includes(Pt)).filter(Dt).filter(Rt).slice(0,E||H-z||y).map(Pt=>Pt.participantId);if(m&&_r?.length){let Pt=Wn({participantIds:_r,autoEntryPositions:!1,entryStatus:on,tournamentRecord:p,event:Q});if(Pt.error)return Pt.error}let dn=$||X;p&&O&&O<=qt.length&&tt(1,O+1).forEach((ce,ue)=>{let Fe={scaleName:dn,scaleDate:l,scaleType:lg,scaleValue:ce,eventType:Y},te=qt[ue];xc({tournamentRecord:p,participantId:te,scaleItem:Fe})});let hr=Wa({...J(d,!1,!0),tournamentRecord:p,seedingScaleName:dn,matchUpFormat:S,eventId:K,isMock:m,event:Q});if(hr.error)return hr;if(!hr.drawDefinition)return{error:br};let{drawDefinition:Xe}=hr,Zt=Xe.drawId;if(Array.isArray(D)&&D.filter(Bn).forEach(Pt=>At({element:Xe,extension:Pt})),U){if(kc({drawDefinition:Xe,event:Q,suppressNotifications:!0}),d.withPlayoffs){let ce=Xe.structures?.[0].structureId,ue=Kp({...d.withPlayoffs,tournamentRecord:p,drawDefinition:Xe,structureId:ce,idPrefix:w,isMock:m,event:Q});if(ue?.error)return ue}let Pt=d.automated===!1;if(m&&!Pt){let ce=ue=>{let Fe=Ol({completeAllMatchUps:ue.completeAllMatchUps,completionGoal:ue.completionGoal,matchUpStatusProfile:o,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:Q});if(Fe.error)return Fe;let te=Fe.completedCount;if(T===Eo){let Je=Xe.structures?.find(fr=>fr.stage===rt);if(!Je)return{error:_t};na({structureId:Je.structureId,tournamentRecord:p,drawDefinition:Xe,event:Q});let $t=M?M-(te??0):void 0,ir=Ol({completionGoal:M?$t:void 0,matchUpStatusProfile:o,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:Q});if(ir.error)return ir}};if(M&&ce({completionGoal:M}),d.outcomes){let{matchUps:ue}=nr({inContext:!0,drawDefinition:Xe,event:Q});for(let Fe of d.outcomes){let{matchUpStatus:te=ge,matchUpStatusCodes:Je,stageSequence:$t=1,matchUpIndex:ir=0,structureOrder:fr,matchUpFormat:pe,drawPositions:me,roundPosition:Sr,stage:jr=rt,roundNumber:Kt,winningSide:Te,scoreString:gr}=Fe,Ee=ue?.reduce((An,hi)=>{let{structureId:ga,matchUpId:ep}=hi;return An[ga]?An[ga].push(ep):An[ga]=[ep],An},{})??[],Rn=Object.assign({},...Object.keys(Ee).map((An,hi)=>({[An]:hi+1}))),Ur=ue?.filter(An=>(!jr||An.stage===jr)&&(!$t||An.stageSequence===$t)&&(!Kt||An.roundNumber===Kt)&&(!Sr||An.roundPosition===Sr)&&(!fr||Rn[An.structureId]===fr)&&(!me||jt(me,An.drawPositions).length===2))?.[ir],Cn=vM({matchUpStatusCodes:Je,tournamentRecord:p,drawDefinition:Xe,targetMatchUp:Ur,matchUpFormat:pe,matchUpStatus:te,scoreString:gr,winningSide:Te});if(Cn?.error)return Cn}}i&&ce({completeAllMatchUps:i})}L&&da({tournamentRecord:p,event:Q})}else{let Pt=pm({drawEntries:Xe.entries,drawName:x||T,qualifyingPositions:P,drawId:Zt,event:Q,stage:G});if(Pt.error)return Pt}return{...C,event:nt(Q),uniqueParticipantIds:ot,targetParticipants:W,drawDefinition:Xe,eventId:K,drawId:Zt}}var _M=()=>({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}),hw=_M;function yE(t){return parseInt(t)}function xM({startTime:t="",endTime:e=""}={}){if(!t||!e||!Ws.test(t)||!Ws.test(e))return!1;let[r,n]=t.split(":").map(yE),[o,i]=e.split(":").map(yE);return o<r?!1:!(r===o&&i<n)}function Sw(t,e){let[r,n]=t.startTime.split(":").map(yE),[o,i]=e.startTime.split(":").map(yE);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function EE({dateAvailability:t}){if(!t)return{error:fA};if(!Array.isArray(t))return{error:rf};let e="Dates must be formated => YYYY-MM-DD",r="Times must be 24 hour => 00:00";for(let n of t){if(typeof n!="object")return{error:rf};let{date:o,startTime:i,endTime:s,bookings:a=[]}=n;if(!i||!s)return{error:rf};if(o&&!Oo.test(o))return{error:Ye,dateAvailability:{date:o},info:e};if(!Ws.test(i))return{error:Co,dateAvailability:{startTime:i},info:r};if(!Ws.test(s))return{error:Co,dateAvailability:{endTime:s},info:r};if(i===s)return{error:Co,dateAvailability:{startTime:i,endTime:s},info:"startTime and endTime are equivalent"};if(!xM({startTime:i,endTime:s}))return{error:Co,dateAvailability:{startTime:i,endTime:s},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:vm};for(let c of a){if(typeof c!="object")return{error:vm};let{startTime:u,endTime:p}=c;if(!Ws.test(u))return{error:Co,booking:{startTime:u},info:r};if(!Ws.test(p))return{error:Co,booking:{endTime:p},info:r};if(u===p)return{error:Co,dateAvailability:{startTime:u,endTime:p},info:"startTime and endTime are equivalent"};if(!xM({startTime:u,endTime:p}))return{error:Co,dateAvailability:{startTime:u,endTime:p},info:"endTime must be after startTime"}}}}return{valid:!0}}function vl({tournamentRecord:t,disableNotice:e,venueId:r,courtId:n,court:o}){let{venue:i}=ti({tournamentRecord:t,venueId:r});if(!i)return{error:ji};i.courts||(i.courts=[]);let s={..._M(),venueId:r,courtId:n};if(s.courtId||(s.courtId=Nt()),i.courts.some(c=>c.courtId===s.courtId))return{error:bA};{let c=(o?.dateAvailability||[]).map(m=>({...m,date:Ut(m.date),startTime:zt(m.startTime),endTime:zt(m.endTime),bookings:m.bookings?.map(({startTime:d,endTime:l,bookingType:f})=>({startTime:zt(d),endTime:zt(l),bookingType:f}))})),u=Object.keys(s);for(let m of u)if(o?.[m])if(m==="dateAvailability"){let d=EE({dateAvailability:c});if(!d.valid&&d.error)return d;s.dateAvailability=c}else s[m]=o[m];let p=s;return i.courts.push(p),e||lt({payload:{venue:i,tournamentId:t.tournamentId},topic:Ri,key:i.venueId}),{...C,court:J(s),venueId:r}}}function UI(t){let{tournamentRecord:e,venueId:r}=t;if(typeof r!="string"||!r)return{error:ai};let n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o=[],i;for(let s of Object.values(n)){let{venue:a}=ti({tournamentRecord:s,venueId:r});if(a){let c=x0({...t,tournamentRecord:s});for(let u of c?.courts??[])o.push(u?.courtId);if(c.error)return c;i=!0}}return i?{...C,courtIds:o}:{error:ji}}function x0({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:r,tournamentRecord:n,courtNames:o=[],courtTimings:i,courtsCount:s,startTime:a,courtIds:c,endTime:u,idPrefix:p,venueId:m,dates:d}){if(!m)return{error:ai};let l=ti({tournamentRecord:n,venueId:m});if(l.error)return l;let{venue:f}=l;if(!Jt(s)||!o)return{error:CA};s=s??o.length;let h=tt(0,s).map(S=>{let T=i?.[S],y=T?d.map(E=>({date:Kn(E),startTime:a,endTime:u,...T})):e;return T&&a&&u&&y.push({startTime:a,endTime:u}),{courtName:o[S]||r&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:y}}).map((S,T)=>{let y=c?.pop()||p&&`${p}-${T+1}`;return vl({disableNotice:!0,tournamentRecord:n,courtId:y,venueId:m,court:S})}).map(S=>S.court).filter(Boolean);return h.length!==s?_({info:"not all courts could be generated",result:{error:B}}):(f&<({payload:{venue:f,tournamentId:n.tournamentId},topic:Ri,key:f.venueId}),{...C,courts:J(h)})}function _l({tournamentRecord:t,ignoreExistingVenues:e,venueProfiles:r,uuids:n}){let{startDate:o,endDate:i}=t,s=[];for(let[a,c]of r.entries()){let{venueAbbreviation:u,venueId:p=n?.pop()??Nt(),dateAvailability:m,startTime:d="07:00",endTime:l="19:00",courtTimings:f,courtsCount:g,courtNames:I,venueName:h,idPrefix:S,courtIds:T}=c,y={venueName:h||`Venue ${a+1}`,venueAbbreviation:u,venueId:p},E=Ec({tournamentRecord:t,venue:y});if(E.error){if(e)continue;return E}s.push(p);let P=js(o,i),A=!Array.isArray(m)&&[{startTime:d,endTime:l}].concat(P.map(U=>({date:Kn(U),startTime:d,endTime:l})));if(g||I){let U=UI({dateAvailability:m||A,tournamentRecord:t,courtTimings:f,courtsCount:g,courtNames:I,startTime:d,idPrefix:S,courtIds:T,endTime:l,venueId:p,dates:P});if(U.error)return U}}return s}function Tw(t){let{tournamentRecord:e,leagueProfiles:r,eventIds:n,venueIds:o,drawIds:i,allUniqueParticipantIds:s,uuids:a}=t,c=0;for(let p of r){let m=[],{tieFormatName:d=Hm,teamProfiles:l=[],teamsCount:f=0,category:g,idPrefix:I,gender:h}=p,S=p.leagueName??p.eventName??`League ${c+1}`,T=p.leagueId??p.eventId??a?.pop()??Nt();n.push(T);let y=ht(p.tieFormat)&&p.tieFormat||io({event:{eventId:T,category:g,gender:h},namedFormat:d,isMock:t.isMock})||void 0;if(!y)return{error:ks};let E=Math.max(f,l.length),P=tt(0,E),{genders:A,teamSize:U}=bl({tieFormat:y,drawSize:E}),N={[lr]:0,[qi]:0,[$o]:0,[Le]:0,ANY:0};Object.keys(A).forEach(R=>N[R]+=A[R]);for(let R of P){let b=l?.[R]?.teamName??`Team ${R+1}`,O=l?.[R]?.teamId||a?.pop()||Nt(),v=p.startDate??t.startDate,x=fa({...p?.participantsProfile,participantsCount:U,consideredDate:v,gendersCount:N,category:g,gender:h,uuids:a}).participants,F=x.map(K=>K.participantId),w=wt,L=O??Em({participantType:w,idPrefix:I,index:R,uuids:a});m.push({participantId:L,entryStatus:Gr,entryStage:rt});let k=l?.[R]?.venueIds??[],G={participantId:L,participantRole:xe,participantName:b,individualParticipantIds:F,participantType:w,homeVenueIds:k};k.forEach(K=>!o.includes(K)&&o.push(K)),s.push(...F),s.push(L);let H=En({participants:[G,...x],tournamentRecord:e});if(H.error)return H}let M={eventName:S,entries:m,eventType:wt,tieFormat:y,category:g,eventId:T,gender:h};if(e.events||(e.events=[]),e.events.push(M),m.length){let R=(Jt(p.roundsCount)&&p.roundsCount)??p.roundsCount===ub?(E-1)*2:E-1,b=Wa({automated:p.automated,tournamentRecord:e,drawType:Fr,roundsCount:R,drawSize:E,event:M});if(b.error)return b;let{drawDefinition:O}=b;if(O){let v=O?.drawId;kc({drawDefinition:O,event:M,suppressNotifications:!0}),i.push(v)}}c++}let u=o.map(p=>({venueId:p}));_l({tournamentRecord:e,ignoreExistingVenues:!0,venueProfiles:u,uuids:a})}var w0=["Generated Tournament","CourtHive Challenge","Replication Crisis","Open Competition","Factory Follies","Mock Tournament","Atomic Culture","Racket Rally","Stats Fail"];function wM(t){let{startDate:e,endDate:r}=t??{},{tournamentName:n=tn(w0),ratingsParameters:o=je,tournamentExtensions:i,policyDefinitions:s,schedulingProfile:a,venueProfiles:c,uuids:u}=t??{},p=t?.isMock===!1?void 0:!0;if(e&&!Mr(e)||r&&!Mr(r))return{error:Ye};if(t.leagueProfiles&&!Array.isArray(t.leagueProfiles)||t.eventProfiles&&!Array.isArray(t.eventProfiles)||t.drawProfiles&&!Array.isArray(t.drawProfiles))return{error:B};if(!e){let S=new Date;e=Kn(r??S),r=Kn(S.setDate(S.getDate()+7))}if(!r){let S=new Date(e);r=Kn(S.setDate(S.getDate()+7))}let m=ym({...t.tournamentAttributes??{},tournamentName:n,startDate:e,endDate:r,isMock:p}),d=c?.length?_l({tournamentRecord:m,venueProfiles:c,uuids:u}):[];if(i?.length&&Array.isArray(i)){let S=i.filter(T=>Bn({extension:T}));S?.length&&Object.assign(m,{extensions:S,isMock:p})}if(typeof s=="object")for(let S of Object.keys(s))ss({policyDefinitions:{[S]:s[S]},tournamentRecord:m});if(!t?.leagueProfiles?.length||t.eventProfiles?.length||t.drawProfiles?.length||t.participantsProfile){let S=lE({tournamentRecord:m,...t});if(!S.success)return S}let l=[],f=[],g=[];if(t.leagueProfiles){let S=Tw({allUniqueParticipantIds:l,tournamentRecord:m,...t,eventIds:f,venueIds:d,drawIds:g});if(S?.error)return S}if(t.drawProfiles){let S=L0({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}if(t.eventProfiles){let S=F0({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}let{scheduledRounds:I=void 0,schedulerResult:h={}}=a?k0({...t,tournamentRecord:m}):{};return Tf(),nt({...C,tournamentRecord:m,scheduledRounds:I,schedulerResult:h,eventIds:f,venueIds:d,drawIds:g})}function L0(t){let{tournamentRecord:e,drawProfiles:r,allUniqueParticipantIds:n,eventIds:o,drawIds:i}=t,s=0;for(let a of r){let c=Um({allUniqueParticipantIds:n,tournamentRecord:e,drawProfile:a,drawIndex:s,...t});if(c.error)return c;let{drawId:u,eventId:p,event:m,uniqueParticipantIds:d}=c;if(a?.addEvent!==!1){if(c=pa({suppressNotifications:!1,internalUse:!0,tournamentRecord:e,event:m}),c.error)return c;u&&i.push(u),o.push(p)}d?.length&&n.push(...d),s+=1}}function F0(t){let{eventProfiles:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o}=t,i=0;for(let s of e){let a=TE({...t,eventIndex:i,eventProfile:s});if(a.error)return a;let{eventId:c,drawIds:u,uniqueParticipantIds:p}=a;u&&o.push(...u),n.push(c),p?.length&&r.push(...p),i+=1}}function k0(t){let{schedulingProfile:e,tournamentRecord:r,autoSchedule:n,periodLength:o,scheduleCompletedMatchUps:i}=t,s=Iw({schedulingProfile:e,tournamentRecord:r});if(s.error)return s;let a=s.scheduledRounds;if(n){let{tournamentId:c}=r,u={[c]:r};return{schedulerResult:Tm({scheduleCompletedMatchUps:i,tournamentRecords:u,periodLength:o}),scheduledRounds:a}}return{scheduledRounds:a}}var GM={};Xt(GM,{anonymizeTournamentRecord:()=>FM,modifyTournamentRecord:()=>kM});function FM({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:r,tournamentName:n,personIds:o=[],tournamentId:i}){if(!r)return{error:q};let s=Array.isArray(t)?vU.concat(...t):vU,a=L=>Array.isArray(t)?L?.extensions?.filter(k=>s.includes(k.name)):L?.extensions,c={};r.extensions=a(r);let u=i||Nt();c[r.tournamentId]=u,r.tournamentId=u,r.createdAt=new Date().toISOString(),r.tournamentName=n||`Anonymized: ${Kn(new Date)}`,r.isMock=!0,delete r.parentOrganisation;for(let L of r.participants||[]){L.extensions=a(L),L.onlineResources=[];let k=Nt();c[L.participantId]=k,L.participantId=k}for(let L of r.participants||[])Array.isArray(L.individualParticipantIds)&&(L.individualParticipantIds=L.individualParticipantIds.map(k=>c[k]));let p=0;for(let L of r.venues||[]){L.venueAbbreviation=`V${p}`,L.extensions=a(L),L.venueName=`Venue #${p}`,L.onlineResources=[],L.addresses=[];let k=Nt();c[L.venueId]=k,L.isMock=!0,p+=1;let G=0;for(let H of L.courts||[])H.courtName=`V${p}C${G}`,H.extensions=a(H),H.onlineResources=[],H.isMock=!0,G+=1}let m=1;for(let L of r.events||[]){L.extensions=a(L),L.onlineResources=[],L.isMock=!0;let k=Nt();c[L.eventId]=k,L.eventId=k;let G=L.category?.categoryName||L.category?.ageCategoryCode||L.category?.ratingType||L.gender;if(L.eventName=`Event ${m} ${G}`,Array.isArray(L.entries))for(let K of L.entries)K.participantId=c[K.participantId];for(let K of L.drawDefinitions||[]){K.extensions=a(K);let Y=Nt();if(c[K.drawId]=Y,K.drawId=Y,K.isMock=!0,Array.isArray(K.entries))for(let V of K.entries)V.participantId=c[V.participantId];let j=V=>{V.extensions=a(V);let $=Nt();c[V.structureId]=$,V.structureId=$;for(let X of V.positionAssignments||[])X.participantId&&(X.participantId=c[X.participantId]);for(let X of V.seedAssignments||[])X.participantId&&(X.participantId=c[X.participantId]);for(let X of V.matchUps||[]){X.isMock=!0;for(let W of X.sides||[])W.lineUp&&(W.lineUp=W.lineUp.map(({participantId:it,collectionAssignments:z})=>({participantId:c[it],collectionAssignments:z})))}};for(let V of K.structures||[])if(j(V),Array.isArray(V.structures))for(let $ of V.structures)j($);for(let V of K.links||[])V.source.structureId=c[V.source.structureId],V.target.structureId=c[V.target.structureId]}let{extension:H}=mt({name:pn,element:L});Array.isArray(H?.value?.flights)&&H?.value.flights?.forEach(K=>{if(K.drawId=c[K.drawId],Array.isArray(K.drawEntries))for(let Y of K.drawEntries)Y.participantId=c[Y.participantId]}),m+=1}let d=r.startDate||Kn(new Date),l=(r.participants||[]).filter(({participantType:L})=>L===Et),f=l.reduce((L,k)=>{let G=k.person?.sex,H=yr(G);return H&&Dn(G)?L[H]+=1:L[$o]+=1,L},{[Le]:0,[lr]:0,[$o]:0}),g=Object.assign({},...Object.keys(f).map(L=>({[L]:mE({category:{ageCategoryCode:"O18"},count:f[L],addressProps:{citiesCount:10},personExtensions:[],consideredDate:d,sex:L})?.persons||[]}))),I={[Le]:0,[lr]:0,[$o]:0},h=l.length,S=l.reduce((L,k)=>{let G=k.person?.addresses?.[0]||{},{city:H,state:K,postalCode:Y}=G;return L.cities.includes(H)||L.cities.push(H),L.states.includes(K)||L.states.push(K),L.postalCodes.includes(Y)||L.postalCodes.push(Y),L},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,y=S.cities.length,E=S.states.length,{cities:P}=sE({count:y||h,participantsCount:h}),{states:A}=aE({count:E||h,participantsCount:h}),{postalCodes:U}=cE({count:T||h,participantsCount:h}),N={cities:P,states:A,postalCodes:U};l.forEach((L,k)=>{let G=L?.person,H=G?.sex||$o,K=Ut(G?.birthDate)?.split("-")[0],Y=I[H],j=g[H][Y];if(I[H]+=1,K){let[,V,$]=j?.birthDate?.split("-")||[],X=[K,V,$].join("-");j.birthDate=X}if(G?.addresses){let V=uE({...N,participantIndex:k,nationalityCode:j.nationalityCode});j.addresses=[V]}j.personId=o?.[k]||Nt(),e?(j.standardFamilyName=j.lastName,j.standardGivenName=j.firstName,L.participantName=`${j.standardGivenName} ${j.standardFamilyName}`):(j.standardFamilyName=G?.standardFamilyName,j.standardGivenName=G?.standardGivenName),delete j.firstName,delete j.lastName,j.extensions=a(G),L.person=j,c[G?.personId]=j.personId}),(r.participants||[]).filter(({participantType:L})=>L===ft).forEach(L=>{let{individualParticipantIds:k}=L;L.participantName=G0({individualParticipantIds:k,individualParticipants:l})});let M=(r.participants||[]).filter(({participantType:L})=>L===wt),R=M.length,b=Am({count:R}).names;M.forEach((L,k)=>{L.participantName=b[k]});let O=(r.participants||[]).filter(({participantType:L})=>L===Qr),v=O.length,x=Am({count:v,nameRoot:"Group"}).names;O.forEach((L,k)=>{L.participantName=x[k]});let{extension:F}=mt({element:r,name:Na});Array.isArray(F?.value)&&F?.value.forEach(L=>{L.tournamentId=c[L.tournamentId],L.structureId=c[L.structureId],L.eventId=c[L.eventId],L.drawId=c[L.drawId]});let{extension:w}=mt({element:r,name:Da});return Array.isArray(w?.value)&&w?.value.forEach(L=>{L.personId=c[L.personId]}),{...C}}function G0({individualParticipantIds:t,individualParticipants:e}){let r=e.filter(({participantId:n})=>t.includes(n)).map(({person:n})=>n?.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(r+="/Unknown"),r}function V0({event:t,eventProfile:e,tournamentRecord:r,allUniqueParticipantIds:n,drawIds:o}){let{gender:i,category:s,eventType:a}=t,{drawProfiles:c,publish:u}=e,p=de(Qn)(a)&&Et||de(Kr)(a)&&ft||a;if(c){let{stageParticipantsCount:m,uniqueParticipantsCount:d,uniqueParticipantStages:l}=fE({drawProfiles:c,category:s,gender:i}),{uniqueDrawParticipants:f=[],uniqueParticipantIds:g=[]}=l?hE({event:{eventType:a,category:s,gender:i},uniqueParticipantsCount:d,participantsProfile:e.participantsProfile,ratingsParameters:e.ratingsParameters,tournamentRecord:r,eventProfile:e,uuids:e.uuids}):{};n.push(...g);let{stageParticipants:I}=gE({targetParticipants:r.participants||[],allUniqueParticipantIds:n,stageParticipantsCount:m,eventParticipantType:p}),h=SE({uniqueDrawParticipants:f,autoEntryPositions:e.autoEntryPositions,stageParticipants:I,tournamentRecord:r,drawProfiles:c,category:s,gender:i,event:t});if(h.error||(h=IE({matchUpStatusProfile:e.matchUpStatusProfile,completeAllMatchUps:e.completeAllMatchUps,randomWinningSide:e.randomWinningSide,tournamentRecord:r,drawProfiles:c,isMock:e.isMock,event:t}),h.error))return h;o.push(...h.drawIds)}return u&&da({tournamentRecord:r,event:t}),C}function yw(t,e){return t?.find((r,n)=>e.eventIndex!==void 0&&n===e.eventIndex||e.eventName&&r.eventName===e.eventName||e.eventId&&r.eventId===e.eventId)}function B0({eventProfiles:t,tournamentRecord:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o,params:i}){let s=e.events?.length||0;for(let a of t){let c=yw(e.events,a);if(c){let u=V0({event:c,eventProfile:{...a,...i},tournamentRecord:e,allUniqueParticipantIds:r,drawIds:o});if(u.error)return u}else{let u=TE({startDate:e.startDate,allUniqueParticipantIds:r,matchUpStatusProfile:i.matchUpStatusProfile,participantsProfile:i.participantsProfile,completeAllMatchUps:i.completeAllMatchUps,autoEntryPositions:i.autoEntryPositions,randomWinningSide:i.randomWinningSide,ratingsParameters:a.ratingsParameters,tournamentRecord:e,eventProfile:a,eventIndex:s,uuids:i.uuids});if(u.error)return u;let{eventId:p,drawIds:m,uniqueParticipantIds:d}=u;m&&o.push(...m),n.push(p),d?.length&&r.push(...d),s+=1}}return C}function H0({drawProfiles:t,tournamentRecord:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o,params:i}){let s=(e.events||[]).flatMap(a=>a.drawDefinitions?.map(()=>1)||[]).reduce((a,c)=>a+c,0);for(let a of t){let c=Um({startDate:e.startDate,allUniqueParticipantIds:r,matchUpStatusProfile:i.matchUpStatusProfile,participantsProfile:i.participantsProfile,completeAllMatchUps:i.completeAllMatchUps,autoEntryPositions:i.autoEntryPositions,hydrateCollections:i.hydrateCollections,randomWinningSide:i.randomWinningSide,ratingsParameters:i.ratingsParameters,tournamentRecord:e,drawProfile:a,drawIndex:s,uuids:i.uuids});if(c.error)return c;let{drawId:u,eventId:p,event:m,uniqueParticipantIds:d}=c;if(c=pa({tournamentRecord:e,event:m,internalUse:!0}),c.error)return c;u&&o.push(u),n.push(p),d?.length&&r.push(...d),s+=1}return C}function W0({schedulingProfile:t,autoSchedule:e,periodLength:r,tournamentRecord:n}){let o,i={};if(t?.length){let s={[n.tournamentId]:n},a=Lc({tournamentRecords:s,schedulingProfile:t});if(a.error)return a;if(e){let{tournamentId:c}=n,u={[c]:n};i=Tm({tournamentRecords:u,periodLength:r})}}return{scheduledRounds:o,schedulerResult:i}}function kM(t){let{participantsProfile:e={},schedulingProfile:r,tournamentRecord:n,autoSchedule:o,eventProfiles:i,periodLength:s,venueProfiles:a,drawProfiles:c,uuids:u}=t;if(!n)return{error:q};let p=[],m=[],d=[];i?.forEach(y=>{let E=yw(n.events,y);E?.gender&&(y.gender=E.gender)});let l=n.participants?.length||void 0;l&&e?.idPrefix&&(e.idPrefix=`${e.idPrefix}-${l}`);let f=lE({startDate:n.startDate,participantsProfile:e,tournamentRecord:n,eventProfiles:i,drawProfiles:c,uuids:u});if(!f.success)return f;if(i){let y=B0({eventProfiles:i,tournamentRecord:n,allUniqueParticipantIds:p,eventIds:m,drawIds:d,params:t});if(y.error)return y}if(c){let y=H0({drawProfiles:c,tournamentRecord:n,allUniqueParticipantIds:p,eventIds:m,drawIds:d,params:t});if(y.error)return y}let g=a?.length?_l({tournamentRecord:n,venueProfiles:a}):[],I=W0({schedulingProfile:r,autoSchedule:o,periodLength:s,tournamentRecord:n});if(I.error)return I;let{scheduledRounds:h,schedulerResult:S}=I;return{totalParticipantsCount:n.participants.length,scheduledRounds:h,schedulerResult:S,...C,eventIds:m,venueIds:g,drawIds:d}}var sR={};Xt(sR,{addDynamicRatings:()=>Yg,addIndividualParticipantIds:()=>dm,addParticipant:()=>wn,addParticipants:()=>En,addPenalty:()=>nR,addPersonRequests:()=>HM,addPersons:()=>oR,createGroupParticipant:()=>zM,createTeamsFromParticipantAttributes:()=>yI,deleteParticipants:()=>ns,filterParticipants:()=>bu,findParticipant:()=>KM,getCompetitionParticipants:()=>QT,getPairedParticipant:()=>Sn,getParticipantEventDetails:()=>XT,getParticipantMembership:()=>JT,getParticipantScaleItem:()=>wc,getParticipantSchedules:()=>ZT,getParticipantSignInStatus:()=>ty,getParticipantTimeItem:()=>sS,getParticipants:()=>Ft,getScaleValues:()=>Aa,mergeParticipants:()=>rR,modifyIndividualParticipantIds:()=>WM,modifyParticipant:()=>lm,modifyParticipantName:()=>QM,modifyParticipantOtherName:()=>YM,modifyParticipantsSignInStatus:()=>jM,modifyPenalty:()=>tR,modifyPersonRequests:()=>VM,mutate:()=>iR,participantScaleItem:()=>Po,query:()=>hN,regenerateParticipantNames:()=>$M,removeIndividualParticipantIds:()=>Tg,removeParticipantIdsFromAllTeams:()=>kp,removePenalty:()=>ZM,removePersonRequests:()=>BM,removeRatings:()=>JM,scaledTeamAssignment:()=>XM,setParticipantScaleItem:()=>xc,setParticipantScaleItems:()=>DD,validateLineUp:()=>Cd});var iR={};Xt(iR,{addDynamicRatings:()=>Yg,addIndividualParticipantIds:()=>dm,addParticipant:()=>wn,addParticipants:()=>En,addPenalty:()=>nR,addPersonRequests:()=>HM,addPersons:()=>oR,createGroupParticipant:()=>zM,createTeamsFromParticipantAttributes:()=>yI,deleteParticipants:()=>ns,findParticipant:()=>KM,mergeParticipants:()=>rR,modifyIndividualParticipantIds:()=>WM,modifyParticipant:()=>lm,modifyParticipantName:()=>QM,modifyParticipantOtherName:()=>YM,modifyParticipantsSignInStatus:()=>jM,modifyPenalty:()=>tR,modifyPersonRequests:()=>VM,regenerateParticipantNames:()=>$M,removeIndividualParticipantIds:()=>Tg,removeParticipantIdsFromAllTeams:()=>kp,removePenalty:()=>ZM,removePersonRequests:()=>BM,removeRatings:()=>JM,scaledTeamAssignment:()=>XM,setParticipantScaleItem:()=>xc,setParticipantScaleItems:()=>DD});function AE(t=0){(typeof t!="number"||isNaN(t))&&(t=0);let e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function UE({personRequests:t,personId:e,requests:r}){t[e]||(t[e]=[]);let n=r.filter(({requestType:o})=>o).map(o=>{let{date:i,startTime:s,endTime:a}=o;return o.requestType===Hc&&(i=Ut(i),s=zt(s),a=zt(a),i&&s&&a)?{date:i,startTime:s,endTime:a,requestType:o.requestType}:o}).filter(Boolean);for(let o of n)o.requestId=AE(),t[e].push(o);return{mergeCount:n.length}}function xl(t){let{tournamentRecords:e,personRequests:r}=t,n=et(t,[{[Re]:!0}]);if(n.error)return n;if(!r)return{...C};let o=Object.values(e);for(let i of o){let s=i.participants??[],a=[];for(let c of Object.keys(r))if(zo({tournamentParticipants:s,personId:c})){let u=r[c];u.length&&a.push({personId:c,requests:u})}Object.keys(a).length&&At({element:i,extension:{value:a,name:Da}})}return{...C}}function VM(t){let{tournamentRecords:e,requests:r,personId:n}=t,o=et(t,[{[Re]:!0},{requests:!0,[He]:Be,[kr]:B}]);if(o.error)return o;let i=r.map(({requestId:u})=>u).filter(Boolean),{personRequests:s}=ki({tournamentRecords:e}),a=u=>{s&&(s[u]=s[u].map(p=>{if(!i.includes(p.requestId))return p;let m=r.find(d=>d.requestId===p.requestId);if(m.requestType)return Object.assign(p,m)}).filter(Boolean))};if(n&&s?.[n])a(n);else if(s)for(let u of Object.keys(s))a(u);let c=r.filter(u=>!u.requestId);return c.length&&UE({personRequests:s,personId:n,requests:c}),xl({tournamentRecords:e,personRequests:s})}function BM(t){let{tournamentRecords:e,requestType:r,requestId:n,personId:o,date:i}=t,s=et(t,[{[Re]:!0}]);if(s.error)return s;let{personRequests:a}=ki({tournamentRecords:e}),c=p=>{a&&(a[p]=a[p].filter(m=>(!r||m.requestType!==r)&&(!n||m.requestId!==n)&&(!i||m.date!==i)),a?.[p]?.length||delete a[p])},u=!r&&!n&&!o&&!i;if(!u){if(o&&a?.[o])c(o);else if(a)for(let p of Object.keys(a))c(p)}return u||!a||!Object.keys(a).length?Ir({name:Da,tournamentRecords:e,discover:!0}):xl({tournamentRecords:e,personRequests:a})}function HM(t){let{tournamentRecords:e,personId:r,requests:n}=t,o=et(t,[{[Re]:!0,[gb]:!0},{requests:!0,[He]:Be,[kr]:B}]);if(o.error)return o;let{personRequests:i}=ki({tournamentRecords:e}),{mergeCount:s}=UE({personRequests:i,personId:r,requests:n});return s&&i?xl({tournamentRecords:e,personRequests:i}):{error:B}}function WM({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n="modifyIndividualParticipantIds";if(!r)return _({result:{error:q},stack:n});if(!e||!t)return _({result:{error:st},stack:n});let o=r.participants||[],i=o.find(l=>l.participantId===e);if(!i)return _({result:{error:re},stack:n});if(![wt,Qr].includes(i.participantType))return _({result:{error:Pn},context:{participantType:i.participantType},stack:n});let s=t.filter(l=>o.find(g=>g.participantId===l)?.participantType!==Et);if(s.length)return _({result:{error:wr,invalidParticipantIds:s},stack:n});let a=i.individualParticipantIds||[],c=t.filter(l=>!a.includes(l)),u=a.filter(l=>!t.includes(l)),p=dm({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:r});if(p.error)return _({result:p,stack:n});let m=Tg({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:r});if(m.error)return _({result:m,stack:n});let{topics:d}=Lr();if(d.includes(rr)){let l=o.find(({participantId:f})=>f===e);lt({topic:rr,payload:{tournamentId:r.tournamentId,participants:[l]}})}return{...p,...m}}function jM({tournamentRecord:t,participantIds:e,signInState:r}){if(!t)return{error:q};if(!Array.isArray(e))return{error:st};if(![Tu,zU].includes(r))return{error:B,signInState:r};let o=t.participants||[];if(!o.length)return{error:ec};let i=o.map(St),s=e.filter(p=>!i.includes(p));if(s.length)return{error:B,context:{invalidParticipantIds:s}};let a=[],c=new Date().toISOString();for(let p of o){let{participantId:m}=p;if(e.includes(m)){let l=Gg({duplicateValues:!1,tournamentRecord:t,participantId:m,timeItem:{itemType:Ic,itemValue:r,createdAt:c}});if(l.error)return l;a.push(p)}}let{topics:u}=Lr();return a.length&&u.includes(rr)&<({topic:rr,payload:{tournamentId:t.tournamentId,participants:a}}),{...C}}function YM({tournamentRecord:t,participantId:e,participantOtherName:r}){if(!t)return{error:q};if(!e)return{error:se};let{participant:n}=Uo({tournamentRecord:t,participantId:e});if(!n)return{error:re};n.participantOtherName=r;let{topics:o}=Lr();return o.includes(rr)&<({topic:rr,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function qM({personFormat:t,person:e}){let r=g=>g.replace(/\W/g,""),n=g=>/^[a-z]*$/.test(r(g)),o=g=>/^[A-Z]*$/.test(r(g)),i=g=>/^[LAST]{4}/.test(r(g)),s=g=>g.toLowerCase().indexOf("l")<g.toLowerCase().indexOf("f"),a=g=>g.indexOf(",")>=0,c=g=>g.toLowerCase().indexOf("f.")>=0,u=g=>g.toLowerCase().indexOf("f")<0,p=g=>g.indexOf(" ")>0;if(!e)return;let m=p(t)?" ":"",d=vS(e?.standardGivenName??""),l=vS(e?.standardFamilyName??"");if(!t)return`${d}${m}${l}`;c(t)&&!a(t)&&!s(t)&&(d=`${d[0]}.`),n(t)?(d=d.toLowerCase(),l=l.toLowerCase()):o(t)?(d=d.toUpperCase(),l=l.toUpperCase()):i(t)&&(l=l.toUpperCase());let f=`${d}${m}${l}`;return u(t)?f=l:s(t)&&(a(t)?f=`${l},${m}${d}`:f=`${l}${m}${d}`),f}function Ew({participantMap:t,participant:e,formats:r}){let{participantType:n,individualParticipantIds:o,person:i}=e,s=n&&r[n];if(n!==Ar&&s){let{personFormat:a,doublesJoiner:c}=s;n===Et&&(e.participantName=qM({person:i,personFormat:a})),n===ft&&(e.participantName=o?.map(u=>{let p=t[u]?.person;return qM({person:p,personFormat:a})}).filter(Boolean).join(c??"/"))}}function $M({tournamentRecord:t,formats:e}){if(!t)return{error:q};if(!ht(e))return{error:st};let r=t.participants??[],n=kI(r,"participantId");for(let o of r)Ew({participant:o,participantMap:n,formats:e});return{...C}}function KM(t){let{tournamentRecord:e,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}=t,s=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="string"&&typeof i!="string")return{error:st,stack:"publicFindParticipant"};let a,c;for(let u of Object.values(s)){c=u.tournamentId;let p=u.participants||[];if(a=zo({tournamentParticipants:p,internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}),a)break}return{participant:a,tournamentId:c,...C}}function zM({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:r=yP,tournamentRecord:n,participantId:o,groupName:i}){if(!n)return{error:q};if(!i)return{error:st,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:B};let a=(Ft({participantFilters:{participantTypes:[Et]},tournamentRecord:n}).participants??[]).map(m=>m.participantId);for(let m of t)if(!a.includes(m))return{error:Pn,participantId:m};let c=nt({participantId:o||Nt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:Qr,participantRole:r}),u=wn({participant:c,tournamentRecord:n});if(u.error)return u;let{topics:p}=Lr();return p.includes(ci)&<({topic:ci,payload:{tournamentId:n.tournamentId,participants:[c]}}),{...C,participant:J(c)}}function QM({tournamentRecord:t,participantName:e,participantId:r}){if(!t)return{error:q};if(!r)return{error:se};if(!e)return{error:st,info:"Missing participantName"};let{participant:n}=Uo({tournamentRecord:t,participantId:r});if(!n)return{error:re};n.participantName=e;let{topics:o}=Lr();return o.includes(rr)&<({topic:rr,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function XM({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:r,initialTeamIndex:n=0,scaledParticipants:o=[],teamParticipantIds:i,tournamentRecord:s,scaleAttributes:a,teamNameBase:c,teamsCount:u,eventId:p,event:m}){if(!s)return{error:q};if(!Array.isArray(i)&&!It(u)&&!p||!It(n)||o&&!Array.isArray(o)||a&&(typeof a!="object"||!Object.keys(a).length))return{error:B};if(!a&&!o.length||!o&&!(e&&a))return{error:st,info:"Missing scaling details"};if(p&&!i){if(m?.eventType!==Or)return{error:$n};i=m?.entries?.filter(({entryStatus:h})=>h===Gr).map(St)}if(!i?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:st};let d=e??o.map(({participantId:h})=>h);r&&(i?.reverse(),n+=1),n>(i?.length||0)-1&&(n=0);let l=i?.slice(n).concat(...i.slice(0,n))??[],f=[];for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(l.includes(S)){if(T!==Ar)return{error:Pn,participant:h};f.push(h)}}if(u&&f.length<u){let h=u-(f?.length||0),S=c??"Team",T=tt(0,h).map(A=>({participantName:`${S} ${A+1}`,participantType:Ar,participantRole:xe})),{participants:y=[]}=En({participants:T,returnParticipants:!0,tournamentRecord:s}),E=y.map(St),P=s.participants?.filter(({participantId:A})=>E.includes(A))??[];f.push(...P)}if(!f.length)return{error:lf};if(t)for(let h of f)h.individualParticipantIds=[];else{let h=f.map(S=>S).flat();e?.length?d=d.filter(S=>!h.includes(S)):o=o?.filter(({participantId:S})=>!h.includes(S))}if(!e?.length&&!o?.length)return{error:ap,info:"Nothing to be done"};if(!o.length){for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(!d.includes(S))continue;if(T!==Et)return{error:Pn,participant:h};let y=Po({scaleAttributes:a,participant:h})?.scaleItem,E=a?.accessor?y?.scaleValue?.[a?.accessor]:y?.scaleValue,P={participantId:S,scaleValue:E};o.push(P)}if(!o.length)return{error:re}}o.sort((h,S)=>a?.sortOrder?(S?.scaleValue||0)-(h?.scaleValue||0):(h?.scaleValue||1/0)-(S?.scaleValue||1/0));for(let h of o)if(!h.participantId)return{error:B,scaledParticipant:h};let g=0;for(;g<o.length;){for(let h of f){if(g+1>o.length)break;let S=o[g];h.individualParticipantIds.push(S.participantId),g++}f.reverse()}let I=f.map(St);for(let h of s.events??[]){if(h.eventType!==Or)continue;let S=(h.entries??[]).filter(T=>I.includes(T.participantId));for(let T of S){let y=T.participantId,P=f.find(U=>U.participantId===y)?.individualParticipantIds;h.entries=(h.entries??[]).filter(U=>!P.includes(U.participantId)),(h.drawDefinitions??[]).forEach(U=>{U.entries=(U.entries??[]).filter(N=>!P.includes(N.participantId))});let{flightProfile:A}=Ht({event:h});(A?.flights||[]).forEach(U=>{U.drawEntries=(U.drawEntries||[]).filter(N=>!P.includes(N.participantId))})}}return{...C,scaledParticipants:o}}function JM(t){let e=et(t,[{[ne]:!0,[wf]:!0},{ratingType:!1,[tr]:s=>je[s]}]);if(e.error)return e;let r=`${t.ratingType}.${Qm}`,n=t.asDynamic?r:t.ratingType,o=[Pi,Ui,t.eventType,n].join("."),i=t.tournamentRecord.participants??[];for(let s of i)s.timeItems&&(s.timeItems=s.timeItems.filter(a=>a.itemType!==o));return{...C}}function ZM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=j0({...t,tournamentRecord:r});if(n.error&&n.error!==$c)return n}return{...C}}function j0({tournamentRecord:t,penaltyId:e}){if(!t)return{error:q};if(!e)return{error:uf};let r=t?.participants??[],n=[],o=!1,i;return r.forEach(s=>{let a=!1;s.penalties=(s.penalties??[]).filter(c=>(c.penaltyId===e&&(a=!0,o||(i=c,o=!0)),a&&n.push(s),c.penaltyId!==e))}),i&<({topic:rr,payload:{tournamentId:t.tournamentId,participants:n}}),i?{...C,penalty:i}:{error:$c}}var Y0=({penaltyId:t=Nt()}={})=>({refereeParticipantId:void 0,penaltyCode:void 0,penaltyType:void 0,extensions:void 0,matchUpId:void 0,createdAt:void 0,issuedAt:void 0,notes:void 0,penaltyId:t}),PE=Y0;function tR(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=q0({...t,tournamentRecord:r});if(n.error&&n.error!==$c||n.success)return n}return{error:$c}}function q0({tournamentRecord:t,modifications:e,penaltyId:r}){if(!t)return{error:q};if(!e)return{error:B,modifications:e};if(!r)return{error:uf};let n=t?.participants??[],o=Object.keys(PE()).filter(c=>c!=="penaltyId"),i=Object.keys(e).filter(c=>o.includes(c));if(!i.length)return{error:up};let s,a=[];return n.forEach(c=>{let u=!1;c.penalties=(c.penalties??[]).map(p=>(p.penaltyId===r&&(u=!0,i.forEach(m=>Object.assign(p,{[m]:e[m]})),s||(s=p)),p)),u&&a.push(c)}),s&<({topic:rr,payload:{tournamentId:t.tournamentId,participants:a}}),s?{...C,penalty:s}:{error:$c}}function eR(t,e,r){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:pt(Object.keys(t).concat(Object.keys(e))).reduce((o,i)=>{if(!e[i])o[i]=t[i];else if(!t[i])o[i]=e[i];else if(typeof t[i]!=typeof e[i])o[i]=e[i];else if(Array.isArray(t[i]))if(r===!0||Array.isArray(r)&&r.includes(i)){let s=pt(t[i].map(a=>JSON.stringify(a)).concat(e[i].map(a=>JSON.stringify(a)))).map(a=>JSON.parse(a));o[i]=s}else o[i]=e[i];else typeof t[i]=="object"?o[i]=eR(t[i],e[i],r):o[i]=e[i];return o},{})}function rR({participants:t=[],tournamentRecord:e,arraysToMerge:r}){if(!e)return{error:q};e.participants||(e.participants=[]);let n=t.filter(Hr(ao)).map(u=>({[u.participantId]:u})),o=Object.assign({},...n),i=[];e.participants=e.participants.map(u=>{if(o[u.participantId]){let p=eR(u,o[u.participantId],r);return i.push(p),p}return u});let s=e.participants.map(Hr(ao))||[],a=t.filter(({participantId:u})=>!s.includes(u)),{topics:c}=Lr();return a.length&&(e.participants=e.participants.concat(...a),c.includes(ci)&<({topic:ci,payload:{participants:a}})),i.length&&c.includes(rr)&<({topic:rr,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:a.length,...C}}function nR(t){let{tournamentRecord:e,participantIds:r}=t,n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o;for(let i of Object.values(n)){let a=(Ft({tournamentRecord:i}).participants??[])?.map(St).filter(c=>r.includes(c));a.length&&(o=$0({...t,penaltyId:t.penaltyId??o,tournamentRecord:i,participantIds:a}).penaltyId)}return o?{...C,penaltyId:o}:{error:re}}function $0({refereeParticipantId:t,tournamentRecord:e,participantIds:r,penaltyCode:n,penaltyType:o,extensions:i,penaltyId:s,matchUpId:a,issuedAt:c,notes:u}){if(!e)return{error:q};if(!r)return{error:se};if(!o)return{error:RA};let m=(e?.participants??[]).filter(f=>r.includes(f.participantId));if(!m.length)return{error:re};let d=new Date().toISOString(),l=Object.assign(PE({penaltyId:s}),{refereeParticipantId:t,penaltyCode:n,penaltyType:o,matchUpId:a,createdAt:d,issuedAt:c,notes:u});return Array.isArray(i)&&i.forEach(f=>At({element:l,extension:f})),m.forEach(f=>{f.penalties||(f.penalties=[]),f.penalties.push(l)}),lt({topic:rr,payload:{tournamentId:e.tournamentId,participants:m}}),{...C,penaltyId:l.penaltyId}}function oR({participantRole:t=xe,tournamentRecord:e,persons:r}){if(!e)return{error:q};if(!Array.isArray(r))return{error:B};if(!Object.keys(Dd).includes(t))return{error:SA};let n=(e.participants||[]).map(({person:f})=>f?.personId).filter(Boolean),o=[],i=r.filter(f=>f&&(!f.personId||!n.includes(f.personId))).map(f=>(f.personId||(f.personId=Nt()),o.push(f.personId),f)),s=(f,g)=>Object.assign({},...Object.keys(f).filter(I=>!g.includes(I)).map(I=>({[I]:f[I]}))),a=i.map(f=>nt({extensions:f.participantExtensions,timeItems:f.participantTimeItems,participantType:Et,participantRole:t,person:s(f,["participantExtensions","participantTimeItems","pairedPersons"])})),c=0,u=0,p=En({participants:a,tournamentRecord:e});if(p.error)return p;u=p.addedCount||0;let m=[],d=Ft({participantFilters:{participantTypes:[Et]},tournamentRecord:e})?.participants??[];if(t===xe&&r.filter(({pairedPersons:f})=>f).forEach(({personId:f,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{let h=[f,I.personId].map(S=>zo({tournamentParticipants:d,personId:S})).filter(Boolean);if(h.length===2){let S=h.map(St);m.push(nt({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:xe,individualParticipantIds:S,participantType:ft}))}})}),m.length){if(p=En({participants:m,tournamentRecord:e}),p.error)return p;c=p.addedCount||0}let l=u+c;return{...C,addedCount:l,newPersonIds:o}}var gR={};Xt(gR,{bulkUpdatePublishedEventIds:()=>cy,getAllEventData:()=>uy,getCourtInfo:()=>Td,getDrawData:()=>cl,getEventData:()=>ul,getEventPublishStatus:()=>Jr,getPublishState:()=>As,getTournamentPublishStatus:()=>Ru,getVenueData:()=>Ac,mutate:()=>fR,publishEvent:()=>da,publishEventSeeding:()=>aR,publishOrderOfPlay:()=>dR,publishParticipants:()=>mR,query:()=>DN,setEventDisplay:()=>yl,unPublishEvent:()=>lR,unPublishEventSeeding:()=>cR,unPublishOrderOfPlay:()=>pR,unPublishParticipants:()=>uR});var fR={};Xt(fR,{publishEvent:()=>da,publishEventSeeding:()=>aR,publishOrderOfPlay:()=>dR,publishParticipants:()=>mR,setEventDisplay:()=>yl,unPublishEvent:()=>lR,unPublishEventSeeding:()=>cR,unPublishOrderOfPlay:()=>pR,unPublishParticipants:()=>uR});function aR({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:r,tournamentRecord:n,status:o=Cr,drawIds:i=[],event:s}){if(!n)return{error:q};if(!s)return{error:Ot};let a=Jr({event:s,status:o}),c=(a?.seeding?.seedingScaleNames||r)&&{...a?.seeding?.seedingScaleNames,...r},u=(a?.seeding?.stageSeedingScaleNames||e)&&{...a?.seeding?.stageSeedingScaleNames,...e},p=nt({stageSeedingScaleNames:u,seedingScaleNames:c,published:!0,drawIds:i});return ma({statusObject:{seeding:p},removePriorValues:t,status:o,event:s}),lt({topic:YU,payload:{tournamentId:n.tournamentId,eventId:s.eventId,drawIds:i}}),{...C}}function cR({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:r,status:n=Cr,drawIds:o,stages:i,event:s}){if(!r)return{error:q};if(!s)return{error:Ot};let a=Jr({event:s});if(a){let c=a.seeding;if(Array.isArray(i)&&c.stageSeedingScaleNames)for(let u of i)c.stageSeedingScaleNames[u]&&delete c.stageSeedingScaleNames[u];Array.isArray(e)&&c?.seedingScaleNames&&(c.seedingScaleNames=c.seedingScaleNames.filter(u=>!e.includes(u))),Array.isArray(o)&&c?.drawIds&&(c.drawIds=c.drawIds.filter(u=>!o.includes(u))),(!Object.values(c.stageSeedingScaleNames??{}).length&&!c.seedingScaleNames?.length&&!c.drawIds?.length||!i&&!e&&!o?.length)&&(delete c.stageSeedingScaleNames,delete c.seedingScaleNames,delete c.drawIds,c.published=!1),ma({statusObject:{seeding:c},removePriorValues:t,status:n,event:s})}return lt({topic:eg,payload:{tournamentId:r.tournamentId,eventId:s.eventId}}),{...C}}function uR(t){let e=Rr(t);if(!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=K0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function K0({removePriorValues:t=!0,tournamentRecord:e,status:r=Cr}){if(!e)return{error:q};let n=`${Ho}.${Wo}`,{timeItem:o}=nn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].participants,ro({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({payload:{tournamentId:e.tournamentId},topic:Mb}),{...C}}function pR(t){let e=Rr(t);if(!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=z0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function z0({removePriorValues:t=!0,tournamentRecord:e,status:r=Cr}){if(!e)return{error:q};let n=`${Ho}.${Wo}`,{timeItem:o}=nn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].orderOfPlay,ro({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({topic:rg,payload:{tournamentId:e.tournamentId}}),{...C}}function mR(t){let e=Rr(t);if(!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=Q0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function Q0({removePriorValues:t,tournamentRecord:e,status:r=Cr}){if(!e)return{error:q};let n=`${Ho}.${Wo}`,{timeItem:o}=nn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r].participants={published:!0},ro({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({payload:{tournamentId:e.tournamentId},topic:$U}),{...C}}function dR(t){let e=Rr(t);if(!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=X0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function X0({scheduledDates:t=[],removePriorValues:e,tournamentRecord:r,status:n=Cr,eventIds:o=[]}){if(!r)return{error:q};let i=`${Ho}.${Wo}`,{timeItem:s}=nn({element:r,itemType:i}),a=s?.itemValue||{[n]:{}};return a[n].orderOfPlay={published:!0,scheduledDates:t,eventIds:o},ro({timeItem:{itemValue:a,itemType:i},element:r,removePriorValues:e}),lt({topic:qU,payload:{tournamentId:r.tournamentId,scheduledDates:t,eventIds:o}}),{...C}}function lR({removePriorValues:t=!0,tournamentRecord:e,status:r=Cr,event:n}){if(!e)return{error:q};if(!n)return{error:Ot};let o=`${Ho}.${Wo}`,{timeItem:i}=Au({itemType:o,event:n}),s=i?.itemValue||{[r]:{}};return delete s[r].structureIds,delete s[r].drawDetails,delete s[r].drawIds,is({event:n,timeItem:{itemValue:s,itemType:o},removePriorValues:t}),ma({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:r,event:n}),lt({topic:tg,payload:{tournamentId:e.tournamentId,eventId:n.eventId}}),{eventId:n.eventId,...C}}var IR={};Xt(IR,{getEntryStatusReports:()=>Uw,getParticipantStats:()=>Aw,getStructureReports:()=>Dw,getVenuesReport:()=>Nw});function Aw({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:r,teamParticipantId:n,tournamentRecord:o,withScaleValues:i,tallyPolicy:s,matchUps:a}){if(!o)return{error:q};if(a&&!Array.isArray(a))return{error:dr};if(a=a??ye({tournamentRecord:o,participantsProfile:i?{withScaleValues:i}:void 0}).matchUps,!a?.length)return{error:no};let u=[];e&&u.push(e),n&&u.push(n);let p=u.length?{participantIds:u}:{participantTypes:[Ar]},m=Ft({participantFilters:p,tournamentRecord:o}).participants??[];if(!m.every(({participantType:U})=>U===Ar))return{error:wr};u.length||u.push(...m.map(St));let d=new Map,l=new Map,f=new Map,g=new Map,I=(U,N="")=>l.get(U)||l.set(U,{participantName:N,participantId:U,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(U);for(let U of m){let{participantId:N,individualParticipantIds:D}=U;g.set(N,D??[]),I(N,U.participantName)}if(n&&!g.get(n))return _({result:{error:re},context:{teamParticipantId:n}});if(e&&!g.get(e))return _({result:{error:re},context:{opponentParticipantId:e}});let h=[],S=U=>{let N=[[],[]];for(let M of U){let R=M.participant;if(R?.participantName){d.set(R.participantId,{participantName:R.participantName,ratings:R.ratings});let b=l.get(R.participantId);b&&(b.participantName=R.participantName)}}let D=({side:M,individualParticipantIds:R})=>M.participantId&&(!R?.length||R.includes(M.participantId))&&[M.participantId]||M.participant?.individualParticipantIds?.length&&(!R?.length||jt(R,M.participant?.individualParticipantIds).length===M.participant?.individualParticipantIds?.length)&&M.participant.individualParticipantIds;if(g.size){let M=(R,b)=>{for(let O of U){if(!O.participant)continue;let v=D({individualParticipantIds:b,side:O});if(v?.length){let x=O.sideNumber;if(!x)continue;let F=[R];r&&F.push(...v),N[x-1]=F;let w=l.get(R);for(let L of v.filter(Boolean))w&&!w.competitorIds.includes(L)&&w.competitorIds.push(L)}}};if(n)(!e||U.every(b=>b.participant&&(D({individualParticipantIds:g.get(n),side:b})||D({individualParticipantIds:g.get(e),side:b}))))&&M(n,g.get(n));else for(let[R,b]of g)M(R,b)}else if(r)for(let M of U){if(!M.participant)continue;let R=D({individualParticipantIds:[],side:M}),b=M.sideNumber;b&&(N[b-1]=R)}return N};for(let U of a){if(!ht(U))return{error:dr};let{matchUpStatus:N,matchUpFormat:D,matchUpType:M,winningSide:R,score:b,sides:O}=U;if(!O||!b||M===xr||N==="BYE")continue;let v=S(O);if(!v.filter(Boolean).length)continue;let x=t&&R&&Du({matchUp:U})?.competitiveness;h.push(U);let F=Lg({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),w=nT({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),{pointsTally:L,tiebreaksTally:k}=oT({matchUpFormat:D,score:b});v.forEach((G,H)=>{for(let K of G){let Y=d.get(K)?.participantName,j=I(K,Y);if(j){let V=(z,Q)=>Q.forEach((ut,ot)=>j[z][ot]+=ut),$=H?[...k].reverse():k,X=H?[...L].reverse():L,W=H?[...w].reverse():w,it=H?[...F].reverse():F;if(V("tiebreaks",$),V("points",X),V("games",W),V("sets",it),R){let z=R-1===H?0:1;j.matchUps[z]+=1}if(x){let z=x.toLowerCase();j.competitiveness[z]||(j.competitiveness[z]=[0,0]),j.competitiveness[z][H]+=1}if(N){let z=N.toLowerCase();j.matchUpStatuses[z]||(j.matchUpStatuses[z]=0),j.matchUpStatuses[z]+=1}}}})}let T=["tiebreaks","matchUps","points","games","sets"],y=["competitive","routine","decisive"],E=new Map,P=(U,N)=>(U??0)+(N??0);for(let[U,N]of l.entries()){for(let D of T){let M=N[D].reduce(P);if(M){let R=N[D][0]/M,b=`${D}Ratio`,O=parseFloat(R.toFixed(2));N[b]=O,f.set(U,!0),E.has(b)||E.set(b,[]),E.get(b)?.push(O)}}for(let D of y){let M=N.competitiveness?.[D]?.reduce(P);if(M){let R=N.competitiveness[D][0]/M,b=`${D}Ratio`,O=parseFloat(R.toFixed(2));N[b]=O}}}if(!n){let U=(N,D)=>D-N;for(let N of l.values())for(let D of T){let M=`${D}Ratio`;if(typeof N[M]=="number"){let R=E.get(M)?.sort(U).indexOf(N[M]);if(typeof R=="number"&&R>=0){let b=`${D}Rank`;N[b]=R+1}}}}let A={relevantMatchUps:h,...C};return n?(A.teamStats=l.get(n),e&&(A.opponentStats=l.get(e))):A.participatingTeamsCount=f.size,A.allParticipantStats=[...l.values()],A}function Pm({participant:t,eventType:e}){let r=t?.person?.personId,n=t?.person?.personOtherIds?.[0],o=t?.person?.tennisId,i=t?.ratings?.[e]?.find(({scaleName:u})=>u==="WTN"),s=i?.scaleValue,{wtnRating:a,confidence:c}=s||{};return{timeStamp:i?.scaleDate,personOtherId:n,confidence:c,wtnRating:a,personId:r,tennisId:o}}function Uw({tournamentRecord:t}){if(!t)return{error:q};let e=t.tournamentId,{participantMap:r}=Ft({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(ye({matchUpFilters:{matchUpTypes:[Ia,Gi]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:f,matchUpType:g})=>f?.flatMap(I=>g===Gi?I?.participant?.individualParticipantIds:I?.participant?.participantId||I.participantId).filter(Boolean)).filter(Boolean),i=[],s={},a={},c={},u=0,p=({id:f,entry:g,eventId:I,eventType:h})=>{let{qualifyingSeeding:S,mainSeeding:T,entryStatus:y,entryStage:E,drawId:P}=g;s[f]||(s[f]=[]);let{participant:A,events:U}=r?.[f]??{},N=Pm({participant:A,eventType:h}),D=U?.[I]?.ranking;y===xg&&i.push(f),s[f].push({participantType:A?.participantType,participantId:f,tournamentId:e,eventType:h,eventId:I,drawId:P,entryStatus:y,entryStage:E,...N,ranking:D,mainSeeding:T,qualifyingSeeding:S})};for(let f of t.events??[]){let g={},I=N=>{g[N]||(g[N]={count:0}),g[N].count+=1},{drawDefinitions:h=[],eventType:S,eventId:T}=f,y=h.flatMap(N=>{let{drawId:D,entries:M}=N;u+=1;let R=({stage:F,stageSequence:w})=>F===rt&&w===1||F===ct,O=(N.structures??[]).filter(R).flatMap(({positionAssignments:F})=>F).filter(Boolean).map(({participantId:F})=>F),v=({participantId:F})=>O.includes(F),x=F=>{let{participantId:w,entryStatus:L,entryStage:k}=F;I(L);let G=r?.[w]?.draws?.[D]?.seedAssignments?.[rt];return{qualifyingSeeding:r?.[w]?.draws?.[D]?.seedAssignments?.[ct],participantId:w,mainSeeding:G,entryStatus:L,entryStage:k,drawId:D}};return M?.filter(v).map(x)}),E=N=>{let D=N.participantId,M=r?.[D].participant.individualParticipantIds?.filter(R=>o.includes(R));return D&&{[D]:{individualParticipantIds:M}}};S===Ko?(()=>{let N=Object.assign({},...y.map(E).filter(Boolean)),D=M=>{N[M.participantId].individualParticipantIds.forEach(R=>{p({id:R,eventType:S,eventId:T,entry:M})})};y.forEach(D)})():y.forEach(N=>{p({id:N?.participantId,eventType:S,eventId:T,entry:N})});let A=Object.values(g).reduce((N,D)=>N+D.count,0);Object.keys(g).forEach(N=>{g[N].pct=g[N].count/A*100}),c[T]={tournamentId:e,eventId:T,entries:y,entryStatuses:g};let U=Object.assign({},...Xr.flatMap(N=>[{[N+"_count"]:g[N]?.count},{[N+"_pct"]:g[N]?.pct}]));a[T]={tournamentId:e,eventId:T,...U}}let m=Object.values(r??{}).filter(({participant:{participantType:f,participantRole:g}})=>f===Et&&g===xe),d=m.filter(({participant:f})=>!o.includes(f.participantId)).map(({participant:f})=>f.participantId),l={nonParticipatingEntriesCount:d.length,individualParticipantsCount:m.length,eventsCount:Object.values(c).length,nonParticipatingParticipantIds:d,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(a).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(c).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}}function Pw({eventType:t,matchUps:e,eventId:r,drawId:n}){let o={},i=g=>{let I=g?.matchUpFormat;I&&(o[I]||(o[I]=0),o[I]+=1)},s=e.filter(g=>r?g.eventId===r:g.drawId===n).reduce((g,I)=>(i(I),(I.sides??[]).flatMap(h=>(h?.participant?.individualParticipants||[h?.participant]).filter(Boolean)).forEach(h=>g[h.participantId]=h),g),{}),a=Object.values(s),c=a.map(g=>Pm({participant:g,eventType:t})).filter(({wtnRating:g})=>g),u=(a.length-c.length)/a.length*100,p=c.reduce((g,I)=>{let{wtnRating:h,confidence:S}=I;return g.totalWTN+=h,g.totalConfidence+=S,g},{totalWTN:0,totalConfidence:0}),m=c?.length?p.totalWTN/c.length:0,d=c?.length?p.totalConfidence/c.length:0,f=Object.values(o).reduce((g,I)=>g+(I||0),0);return{matchUpFormatCounts:o,matchUpsCount:f,avgConfidence:d,pctNoRating:u,avgWTN:m}}function Dw(t){let{tournamentRecord:e,extensionProfiles:r,firstFlightOnly:n,firstStageSequenceOnly:o=!0}=t;if(!e)return{error:ha};let i=[],s={},a={},c=[],u=Object.assign({},...(r??[]).map(({name:I,label:h,accessor:S})=>{let T=mt({element:e,name:I})?.extension?.value,y=S?ys({element:T,accessor:S})?.value:T;return{[h??I]:y}})),p=e?.tournamentId,d=ye({participantsProfile:{withScaleValues:!0},tournamentRecord:e}).matchUps??[],l=I=>nn({itemType:Yf,itemSubTypes:[Ao],element:{timeItems:I}})?.timeItem?.itemValue?.scaleBasis,f=({positionManipulations:I})=>{I?.forEach(h=>{let{structureId:S,name:T}=h,y=h.drawPositions??[h.drawPosition];s[S]??=[],s[S].push(`${T}: ${y.join("/")}`)})},g=e?.events?.flatMap(({timeItems:I,drawDefinitions:h=[],extensions:S,eventType:T,eventName:y,eventId:E,category:P})=>{let U=S?.find(x=>x.name===pn)?.value?.flights?.map(x=>({[x.drawId]:x.flightNumber})),N=U&&Object.assign({},...U),D=S?.find(x=>x.name===Pa),M=I?.find(x=>x.itemType===Pa),R=D?.value?.length??M?.itemValue??0,b=Object.values(N??{}),O=N&&Math.min(...b),v=l(I);return a[E]={seedingBasis:v?JSON.stringify(v):void 0,totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:R,tournamentId:p,eventId:E},h.filter(x=>!n||!U||N[x.drawId]===O).flatMap(x=>{let{matchUpFormat:F,tieFormat:w,timeItems:L,extensions:k,structures:G,drawName:H,drawType:K,drawId:Y}=x,{matchUpFormatCounts:j,matchUpsCount:V,avgConfidence:$,pctNoRating:X,avgWTN:W}=Pw({eventType:T,matchUps:d,drawId:Y}),it=l(L)??v,z=J0({extensions:k}),Q=z?.length??0;return f({positionManipulations:z}),a[E].totalPositionManipulations+=Q,a[E].generatedDrawsCount+=1,Q>a[E].maxPositionManipulations&&(a[E].maxPositionManipulations=Q),G?.filter(ut=>(ut.stageSequence===1||!o)&&[ct,rt,qe,fe].includes(ut.stage)).map(ut=>{let ot=[rt,fe].includes(ut.stage)?d.find(Cn=>Cn.structureId===ut.structureId&&Cn.finishingRound===1&&Cn.winningSide):void 0;ut.stage===rt&&i.push({eventName:y,drawName:H,structureId:ut.structureId});let Rt=ot?.sides?.find(Cn=>Cn.sideNumber===ot.winningSide)?.participant,De=Rt?.participantType===Ar&&Rt.participantId,qt=Rt?.participantType===ft?Rt.individualParticipants:[],Se=Pm({participant:qt?.[0]??Rt,eventType:T}),{personId:_r,personOtherId:dn,tennisId:hr,confidence:Xe,wtnRating:Zt}=Se||{},Pt=Pm({participant:qt?.[1],eventType:T}),{personId:ce,personOtherId:ue,tennisId:Fe,confidence:te,wtnRating:Je}=Pt||{},{ageCategoryCode:$t,categoryName:ir,subType:fr}=P??{},pe=ut.matchUpFormat??F,Sr=(j[pe]??0)/V*100,{tieFormatName:jr,tieFormatDesc:Kt}=sl(w),{tieFormatName:Te,tieFormatDesc:gr}=sl(ut.tieFormat),Ee=Kt===gr,Rn=!Ee&&Te,ee=ut.tieFormat&&!Ee&&gr,Ur=z?.filter(Cn=>Cn.structureId===ut.structureId)?.length??0;return{...u,tournamentId:p,eventId:E,structureId:ut.structureId,drawId:Y,eventType:T,category:fr,categoryName:ir,ageCategoryCode:$t,flightNumber:N?.[Y],drawType:K,stage:ut.stage,seedingBasis:it?JSON.stringify(it):void 0,winningPersonId:_r,winningPersonOtherId:dn,winningPersonTennisId:hr,winningPersonWTNrating:Zt,winningPersonWTNconfidence:Xe,winningPerson2Id:ce,winningPerson2OtherId:ue,winningPerson2TennisId:Fe,winningPerson2WTNrating:Je,winningPerson2WTNconfidence:te,winningTeamId:De,positionManipulations:Ur,pctNoRating:X,matchUpFormat:pe,pctInitialMatchUpFormat:Sr,matchUpsCount:V,drawTieFormatName:jr,drawTieFormatDesc:Kt,tieFormatName:Rn,tieFormatDesc:ee,avgConfidence:$,avgWTN:W}})})});return i.forEach(({eventName:I,drawName:h,structureId:S})=>{s[S]?.length&&c.push({eventName:I,drawName:h,actions:s[S]})}),{eventStructureReports:Object.values(a),structureReports:g,flightReports:c}}function J0({extensions:t}){return t?.find(({name:e})=>e===lc)?.value?.slice(1)}function Nw({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:r,venueIds:n=[],dates:o=[]}){if(!Array.isArray(o))return{error:B,dates:o};if(!Array.isArray(n))return{error:B,venueIds:n};if(!(e&&Object.keys(e).filter(l=>!r||l===r)||[]).length)return{error:xt};if(!o.every(Mr))return{error:Ye};let a=Ro({tournamentRecords:e,ignoreDisabled:t,dates:o});if(a.error)return a;let c=a?.venues?.filter(({venueId:l})=>!n?.length||n.includes(l)),u=a.courts?.reduce((l,f)=>(f.dateAvailability?.forEach(g=>{let I=g.date;l.includes(I)||l.push(I)}),l),[]).filter(l=>!o.length||o.includes(l)),p={venueIds:c?.map(({venueId:l})=>l)},{matchUps:m}=Mn({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:p});return{venuesReport:c?.map(l=>Z0(u,l,m))}}function Z0(t,e,r){let{venueId:n,courts:o,venueName:i}=e,s={};return t.forEach(a=>{let c=0,u=0,p=0;for(let l of o){let f=l.dateAvailability.find(h=>h.date===a),I=(f&&_s({courtDate:f}).timeSlots)?.reduce((h,S)=>{let{startTime:T,endTime:y}=S,E=Yt(y)-Yt(T);return h+E},0);I&&(p+=1),c+=I}let m=r.filter(({schedule:l})=>l.venueId===n&&zn(a,l.scheduledDate));m.forEach(({schedule:l})=>{let f=zt(l.scheduledTime),g=$r(f,l.averageMinutes),I=Yt(g)-Yt(f);u+=I});let d=c?(u/c*100).toFixed(2):"100";s[a]={scheduledMatchUpsCount:m.length,availableCourts:p,availableMinutes:c,scheduledMinutes:u,percentUtilization:d}}),{venueId:n,venueName:i,venueReport:s}}var RR={};Xt(RR,{addMatchUpCourtOrder:()=>Xy,addMatchUpEndTime:()=>Zy,addMatchUpOfficial:()=>SM,addMatchUpResumeTime:()=>eE,addMatchUpScheduleItems:()=>Im,addMatchUpScheduledDate:()=>fm,addMatchUpScheduledTime:()=>ii,addMatchUpStartTime:()=>Jy,addMatchUpStopTime:()=>tE,addSchedulingProfileRound:()=>AI,allocateTeamMatchUpCourts:()=>gm,assignMatchUpCourt:()=>as,assignMatchUpVenue:()=>la,bulkRescheduleMatchUps:()=>UR,bulkScheduleMatchUps:()=>Wc,bulkScheduleTournamentMatchUps:()=>Xu,bulkUpdateCourtAssignments:()=>TR,calculateScheduleTimes:()=>DI,clearMatchUpSchedule:()=>DR,clearScheduledMatchUps:()=>Sm,courtGridRows:()=>dl,findMatchUpFormatTiming:()=>im,findVenue:()=>ti,generateBookings:()=>hm,generateVirtualCourts:()=>mm,getMatchUpsToSchedule:()=>pl,getPersonRequests:()=>ki,getProfileRounds:()=>ml,getScheduledRoundsDetails:()=>$u,getSchedulingProfile:()=>oi,getSchedulingProfileIssues:()=>my,matchUpScheduleChange:()=>PR,modifyMatchUpFormatTiming:()=>nI,mutate:()=>MR,proAutoSchedule:()=>SR,proConflicts:()=>ER,publicFindCourt:()=>PS,query:()=>CN,removeEventMatchUpFormatTiming:()=>Tl,removeMatchUpCourtAssignment:()=>hR,reorderUpcomingMatchUps:()=>AR,scheduleMatchUps:()=>yR,scheduleProfileRounds:()=>Tm,setMatchUpDailyLimits:()=>NR,setMatchUpHomeParticipantId:()=>fI,setSchedulingProfile:()=>Lc,toggleParticipantCheckInState:()=>Al,validateSchedulingProfile:()=>sm});var MR={};Xt(MR,{addMatchUpCourtOrder:()=>Xy,addMatchUpEndTime:()=>Zy,addMatchUpOfficial:()=>SM,addMatchUpResumeTime:()=>eE,addMatchUpScheduleItems:()=>Im,addMatchUpScheduledDate:()=>fm,addMatchUpScheduledTime:()=>ii,addMatchUpStartTime:()=>Jy,addMatchUpStopTime:()=>tE,addSchedulingProfileRound:()=>AI,allocateTeamMatchUpCourts:()=>gm,assignMatchUpCourt:()=>as,assignMatchUpVenue:()=>la,bulkRescheduleMatchUps:()=>UR,bulkScheduleMatchUps:()=>Wc,bulkScheduleTournamentMatchUps:()=>Xu,bulkUpdateCourtAssignments:()=>TR,calculateScheduleTimes:()=>DI,clearMatchUpSchedule:()=>DR,clearScheduledMatchUps:()=>Sm,findMatchUpFormatTiming:()=>im,generateBookings:()=>hm,generateVirtualCourts:()=>mm,matchUpScheduleChange:()=>PR,modifyMatchUpFormatTiming:()=>nI,proAutoSchedule:()=>SR,proConflicts:()=>ER,removeEventMatchUpFormatTiming:()=>Tl,removeMatchUpCourtAssignment:()=>hR,reorderUpcomingMatchUps:()=>AR,scheduleMatchUps:()=>yR,scheduleProfileRounds:()=>Tm,setMatchUpDailyLimits:()=>NR,setMatchUpHomeParticipantId:()=>fI,setSchedulingProfile:()=>Lc,toggleParticipantCheckInState:()=>Al,validateSchedulingProfile:()=>sm});function DI({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:r=90,remainingScheduleTimes:n,clearScheduleDates:o,tournamentRecords:i,periodLength:s,scheduleDate:a,startTime:c,venueIds:u,endTime:p}){if(typeof i!="object"||!Object.keys(i).length)return{error:xt};s=s??zu({recoveryMinutes:e,averageMatchUpMinutes:r});let{courts:m,venues:d}=Ro({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),l=m?.filter(M=>!u||u.includes(M.venueId));c||(c=l?.reduce((M,R)=>{let O=R.dateAvailability?.find(v=>!v.date||zn(a,v.date))?.startTime??R.startTime;return O&&(!M||Yt(O)<Yt(M))?O:M},void 0)),p||(p=l?.reduce((M,R)=>{let O=R.dateAvailability?.find(v=>!v.date||zn(a,v.date))?.endTime??R.endTime;return O&&(!M||Yt(O)>Yt(M))?O:M},void 0));let f=Object.values(i),g=Object.assign({},...f.map(M=>(M.events??[]).map(R=>{let{scheduleTiming:b}=Ra({tournamentRecord:M,event:R});return{[R.eventId]:{event:R,scheduleTiming:b}}})).flat()),h=Ku({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:a,venueIds:u}}),S=h?.dateMatchUps??[],T=h?.completedMatchUps??[],y=[];y.push(...S),y.push(...T);let E={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:e}}]},P=y?.map(({eventId:M,schedule:R,matchUpFormat:b})=>{let{event:O,scheduleTiming:v}=g[M],x=O?.eventType,F={...v,defaultTiming:E,matchUpFormat:b},{averageMinutes:w,recoveryMinutes:L}=xp({eventType:x,timingDetails:F}),{courtId:k,venueId:G}=R,H=zt(R.scheduledTime),K=$r(H,w);return{recoveryMinutes:L,averageMinutes:w,periodLength:s,startTime:H,endTime:K,courtId:k,venueId:G}}),A={calculateStartTimeFromCourts:t,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:a,clearScheduleDates:o,periodLength:s,startTime:c,endTime:p,bookings:P,courts:l},{scheduleTimes:U}=El(A),N=u?.length===1&&u[0]||d?.length===1&&d[0].venueId||void 0,D=y.map(Ue);return{venueId:N,scheduleTimes:U,dateScheduledMatchUpIds:D}}function hR(t){let e=et(t,[{[Re]:!0}]);if(e.error)return e;let{removePriorValues:r,tournamentRecords:n,tournamentId:o,courtDayDate:i,matchUpId:s,courtId:a,drawId:c}=t,u=n[o];if(!u)return{error:q};let{drawDefinition:p,event:m}=jo({tournamentRecord:u,drawId:c});if(!p)return{error:Z};let d=Vt({drawDefinition:p,event:m,matchUpId:s});if(d.error)return d;if(d?.matchUp?.matchUpType===xr){let{itemValue:l}=Zo({timeItems:d.matchUp.timeItems??[],itemType:lo}),f=a&&l.filter(I=>I.courtId!==a);return Zr({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:p,matchUpId:s,timeItem:{itemType:lo,itemValue:f}})}else return as({tournamentRecord:u,drawDefinition:p,courtDayDate:i,courtId:"",matchUpId:s})}function SR({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:r,matchUps:n}){if(!Br(n))return{error:B};if(n.some(({hasContext:g})=>!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Kc};let i=Ku({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(i.error)return i;let{rows:s}=i,a=[],c=g=>[(g.sides||[]).map(I=>[I.participantId,I.participant?.individualParticipantIds]),(g.potentialParticipants||[]).flat().map(I=>[I.participantId,I.individualParticipantIds])].flat(1/0).filter(Boolean),u=s?.reduce((g,I)=>{let h=[],S=[];Object.values(I).forEach(y=>{if(ht(y)&&(y.matchUpId&&(h.push(y.matchUpId),a.push(y)),y.sides)){let E=c(y);S.push(...E)}});let T=Object.values(I).filter(y=>ht(y)&&!y.matchUpId);return g.concat({matchUpIds:h,availableCourts:T,rowId:I.rowId,participantIds:S})},[]);n.filter(({matchUpStatus:g})=>g&&g!=="BYE"&&(t||!ae.includes(g))).sort(xi);let p=an({matchUps:n.concat(a),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,m=[],d=[];for(;n.length&&u.length;){let g=u.shift(),I=[];for(;n.length&&g.availableCourts.length;){let h=n.concat(I).map(D=>D.matchUpId),S=n.shift(),T=S?.matchUpId,y=T&&p[T].matchUpIds.concat(p[T].dependentMatchUpIds),E=T&&h.some(D=>p[T].matchUpIds.includes(D)),P=T&&d.some(D=>p[T].dependentMatchUpIds.includes(D)),A=g.matchUpIds.some(D=>y.includes(D)),U=c(S),N=g.participantIds.some(D=>U.includes(D));if(S&&!A&&!E&&!N&&!P){let D=g.availableCourts.shift();Object.assign(S.schedule,D.schedule),Object.assign(D,S),m.push(S),g.participantIds.push(...U),g.matchUpIds.push(T)}else S&&I.push(S)}n.push(...I),d.push(...g.matchUpIds)}let l=m.map(({matchUpId:g,tournamentId:I,schedule:h,drawId:S})=>({tournamentId:I,matchUpId:g,drawId:S,schedule:{...h,scheduledDate:r}}));return i=Wc({tournamentRecords:e,matchUpDetails:l}),{...i,scheduled:m,notScheduled:n}}function TR(t){let{courtDayDate:e}=t,r=et(t,[{courtAssignments:!0,[He]:Be,[kr]:st},{[Re]:!0}]);if(r.error)return r;let n=t.courtAssignments.reduce((s,a)=>{let{tournamentId:c}=a;return s[c]||(s[c]=[]),s[c].push(a),s},{}),o;return Object.keys(n).every(s=>{let a=t[Re][s];if(!a)return o={error:q},!1;let c=n[s].reduce((p,m)=>{let{drawId:d}=m;return p[d]||(p[d]=[]),p[d].push(m),p},{});Object.keys(c).every(p=>{let{drawDefinition:m}=ze({tournamentRecord:a,drawId:p});return m?(c[p].every(d=>{let{matchUpId:l,courtId:f}=d,g=as({tournamentRecord:a,drawDefinition:m,courtDayDate:e,matchUpId:l,courtId:f});if(g.success)return g?.success;o={error:kA}}),!0):(o={error:Z},!1)})}),o||C}function yR(t){let{tournamentRecords:e,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:o=0,recoveryMinutesMap:i,matchUpPotentialParticipantIds:s={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:p=!0,remainingScheduleTimes:m,clearScheduleDates:d,periodLength:l=30,scheduleDate:f,matchUpIds:g,venueIds:I,startTime:h,endTime:S,dryRun:T}=t,y=et(t,[{[Re]:!0,[mc]:!0},{[tr]:Mr,[kr]:Ye,[db]:!0},{[tr]:V=>!V||!isNaN(V),[Ib]:!1,[kr]:B,[hb]:!1,[Sb]:!1}]);if(y.error)return y;let E=t.competitionMatchUps??Mn({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],P=t.matchUpDependencies??an({includeParticipantDependencies:!0,matchUps:E,tournamentRecords:e}).matchUpDependencies;E.forEach(V=>{V.schedule?.scheduledDate&&zn(f,Ut(V.schedule.scheduledDate))&&ua({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:V})});let A=g.map(V=>E.find($=>$.matchUpId===V)).filter(Boolean),{venueId:U,scheduleTimes:N,dateScheduledMatchUpIds:D}=DI({tournamentRecords:e,remainingScheduleTimes:m,startTime:zt(h),endTime:zt(S),scheduleDate:Ut(f),averageMatchUpMinutes:n,clearScheduleDates:d,periodLength:l,venueIds:I}),M={},R=[],b={},O={},v={};E.filter(({matchUpId:V})=>D?.includes(V)).forEach(V=>{TI({matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUp:V,value:1});let $=V.schedule?.scheduledTime;if($){b[V.matchUpId]=$;let X=i?.[V.matchUpId];Bc({recoveryMinutes:X||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:P,scheduleTime:$,matchUp:V})}});let F=A.filter(V=>{let $=D?.includes(V.matchUpId),X=["BYE",Gt,ge,vr,Me,Bt].includes(V?.matchUpStatus);return!$&&!V.winningSide&&!X}),{matchUpMap:w,overLimitMatchUpIds:L,participantIdsAtLimit:k}=F.reduce((V,$)=>{let{drawId:X,tournamentId:W,matchUpType:it}=$,{participantIdsAtLimit:z,relevantParticipantIds:Q}=Cl({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,matchUpDailyLimits:u,matchUp:$});return z?.length?(V.overLimitMatchUpIds.push($.matchUpId),V.participantIdsAtLimit.push(...z),V):(Q.forEach(ut=>{Ya({individualParticipantProfiles:a,participantId:ut});let ot=a[ut].counters;ot[it]?ot[it]+=1:ot[it]=1,ot[fo]?ot[fo]+=1:ot[fo]=1}),V.matchUpMap[W]||(V.matchUpMap[W]={}),V.matchUpMap[W][X]?V.matchUpMap[W][X].push($):V.matchUpMap[W][X]=[$],ua({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:$}),V)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter(({matchUpId:V})=>!L.includes(V));let G=0,H=N?.length??0,{personRequests:K}=ki({tournamentRecords:e,requestType:Hc});for(;N?.length&&F.length&&G<=H;){G++;let{scheduleTime:V}=N.shift(),$=F.find(X=>{let{matchUpId:W}=X,{dependenciesScheduled:it,remainingDependencies:z}=Nl({matchUpScheduleTimes:b,matchUpDependencies:P,allDateMatchUpIds:r,matchUp:X});if(!it)return v[W]||(v[W]=[]),v[W].push({scheduleTime:V,remainingDependencies:z}),!1;let{enoughTime:Q}=Rl({individualParticipantProfiles:a,matchUpNotBeforeTimes:c,matchUpDependencies:P,scheduleTime:V,matchUp:X});if(!Q)return O[W]||(O[W]=[]),O[W].push({scheduleTime:V}),!1;let{conflicts:ut}=Ml({potentials:p,averageMatchUpMinutes:n,requestConflicts:M,personRequests:K,scheduleTime:V,scheduleDate:f,matchUp:X});if(ut?.length)return!1;let ot=i?.[X.matchUpId];return Bc({recoveryMinutes:ot||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:P,scheduleTime:V,matchUp:X}),b[X.matchUpId]=V,!0});F=F.filter(({matchUpId:X})=>X!==$?.matchUpId),$||R.push(V)}F.forEach(V=>{TI({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,value:-1,matchUp:V})});let Y=[];Object.keys(w).forEach(V=>{let $=e[V];$&&Object.keys(w[V]).forEach(X=>{let{drawDefinition:W}=jo({tournamentRecord:$,drawId:X});W&&w[V][X].forEach(({matchUpId:z})=>{let Q=b[z];if(Q){let ut=Q.split(":").map(oo).join(":"),ot=`${Ut(f)}T${ut}`;T?Y.push(z):(ii({drawDefinition:W,matchUpId:z,scheduledTime:ot}).success&&Y.push(z),U&&la({tournamentRecords:e,tournamentRecord:$,drawDefinition:W,matchUpId:z,venueId:U}))}})})});let j=od(F);return{...C,requestConflicts:Object.values(M),remainingScheduleTimes:N?.map(({scheduleTime:V})=>V),individualParticipantProfiles:a,matchUpNotBeforeTimes:c,participantIdsAtLimit:k,skippedScheduleTimes:R,overLimitMatchUpIds:L,scheduledMatchUpIds:Y,noTimeMatchUpIds:j,recoveryTimeDeferred:O,dependencyDeferred:v}}function ER({tournamentRecords:t,matchUps:e}){if(!Br(e))return{error:no};if(e.some(({matchUpId:f,hasContext:g})=>f&&!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Kc};let r=Math.max(...e.map(({schedule:f})=>f?.courtOrder||1).map(f=>dt(f))),n=tt(1,r+1).map(f=>e.filter(g=>dt(g.schedule?.courtOrder)===f)),o={},i={},s={};n.flat().filter(Boolean).sort(xi).forEach(({schedule:f})=>delete f[fg]);let c=pt(e.map(({drawId:f})=>f)),u=an({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:c}).matchUpDependencies,p=n.map((f,g)=>f.reduce((I,h)=>{if(!h.matchUpId)return I;let{matchUpId:S,winnerMatchUpId:T,loserMatchUpId:y,schedule:E,sides:P,potentialParticipants:A}=h,U=E?.courtId;o[S]=g,i[U]=[],I.matchUpIds.push(S),s[S]=h;let N=u[S].matchUpIds;N.length&&I.sourceMatchUpIds.push(...N);let D=P?.map(R=>[R.participant?.individualParticipantIds,R.participantId]).flat().filter(Boolean)??[],M=A?.flat().map(({individualParticipantIds:R,participantId:b})=>[R,b]).flat().filter(Boolean)||[];return I.participantIds.push(...M,...D),T&&I.targetMatchUpIds.push(T),y&&I.targetMatchUpIds.push(y),I},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),m=(f,g)=>u[f].sources.reduce((I,h,S)=>h.includes(g)&&S+1||I,0),d=p.map(()=>[]),l=(f,g,I,h)=>{if(!s[f].schedule[fg]){s[f].schedule[fg]=g,s[f].schedule[iP]=h,d[o[f]].push({matchUpId:f,issueType:I,issueIds:h,issue:g});let S=s[f].schedule.courtId;i[S]||(i[S]=[]),i[S].push({matchUpId:f,issue:g,issueType:I,issueIds:h})}};return p.forEach((f,g)=>{let I=g?p[g-1]:void 0,h=p.slice(g+1),S={},T=Er(f.participantIds),y=Object.keys(T).filter(A=>T[A]>1),E=f.matchUpIds.filter(A=>u[A].participantIds.some(U=>y.includes(U)));E.forEach(A=>{S[A]||(S[A]={}),S[A][Tc]||(S[A][Tc]=E.filter(U=>U!==A))});let P=I&&f.participantIds.filter(A=>I.participantIds.includes(A));P&&P.forEach(A=>{let U=f.matchUpIds.concat(I.matchUpIds).filter(N=>u[N].participantIds.includes(A));U.forEach(N=>{S[N]||(S[N]={}),S[N][yc]||(S[N][yc]=U.filter(D=>D!==N))})}),f.matchUpIds.forEach(A=>{let U=u[A].matchUpIds;for(let D of h){let M=D.matchUpIds.filter(R=>U.includes(R));M?.length&&(M.forEach(R=>l(R,yS,Ca,[A])),l(A,yS,Ca,M))}if(S[A]?.[Tc]&&l(A,Tc,TS,S[A][Tc]),f.sourceMatchUpIds.includes(A)){let D=f.matchUpIds.filter(M=>u[M].matchUpIds.includes(A));l(A,Tc,Ca,D),f.matchUpIds.filter(M=>u[M].matchUpIds.includes(A)).forEach(M=>l(M,Tc,Ca,[A]))}let N=I?.matchUpIds?.filter(D=>m(A,D)>1);if(N?.length&&(l(A,ES,Ca,N),N.forEach(D=>l(D,ES,Ca,[A]))),S[A]?.[yc]&&l(A,yc,TS,S[A][yc]),I?.targetMatchUpIds?.includes(A)){let D=s[A].schedule.courtId,M=U.filter(b=>I.matchUpIds.includes(b));M.some(b=>s[b].schedule.courtId===D)||(M.forEach(b=>l(b,yc,Ca,[A])),l(A,yc,Ca,M))}})}),{courtIssues:i,rowIssues:d}}function AR(t){let e="reorderUpcomingMatchUps",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return _({result:{error:xt},stack:e});let{matchUpsContextIds:n,firstToLast:o}=t;if(!n)return _({result:{error:st},stack:e});let i=n?.length;if(!i)return{...C};let s=0;return n.forEach((c,u)=>{let{tournamentId:p,drawId:m,matchUpId:d}=c,l=u+(o?-1:1);l<0&&(l=i-1),l===i&&(l=0);let f=n[l].schedule.scheduledTime,g=a({tournamentId:p,scheduledTime:f,matchUpId:d,drawId:m});if(g.success)s++;else return g}),s===i?C:_({result:{error:FA},stack:e});function a({tournamentId:c,scheduledTime:u,matchUpId:p,drawId:m}){let d=r[c],{drawDefinition:l}=jo({tournamentRecord:d,drawId:m});return l?ii({drawDefinition:l,scheduledTime:u,matchUpId:p}):{error:br}}}function UR(t){let{scheduleChange:e,matchUpIds:r,dryRun:n}=t;if(!r||!Array.isArray(r))return{error:ps};if(typeof e!="object")return{error:B};let o=Rr(t),i=[],s=[];for(let c of Object.values(o)){let u=tB({tournamentRecord:c,scheduleChange:e,matchUpIds:r,dryRun:n});if(u.error)return u;Array.isArray(u.notRescheduled)&&s.push(...u.notRescheduled);let p=od(u.notRescheduled),m=[];u.rescheduled?.forEach(d=>{let{matchUpId:l}=d;p.includes(l)&&m.push(l),i.push(d)}),m.length&&(s=u?.notRescheduled?.filter(({matchUpId:d})=>!m.includes(d))||[])}let a=!!(i.length&&!s.length);return{...C,rescheduled:i,notRescheduled:s,allRescheduled:a}}function tB({tournamentRecord:t,scheduleChange:e,matchUpIds:r,dryRun:n}){if(!t)return{error:q};if(!r||!Array.isArray(r))return{error:ps};if(typeof e!="object")return{error:B};let o=[],i=[],{minutesChange:s,daysChange:a}=e;if(!s&&!a)return{...C};if(s&&isNaN(s))return{error:B};if(a&&isNaN(a))return{error:B};let{matchUps:c}=ye({matchUpFilters:{matchUpIds:r},tournamentRecord:t}),u=({matchUpStatus:y})=>!ae.includes(y),p=c?.filter(y=>Ha({schedule:y.schedule})).filter(y=>u({matchUpStatus:y.matchUpStatus}));if(!p?.length)return{...C};let{tournamentInfo:m}=bs({tournamentRecord:t}),{startDate:d,endDate:l}=m,f=p?.reduce((y,E)=>{let{matchUpId:P,drawId:A}=E;return y[A]?y[A].push(P):y[A]=[P],y},{}),g=1440;for(let y of Object.keys(f)){let E=jo({tournamentRecord:t,drawId:y});if(E.error)return E;let P=E.drawDefinition,A=f[y].filter(U=>r.includes(U));for(let U of A)if(U&&P){let D=p.find(x=>x.matchUpId===U)?.schedule,{scheduledTime:M,scheduledDate:R}=D,b,O,v;if(!b&&a&&R){let x=Ut(R);v=Ip(x,a),b=new Date(v)<new Date(d)||new Date(v)>new Date(l)}if(s&&M){let x=Ut(M),w=Yt(zt(M))+s;if(b=w<0||w>g,!b){let L=$r(M,s),k=x&&v||R===x&&x;O=k?`${k}T${L}`:L}}if(b)i.push(U);else{if(!n){if(O){let x=ii({scheduledTime:O,drawDefinition:P,matchUpId:U});if(x.error)return x}if(v){let x=fm({scheduledDate:v,drawDefinition:P,matchUpId:U});if(x.error)return x}}(O||v)&&o.push(U)}}}let I=ye({matchUpFilters:{matchUpIds:r},tournamentRecord:t}).matchUps??[],h=I.filter(({matchUpId:y})=>o.includes(y)),S=I.filter(({matchUpId:y})=>i.includes(y)),T=h.length&&!S.length;return{...C,rescheduled:h,notRescheduled:S,allRescheduled:T}}function PR(t){let e="matchUpScheduleChange",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return{error:xt};let{sourceMatchUpContextIds:n,targetMatchUpContextIds:o,sourceCourtId:i,targetCourtId:s,courtDayDate:a}=t||{},{drawId:c,matchUpId:u,tournamentId:p}=n||{},{drawId:m,matchUpId:d,tournamentId:l}=o||{};if(!u&&!d)return _({result:{error:st},stack:e});let{matchUps:f}=Mn({matchUpFilters:{matchUpIds:[u,d].filter(Boolean),drawIds:[c,m].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=f?.find(({matchUpId:y})=>y===u),I=f?.find(({matchUpId:y})=>y===d),h=0;if(s&&u&&!d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y?.success&&h++,y.error)return _({result:y,stack:e})}else if(i&&s&&u&&d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y.success&&h++,y.error)return _({result:y,stack:e,info:"source"});let E=S({tournamentId:l,sourceCourtId:s,matchUpId:d,matchUp:I,courtId:i,drawId:m,tournamentRecords:r,courtDayDate:a});if(E.success&&h++,E.error)return _({result:E,stack:e,info:"target"})}else return{error:st};return h?C:_({result:{error:Bs},stack:e});function S(y){let{tournamentRecords:E,tournamentId:P,matchUp:A,drawId:U}=y,N=E[P],{drawDefinition:D}=jo({tournamentRecord:N,drawId:U});return A.matchUpType===Wt?T({...y,tournamentRecord:N,drawDefinition:D}):as({...y,tournamentRecord:N,drawDefinition:D})}function T({removePriorValues:y,tournamentRecords:E,tournamentRecord:P,drawDefinition:A,sourceCourtId:U,courtDayDate:N,matchUpId:D,matchUp:M,courtId:R}){let b=[R].concat(M.schedule.allocatedCourts.map(({courtId:O})=>O).filter(O=>O!==U));return gm({removePriorValues:y,tournamentRecords:E,tournamentRecord:P,drawDefinition:A,courtDayDate:N,matchUpId:D,courtIds:b})}}function DR({scheduleAttributes:t=[lo,Jo,Ji,Zi,ts,Bo,vi,Oi,es],tournamentRecord:e,drawDefinition:r,matchUpId:n}){let o="clearMatchUpSchedule",i=r?nr({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:ye({matchUpFilters:{matchUpIds:[n]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:we};let s=(i.timeItems??[]).filter(a=>a?.itemType&&!t.includes(a?.itemType));return i.timeItems=s,gt({tournamentId:e.tournamentId,context:o,drawDefinition:r,matchUp:i}),{...C}}function NR(t){let{tournamentRecord:e,tournamentId:r,dailyLimits:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="object"||!Object.keys(o).length)return{error:xt};if(typeof n!="object")return{error:So};let i=Object.keys(o).filter(s=>!r||r===s);if(r&&!i.includes(r))return{error:B};for(let s of i){let a=o[s],c=At({extension:{name:lu,value:{dailyLimits:n}},element:a});if(c.error)return c}return{...C}}var kR={};Xt(kR,{addCollectionDefinition:()=>RI,addCollectionGroup:()=>_R,aggregateTieFormats:()=>LR,compareTieFormats:()=>ni,getTieFormat:()=>al,modifyCollectionDefinition:()=>NI,modifyTieFormat:()=>wR,mutate:()=>FR,orderCollectionDefinitions:()=>vR,query:()=>EN,removeCollectionDefinition:()=>MI,removeCollectionGroup:()=>bR,tieFormatGenderValidityCheck:()=>km,validateCollectionDefinition:()=>eu});var FR={};Xt(FR,{addCollectionDefinition:()=>RI,addCollectionGroup:()=>_R,aggregateTieFormats:()=>LR,modifyCollectionDefinition:()=>NI,modifyTieFormat:()=>wR,orderCollectionDefinitions:()=>vR,removeCollectionDefinition:()=>MI,removeCollectionGroup:()=>bR});function Ii({drawDefinition:t,structureId:e,matchUpId:r,structure:n,matchUp:o,eventId:i,event:s}){let a="getTieFormat",c;if(e=n?.structureId??e,r=o?.matchUpId??r,(r||e)&&!t)return{error:Z};if(i&&s)c=di(s);else if(r){if(t&&(!o||!n)){let u=Vt({drawDefinition:t,matchUpId:r});if(u.error)return u;if(u.matchUp?.matchUpType!==xr)return _({result:{error:dr},stack:a});n||(n=u.structure),o||(o=u.matchUp)}c=Cp({item:o,drawDefinition:t,structure:n,event:s})||Cp({item:n,drawDefinition:t,structure:n,event:s})||di(t)||di(s)}else if(t&&e){if(!n){let u=at({drawDefinition:t,structureId:e});if(u.error)return u;n=u?.structure}c=Cp({item:n,drawDefinition:t,structure:n,event:s})||di(t)||di(s)}else c=di(t)||di(s);return c?{...C,structure:n,tieFormat:c,matchUp:o}:_({result:{error:ks},stack:a})}function wl({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![ae].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Hn&&!he(t))}function CR({from:t,to:e}){let r=Object.keys(t),n=jt(r,Object.keys(e)).length===r.length,i=r.filter(c=>t[c]!==e[c]).map(c=>({countChange:e[c]-t[c],collectionId:c})),s=r.every(c=>t[c]===e[c]);return{equivalent:n&&s,matchUpsCountChanges:i}}function Rw({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,structure:n,tieFormat:o,eventId:i,matchUp:s,event:a,uuids:c}){let u="updateTieFormat",p=e?.tournamentId,m=0,d=0,l=0,f=0,g=o?.collectionDefinitions.reduce((P,A)=>(P[A.collectionId]=(P[A.collectionId]||0)+A.matchUpCount,P),{}),I=({tieFormat:P})=>{let A=P?.collectionDefinitions.reduce((U,N)=>(U[N.collectionId]=(U[N.collectionId]||0)+N.matchUpCount,U),{});return CR({from:A,to:g}).equivalent},h=Ii({drawDefinition:r})?.tieFormat,S=Ii({event:a})?.tieFormat;if(a&&i){for(let P of a.drawDefinitions??[])T({drawDefinition:P});a.tieFormat=or(o),f+=1}else if(s){if(!s.tieMatchUps)return _({result:{error:dr},stack:u});let P=Er(s.tieMatchUps?.map(({collectionId:M})=>M)),A=CR({to:g,from:P}),{changes:U,changesArePossible:N,cannotChangeReaon:D}=Mw({matchUp:s,check:A});if(A.equivalent)if(wl({matchUp:s,updateInProgressMatchUps:t}))s.tieFormat=or(o),f+=1;else return _({result:{error:nf},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});else if(N)E({tieFormat:o,matchUp:s,changes:U,uuids:c});else return _({context:{collectionMap:g,matchUpMap:P},result:{error:Yo},info:D||"specified changes not possible",stack:u});d+=1,gt({eventId:a?.eventId,context:u,drawDefinition:r,tournamentId:p,matchUp:s})}else if(n){let A=y({inheritedTieFormat:h??S,structure:n})?.modifiedMatchUpsCount;A&&(d+=A,m+=1,f+=1);let U=!n.tieFormat||ni({ancestor:n.tieFormat,descendant:o}).different;U&&(n.tieFormat=or(o),m+=1,f+=1),(A||U)&&r&&bt({structureIds:[n.structureId],eventId:a?.eventId,drawDefinition:r})}else if(r)T({drawDefinition:r}),r.tieFormat=or(o),f+=1;else return{error:Z};return{modifiedStructuresCount:m,modifiedMatchUpsCount:d,addedMatchUpsCount:l,modifiedCount:f,...C,tieFormat:o};function T({drawDefinition:P}){let A=P.structures||[],U=[];for(let N of A){if(N.tieFormat)continue;let M=y({inheritedTieFormat:S,structure:N})?.modifiedMatchUpsCount;if(M){m+=1,d+=M;let R=N.structureId;U.push(R)}}return bt({structureIds:U,eventId:a?.eventId,drawDefinition:P}),U.length}function y({inheritedTieFormat:P,structure:A}){let U=0,N=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:A})?.matchUps||[];for(let D of N){let M=wl({matchUp:D,updateInProgressMatchUps:t}),R=!1,b=Er(D.tieMatchUps?.map(({collectionId:v})=>v)),O=CR({from:b,to:g});if(O.equivalent)D.tieFormat&&I(D)&&M&&(D.tieFormat=or(o),R=!0);else{let{changes:v,changesArePossible:x}=Mw({matchUp:D,check:O});if(x&&!D.tieFormat)E({changes:v,matchUp:D,tieFormat:o,uuids:c});else if(P)(!D.tieFormat||ni({ancestor:P,descendant:D.tieFormat}).different)&&(D.tieFormat=P,R=!0);else return _({result:{error:ks},stack:u})}R&&(U+=1,gt({tournamentId:e?.tournamentId,drawDefinition:r,context:u,eventId:i,matchUp:D}))}return{modifiedMatchUpsCount:U}}function E({uuids:P,matchUp:A,tieFormat:U,changes:N}){A.tieFormat=or(U);let D=[],M=[];return N.forEach(R=>{if(R.countChange>0){let b=Math.max(0,...A.tieMatchUps.filter(x=>x.collectionId===R.collectionId).map(Hr("collectionPosition"))),O=U.collectionDefinitions.find(x=>x.collectionId===R.collectionId),v=wu({matchUpsLimit:R.countChange,collectionPositionOffset:b,collectionDefinition:O,matchUp:A,uuids:P});M.push(...J(v,!1,!0)),l+=M.length,A.tieMatchUps.push(...v)}else{let b=R.toBePlayedTieMatchUpIds.slice(0,Math.abs(R.countChange));console.log("remove",b.length),D.push(...b),A.tieMatchUps=A.tieMatchUps.filter(({matchUpId:O})=>!b.includes(O))}}),M.length&&Fo({matchUps:M,drawDefinition:r,tournamentId:p,eventId:i}),D.length&&_n({matchUpIds:D,action:"updateTieFormat",drawDefinition:r,tournamentId:p,eventId:i}),{matchUpIdsRemoved:D,matchUpsAdded:M}}}function Mw({check:t,matchUp:e}){let r="",n=[];return{changesArePossible:t.matchUpsCountChanges.every(({collectionId:i,countChange:s})=>{let a=e.tieMatchUps.filter(u=>u.collectionId===i&&u.matchUpStatus===Qt).map(Hr("matchUpId")),c=a.length+s>=0||s>0;return!c&&s<0&&(r="Insufficient TO_BE_PLAYED matchUps"),n.push({toBePlayedTieMatchUpIds:a,collectionId:i,countChange:s}),c}),changes:n,cannotChangeReaon:r}}function Ju({appliedPolicies:t,drawDefinition:e,auditData:r}){if(!t?.audit?.[nd])return;let{extension:n}=mt({name:nd,element:e}),o={value:Array.isArray(n?.value)?n?.value.concat(r):[r],name:nd};At({element:e,extension:o})}function NI({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:r,collectionName:n,tieFormatName:o,drawDefinition:i,matchUpFormat:s,matchUpCount:a,collectionId:c,matchUpType:u,structureId:p,matchUpId:m,category:d,eventId:l,gender:f,event:g,collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y}){let E="modifyCollectionDefinition";if(s&&!Nr({matchUpFormat:s}))return _({result:{error:B},context:{matchUpFormat:s},stack:E});if(n&&typeof n!="string")return _({result:{error:B},context:{collectionName:n},stack:E});if(f&&!Object.values(Fm).includes(f))return _({result:{error:B},context:{gender:f},stack:E});if(d&&typeof d!="object")return _({result:{error:B},context:{category:d},stack:E});let P={collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y};if(!Object.values(P).filter(Boolean).length&&!r&&!n&&!s&&!a&&!u)return _({result:{error:st},stack:E});if(Object.values(P).filter(Boolean).length>1)return _({info:"Only one value assignment allowed per collectionDefinition",result:{error:B},stack:E});let A=Ii({drawDefinition:i,structureId:p,matchUpId:m,eventId:l,event:g});if(A.error)return _({result:A,stack:E});let{matchUp:U,structure:N,tieFormat:D}=A,M=or(D),R=D?.collectionDefinitions.find(Y=>Y.collectionId===c),b=M?.collectionDefinitions.find(Y=>Y.collectionId===c);if(!R)return _({info:"source collectionDefinition",result:{error:Oe},context:{collectionId:c},stack:E});let O=h??S??T??y;if(I?.length){let Y=GI({matchUpCount:a??R?.matchUpCount??0,collectionValueProfiles:I});if(Y.errors)return _({result:{error:B},info:Y.errors,stack:E})}else if(O&&!It(O))return _({result:{error:B},info:"value is not an integer",context:{value:O},stack:E});let v=(Y,j)=>jt(Object.keys(Y),Object.keys(j)).length===Object.keys(Y).length&&jt(Object.values(Y),Object.values(j)).length===Object.values(Y).length,x=I&&(!R.collectionValueProfiles||!v(R.collectionValueProfiles,I)),F=It(h)&&R.collectionValue!==h||It(S)&&R.matchUpValue!==S||It(T)&&R.scoreValue!==T||It(y)&&R.setValue!==y||x,w=[];if(F&&(b.collectionValueProfiles=void 0,b.collectionValue=void 0,b.matchUpValue=void 0,b.scoreValue=void 0,b.setValue=void 0,Object.assign(b,P),w.push({collectionId:c,...nt(P)})),(It(T)||It(y))&&b.collectionGroupNumber){let Y=b.collectionGroupNumber;M.collectionDefinitions=M.collectionDefinitions.map(j=>{let{collectionGroupNumber:V,...$}=j;return V===Y?$:j}),M.collectionGroups=M.collectionGroups.filter(({groupNumber:j})=>j!==Y),w.push({collectionId:c,change:"collectionGroupNumber removed"})}let{aggregateValue:L,valueGoal:k}=Os(M),G=nt({aggregateValue:L,valueGoal:k});if((G.aggregateValue!==D?.winCriteria.aggregateValue||G.valueGoal!==D?.winCriteria.valueGoal)&&(M.winCriteria=G,w.push({collectionId:c,winCriteria:G})),It(r)&&R.collectionOrder!==r&&(b.collectionOrder=r,w.push({collectionId:c,collectionOrder:r})),n&&R.collectionName!==n&&(b.collectionName=n,w.push({collectionId:c,collectionName:n})),s&&R.matchUpFormat!==s&&(b.matchUpFormat=s,w.push({collectionId:c,matchUpFormat:s})),It(a)&&R.matchUpCount!==a&&(b.matchUpCount=a,w.push({collectionId:c,matchUpCount:a})),u&&R.matchUpType!==u)return _({result:{error:pp},context:{matchUpType:u},stack:E});d&&R.category!==d&&(b.category=d,w.push({collectionId:c,category:d})),f&&R.gender!==f&&(b.gender=f,w.push({collectionId:c,gender:f}));let H=nt(M);if(A=ar({tieFormat:H}),A.error)return _({result:A,stack:E});if(!w.length)return _({result:{...C,modifications:w}});if(D?.tieFormatName!==o?(H.tieFormatName=o,w.push({tieFormatName:o})):w.length&&(delete H.tieFormatName,w.push("tieFormatName removed: modifications without new tieFormatName")),A=Rw({tieFormat:H,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:i,structure:N,eventId:l,matchUp:U,event:g}),!A.error){let{appliedPolicies:Y}=Tt({tournamentRecord:e}),j=nt({collectionDefinition:b,drawId:i?.drawId,action:E,structureId:p,matchUpId:m,eventId:l});Ju({appliedPolicies:Y,drawDefinition:i,auditData:j})}return _({result:{...A,modifications:w},stack:E})}function Cw({updateInProgressMatchUps:t,drawDefinition:e,structureId:r,structure:n,matchUpId:o,matchUp:i}){let s=[];return o&&i?s=[i]:r&&n?s=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:n})?.matchUps??[]:e&&(s=nr({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:s.filter(c=>!c.winningSide&&c.matchUpStatus!==ge&&(t||c.matchUpStatus!==Hn&&!he(c)))}}function bw({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUps:n,tieFormat:o,event:i}){for(let s of n){let a=!!s.tieFormat;a&&(s.tieFormat=or(o));let c;if(t){let u=Tt({tournamentRecord:e,drawDefinition:r,event:i}).appliedPolicies,p=go({matchUpId:s.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:u,drawDefinition:r,event:i});if(p.error)return p;c=p.score}a&&!c&>({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:i?.eventId,matchUp:s,drawDefinition:r})}return{...C}}function DE({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:r,wasAggregateValue:n,tieFormatName:o,drawDefinition:i,structureId:s,structure:a,tieFormat:c,matchUpId:u,matchUp:p,eventId:m,event:d}){let{aggregateValue:l,valueGoal:f}=Os(c);c.winCriteria=nt({aggregateValue:l,valueGoal:f}),(e&&e!==f||l&&!n)&&(o?c.tieFormatName=o:delete c.tieFormatName);let{targetMatchUps:g}=Cw({updateInProgressMatchUps:t,drawDefinition:i,structureId:s,structure:a,matchUpId:u,matchUp:p});bw({updateInProgressMatchUps:t,tournamentRecord:r,targetMatchUps:g,drawDefinition:i,tieFormat:c,event:d});let I=nt(c),h=ar({tieFormat:I});if(h.error)return h;if(m&&d)d.tieFormat=I;else if(u&&p)p.tieFormat=c;else if(a)a.tieFormat=I;else if(i)i.tieFormat=I;else if(!p||!i)return{error:Z};return bt({drawDefinition:i,eventId:d?.eventId}),{...C}}function bR({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,matchUpId:s,matchUp:a,eventId:c,event:u}){if(!e)return{error:st};if(isNaN(e))return{error:B};let p="removeCollectionGroup",m=a?void 0:Ii({drawDefinition:n,structureId:i,matchUpId:s,eventId:c,event:u});if(m?.error)return _({result:m,stack:p});let d=m?.structure;a=a??m?.matchUp;let l=m?.tieFormat,f=l?.winCriteria.valueGoal,g=l?.winCriteria.aggregateValue,I=or(l);if(m=ar({tieFormat:I}),m.error)return _({result:m,stack:p});let h=[];if(I.collectionDefinitions=I.collectionDefinitions.map(S=>{let{collectionGroupNumber:T,...y}=S;return T!==e?S:(h.push(S.collectionId),y)}),I.collectionGroups=I.collectionGroups.filter(({groupNumber:S})=>S!==e),m=DE({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:g,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,structure:d,tieFormat:I,matchUpId:s,matchUp:a,eventId:c,event:u}),!m.error){let{appliedPolicies:S}=Tt({tournamentRecord:r}),T=nt({drawId:n?.drawId,collectionGroupNumber:e,action:p,structureId:i,matchUpId:s,eventId:c});Ju({appliedPolicies:S,drawDefinition:n,auditData:T})}return _({result:{...m,modifiedCollectionIds:h},stack:p})}function Ll({tieFormat:t,orderMap:e}){let r=or(t);return r.collectionDefinitions?.forEach(n=>{let o=e[n.collectionId];o&&(n.collectionOrder=o)}),r.collectionDefinitions?.sort((n,o)=>za(n.collectionOrder)-za(o.collectionOrder)),r}function vR({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,orderMap:o,eventId:i,matchUp:s,event:a}){if(typeof o!="object"||!Object.values(o).every(p=>It(p)))return _({result:{error:B},context:{orderMap:o}});let c=r?at({drawDefinition:e,structureId:r}):void 0;if(c?.error)return c;let u=c?.structure;if(i&&a?.tieFormat)Ow({tournamentRecord:t,event:a,orderMap:o});else if(n){let p=e&&Vt({drawDefinition:e,matchUpId:n});if(p?.error)return p;if(s=p.matchUp,!s)return{error:mr};let m=al({tournamentRecord:t,matchUpId:n,structure:u,drawDefinition:e,event:a})?.tieFormat;s.tieFormat=Ll({tieFormat:m,orderMap:o}),gt({tournamentId:t?.tournamentId,eventId:a?.eventId,drawDefinition:e,matchUp:s})}else if(r)if(u?.tieFormat)u.tieFormat=Ll({tieFormat:u.tieFormat,orderMap:o}),vw({eventId:a?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:o}),bt({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)OR({structureIds:[r],tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else if(a?.tieFormat)Ow({structureIds:[r],tournamentRecord:t,orderMap:o,event:a});else return{error:Oe};else if(e?.tieFormat)OR({tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else return{error:Oe};return{...C}}function Ow({tournamentRecord:t,structureIds:e,orderMap:r,event:n}){let o=Ll({tieFormat:n.tieFormat,orderMap:r});e?.length||(n.tieFormat=o);for(let i of n.drawDefinitions??[])OR({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:r,event:n})}function OR({tournamentRecord:t,drawDefinition:e,structureIds:r,orderMap:n,event:o}){let i=e.tieFormat??o?.tieFormat,s=Ll({tieFormat:i,orderMap:n});r?.length||(e.tieFormat=s);let a=[];for(let c of e.structures??[])r?.length&&!r.includes(c.structureId)||((c.tieFormat||r?.includes(c.structureId))&&(c.tieFormat=Ll({tieFormat:c.tieFormat??e.tieFormat??o?.tieFormat,orderMap:n})),vw({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,structure:c,orderMap:n}),a.push(c.structureId));bt({drawDefinition:e,structureIds:a})}function vw({tournamentRecord:t,drawDefinition:e,structure:r,orderMap:n,eventId:o}){let i=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:r})?.matchUps;for(let s of i)s.tieFormat&&(s.tieFormat=Ll({tieFormat:s.tieFormat,orderMap:n}),gt({tournamentId:t?.tournamentId,drawDefinition:e,eventId:o,matchUp:s}))}function MI({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,collectionId:i,structureId:s,matchUpId:a,eventId:c,matchUp:u,event:p}){let m="removeCollectionDefinition",d=u?void 0:Ii({drawDefinition:n,structureId:s,matchUpId:a,eventId:c,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;u=u??d?.matchUp;let f=d?.tieFormat,g=or(f);if(d=ar({tieFormat:g}),d.error)return _({result:d,stack:m});let I=g?.collectionDefinitions?.find(M=>M.collectionId===i);if(!I)return _({result:{error:Oe,collectionId:i}});g.collectionDefinitions=g.collectionDefinitions.filter(M=>M.collectionId!==i),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(M=>{let{collectionGroupNumber:R,...b}=M;return b}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:M})=>M!==I.collectionGroupNumber));let{aggregateValue:h,valueGoal:S}=Os(g);g.winCriteria=nt({aggregateValue:h,valueGoal:S});let T=f?.winCriteria.valueGoal,y=f?.winCriteria.aggregateValue;(T&&T!==S||h&&!y)&&(o?g.tieFormatName=o:delete g.tieFormatName);let E=[];a&&u?E=[u]:s&&l?E=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:l})?.matchUps??[]:n?E=nr({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:n})?.matchUps??[]:p&&(E=to({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:n})?.matchUps??[]);let P=(E||[]).filter(M=>{let b=M.tieMatchUps?.filter(v=>v.collectionId===i)?.some(he),O=e&&M.tieFormat?ni({descendant:M.tieFormat,ancestor:g})?.different:!1;return t&&!b||!M.winningSide&&M.matchUpStatus!==ge&&(t||M.matchUpStatus!==Hn&&!he(M)&&!O)});if(!P.length)return{error:Bs};let{appliedPolicies:A}=Tt({tournamentRecord:r});if(a&&u&&t){let M=u.tieMatchUps?.filter(R=>R.collectionId===i);for(let R of M??[]){let b=ws({matchUpId:R.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:r,appliedPolicies:A,drawDefinition:n,event:p});if(b.error||(b=Vt({drawDefinition:n,matchUpId:a}),b.error))return b;u=b?.matchUp}}let U=[];for(let M of P){for(let R of M?.sides??[])R.lineUp=(R.lineUp??[]).map(b=>({participantId:b.participantId,collectionAssignments:(b?.collectionAssignments??[]).filter(O=>O.collectionId!==i)}));if(M.tieMatchUps=(M.tieMatchUps??[]).filter(R=>{let b=R.collectionId===i;return b&&U.push(R.matchUpId),!b}),M.tieFormat&&(M.tieFormat=or(g)),t){let R=go({matchUpId:M.matchUpId,exitWhenNoValues:!0,tournamentRecord:r,appliedPolicies:A,drawDefinition:n,event:p});if(R.error)return R}gt({tournamentId:r?.tournamentId,eventId:p?.eventId,drawDefinition:n,context:m,matchUp:M})}U.length&&_n({tournamentId:r?.tournamentId,matchUpIds:U,eventId:p?.eventId,drawDefinition:n});let N=nt(g);if(d=ar({tieFormat:N}),d.error)return _({result:d,stack:m});if(c&&p)p.tieFormat=N;else if(a&&u)u.tieFormat=N;else if(l)l.tieFormat=N;else if(n)n.tieFormat=N;else if(!u||!n)return{error:Z};bt({drawDefinition:n,eventId:p?.eventId});let D=nt({drawId:n?.drawId,action:m,collectionId:i,structureId:s,matchUpId:a,eventId:c});return Ju({appliedPolicies:A,drawDefinition:n,auditData:D}),{tieFormat:N,deletedMatchUpIds:U,targetMatchUps:P,...C}}function _R({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:r,drawDefinition:n,collectionIds:o,tieFormatName:i,structureId:s,matchUpId:a,matchUp:c,eventId:u,event:p}){let m="addCollectionGroup";if(!Array.isArray(o))return _({result:{error:st},stack:m});let d=c?void 0:Ii({drawDefinition:n,structureId:s,matchUpId:a,eventId:u,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;c=c||d?.matchUp;let f=d?.tieFormat,g=f?.winCriteria.valueGoal,I=or(f);if(d=ar({tieFormat:I}),d.error)return _({result:d,stack:m});for(let T of I.collectionDefinitions){let{collectionId:y,collectionGroupNumber:E}=T;if(E&&o.includes(y))return _({info:"collectionIds cannot be part of other collectionGroups",result:{error:B},stack:m})}let S=(I.collectionGroups||[]).reduce((T,y)=>y.groupNumber>T?y.groupNumber:T,0)+1;return r.groupNumber=S,I.collectionDefinitions=I.collectionDefinitions.map(T=>o.includes(T.collectionId)?{...T,collectionGroupNumber:S}:T),I.collectionGroups=[...I.collecitonGroups||[],r],DE({updateInProgressMatchUps:t,originalValueGoal:g,tournamentRecord:e,drawDefinition:n,tieFormatName:i,structureId:s,structure:l,tieFormat:I,matchUpId:a,matchUp:c,eventId:u,event:p})}function RI({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:r,tournamentRecord:n,policyDefinitions:o,enforceCategory:i,referenceGender:s,drawDefinition:a,tieFormatName:c,enforceGender:u,structureId:p,matchUpId:m,matchUp:d,eventId:l,uuids:f,event:g}){let I="addCollectionDefinition",h=Tt({tournamentRecord:n,drawDefinition:a,event:g}).appliedPolicies??{},S=o?.[er]??h?.[er];i=i??S?.participants?.enforceCategory;let T=(u??S?.participants?.enforceGender)!==!1,y=!!((r??g?.category)&&i!==!1),E=!!((s??g?.gender)&&T),P=eu({referenceCategory:r??g?.category,collectionDefinition:e,referenceGender:s,checkCategory:y,checkGender:E,event:g});if(P.error)return _({result:P,stack:I});let A=d?.tieFormat?void 0:Ii({drawDefinition:a,structureId:p,matchUpId:m,eventId:l,event:g});if(A?.error)return _({result:{error:A.error},stack:I});let U=A?.structure;d=d??A?.matchUp;let N=d?.tieFormat??A?.tieFormat,D=or(N);if(A=ar({tieFormat:D}),A?.error)return _({result:{error:A.error},stack:I});if(!e.collectionId)e.collectionId=Nt();else if(D.collectionDefinitions.map(({collectionId:G})=>G).includes(e.collectionId))return _({context:{collectionId:e.collectionId},result:{error:BA}});D.collectionDefinitions.push(e),D.collectionDefinitions.sort((k,G)=>(k.collectionOrder||0)-(G.collectionOrder||0)).forEach((k,G)=>k.collectionOrder=G+1);let{aggregateValue:M,valueGoal:R}=Os(D);D.winCriteria=nt({aggregateValue:M,valueGoal:R});let b=N?.winCriteria.valueGoal,O=N?.winCriteria.aggregateValue;(b&&b!==R||M&&!O)&&(c?D.tieFormatName=c:delete D.tieFormatName);let v=[],x=[],F=[],w=nt(D);if(A=ar({tieFormat:w}),A?.error)return _({result:{error:A.error},stack:I});if(l&&g){g.tieFormat=w;for(let k of g.drawDefinitions??[])if(!k.tieFormat)for(let G of k.structures??[]){if(G.tieFormat)continue;let H=xR({updateInProgressMatchUps:t,collectionDefinition:e,structure:G,uuids:f});x.push(...H.newMatchUps),F.push(...H.targetMatchUps),v.push(G.structureId)}NE({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:v,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(p&&U){U.tieFormat=w;let k=xR({updateInProgressMatchUps:t,collectionDefinition:e,structure:U,uuids:f});x.push(...k.newMatchUps),F=k.targetMatchUps,NE({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:v,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(m&&d){if(!wl({matchUp:d,updateInProgressMatchUps:t}))return _({result:{error:nf},stack:I});d.tieFormat=w;let k=wu({collectionDefinition:e,matchUp:d,uuids:f});Array.isArray(d.tieMatchUps)||(d.tieMatchUps=[]),d.tieMatchUps.push(...k),x.push(...k),NE({modifiedMatchUps:[d],eventId:g?.eventId,modifiedStructureIds:v,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(a){a.tieFormat=w;for(let k of a.structures??[]){let G=xR({updateInProgressMatchUps:t,collectionDefinition:e,structure:k,uuids:f});v.push(k.structureId),x.push(...G.newMatchUps),F.push(...G.targetMatchUps)}NE({modifiedMatchUps:F,eventId:g?.eventId,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else return{error:Z};let L=nt({drawId:a?.drawId,collectionDefinition:e,action:I,structureId:p,matchUpId:m,eventId:l});return Ju({appliedPolicies:h,drawDefinition:a,auditData:L}),{tieFormat:w,targetMatchUps:F,addedMatchUps:x,...C}}function xR({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:n}){let o=[],s=(yt({matchUpFilters:{matchUpTypes:[Wt]},structure:r})?.matchUps).filter(a=>wl({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat);for(let a of s){let c=wu({collectionDefinition:e,matchUp:a,uuids:n});Array.isArray(a.tieMatchUps)||(a.tieMatchUps=[]),a.tieMatchUps.push(...c),o.push(...c)}return{newMatchUps:o,targetMatchUps:s}}function NE({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:o,eventId:i,stack:s}){Fo({tournamentId:e?.tournamentId,matchUps:o,drawDefinition:n,eventId:i}),r?.forEach(a=>{gt({tournamentId:e?.tournamentId,drawDefinition:n,context:s,matchUp:a,eventId:i})}),bt({structureIds:t,drawDefinition:n,eventId:i})}function wR({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:r,tournamentRecord:n,considerations:o,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,uuids:u,event:p}){let m="modifyTieFormat";if(!ar({tieFormat:r}).valid)return _({result:{error:Yo},info:"falied validation",stack:m});let d=Ii({drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(d.error)return _({result:d,stack:m});let{matchUp:l,tieFormat:f}=d,g=or(f),I=ni({descendant:r,ancestor:g,considerations:o});if(I.invalid)return _({context:{invalid:I.invalid},result:{error:Yo},stack:m});if(!I?.different)return _({result:{...C},info:"Nothing to do",stack:m});let h=g.collectionDefinitions.map(({collectionId:D})=>D),S=r.collectionDefinitions.map(({collectionId:D})=>D),T=h.filter(D=>!S.includes(D)),y=r.collectionDefinitions.filter(({collectionId:D})=>!h.includes(D)),E=y.map(Hr("collectionId")),P=[],A,U=r.tieFormatName;for(let D of r.collectionDefinitions){if(E.includes(D.collectionId))continue;let M=NI({updateInProgressMatchUps:t,...D,tournamentRecord:n,tieFormatName:U,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(M.modifications&&P.push(...M.modifications),M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}for(let D of y){let M=RI({updateInProgressMatchUps:t,collectionDefinition:D,tournamentRecord:n,drawDefinition:i,tieFormatName:U,structureId:s,matchUpId:a,matchUp:l,eventId:c,uuids:u,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}for(let D of T){let M=MI({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:n,drawDefinition:i,tieFormatName:U,collectionId:D,structureId:s,matchUpId:a,eventId:c,matchUp:l,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}return f?.tieFormatName!==U?(A.tieFormatName=U,P.push({tieFormatName:U})):(P.length||E.length||T.length)&&(delete A.tieFormatName,P.push("tieFormatName removed: modifications without new tieFormatName")),A.collectionDefinitions=A.collectionDefinitions.sort((D,M)=>za(D.collectionOrder)-za(M.collectionOrder)).map((D,M)=>({...D,collectionOrder:M+1})),{processedTieFormat:or(A),modifications:P,...C}}function LR({tournamentRecord:t}){if(!t)return{error:q};let e=0;for(let r of t.events??[]){let n=r.tieFormats??[],o=p=>{if(!p.tieFormat)return;let m;for(let d of n)ni({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);if(m)p.tieFormatId=m,delete p.tieFormat;else{let d=J(p.tieFormat,void 0,!0);d.tieFormatId||(d.tieFormatId=Nt()),p.tieFormatId=d.tieFormatId,delete p.tieFormat,n.push(d),e+=1}},i=r.eventType;o({tieFormat:r.tieFormat,eventType:i});for(let p of r.drawDefinitions??[]){o({tieFormat:p.tieFormat,eventType:i});for(let m of p.structures??[])o({tieFormat:m.tieFormat,eventType:i})}let s=(p,m)=>{let d=c.matchUps?.find(l=>l.matchUpId===p);d&&(d.tieFormatId=m,delete d.tieFormat,gt({tournamentId:t?.tournamentId,eventId:r.eventId,matchUp:d}))},a=p=>{let m=J(p.tieFormat,void 0,!0);m.tieFormatId||(m.tieFormatId=Nt()),n.push(m),e+=1,s(p.matchUpId,m.tieFormatId)},c=to({matchUpFilters:{matchUpTypes:[xr]},event:r}),u=c.matchUps??[];for(let p of u){let m;for(let d of n)p.tieFormat&&ni({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);m?s(p.matchUpId,m):a(p)}n.length&&(r.tieFormats=n)}return{...C,addedCount:e}}var XR={};Xt(XR,{addDrawDefinitionExtension:()=>Pp,addEventExtension:()=>xo,addEventTimeItem:()=>is,addExtension:()=>At,addNotes:()=>$p,addOnlineResource:()=>jR,addParticipantExtension:()=>RU,addParticipantTimeItem:()=>Gg,addTimeItem:()=>ro,addTournamentExtension:()=>Vf,addTournamentTimeItem:()=>_c,analyzeDraws:()=>Vu,analyzeTournament:()=>sy,copyTournamentRecord:()=>GR,createTournamentRecord:()=>ym,generate:()=>VR,getAggregateTeamResults:()=>iy,getAllowedDrawTypes:()=>rl,getAllowedMatchUpFormats:()=>ey,getAppliedPolicies:()=>Tt,getCompetitionDateRange:()=>ol,getCompetitionPenalties:()=>ry,getPolicyDefinitions:()=>Go,getTournamentInfo:()=>bs,getTournamentPenalties:()=>nl,getTournamentPersons:()=>oy,getTournamentPoints:()=>il,getTournamentStructures:()=>HS,getTournamentTimeItem:()=>cd,hydrateTournamentRecord:()=>BR,mutate:()=>QR,query:()=>TN,removeDrawDefinitionExtension:()=>CU,removeEventExtension:()=>Dp,removeExtension:()=>Ir,removeNotes:()=>Fg,removeOnlineResource:()=>WR,removeParticipantExtension:()=>bU,removeTournamentExtension:()=>Bf,setTournamentCategories:()=>$R,setTournamentDates:()=>CI,setTournamentEndDate:()=>zR,setTournamentName:()=>YR,setTournamentNotes:()=>qR,setTournamentStartDate:()=>KR,setTournamentStatus:()=>HR});var VR={};Xt(VR,{copyTournamentRecord:()=>GR,createTournamentRecord:()=>ym});function GR(t){let e=et(t,[{tournamentRecord:!0,startDate:!0,endDate:!1,tournamentName:!0}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord,o=1440*60*1e3,s=(r&&n?new Date(Ut(n)).getTime()-new Date(Ut(r)).getTime():0)/o,a=t.endDate||ch(t.startDate,s),c=l=>l?.filter(({itemType:f})=>t.itemTypeList?.includes(f)),u=l=>l?.filter(({name:f})=>t.extensionList?.includes(f)),p=l=>{let{timeItems:f,extensions:g,...I}=l;return J({...I,timeItems:c(f),extensions:u(g)},!1,!0)},m=l=>{let{drawDefinitions:f,timeItems:g,extensions:I,startDate:h,endDate:S,...T}=l;return J({extensions:u(I),timeItems:c(g),startDate:t.startDate,endDate:a,...T},!1,!0)},d={participants:t.copyParticipants?t.tournamentRecord.participants?.map(p)??[]:[],parentOrganisation:J({...t.tournamentRecord.parentOrganisation},!1,!0),venues:J(t.tournamentRecord.venues??[],!1,!0),extensions:u(t.tournamentRecord.extensions),timeItems:c(t.tournamentRecord.timeItems),events:t.tournamentRecord.events?.map(m)??[],weekdays:[...t.tournamentRecord.weekdays??[]],tournamentName:t.tournamentName,startDate:t.startDate,tournamentId:Nt(),endDate:a};return{...C,tournamentRecord:d}}var QR={};Xt(QR,{addDrawDefinitionExtension:()=>Pp,addEventExtension:()=>xo,addEventTimeItem:()=>is,addExtension:()=>At,addNotes:()=>$p,addOnlineResource:()=>jR,addParticipantExtension:()=>RU,addParticipantTimeItem:()=>Gg,addTimeItem:()=>ro,addTournamentExtension:()=>Vf,addTournamentTimeItem:()=>_c,hydrateTournamentRecord:()=>BR,removeDrawDefinitionExtension:()=>CU,removeEventExtension:()=>Dp,removeExtension:()=>Ir,removeNotes:()=>Fg,removeOnlineResource:()=>WR,removeParticipantExtension:()=>bU,removeTournamentExtension:()=>Bf,setTournamentCategories:()=>$R,setTournamentDates:()=>CI,setTournamentEndDate:()=>zR,setTournamentName:()=>YR,setTournamentNotes:()=>qR,setTournamentStartDate:()=>KR,setTournamentStatus:()=>HR});function BR(t){let{tournamentRecord:e,eventProfiles:r=[],directives:n,policyDefinitions:o}=t;return e?((e.events||[]).forEach(s=>{let a=r.find(c=>c.eventId&&c.eventId===s.eventId);(a?.directives?.hydrateRoundNames||n?.hydrateRoundNames)&&s.drawDefinitions?.forEach(c=>{(a?.policyDefinitions?.[vo]||o?.[vo])&&by({drawDefinition:c,appliedPolicies:o})})}),{tournamentRecord:e}):{error:q}}var eB="ABANDONED",rB="ACTIVE",nB="CANCELLED",oB="COMPLETED",iB="IN_PROGRESS",ME={ABANDONED:eB,ACTIVE:rB,CANCELLED:nB,COMPLETED:oB,IN_PROGRESS:iB};function HR({tournamentRecord:t,status:e}){return t?e&&!Object.keys(ME).includes(e)?{error:B,info:"Unknown status"}:(t.tournamentStatus=e,{...C}):{error:q}}function WR(t){let e=et(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:Oe}});Fl({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:Oe}}):_({result:{error:re}});if(s){if(u.person?.personId!==s)return _({result:{error:Hi}});Fl({element:u.person,onlineResource:n})}else Fl({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:Vs}});Fl({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:ji}});Fl({element:u,onlineResource:n})}else Fl({element:r,onlineResource:n}),lt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Xi});return{...C}}function Fl({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>!(n?.[cc]===e[cc]&&n?.[uc]===e[uc]&&n?.[pc]===e[pc]));t.onlineResources=r}function jR(t){let e=et(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:Oe}});kl({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:Oe}}):_({result:{error:re}});if(s){if(u.person?.personId!==s)return _({result:{error:Hi}});kl({element:u.person,onlineResource:n})}else kl({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:Vs}});kl({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:ji}});kl({element:u,onlineResource:n})}else kl({element:r,onlineResource:n}),lt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Xi});return{...C}}function kl({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>n?.[cc]!==e[cc]&&n?.[uc]!==e[uc]&&n?.[pc]!==e[pc]);return r.push(e),t.onlineResources=r,{...C}}function YR({tournamentRecord:t,promotionalName:e,tournamentName:r,formalName:n}){if(!t)return{error:q};let o=t.tournamentId,i={tournamentId:o};return r&&r!==t.tournamentName&&(t.tournamentName=r,i.tournamentName=r),e&&e!==t.promotionalName&&(t.promotionalName=e,i.promotionalName=e),n&&n!==t.formalName&&(t.formalName=n,i.formalName=n),t.promotionalName===t.tournamentName&&(delete t.promotionalName,i.promotionalName=""),t.formalName===t.tournamentName&&(delete t.formalName,i.formalName=""),Object.keys(i).length>1&<({topic:Xi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:o,...i}}),{...C}}function qR({tournamentRecord:t,notes:e}){if(!t)return{error:q};let r=e?$p({element:t,notes:e}):Fg({element:t});return r.error?r:(lt({topic:Xi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,notes:e??""}}),{...C})}function $R({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(r=>r.categoryName&&r.type),t.tournamentCategories=e,lt({topic:Xi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,categories:e}}),{...C}):{error:q}}function _w({tournamentRecord:t}){if(!t)return{error:q};let{startDate:e,endDate:r}=t,n=js(e,r),o=[];for(let i of t.venues||[])i?.courts?.length&&o.push(...i.courts);for(let i of o){let{startTime:s,endTime:a}=(i.dateAvailability??[]).reduce((p,m)=>{let d=Yt(p.startTime),l=Yt(p.endTime);return m.startTime&&Yt(m.startTime)<d&&(p.startTime=m.startTime),m.endTime&&Yt(m.endTime)>l&&(p.endTime=m.endTime),p},{startTime:"08:00",endTime:"18:00"}),c=n.map(p=>i.dateAvailability?.find(d=>d.date===p)??{date:p,startTime:s,endTime:a}),u=i.dateAvailability?.find(p=>!p.date);u&&c.unshift(u),i.dateAvailability=c}return{...C}}function CI(t){let{tournamentRecord:e,startDate:r,endDate:n,weekdays:o}=t,i=t.activeDates?.filter(Boolean),s=et(t,[{tournamentRecord:!0},{[tr]:l=>Oo.test(l),[kr]:Ye,startDate:!1,endDate:!1},{[tr]:l=>l.filter(Boolean).every(f=>Oo.test(f)),[kr]:Ye,activeDates:!1},{[tr]:Fy,weekdays:!1}]);if(s.error)return s;if(n&&r&&new Date(n)<new Date(r))return{error:B};if(n&&r&&new Date(r)>new Date(n))return{error:B};if(i?.length){let l=r||e.startDate,f=n||e.endDate,g=!l||i.every(h=>new Date(h)>=new Date(l)),I=!f||i.every(h=>new Date(h)<=new Date(f));if(!g||!I)return{error:Ye}}let a;(r&&e.startDate&&new Date(r)>new Date(e.startDate)||n&&e.endDate&&new Date(n)<new Date(e.endDate))&&(a=!0);let c=js(e.startDate,e.endDate);r&&(e.startDate=r),n&&(e.endDate=n);let u=js(e.startDate,e.endDate),p=c.filter(l=>!u.includes(l)),m=u.filter(l=>!c.includes(l));for(let l of e.events??[])r&&l.startDate&&new Date(l.startDate)<new Date(r)&&(l.startDate=r),n&&l.startDate&&new Date(l.startDate)>new Date(n)&&(l.startDate=r??n),n&&l.endDate&&new Date(l.endDate)>new Date(n)&&(l.endDate=n),r&&l.endDate&&new Date(l.endDate)<new Date(r)&&(l.endDate=n??r);r&&e.endDate&&new Date(r)>new Date(e.endDate)&&(e.endDate=r),n&&e.startDate&&new Date(n)<new Date(e.startDate)&&(e.startDate=n),i&&(e.activeDates=i),o&&(e.weekdays=o);let d=a&&sB({tournamentRecord:e})?.unscheduledMatchUpIds;return _w({tournamentRecord:e}),lt({payload:nt({parentOrganisation:e.parentOrganisation,tournamentId:e.tournamentId,activeDates:i,startDate:r,weekdays:o,endDate:n}),topic:Xi}),{...C,unscheduledMatchUpIds:d,datesAdded:m,datesRemoved:p}}function KR({tournamentRecord:t,startDate:e}){return e?CI({tournamentRecord:t,startDate:e}):{error:Ye}}function zR({tournamentRecord:t,endDate:e}){return e?CI({tournamentRecord:t,endDate:e}):{error:Ye}}function sB({tournamentRecord:t}){let e=ye({tournamentRecord:t}).matchUps??[],r=t.startDate&&new Date(t.startDate),n=t.endDate&&new Date(t.endDate),o=[],i=[];for(let s of e){let{schedule:a,matchUpId:c}=s;if(a&&a.scheduledDate){let u=new Date(a.scheduledDate);(r&&u<r||n&&u>n)&&(i.push(c),o.includes(a.scheduledDate)||o.push(a.scheduledDate))}}return o.length&&!Sm({scheduledDates:o,tournamentRecord:t}).clearedScheduleCount?{error:WE}:{unscheduledMatchUpIds:i}}var aC={};Xt(aC,{addCourt:()=>vl,addCourts:()=>UI,addVenue:()=>Ec,deleteCourt:()=>oC,deleteVenue:()=>CE,deleteVenues:()=>ZR,disableCourts:()=>tC,disableVenues:()=>eC,enableCourts:()=>rC,enableVenues:()=>nC,generate:()=>JR,generateCourts:()=>uI,getCompetitionVenues:()=>om,getCourts:()=>Ny,getVenuesAndCourts:()=>Ro,modifyCourt:()=>OI,modifyCourtAvailability:()=>bI,modifyVenue:()=>iC,mutate:()=>sC,publicFindVenue:()=>US,query:()=>wN});var JR={};Xt(JR,{generateCourts:()=>uI});var sC={};Xt(sC,{addCourt:()=>vl,addCourts:()=>UI,addVenue:()=>Ec,deleteCourt:()=>oC,deleteVenue:()=>CE,deleteVenues:()=>ZR,disableCourts:()=>tC,disableVenues:()=>eC,enableCourts:()=>rC,enableVenues:()=>nC,modifyCourt:()=>OI,modifyCourtAvailability:()=>bI,modifyVenue:()=>iC});function Gl(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:q};if(!t?.courtId)return{error:Bi};let{scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n,venueMatchUps:o,courtId:i}=t,{schedulingProfile:s}=oi({tournamentRecord:r});if(Array.isArray(o))return{matchUps:u({matchUps:o,courtId:i})};let{matchUps:a}=ye({scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n});return{matchUps:u({matchUps:a,courtId:i})};function u({matchUps:p,courtId:m}){let d=p.filter(l=>{let f=l.schedule?.allocatedCourts?.map(({courtId:g})=>g);return l.schedule?.courtId===m||f?.includes(m)});return gl({matchUps:d,schedulingProfile:s})}}function xw({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r,venueId:n}){if(!e)return{error:q};if(!n)return{error:ai};let{schedulingProfile:o}=oi({tournamentRecord:e}),{matchUps:i}=ye({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r});return{matchUps:a({matchUps:i,venueId:n})};function a({matchUps:c,venueId:u}){let p=c.filter(m=>{let d=m.schedule?.allocatedCourts?.map(({venueId:l})=>l);return m.schedule?.venueId===u||d?.includes(u)});return gl({matchUps:p,schedulingProfile:o})}}function bI({tournamentRecord:t,dateAvailability:e,disableNotice:r,venueMatchUps:n,courtId:o,force:i}){if(!t)return{error:q};if(!o)return{error:Bi};let s=EE({dateAvailability:e});if(s.error)return s;let{updatedDateAvailability:a,totalMergeCount:c}=aB(e);e=a;let u=hs({tournamentRecord:t,courtId:o});if(u.error)return u;let{court:p,venue:m}=u,{matchUps:d}=Gl({tournamentRecord:t,venueMatchUps:n,courtId:o});if(d?.length){let l=Tt({tournamentRecord:t})?.appliedPolicies,f=i??l?.[_o]?.allowDeletionWithScoresPresent?.courts,g=[];g.length&&(f||console.log("throw error: scheduled court matchUps",g.length))}return p&&(p.dateAvailability=e,!r&&m&<({payload:{venue:m,tournamentId:t.tournamentId},topic:Ri,key:m.venueId})),{...C,totalMergeCount:c}}function aB(t){let e=0,r=t.reduce((o,i)=>{let{date:s,startTime:a,endTime:c,bookings:u}=i;return o[s]||(o[s]=[]),o[s].push({startTime:a,endTime:c,bookings:u}),o},{}),n=[];return Object.keys(r).forEach(o=>{r[o].sort(Sw);let{mergedAvailability:i,mergeCount:s}=cB(r[o]);n.push(...i.map(a=>({date:o,...a}))),e+=s}),{updatedDateAvailability:n,totalMergeCount:e}}function cB(t){let e,r,n,o=t.length,i=0,s=[];for(;t.length&&o;){let c=t.shift(),{startTime:u,endTime:p,bookings:m}=c;if(o-=1,!e)e=u,n=m,r=p;else if(ya(Ge(r),Ge(u),!1)>0){let l={startTime:e,endTime:r};n?.length&&(l.bookings=n),s.push(l),e=u,n=m,r=p}else m&&(n?n.push(m):n=m),r=p,i+=1}let a={startTime:e,endTime:r};return n?.length&&(a.bookings=n),s.push(a),{mergedAvailability:s,mergeCount:i}}function Vl({matchUpsCount:t=0}){let r=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:qA,info:r}}function RE({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:n}){let o="removeCourtAssignment";if(!r)return{error:sr};if(!e&&!n)return{error:cn};let i;if(!e){if(!t)return{error:q};({drawDefinition:e}=ze({tournamentRecord:t,drawId:n}))}if(e)({matchUp:i}=Vt({drawDefinition:e,matchUpId:r}));else{if(!t)return{error:q};let s=ye({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=sT({matchUps:s,matchUpId:r}))}return i?(i.timeItems&&i.timeItems.find(a=>[Jo,lo].includes(a.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:a})=>![Jo,lo].includes(a)),gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:i})),{...C}):{error:we}}function CE(t){if(typeof t?.venueId!="string")return{error:ai};let{tournamentRecord:e,venueId:r,force:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(o).length)return{error:q};let s=Mn({tournamentRecords:o,contextFilters:{venueIds:[r]}}).matchUps??[],a=Tt({tournamentRecord:e})?.appliedPolicies,c=n??a?.[_o]?.allowDeletionWithScoresPresent?.venues;if(!s.length||c)for(let u of Object.values(o)){for(let m of s){let d=RE({matchUpId:m.matchUpId,drawId:m.drawId,tournamentRecord:u});if(d.error)return d}let p;u.venues=(u.venues??[]).filter(m=>m?.venueId!==r?!0:(p=!0,!1)),p&<({payload:{venueId:r,tournamentId:u.tournamentId},topic:$f,key:r})}else return Vl({matchUpsCount:s.length});return Fc({tournamentRecords:o}),{...C}}function ZR({tournamentRecord:t,venueIds:e,force:r}){if(!t)return{error:q};if(!Array.isArray(e))return{error:B};for(let n of t.venues||[]){let{venueId:o}=n;if(e.includes(o)){let{venueId:i}=n,s=CE({tournamentRecord:t,venueId:i,force:r});if(s.error)return s}}return{...C}}function tC(t){let{courtIds:e,dates:r}=t,n=Rr(t),o=[{[Re]:!0,[Ap]:!0}],i=et(t,o);if(i.error)return i;for(let s of Object.values(n))uB({tournamentRecord:s,courtIds:e,dates:r});return{...C}}function uB({tournamentRecord:t,courtIds:e,dates:r}){let n=Array.isArray(r)&&r.length?{dates:r}:!0,o=i=>At({extension:{value:n,name:uo},creationTime:!1,element:i});for(let i of t.venues||[])for(let s of i.courts||[])if(e?.includes(s.courtId)){let a=o(s);if(a.error)return a}return{...C}}function eC(t){let{tournamentRecords:e,tournamentId:r,venueIds:n}=t,o=[{[Re]:!0,[Up]:!0}],i=et(t,o);if(i.error)return i;let s=Object.keys(e).filter(a=>!r||a===r);for(let a of s){let c=e[a];pB({tournamentRecord:c,venueIds:n})}return{...C}}function pB({tournamentRecord:t,venueIds:e}){for(let r of t.venues||[])if(e?.includes(r.venueId)){let n=At({creationTime:!1,element:r,extension:{name:uo,value:!0}});if(n.error)return n}return{...C}}function rC(t){let e=Rr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[Ap]:!0});let n=et(t,r);if(n.error)return n;let{enableAll:o,courtIds:i,dates:s}=t;for(let a of Object.values(e))mB({tournamentRecord:a,courtIds:i,enableAll:o,dates:s});return{...C}}function mB({tournamentRecord:t,courtIds:e,enableAll:r,dates:n}){for(let o of t.venues||[])for(let i of o.courts||[])if(r||e?.includes(i.courtId))if(Array.isArray(n)){let{extension:s}=mt({element:i,name:uo});if(s){let a=s.value;Array.isArray(a.dates)&&(a.dates=a.dates.filter(c=>!n.includes(c))),At({extension:{name:uo,value:a},creationTime:!1,element:i})}}else Ir({element:i,name:uo});return{...C}}function nC(t){let e=Rr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[Up]:!0});let n=et(t,r);if(n.error)return n;let{venueIds:o,enableAll:i}=t;for(let s of Object.values(e))for(let a of s.venues||[])(i||o?.includes(a.venueId))&&Ir({element:a,name:uo});return{...C}}function oC(t){let{courtId:e,disableNotice:r,force:n}=t,o=Rr(t),i=et(t,[{[Re]:!0,[Fh]:!0}]);if(i.error)return i;let s,a;for(let c of Object.values(o)){if(a=dB({tournamentRecord:c,disableNotice:r,courtId:e,force:n}),a.error&&a.error!==Vs)return a;a.success&&(s=!0)}return s?{...C}:a}function dB({tournamentRecord:t,disableNotice:e,courtId:r,force:n}){let o=hs({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.venue,{matchUps:s}=Gl({tournamentRecord:t,courtId:r}),a=Tt({tournamentRecord:t})?.appliedPolicies,c=n??a?.[_o]?.allowDeletionWithScoresPresent?.courts;if(!s?.length||c){for(let u of s??[]){let p=RE({matchUpId:u.matchUpId,drawId:u.drawId,tournamentRecord:t});if(p.error)return p}i&&(i.courts=(i.courts??[]).filter(u=>u.courtId!==r),e||lt({payload:{venue:i,tournamentId:t.tournamentId},topic:Ri,key:i.venueId}))}else return Vl({matchUpsCount:s.length});return{...C}}function OI(t){let{disableNotice:e,modifications:r,courtId:n,force:o,venueMatchUps:i}=t,s=Rr(t);if(!Object.keys(s).length)return{error:xt};let a,c;for(let u of Object.values(s)){let p=lB({tournamentRecord:u,disableNotice:e,venueMatchUps:i,modifications:r,courtId:n,force:o});if(p?.error)return p;a=!0}return a?{...C}:c}function lB({tournamentRecord:t,disableNotice:e,venueMatchUps:r,modifications:n,courtId:o,force:i}){if(!t)return{error:q};if(!o)return{error:Bi};if(!n||typeof n!="object")return{error:So};let s=hs({tournamentRecord:t,courtId:o});if(s.error)return s;let{venue:a,court:c}=s,u=Object.keys(hw()).filter(l=>l!=="courtId");if(!Object.keys(n).filter(l=>u.includes(l)).length)return{error:up};let m=u.filter(l=>!["dateAvailability"].includes(l)),d=Object.keys(n).filter(l=>m.includes(l));if(c&&d.forEach(l=>Object.assign(c,{[l]:n[l]})),n.dateAvailability){let l=bI({dateAvailability:n.dateAvailability,tournamentRecord:t,venueMatchUps:r,disableNotice:e,courtId:o,force:i});if(l.error)return l}return e||lt({payload:{venue:a,tournamentId:t.tournamentId},topic:Ri,key:a?.venueId}),{...C,court:J(c)}}var fB=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]}),ww=fB;function iC(t){let{modifications:e,venueId:r,force:n}=t,o=Rr(t);if(!Object.keys(o).length)return{error:xt};if(typeof r!="string")return{error:ai};let i,s;for(let a of Object.values(o)){let c=gB({tournamentRecord:a,modifications:e,venueId:r,force:n});if(c.success&&(s=!0),c.error&&(i=c.error),c.error&&c.error!==ji)return c}return Fc({tournamentRecords:o}),s?{...C}:{error:i}}function gB({tournamentRecord:t,modifications:e,venueId:r,force:n}){if(!t)return{error:q};if(!e||typeof e!="object")return{error:So};if(!r)return{error:ai};let o=Tt({tournamentRecord:t})?.appliedPolicies,i=n??o?.[_o]?.allowDeletionWithScoresPresent?.venues,{matchUps:s}=xw({tournamentRecord:t,venueId:r}),a=ti({tournamentRecord:t,venueId:r});if(a.error)return a;let c=a.venue,u=Object.keys(ww()).filter(h=>h!=="venueId");if(!Object.keys(e).filter(h=>u.includes(h)).length)return{error:up};let m=u.filter(h=>!["courts","onlineResources"].includes(h)),d=Object.keys(e).filter(h=>m.includes(h));c&&d.forEach(h=>Object.assign(c,{[h]:e[h]}));let l=c?.courts?.map(h=>h.courtId)??[],f=e.courts?.map(h=>h.courtId)||[],g=f.length?l.filter(h=>!f.includes(h)):e?.courts&&l,I=[];if(g?.length){let S=c?.courts?.filter(T=>g.includes(T.courtId))?.map(T=>{let y=Gl({courtId:T.courtId,tournamentRecord:t,venueMatchUps:s});for(let E of y.matchUps??[])I.push({matchUpId:E.matchUpId,drawId:E.drawId});return y.matchUps?.length??0}).reduce((T,y)=>T+y);if(c&&(!S||i))c.courts=c.courts?.filter(T=>f.includes(T.courtId)),Xu({schedule:{courtId:"",scheduledDate:""},matchUpDetails:I,removePriorValues:!0,tournamentRecord:t});else return Vl({matchUpsCount:S})}if(e.courts)for(let h of e.courts){let{courtId:S}=h||{},T=OI({modifications:h,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:S,force:n});if(T.error===Vs&&(T=vl({disableNotice:!0,tournamentRecord:t,venueId:r,court:h})),T.error)return T}return Fc({tournamentRecord:t}),c&<({payload:{venue:c,tournamentId:t.tournamentId},topic:Ri,key:c?.venueId}),{...C,venue:J(c)}}var cC={};Xt(cC,{JSON2CSV:()=>Bw,UUID:()=>Nt,UUIDS:()=>ph,allNumeric:()=>wI,attributeFilter:()=>Qi,chunkArray:()=>Ae,chunkByNth:()=>Wl,chunkSizeProfile:()=>kE,constantToString:()=>Qe,countValues:()=>yC,createMap:()=>kI,dateTime:()=>uh,definedAttributes:()=>nt,dehydrateMatchUps:()=>Vw,extractAttributes:()=>uP,flattenJSON:()=>OE,generateDateRange:()=>js,generateHashCode:()=>MC,generateRange:()=>tt,generateTimeCode:()=>AE,groupValues:()=>LE,hasAttributeValues:()=>NC,instanceCount:()=>Er,intersection:()=>jt,isConvertableInteger:()=>It,isNumeric:()=>Jt,isOdd:()=>_I,isPowerOf2:()=>Ln,makeDeepCopy:()=>J,matchUpScheduleSort:()=>Gw,matchUpSort:()=>xi,nearestPowerOf2:()=>Cm,nextPowerOf2:()=>us,noNulls:()=>TC,noNumeric:()=>LI,numericSort:()=>le,occurrences:()=>EC,overlap:()=>ke,randomMember:()=>Un,randomPop:()=>tn,shuffleArray:()=>Tr,structureSort:()=>Ni,subSort:()=>AC,undefinedToNull:()=>FI,unique:()=>pt,visualizeScheduledMatchUps:()=>Lw});function Lw({scheduledMatchUps:t,showGlobalLog:e}){dO();let r=t?.reduce((o,{structureId:i})=>o.includes(i)?o:o.concat(i),[]),n=Array.isArray(r)&&{...r.map(o=>{let{structureName:i,matchUpType:s}=t.find(a=>a.structureId===o);return{[o]:`${i} ${s}`}})};r?.forEach(o=>{Tn({color:"blue",method:"draw",structure:n[o],keyColors:{structure:"magenta"}},!0);let i=t.filter(a=>a.structureId===o),s=Ke({matchUps:i})?.roundMatchUps||[];Object.keys(s).forEach(a=>{Tn({roundNumber:a,keyColors:{roundNumber:"brightcyan"}},!0),s[a].forEach(({matchUpId:c,schedule:u})=>{let p=zt(u.scheduledTime);Tn({matchUpId:c,time:p,date:u.scheduledDate,venue:u.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&mO()}var{extractTime:Fw,timeStringMinutes:kw}=uh;function Gw(t,e){let r=t.schedule??{},n=e.schedule??{};if(r.scheduledDate&&!n.scheduledDate)return 1;if(n.scheduledDate&&!r.scheduledDate)return-1;if(r.scheduledDate&&n.scheduledDate){if(r.scheduledDate===n.scheduledDate){if(r.scheduledTime&&!n.scheduledTime)return 1;if(n.scheduledTime&&!r.scheduledTime)return-1;if(r.scheduledTime&&n.scheduledTime){let o=kw(Fw(r.scheduledTime)),i=kw(Fw(n.scheduledTime));return o-i}}return new Date(r.scheduledDate).getTime()-new Date(n.scheduledDate).getTime()}return 0}function Vw({tournamentRecord:t}){if(!t)return{error:q};if(typeof t!="object"||!t.tournamentId)return{error:B};let{matchUps:e}=ye({tournamentRecord:t,inContext:!1});if(e?.length){let r=IB({tournamentRecord:t});SB(e,r)}return{...C}}function IB({tournamentRecord:t}){let e={};for(let r of t.events||[]){r.matchUpFormat&&(e[r.eventId]=r.matchUpFormat);for(let n of r.drawDefinitions||[]){n.matchUpFormat&&(e[n.drawId]=n.matchUpFormat);for(let o of n.structures||[]){o.matchUpFormat&&(e[o.structureId]=o.matchUpFormat);for(let i of o.structures||[])i.matchUpFormat&&(e[i.structureId]=i.matchUpFormat)}}}return e}var hB=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function SB(t,e={}){for(let r of t){let{structureId:n,drawId:o,eventId:i}=r,s=e[n]||e[o]||e[i],a=r.matchUpFormat===s?void 0:r.matchUpFormat;for(let c of Object.keys(r))hB.includes(c)||delete r[c];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,a&&(r.matchUpFormat=a)}}function Bw(t,e){if(e&&typeof e!="object")return{error:B};let{columnTransform:r={}}=e||{},{includeTransformAccessors:n,includeHeaderRow:o=!0,returnTransformedJSON:i,removeEmptyColumns:s,onlyHeaderRow:a,columnAccessors:c=[],functionMap:u={},columnMap:p={},valuesMap:m={},context:d={},delimiter:l='"',columnJoiner:f=",",rowJoiner:g=`\r
|
|
26
|
+
`),u=r?.map(({key:l,value:f})=>`${l}="${f}"`).join(" "),p=u?` ${u}`:"";if(e==="childArray")return c;let m=c?.length?`${i}${c}${i}`:"",d=a?.length?`${i}${a}${i}`:"";return`<${e}${p}>${m}${d}</${e}>`}function Dx(t){let e=et(t,[{[ne]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{startDate:n,tournamentId:o,tournamentName:i}=r,{participantMap:s,matchUps:a,mappedMatchUps:c}=Ft({withMatchUps:!0,withEvents:!0,tournamentRecord:r}),u=r.participants.filter(y=>y.participantType===wt),p=a?.filter(y=>y.matchUpType===wt)??[],m=p?.reduce((y,E)=>{let P=E?.tieMatchUps??[];return P&&[...y,...P]},[])??[],d=a?.filter(y=>y.matchUpType===Lt)??[],l=a?.filter(y=>y.matchUpType===vt)??[],f=m.length===d.length+l.length,g=p.length===1&&f,h={mappedMatchUps:c,participantMap:s,tournamentName:i,tournamentId:o,tournament:f?"N":"Y",startDate:n},S=[],T=[];if(g){let y=p[0],{json:E,xml:P}=Ux({teamParticipants:u,teamMatchUp:y,...h,doubles:l,singles:d});T.push(E),S.push(P)}else for(let y of p){let E=y?.sides?.map(({participant:N})=>N?.participantId).filter(Boolean);if(E?.length!==2)continue;let P=E.map(N=>N&&s?.[N]?.participant),{xml:A,json:U}=Ux({doubles:y.tieMatchUps?.filter(N=>N.matchUpType===vt),singles:y.tieMatchUps?.filter(N=>N.matchUpType===Lt),teamParticipants:P,teamMatchUp:y,...h});T.push(U),S.push(A)}return{json:T,xml:S,...C}}function Ux({teamParticipants:t,mappedMatchUps:e,participantMap:r,tournamentName:n,tournamentId:o,teamMatchUp:i,tournament:s,startDate:a,doubles:c,singles:u}){let p=t?.find(y=>y.participantRoleResponsibilities?.includes("Home")),m=t?.filter(y=>y.participantId!==p?.participantId),d=Kn(a,"/","MDY"),l=p?.participantName||m?.[1]?.participantName,f=p?.participantId||m?.[1]?.participantId,g=m?.[0]?.participantName,I=m?.[0]?.participantId,h={},S=t.map(y=>({team:{...s0({teamParticipant:y,teamMatchUp:i,uniValues:h,participantMap:r,mappedMatchUps:e,homeid:f})}})),T=nt({venue:{tournamentname:s?n:void 0,neutralgame:p?"N":"Y",gameid:o,officials:{},tournament:s,rules:{},homename:l,visname:g,homeid:f,visid:I,date:d},childArray:S,singles_matches:u?.map(y=>Px({matchUp:y,homeid:f,uniValues:h})),doubles_matches:c?.map(y=>Px({matchUp:y,homeid:f,uniValues:h}))});return{json:T,xml:cM({json:T,tagName:"tngame"})}}function o0({homeid:t,uniValues:e,participant:r}){if(!r)return{};let n=r.individualParticipants?.length===2,o=n?pt(r.individualParticipants?.map(g=>g.teams?.[0]?.participantId)):[],i=n?pt(r.individualParticipants?.map(g=>g.teams?.[0]?.teamId)):[],s=!n&&r.teams?.[0]?.participantId||o?.length===1&&o[0]||void 0,a=!n&&r.teams?.[0]?.teamId||i?.length===1&&i[0]||s,c=n?void 0:r.participantName,u=r.individualParticipants?.[0]?.participantName,p=r.individualParticipants?.[1]?.participantName,m=t&&(s===t?"H":"V")||"",d=n?void 0:e[s][r.participantId],l=e[s][r.individualParticipants?.[0]?.participantId],f=e[s][r.individualParticipants?.[1]?.participantId];return nt({vh:m,uni:d,uni_1:l,uni_2:f,team:a,name:c,name_1:u,name_2:p})}function i0({sets:t,sideNumber:e}){return Object.assign({},...t?.map(r=>{let{setNumber:n,side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a}=r,c=`set_${n}`,u=`tie_${n}`,p=e===1?o:i,m=e===1?s:a;return{[c]:p,[u]:m}})??[])}function s0({teamParticipant:t,teamMatchUp:e,participantMap:r,mappedMatchUps:n,homeid:o,uniValues:i}){let{participantId:s,participantName:a}=t,c=o&&(s===o?"H":"V")||"",u=r?.[s]?.matchUps,p=u&&Object.keys(u),m=e?.sides?.find(({participant:E})=>E.participantId===s)?.sideNumber,d=e?.score?.sets?.[0]?.[`side${m}Score`]??0;i[s]={};let l={SINGLES:{w:0,l:0},DOUBLES:{w:0,l:0}},f=[],g=[],I=0;for(let E of p??[]){let P=n?.[E],A=P.sides.find(({participant:N})=>N.participantId===s)?.sideNumber,U=P.score?.sets?.[0]?.[`side${A}Score`]??0;I+=U;for(let N of P.tieMatchUps??[]){let{matchUpType:D,winningSide:M}=N,R=M&&(M===A?"w":"l")||"";R&&(l[D][R]+=1);let b=R==="w"?"1":"0",O=R==="l"?"1":"0";if(D===Lt){let v=g.length+1;g.push({singles_pair:{pair:v,won:b,lost:O,tied:"0"}})}else if(D===vt){let v=f.length+1;f.push({doubles_pair:{pair:v,won:b,lost:O,tied:"0"}})}}}let h=[{singles:{childArray:g,won:l.SINGLES.w,lost:l.SINGLES.l}},{doubles:{childArray:f,won:l.DOUBLES.w,lost:l.DOUBLES.l}}],S=[],T=1;for(let E of t.individualParticipantIds){let P=r?.[E];if(P){let{participant:A,counters:U}=P,N={won:U?.DOUBLES?.wins||0,lost:U?.DOUBLES?.losses||0},D={won:U?.SINGLES?.wins||0,lost:U?.SINGLES?.losses||0},{participantName:M,participantId:R}=A;i[s][R]=T,S.push({player:{name:M,uni:T,singles:D,doubles:N}})}T+=1}return{vh:c,id:s,name:a,score:d||I,totals:h,childArray:S}}function Px({matchUp:t,homeid:e,uniValues:r}){let{collectionPosition:n,orderOfFinish:o,matchUpType:i,sides:s}=t??{},a=s?.map(u=>{let{sideNumber:p,participant:m}=u,d=i0({sets:t.score?.sets,sideNumber:p});return{[i===Lt?"singles_score":"doubles_score"]:{...o0({homeid:e,uniValues:r,participant:m}),...d}}});return{[i===Lt?"singles_match":"doubles_match"]:{match:n,order:o,childArray:a}}}var a0="DESC",Vy="DESC",Nx={ASC:"ASC",ASCENDING:"ASC",DESC:a0,DESCENDING:Vy};function By(t){let{tieFormat:e}=t,{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:o,scaleAccessor:i,singlesOnly:s,attach:a,event:c}=t;if(c?.eventType!==Or)return{error:$n};if(!n)return{error:q};if(!e&&!o)return{error:br};if(e=e??We({drawDefinition:o,event:c})?.tieFormat,ar({tieFormat:e}).error)return{error:Yo};if(typeof i!="object"&&!r)return{error:B,context:{scaleAccessor:i}};let u={},m=(o?.entries??c?.entries??[]).filter(R=>R?.entryStatus===Gr).map(St),{participants:d=[]}=Ft({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),l=d.filter(({participantId:R})=>m.includes(R)),f=R=>R===Ai?"rankings":"ratings",g=c?.category?.categoryName??c?.category?.ageCategoryCode,{scaleName:I=g,scaleType:h=Ai,sortOrder:S,accessor:T}=i||{},y=f(h),E=(R,b)=>{let O=R[y]?.[b];if(!O&&r&&(O=R[y]?.[Ia]),Array.isArray(O)){let v=O.find(x=>x.scaleName===I)?.scaleValue;if(Jt(v))return v;if(T&&typeof v=="object")return v[T]}return 0},P=(R,b,O)=>{let v=S===Vy?b:R,x=S===Vy?R:b;return E(v,O)-E(x,O)},A=(R,b)=>P(R,b,Ia),U=(R,b)=>P(R,b,Gi),N=[],D=e?.collectionDefinitions??[];for(let R of l){let b=R.individualParticipants?.sort(A)??[],O=s?b:R.individualParticipants?.sort(U)??[],v={};for(let F of D){let w=[],{collectionId:L,matchUpCount:k,matchUpType:G,gender:H}=F,K=de(Ia)(G);tt(0,k).forEach(Y=>{let j=K?b:O??[],V=Y+1,$=[];tt(0,K?1:2).forEach(X=>{let W=j?.find(it=>{let z=yr(H),Q=z&&(Dn(H)&&z||en(H)&&[Le,lr][X]);return(!Q||Q===it.person?.sex)&&!w.includes(it.participantId)})?.participantId;W&&($.push(W),w.push(W),v[W]||(v[W]=[]),v[W].push({collectionPosition:V,collectionId:L}))}),K||N.push($)})}let x=Object.keys(v).map(F=>({collectionAssignments:v[F],participantId:F}));u[R.participantId]=x}let M=[];for(let R of N){let{participant:b}=Sn({tournamentParticipants:d,participantIds:R});if(!b){let O={individualParticipantIds:R,participantRole:xe,participantType:ft};M.push(O)}}if(a){for(;M.length;)wn({participant:M.pop(),tournamentRecord:n});At({element:o,extension:{name:wo,value:u}})}return{...C,lineUps:u,participantsToAdd:M}}function uI(t){if(!t)return{error:st};let e=et(t,[{dates:!1,[tr]:s=>Array.isArray(s)&&s.every(Mr)},{uuids:!1,[tr]:s=>Array.isArray(s)&&s.every(kt)},{startTime:!1,endTime:!1,[tr]:sh},{idPrefix:!1,namePrefix:!1,[tr]:kt},{count:!0,[tr]:Jt}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord??{},o=t.dates||r&&n&&js(r,n)||[],i=tt(1,t.count+1).map(s=>nt({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${s}`)??Nt(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${s}`),dateAvailability:o.map(a=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:a}))}));return{...C,courts:i}}var uM={};Xt(uM,{default:()=>c0,garman:()=>Cx});function ja({court:t,date:e}){let r=e&&t.dateAvailability.find(o=>zn(o.date,e)),n=t.dateAvailability.find(o=>!o.date);return r||n}function _s(t){let e=et(t,[{courtDate:!0,_ofType:zr}]);if(e.error)return e;let{includeBookingTypes:r=[],courtDate:n}=t,o=[],i=Ge(n.startTime);(n.bookings||[]).filter(a=>!a.bookingType||!r.includes(a.bookingType)).sort((a,c)=>Nf(a.startTime).localeCompare(Nf(c.startTime))).forEach(a=>{let c={startTime:zt(i.toISOString()),endTime:a.startTime};Ge(a.startTime)>i&&o.push(c),Ge(a.endTime)>i&&(i=Ge(a.endTime))});let s={startTime:zt(i.toISOString()),endTime:n.endTime};return Ge(n.endTime)>i&&o.push(s),{timeSlots:o}}function Mx({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:r,periodEndTime:n}){let o=s=>{let{timeSlots:a}=_s({includeBookingTypes:e,courtDate:s});return!!a?.filter(i)?.length};function i(s){let a=Ge(s.startTime),c=Ge(s.endTime);return a>r||c<n?!1:ya(r,c)>=t}return{enoughTime:o}}function Hy(t){let e=et(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:Be}]);if(e.error)return e;let{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:o,date:i}=t,s=t.courts,a=Ge(o),c=Rf(a,r),{enoughTime:u}=Mx({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:a,periodEndTime:c});return{availableToScheduleCount:(s?.filter(m=>{if(!Array.isArray(m.dateAvailability))return!1;let d=ja({date:i,court:m});return!!(d&&u(d))})||[]).length,...C}}function mm(t){let{remainingScheduleTimes:e=[],clearScheduleDates:r,periodLength:n=30,scheduleDate:o,courts:i=[]}=t,{bookings:s=[]}=t;if(!Array.isArray(i)||!i.length)return{error:B,courts:i};if(!Array.isArray(s))return{error:vm};if(!Mr(o))return{error:Ye};r&&(Array.isArray(r)?r.includes(o)&&(s=[]):s=[]);let{courtBookings:a,unassignedBookings:c}=s.reduce((l,f)=>{let{courtId:g}=f;return g?l.courtBookings[g]?l.courtBookings[g].push(f):l.courtBookings[g]=[f]:l.unassignedBookings.push(f),l},{courtBookings:{},unassignedBookings:[]}),u=i.map((l,f)=>{let{courtId:g,courtName:I}=l,h=a[g]||[],S=ja({date:o,court:l})||{},{bookings:T=[],startTime:y,endTime:E,date:P}=S,U=[e[f]&&{startTime:y,endTime:e[f]},...J(T,!1,!0),...h].filter(Boolean);return{courtId:g,courtName:I,dateAvailability:{bookings:U,startTime:y,endTime:E,date:P}}});c.sort((l,f)=>Yt(l.startTime)-Yt(f.startTime));let p=()=>u.map(l=>{let f=l.dateAvailability,{timeSlots:g=[]}=_s({courtDate:f});return{courtName:l.courtName,courtId:l.courtId,timeSlots:g}}).flat(),m=[];for(let l of c){let{startTime:f,endTime:g,averageMinutes:I,recoveryMinutes:h,matchUpId:S}=l,T=Yt(f),y=Yt(g),P=p().reduce((A,{courtId:U,courtName:N,timeSlots:D})=>{let M;return D.find(({startTime:b,endTime:O})=>{M=Yt(b)-T;let v=T>=Yt(b);return y<=Yt(O)&&A.startDifference!==0&&((M===0||M+n>=0)&&(A.startDifference===void 0||M<A.startDifference)||v)})?{courtName:N,courtId:U,startDifference:M}:A},{});if(P.courtId){let A={averageMinutes:I,recoveryMinutes:h,matchUpId:S,startTime:f,endTime:g};m.push(A),u.find(({courtId:N})=>N===P.courtId)?.dateAvailability.bookings.push(A)}else console.log({unassignedBooking:l})}return{virtualCourts:u.map(({courtId:l,courtName:f,dateAvailability:g})=>({dateAvailability:[g],courtName:f,courtId:l})),assignedBookings:m}}function zu({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:r}){let n=(t||90)+(r||0);return e>n?n:e||30}function Wy(t){let{startTime:e="8:00",endTime:r="20:30",count:n=10,date:o}=t??{};return tt(0,n).map(()=>({dateAvailability:[{date:o,startTime:e,endTime:r}]}))}function Gc({scheduleDate:t,startTime:e,endTime:r,courts:n}){let o=e&&"startTime"||r&&"endTime"||void 0;return n.reduce((i,s)=>{let a=ja({date:t,court:s}),c=o&&(a?.[o]||s[o]);return c&&(!i||e&&Yt(c)<Yt(i)||r&&Yt(c)>Yt(i))?c:i},void 0)}function Rx({averageMinutes:t,startTime:e,endTime:r,courts:n,date:o}){e=e||Gc({courts:n,scheduleDate:o,startTime:!0}),r=r||Gc({courts:n,scheduleDate:o,endTime:!0});let i;if(e&&r){let s=Ge(e),a=Ge(r);for(let c of n||[]){if(!Array.isArray(c.dateAvailability))continue;let u=ja({court:c,date:o}),{timeSlots:p}=_s({courtDate:u});p?.forEach(m=>{let d=Ge(m.startTime),l=Ge(m.endTime);if(d>a||d<s||l<s)return!1;if(ya(d,l)>=t){let I=zt(d.toISOString());(!i||I<i)&&(i=I)}})}}return{firstTimeSlotStartTime:i}}function El(t){let e=et(t,[{courts:!0,_ofType:Be}]);if(e.error)return e;let{date:r=Mf(),startTime:n="08:00",endTime:o="19:00",periodLength:i,courts:s}=t,{calculateStartTimeFromCourts:a=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:p,courtsCount:m,bookings:d}=t;i=i||zu({averageMatchUpMinutes:u}),r=Ut(r),n=zt(n),o=zt(o);let l=0,f=0,g=0,I=0,h=0;!s&&m&&(s=Wy({startTime:n,endTime:o,count:m,date:r}));let{virtualCourts:S}=mm({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:r,periodLength:i,bookings:d,courts:s}),{firstTimeSlotStartTime:T}=Rx({averageMinutes:u,courts:S,startTime:n,endTime:o,date:r});a&&T&&(n=T??n);let y=Yt(n),P=Yt(o)-y,A=Math.floor(P/i),N=tt(0,A+1).map(M=>{let R=y+M*i,b=JC(R),O=Hy({courts:S??[],averageMatchUpMinutes:u,periodStart:b,date:r});if(O.error)return{error:O.error};let{availableToScheduleCount:v=0}=O,x=v>f?v-f:0;h+=M?v:0;let F=M?h/M:v,L=i*F/u,k=M?L*(M-1)+F:F,G=v?f&&k-l||x:0;l=k,f=v,g+=G;let H=dt(g)-I;return I+=H,{periodStart:b,add:H,availableToScheduleCount:v,newCourts:x,totalMatchUps:I}});return{scheduleTimes:N.reduce((M,R)=>{let O=tt(0,R.add).map(()=>({scheduleTime:R.periodStart}));return M.concat(...O)},[]).flat(),timingProfile:N,totalMatchUps:I}}var Cx={getCourtsAvailableAtPeriodStart:Hy,generateTimeSlots:_s,getScheduleTimes:El,courtGenerator:Wy},c0=Cx;var jy={};Xt(jy,{isValid:()=>Nr,isValidMatchUpFormat:()=>Nr,parse:()=>Ne,stringify:()=>gp});var bM={};Xt(bM,{allCompetitionMatchUps:()=>Mn,allDrawMatchUps:()=>nr,allEventMatchUps:()=>to,allTournamentMatchUps:()=>ye,analyzeMatchUp:()=>cm,applyLineUps:()=>RM,assignMatchUpSideParticipant:()=>mM,assignTieMatchUpParticipantId:()=>Pl,bulkMatchUpStatusUpdate:()=>PM,calculateWinCriteria:()=>Os,checkInParticipant:()=>mI,checkMatchUpIsComplete:()=>Ts,checkOutParticipant:()=>pI,competitionScheduleMatchUps:()=>Ku,disableTieAutoCalc:()=>AM,drawMatchUps:()=>Dy,enableTieAutoCalc:()=>TM,eventMatchUps:()=>Il,filterMatchUps:()=>_i,findMatchUp:()=>tI,getAllDrawMatchUps:()=>ie,getAllStructureMatchUps:()=>yt,getCheckedInParticipantIds:()=>Is,getCompetitionMatchUps:()=>am,getEventMatchUpFormatTiming:()=>Iy,getHomeParticipantId:()=>yy,getMatchUpCompetitiveProfile:()=>Du,getMatchUpContextIds:()=>Ey,getMatchUpDailyLimits:()=>Sl,getMatchUpDailyLimitsUpdate:()=>hy,getMatchUpDependencies:()=>an,getMatchUpFormat:()=>Ay,getMatchUpFormatTiming:()=>Nu,getMatchUpFormatTimingUpdate:()=>fy,getMatchUpScheduleDetails:()=>yd,getMatchUpType:()=>Ed,getMatchUpsStats:()=>Uy,getModifiedMatchUpFormatTiming:()=>fl,getParticipantResults:()=>ku,getPredictiveAccuracy:()=>Ty,getRoundMatchUps:()=>Ke,getRounds:()=>Py,isValidMatchUpFormat:()=>Nr,matchUpActions:()=>Bd,mutate:()=>CM,participantScheduledMatchUps:()=>Sy,query:()=>xN,removeDelegatedOutcome:()=>yM,removeMatchUpSideParticipant:()=>lI,removeTieMatchUpParticipantId:()=>lM,replaceTieMatchUpParticipantId:()=>dI,resetAdHocMatchUps:()=>NM,resetMatchUpLineUps:()=>gI,resetScorecard:()=>hI,resetTieFormat:()=>II,setDelegatedOutcome:()=>DM,setMatchUpFormat:()=>UM,setMatchUpStatus:()=>Qu,setOrderOfFinish:()=>MM,substituteParticipant:()=>EM,tallyParticipantResults:()=>Fa,toggleParticipantCheckInState:()=>Al,tournamentMatchUps:()=>hl,updateTieMatchUpScore:()=>go,validMatchUp:()=>pg,validMatchUps:()=>Br});var CM={};Xt(CM,{applyLineUps:()=>RM,assignMatchUpSideParticipant:()=>mM,assignTieMatchUpParticipantId:()=>Pl,bulkMatchUpStatusUpdate:()=>PM,checkInParticipant:()=>mI,checkOutParticipant:()=>pI,disableTieAutoCalc:()=>AM,enableTieAutoCalc:()=>TM,findMatchUp:()=>tI,removeDelegatedOutcome:()=>yM,removeMatchUpSideParticipant:()=>lI,removeTieMatchUpParticipantId:()=>lM,replaceTieMatchUpParticipantId:()=>dI,resetAdHocMatchUps:()=>NM,resetMatchUpLineUps:()=>gI,resetScorecard:()=>hI,resetTieFormat:()=>II,setDelegatedOutcome:()=>DM,setMatchUpFormat:()=>UM,setMatchUpStatus:()=>Qu,setOrderOfFinish:()=>MM,substituteParticipant:()=>EM,toggleParticipantCheckInState:()=>Al,updateTieMatchUpScore:()=>go});function mM({tournamentRecord:t,drawDefinition:e,participantId:r,sideNumber:n,matchUpId:o,event:i}){if(r&&typeof r!="string")return{error:ln};if(!e)return{error:Z};if(!o)return{error:sr};let s=n===void 0;if(s&&(n=1),![1,2].includes(n))return _({result:{error:B,context:{sideNumber:n}}});let{matchUp:a,structure:c}=Vt({drawDefinition:e,matchUpId:o,event:i});if(!a)return{error:we};if(!(!c?.structures&&!(e.drawType&&e.drawType!==Fr)&&!c?.matchUps?.find(({roundPosition:p})=>!!p)))return{error:Om};if(!r&&(a?.score?.scoreStringSide1||ae.includes(a?.matchUpstatus)||a?.matchUpStatus&&[oe,be].includes(a.matchUpStatus)))return{error:ip,info:"matchUp has completed status or score"};if(a){if(a.sides=[1,2].map(p=>{let m=a.sides?.find(d=>d.sideNumber===p)??{sideNumber:p};return n===p?{...m,participantId:r}:m}),s)for(let p of a.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);gt({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a})}return{...C,sidesSwapped:s}}function Zr({removePriorValues:t,tournamentRecord:e,duplicateValues:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:s,event:a}){let{matchUp:c}=Vt({drawDefinition:n,event:a,matchUpId:i});if(!c)return{error:we};let u=ro({removePriorValues:t,element:c,duplicateValues:r,timeItem:s});return o||gt({tournamentId:e?.tournamentId,eventId:a?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function pI(t){let e=[{[ne]:!0},{[Ce]:!0},{[ao]:!0},{[gn]:!0}],r=et(t,e);if(r.error)return r;let n=vs(t,[{[ds]:Gn,attr:{[uu]:!0}}]);if(n.error)return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=n?.matchUp?.matchUp,{matchUpStatus:u,score:p}=c??{};if(u&&id.includes(u)||u&&ae.includes(u)||he({score:p}))return{error:zE};let m=Is({matchUp:c});if(m?.error)return m;let{checkedInParticipantIds:d,allRelevantParticipantIds:l}=m??{};if(!l?.includes(s))return{error:ln};if(!d?.includes(s))return{error:PA};let f=IS({matchUp:c});if(f?.error)return f;let{sideParticipantIds:g,nestedIndividualParticipantIds:I}=f??{},h=g?.indexOf(s);return h!==void 0&&[0,1].includes(h)&&(I?.[h]??[]).forEach(T=>{Zr({drawDefinition:i,matchUpId:a,timeItem:{itemType:hd,itemValue:T}})}),Zr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:hd}}),{...C,checkedOut:!0}}function mI(t){let e=[{[ne]:!0},{[Ce]:!0},{[ao]:!0},{[gn]:!0}],r=et(t,e);if(r[In])return r;let n=vs(t,[{[ds]:Gn,attr:{[uu]:!0}}]);if(n[In])return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=Is({matchUp:n?.matchUp?.matchUp});if(c?.error)return c;let{checkedInParticipantIds:u,allRelevantParticipantIds:p}=c??{};if(!p?.includes(s))return{[In]:ln};let m={...C,checkedIn:!0};return u?.includes(s)||Zr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:Id}}),m}function Al(t){let e=et(t,[{[ao]:!0,[Ce]:!0,[gn]:!0}]);if(e.error)return e;let r=t.tournamentId??t.activeTournamentId,n=t.tournamentRecord??(r&&t.tournamentRecords?.[r]);if(!n)return{error:q};let i=vs(t,[{[ds]:Gn,attr:{[uu]:!0},[In]:we}]).matchUp?.matchUp;if(!i)return{error:we};let{checkedInParticipantIds:s=[]}=Is({matchUp:i}),{participantId:a,matchUpId:c,drawDefinition:u}=t;return a&&s.includes(a)?pI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i}):mI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i})}function Ul({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:n}){if(!t)return{error:q};if(!e)return{error:cn};if(!n)return{error:qr};let o=Pe({drawDefinition:e}),{matchUp:i}=Vt({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!i)return{error:we};let{matchUp:s,structure:a}=Vt({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:n});if(!s)return{error:we};let{collectionPosition:c,drawPositions:u,collectionId:p,matchUpTieId:m,matchUpType:d}=s;if(d&&!Yc([Lt,vt],d))return{error:dr};let{positionAssignments:l}=Ct({structure:a}),f=l?.filter(P=>u?.includes(P.drawPosition)),{matchUp:g}=Vt({matchUpId:m,drawDefinition:e,matchUpsMap:o}),I=g?.sides?.map(St)??[],h=f?.map(St)??[],S=[...I,...h],{participants:T}=Ft({tournamentRecord:t,participantFilters:{participantTypes:[wt],participantIds:S}}),{matchUp:y}=Vt({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),E=We({matchUp:g,drawDefinition:e,structure:a,event:n})?.tieFormat;return{inContextDualMatchUp:y,inContextTieMatchUp:s,relevantAssignments:f,collectionPosition:c,teamParticipants:T,collectionId:p,matchUpType:d,dualMatchUp:g,tieMatchUp:i,tieFormat:E,structure:a,...C}}function dI(t){let e=Ul(t);if(e.error)return e;let r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:o,newParticipantId:i,drawDefinition:s,substitution:a,event:c}=t;if(!n||!i)return _({result:{error:se},stack:r});if(n===i)return{...C};let{inContextDualMatchUp:u,inContextTieMatchUp:p,collectionPosition:m,collectionId:d,dualMatchUp:l,tieMatchUp:f,tieFormat:g}=e,I=p?.matchUpType,h=p?.sides?.find(k=>k.participant?.participantId===n||k.participant?.individualParticipantIds?.includes(n));if(!h)return{error:re};let S=Ft({tournamentRecord:o,participantFilters:{participantIds:[n,i]}})?.participants??[];if(S.length!==2)return _({result:{error:se},stack:r});if(S[0].participantType!==S[1].participantType)return _({result:{error:Pn},stack:r});let{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:s,event:c}),y=t.policyDefinitions?.[er]??T?.[er]??Ps[er],E=S.find(({participantId:k})=>k===i);if((t.enforceGender??y?.participants?.enforceGender)!==!1&&Dn(p?.gender)&&yr(p?.gender)!==yr(E?.person?.sex))return{error:Hi,info:"Gender mismatch"};let A=y?.processCodes?.substitution;ka({tournamentId:o.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:s,dualMatchUp:l});let U=l?.sides?.find(({sideNumber:k})=>k===h.sideNumber);if(!U)return _({result:{sideNumber:h.sideNumber,existingParticipantId:n,error:Oe},stack:r});if(p?.sides?.flatMap(k=>k.participant?.individualParticipantIds||k.participant?.participantId||[])?.includes(i))return _({result:{error:sp},stack:r});let D=u?.sides?.find(({sideNumber:k})=>k===h.sideNumber)?.participantId,M=U.lineUp,R=M?.find(({participantId:k})=>i===k),b=M?.reduce((k,G)=>G.substitutionOrder>k?G.substitutionOrder:k,0),O=M?.map(k=>{let G=J(k,!1,!0);if(![n,i].includes(G.participantId))return G;if(!a&&[n,i].includes(G.participantId)&&(G.collectionAssignments=G.collectionAssignments?.filter(H=>!(H.collectionPosition===m&&H.collectionId===d))),a&&n===G.participantId&&(G.collectionAssignments=G.collectionAssignments.map(H=>H.collectionPosition===m&&H.collectionId===d&&H.substitutionOrder===void 0?{...H,substitutionOrder:b}:H)),G.participantId===i){G.collectionAssignments||(G.collectionAssignments=[]);let H={collectionId:d,collectionPosition:m};a&&(H.previousParticipantId=n,H.substitutionOrder=(b??0)+1),G.collectionAssignments.push(H)}return G})??[];if(!R){let k={collectionId:d,collectionPosition:m};a&&(k.substitutionOrder=(b??0)+1,k.previousParticipantId=n);let G={collectionAssignments:[k],participantId:i};O.push(G)}let v=I===vt,{assignedParticipantIds:x}=Lp({lineUp:M,collectionPosition:m,collectionId:d}),{assignedParticipantIds:F}=Lp({lineUp:O,collectionPosition:m,collectionId:d});if(U.lineUp=O,D&&g){let k=os({participantId:D,lineUp:O,drawDefinition:s,tieFormat:g});if(k.error)return _({result:k,stack:r})}else console.log("team participantId not found");let w,L;if(v){let{tournamentRecord:k}=t,G=Sn({participantIds:F,tournamentRecord:k});if(!G.participant){let Y=wn({returnParticipant:!0,pairOverride:!0,tournamentRecord:k,participant:{participantRole:xe,individualParticipantIds:F,participantType:ft}});if(Y.error)return _({result:Y,stack:r});w=Y.participant?.participantId}G=Sn({participantIds:x,tournamentRecord:k});let H=G.participant?.participantId;H&&ns({participantIds:[H],tournamentRecord:k}).success&&(L=H)}if(a||h.substitutions?.length===1){if(a)A&&f&&(f.processCodes=pt([...f?.processCodes??[],...A]));else for(let k of A||[]){let G=f?.processCodes?.lastIndexOf(k);G!==void 0&&f?.processCodes?.splice(G,1)}f&>({tournamentId:o?.tournamentId,matchUp:f,context:r,drawDefinition:s})}return l&>({tournamentId:o?.tournamentId,matchUp:l,context:r,drawDefinition:s}),{...C,modifiedLineUp:O,participantRemoved:L,participantAdded:w}}function Yy({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:r,drawDefinition:n,participantIds:o,collectionId:i}){if(!i||!t||!Array.isArray(o))return{modifiedLineUp:r?.lineUp||[],error:B};let s=r?.lineUp||Ss({participantId:e,drawDefinition:n})?.lineUp,a=[],c=[];return{modifiedLineUp:s?.map(p=>{if(!o.includes(p.participantId))return p;let m=p.collectionAssignments?.filter(d=>{let l=d.collectionId===i&&d.collectionPosition===t;return l&&(d.previousParticipantId&&a.push(d.previousParticipantId),c.push({participantId:p.participantId,...d})),!l});return{participantId:p.participantId,collectionAssignments:m}}).filter(Boolean)||[],assignmentsRemoved:c,previousParticipantIds:a}}function bx({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n=(r.events||[]).filter(i=>i?.eventType===_e&&i?.entries?.some(s=>s.participantId===e)),o=i=>!t.includes(i.participantId);for(let i of n){i.entries=(i.entries||[]).filter(o);let{flightProfile:s}=Ht({event:i});s?.flights?.forEach(a=>{a.drawEntries=(a.drawEntries||[]).filter(o)}),i?.drawDefinitions?.forEach(a=>{a.entries=(a.entries||[]).filter(o)})}return{...C}}function dm({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:r,tournamentRecord:n}){let o="addIndividualParticipantIds";if(!n)return _({result:{error:q},stack:o});if(!e||!t)return _({result:{error:st},stack:o});let i=n.participants??[],s=i.find(m=>m.participantId===e);if(!s)return _({result:{error:re},stack:o});if(s?.participantType&&![wt,Qr].includes(s.participantType))return _({context:{participantType:s.participantType},result:{error:Pn},stack:o});let a=t.filter(m=>i.find(l=>l.participantId===m)?.participantType!==Et);if(a.length)return _({result:{error:wr,invalidParticipantIds:a},stack:o});s.individualParticipantIds||(s.individualParticipantIds=[]);let c=s.individualParticipantIds,u=t.filter(m=>!c.includes(m));u.length&&(r&&kp({individualParticipantIds:u,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...u));let{topics:p}=Lr();if(p.includes(rr)){let m=i.find(({participantId:d})=>d===e);lt({topic:rr,payload:{participants:[m]}})}return bx({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}),{groupingParticipant:J(s,!1,!0),added:u.length,...C}}function lm(t){let{updateParticipantName:e=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o,pairOverride:i,participant:s}=t;if(!o)return{error:q};if(!s)return{error:Wi};if(!s.participantId)return wn({tournamentRecord:o,participant:s});let{participant:a}=Uo({participantId:s.participantId,tournamentRecord:o});if(!a)return wn({tournamentRecord:o,participant:s});let{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:p,participantName:m,participantRole:d,participantType:l,onlineResources:f,contacts:g,person:I}=s;if(l&&a.participantType!==l)return{error:hA};let h={};if(g&&(h.contacts=g),f&&(h.onlineResources=f),p&&kt(p)&&(h.participantOtherName=p),m&&kt(m)&&(h.participantName=m),Array.isArray(u)){let{participants:S}=Ft({participantFilters:{participantTypes:[Et]},tournamentRecord:o}),T=S?.map(St);if(T){let y=u.filter(E=>kt(E)&&T.includes(E));([Qr,Wt].includes(l||a.participantType)||l===ft&&(y.length===2||i))&&(h.individualParticipantIds=y),a.participantType===yu.PAIR&&e&&(h.participantName=u0({individualParticipants:S,newValues:h}))}}return Object.keys(Dd).includes(d)&&(h.participantRole=d),Object.keys(yu).includes(l)&&(h.participantType=l),Array.isArray(c)&&(h.participantRoleResponsibilties=c),a.participantType===yu.INDIVIDUAL&&I&&p0({updateParticipantName:e,existingParticipant:a,newValues:h,person:I}),Object.assign(a,nt(h)),r&&dm({individualParticipantIds:[a.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o}),lt({topic:rr,payload:{tournamentId:o.tournamentId,participants:[a]}}),{participant:J(a),...C}}function u0({individualParticipants:t,newValues:e}){let r=e.individualParticipantIds,n=t.filter(({participantId:o})=>r.includes(o)).map(({person:o})=>o?.standardFamilyName).filter(Boolean).sort().join("/");return r.length===1&&(n+="/Unknown"),n}function p0({updateParticipantName:t,existingParticipant:e,newValues:r,person:n}){let o={},{standardFamilyName:i,standardGivenName:s,nationalityCode:a,personId:c,birthdate:u,tennisId:p,sex:m}=n;m&&Object.keys(Fm).includes(m)&&(o.sex=m);let d;if(kt(c)&&(o.personId=c),a&&kt(a)&&(m0(a)||a==="")&&(o.nationalityCode=a),i&&typeof kt(i)&&i.length>1&&(o.standardFamilyName=i,d=!0),s&&typeof kt(s)&&s.length>1&&(o.standardGivenName=s,d=!0),d&&t){let l=`${o.standardGivenName} ${o.standardFamilyName}`;r.participantName=l}u&&Mr(u)&&(o.birthdate=u),p&&kt(p)&&(o.tennisId=p),Object.assign(e.person,o)}function m0(t){return ui.flatMap(({iso:e,ioc:r})=>[e,r]).filter(Boolean).includes(t)}function Pl(t){let e=Ul(t);if(e.error)return e;let r="assignTieMatchUpParticipantId",n=t.teamParticipantId,{tournamentRecord:o,drawDefinition:i,participantId:s,event:a}=t;if(!s)return _({result:{error:se},stack:r});if(t.sideNumber&&![1,2].includes(t.sideNumber))return _({result:{error:tf},stack:r});let{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:p,collectionPosition:m,teamParticipants:d,collectionId:l,matchUpType:f,dualMatchUp:g,tieFormat:I}=e;if(u?.sides?.flatMap(V=>V.participant?.individualParticipantIds||V.participant?.participantId||[])?.includes(s))return _({result:{...C},stack:r});n=n??(t.sideNumber?c?.sides?.find(V=>V.sideNumber===t.sideNumber)?.participantId:void 0);let S=Ft({participantFilters:{participantIds:[s]},tournamentRecord:o})?.participants?.[0];if(!S)return _({result:{error:re},stack:r});let{appliedPolicies:T}=Tt({tournamentRecord:o,drawDefinition:i,event:a}),y=t.policyDefinitions?.[er]??T?.[er]??Ps[er];if((t.enforceGender??y?.participants?.enforceGender)!==!1&&Dn(u?.gender)&&yr(u?.gender)!==yr(S.person?.sex))return{error:Hi,info:"Gender mismatch"};let{individualParticipantIds:P,participantType:A}=S;if(de(Lt)(f)&&A!==Et)return{error:Pn};let U=A===Et?[s]:P,N=n&&d?.find(({participantId:V})=>V===n)||d?.find(({individualParticipantIds:V})=>ke(U,V));if(!N)return{error:lf};if(n||(n=N.participantId),!n)return{error:re};let M=p?.find(V=>V.participantId===N?.participantId)?.drawPosition,R=g?.sides?.find(V=>V.participantId===n)?.sideNumber,b=u?.sides?.find(V=>M&&V.drawPosition===M)?.sideNumber,O=R??b??t.sideNumber;if(!I)return{error:ks};if(!I.collectionDefinitions?.find(V=>V.collectionId===l))return{error:cA};ka({tournamentId:o.tournamentId,eventId:a.eventId,inContextDualMatchUp:c,drawDefinition:i,dualMatchUp:g});let x=g?.sides?.find(V=>V.sideNumber===O),F=u?.sides?.find(V=>V.sideNumber===O),k=(x?.lineUp??Ss({participantId:n,drawDefinition:i})?.lineUp)?.filter(V=>V.collectionAssignments?.find($=>$.collectionPosition===m&&$.collectionId===l&&!$.previousParticipantId))?.map(V=>V?.participantId),G=k?.length>1&&k||(A===ft?S.individualParticipantIds:[s]),H=Yy({collectionPosition:m,teamParticipantId:n,dualMatchUpSide:x,drawDefinition:i,participantIds:G,collectionId:l});if(H.error)return _({result:H,stack:r});let{modifiedLineUp:K}=H,Y;if(f===vt){if(A!==ft){let V=dM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:K,participantId:s,collectionId:l,tieFormat:I});if(V?.error)return _({result:V,stack:r});if(V=j({side:F}),V.error)return V;Y=V.deletedParticipantId,x&&(x.lineUp=K),g&>({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i})}else if(A===ft)for(let V of G)dM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:K,participantId:V,collectionId:l,tieFormat:I})}else{let V=dM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:K,participantId:s,collectionId:l,tieFormat:I});if(V?.error)return V}if(x&&(x.lineUp=K),g&>({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i}),Y){let{error:V}=ns({participantIds:[Y],tournamentRecord:o});V&&console.log("cleanup")}return{...C,modifiedLineUp:K};function j({side:V}){let $;if(V.participant){let X=V.participant.individualParticipantIds||[];if(X.filter(Boolean).length===1){let{participant:it}=Sn({participantIds:X,tournamentRecord:o});X.push(s);let{participant:z}=Sn({participantIds:X,tournamentRecord:o});if(!z&&it){it.individualParticipantIds=X;let Q=lm({pairOverride:!0,tournamentRecord:o,participant:it});if(Q.error)return Q}else $=it?.participantId}}else{let W=wn({participant:{individualParticipantIds:[s],participantRole:xe,participantType:ft},pairOverride:!0,tournamentRecord:o});if(W.error)return W}return{...C,deletedParticipantId:$}}}function dM({collectionPosition:t,teamParticipantId:e,drawDefinition:r,modifiedLineUp:n,participantId:o,collectionId:i,tieFormat:s}){let a=Ss({participantId:e,drawDefinition:r})?.lineUp,c=(n||a)?.find(p=>p?.participantId===o),u={collectionId:i,collectionPosition:t};if(c)c.collectionAssignments.push(u);else{let p={collectionAssignments:[u],participantId:o};n.push(p)}return os({participantId:e,lineUp:n,drawDefinition:r,tieFormat:s})}function lM(t){let{tournamentRecord:e,drawDefinition:r,participantId:n,event:o}=t,i="removeTieMatchUpParticiapantId";if(!n)return _({result:{error:se},stack:i});let s=Ul(t);if(s.error)return s;let{appliedPolicies:a}=Tt({tournamentRecord:e,drawDefinition:r,event:o}),u=(t.policyDefinitions?.[er]??a?.[er]??Ps[er])?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:m,relevantAssignments:d,collectionPosition:l,teamParticipants:f,collectionId:g,matchUpType:I,dualMatchUp:h,tieMatchUp:S,tieFormat:T}=s;if(!h)return _({result:{error:mr},stack:i});let y=m?.sides?.find(R=>R.participant?.participantId===n||R.participant?.individualParticipantIds?.includes(n));if(!y)return _({result:{error:re},stack:i});let E=t.policyDefinitions?.[rn]??a?.[rn];if(!y.substitutions?.length&&(he({score:m?.score})||m?.winningSide)&&E?.requireParticipantsForScoring!==!1)return _({result:{error:jA},stack:i});let P=p?.sides?.find(({sideNumber:R})=>R===y.sideNumber)?.participantId;if(!P)return _({result:{error:re},stack:i});let A=Ft({participantFilters:{participantIds:[n]},tournamentRecord:e})?.participants?.[0];if(!A)return _({result:{error:re},stack:i});if(I===Lt&&A.participantType===ft)return _({result:{error:Hi},stack:i});let U=A.participantType===Et?[n]:A.individualParticipantIds;ka({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:h});let N=h.sides?.find(({sideNumber:R})=>R===y.sideNumber);if(!N&&(h.sides?.filter(({lineUp:R})=>!R).length||0)<2){let R=f?.map(({participantId:b})=>({drawPosition:d?.find(O=>O.participantId===b)?.drawPosition,teamParticipantId:b}));N=h.sides?.find(b=>R?.find(({drawPosition:O})=>O===b.drawPosition)?.teamParticipantId===P)}if(!N)return _({result:{error:re,context:{participantId:n}}});let{modifiedLineUp:D,previousParticipantIds:M}=Yy({collectionPosition:l,teamParticipantId:P,dualMatchUpSide:N,participantIds:U,drawDefinition:r,collectionId:g});if(N.lineUp=D,P&&T&&os({participantId:P,lineUp:D,drawDefinition:r,tieFormat:T}),I===vt&&A.participantType===Et){let R=m?.sides?.find(v=>v.sideNumber===N?.sideNumber),{participantId:b}=R??{},O=b&&Ft({participantFilters:{participantIds:[b]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(O){let v=O?.individualParticipantIds?.filter(x=>x!==n)??[];if(M&&v.push(...M),v.length>2)return _({result:{error:wr},stack:i});if(O.draws?.length){if(v.length===1){let{participant:x}=Sn({participantIds:v,tournamentRecord:e});if(!x){let w=wn({participant:{participantRole:xe,individualParticipantIds:v,participantType:ft},pairOverride:!0,tournamentRecord:e});if(w.error)return _({result:w,stack:i})}}}else if(v.length){O.individualParticipantIds=v;let x=lm({participant:O,pairOverride:!0,tournamentRecord:e});if(x.error)return _({result:x,stack:i})}else{let x=ns({participantIds:[b],tournamentRecord:e});x.error&&console.log("cleanup",{result:x})}}else return _({result:{error:re},stack:i})}if(y.substitutions?.length===1&&!m?.sides?.find(b=>b.sideNumber!==y.sideNumber)?.substitutions?.length&&S?.processCodes?.length){for(let b of u||[]){let O=S.processCodes.lastIndexOf(b);S.processCodes.splice(O,1)}gt({tournamentId:e?.tournamentId,matchUp:S,context:i,drawDefinition:r})}return gt({tournamentId:e?.tournamentId,matchUp:h,context:i,drawDefinition:r}),{...C,modifiedLineUp:D}}function lI(t){let e=et(t,[{[ne]:!0,[Ce]:!0,[gn]:!0}]);if(e.error)return e;let{drawDefinition:r,sideNumber:n,matchUpId:o,event:i}=t;if(n&&![1,2].includes(n))return{error:B,sideNumber:n};let{matchUp:s,structure:a}=Vt({drawDefinition:r,matchUpId:o,event:i});return s?cr({structure:a})?(s.sides?.forEach(c=>{(!n||c.sideNumber===n)&&delete c.participantId}),gt({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:r,matchUp:s}),{...C}):{error:Om}:{error:we}}function Ox({matchUpStatuses:t=["BYE",Bt,Gt],drawPositionMatchUps:e,loserDrawPosition:r,sourceMatchUps:n}){let o=e?.reduce((p,m)=>!p||m.roundNumber>p.roundNumber?m:p,void 0),i=o?.drawPositions?.find(p=>p!==r),s=n.filter(p=>p?.drawPositions?.includes(i)).map(p=>p.matchUpStatus),a=n.filter(p=>p?.drawPositions?.includes(r)).map(p=>p.matchUpStatus),c=ke(s||[],t),u=ke(a||[],t);return{sourceMatchUp:o,winnerHadMatchUpStatus:c,winnerMatchUpStatuses:s,loserHadMatchUpStatus:u,loserMatchUpStatuses:a}}function vx({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,structureId:s,dualMatchUp:a,roundNumber:c,matchUpsMap:u,event:p}){let{structure:m}=at({drawDefinition:i,structureId:s});if(m?.structureType===Ve)return{...C};u=u??Pe({drawDefinition:i});let l=(u?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:f}=Es({drawPosition:r,matchUps:l}),g=l?.filter(h=>h.roundNumber>=c&&h.roundNumber!==f&&h.drawPositions?.includes(r)),{positionAssignments:I}=Ct({drawDefinition:i,structureId:s});for(let h of g??[])d0({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:I,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,dualMatchUp:a,matchUpsMap:u,matchUp:h,event:p});return{...C}}function d0({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:r,targetDrawPosition:n,tournamentRecord:o,sourceMatchUpId:i,drawDefinition:s,dualMatchUp:a,matchUpsMap:c,matchUp:u,event:p}){let m="removeSubsequentDrawPosition";if(a){let g=t.find(({matchUpId:h})=>u.matchUpId===h).sides?.find(h=>h.drawPosition===n)?.sideNumber,I=u.sides?.find(h=>h.sideNumber===g);I&&delete I.lineUp}u.drawPositions=(u.drawPositions||[]).map(f=>f===n?void 0:f).filter(Boolean);let l=e.filter(({drawPosition:f})=>u.drawPositions?.includes(f)).filter(f=>f.bye).length;return u.matchUpStatus=l&&"BYE"||pr(u.matchUpStatus)&&u.matchUpStatus||Qt,pr(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&FS({inContextDrawMatchUps:t,sourceMatchUpStatus:r,sourceMatchUpId:i,matchUpsMap:c,matchUp:u}),gt({tournamentId:o?.tournamentId,eventId:p?.eventId,context:`${m}-${n}`,drawDefinition:s,matchUp:u}),{...C}}function Vc(t){let{dualWinningSideChange:e,inContextDrawMatchUps:r,tournamentRecord:n,drawDefinition:o,matchUpStatus:i,matchUpsMap:s,dualMatchUp:a,targetData:c,matchUpId:u,structure:p,event:m}=t,d=!!t.matchUp.collectionId,l=cr({structure:p}),{drawPositions:f,winningSide:g}=c.matchUp||{};if(!l&&!f)return{error:Ja};let{targetLinks:{loserTargetLink:I,winnerTargetLink:h,byeTargetLink:S},targetMatchUps:{loserMatchUp:T,winnerMatchUp:y,byeMatchUp:E}}=c,P=Yn({...t,matchUpStatus:i||Qt,removeWinningSide:!0});if(P.error)return P;let A;if(d){let{matchUpTieId:w,matchUpsMap:L}=t;if(A=go({appliedPolicies:t.appliedPolicies,matchUpId:w,tournamentRecord:n,drawDefinition:o,matchUpsMap:L,event:m}),!e&&!A.removeWinningSide)return{...C}}if(l)return{...C};let{matchUps:U}=yt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:o,matchUpsMap:s,structure:p}),{positionAssignments:N}=Ie({structure:p}),D=g-1,M=1-D,R=f[D],b=f[M],{winnerParticipantId:O,loserParticipantId:v}=N?.reduce((w,L)=>(L.drawPosition===b&&(w.loserParticipantId=L.participantId),L.drawPosition===R&&(w.winnerParticipantId=L.participantId),w),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},x=U.filter(w=>w.drawPositions?.includes(b));if(y&&fM({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:r,winningDrawPosition:R,winnerParticipantId:O,tournamentRecord:n,winnerTargetLink:h,drawDefinition:o,winnerMatchUp:y,dualMatchUp:a,matchUpsMap:s}),T){let{winnerHadMatchUpStatus:w}=Ox({drawPositionMatchUps:x,loserDrawPosition:b,sourceMatchUps:U}),k=I.linkCondition===kn;if(w&&k){let H=Math.min(...T.drawPositions);qy({targetLink:I,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:H,matchUpsMap:s,event:m})}let G=l0({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:v,tournamentRecord:n,loserTargetLink:I,drawDefinition:o,loserMatchUp:T,dualMatchUp:a,matchUpsMap:s,event:m});if(G.error)return G}if(E){let w=Math.min(...E.drawPositions);qy({sourceMatchUpId:u,targetLink:S,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:w,matchUpsMap:s,event:m})}return{...C,...A&&{tieMatchUpResult:A}}}function fM({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:r,winnerParticipantId:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:p,event:m}){let{structureId:d,roundNumber:l}=c,f="removeDirectedWinner";if(i){let g=i.target.structureId,{structure:I}=at({drawDefinition:a,structureId:g});if(!I)return{error:_t};let{positionAssignments:h}=Ie({structure:I});I.seedAssignments=(I.seedAssignments??[]).filter(N=>N.participantId!==n);let T=h?.find(N=>N.participantId===n)?.drawPosition,{matchUps:y}=yt({drawDefinition:a,structure:I,event:m}),E=y.map(N=>N.drawPositions).flat(1/0).filter(Boolean),P=Er(E);if((T?P[T]:void 0)===1)h?.forEach(N=>{N.participantId===n&&delete N.participantId});else{let N=y.filter(({drawPositions:D})=>D.includes(T));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:N,winnerTargetLink:i})}let U=u?.drawMatchUps?.find(({matchUpId:N})=>N===c.matchUpId);U&>({tournamentId:o?.tournamentId,eventId:m?.eventId,matchUp:U,context:f,drawDefinition:a})}return l&&vx({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,dualMatchUp:p,matchUpsMap:u,roundNumber:l,structureId:d}),{...C}}function l0({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:r,loserTargetLink:n,sourceMatchUpId:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,dualMatchUp:c,event:u}){let p="removeDirectedLoser",m=n.target.structureId,{structure:d}=at({drawDefinition:i,structureId:m});if(!d)return{error:_t};let{positionAssignments:l}=Ie({structure:d}),f=l?.find(g=>g.participantId===e)?.drawPosition;if(l?.forEach(g=>{g.participantId===e&&delete g.participantId}),o&&t){let g=a?.drawMatchUps?.find(({matchUpId:I})=>I===s.matchUpId);g.matchUpStatusCodes=t===oe?["WO","WO"]:[]}if(d.seedAssignments=(d.seedAssignments??[]).filter(g=>g.participantId!==e),c){let g=s?.sides.reduce((S,T,y)=>T.drawPosition===f?y:S,void 0),I=a?.drawMatchUps?.find(({matchUpId:S})=>S===s.matchUpId),h=I?.sides?.[g];h&&(delete h.lineUp,gt({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:I,context:p,drawDefinition:i}))}return{...C}}function qy({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,targetLink:i,event:s}){let a=i.target.structureId,c="removeDirectedBye";Tn({color:"brightyellow",method:c,drawPosition:n});let u=Uc({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:a,event:s});return _({result:u,stack:c})}function _x(t){let{matchUpFormat:e,score:r}=t,n=r?.sets?.length,o=e&&Ne(e),{setFormat:i,finalSetFormat:s,bestOf:a}=o??{};return(a&&n===a&&s||i)?.timed||!1}function xx({tournamentRecord:t,drawDefinition:e,structure:r,matchUp:n}){let o="attemptToSetMatchUpStatusBYE";if(n?.winningSide)return _({result:{error:Ta},context:{matchUpStatus:"BYE"},stack:o});let{positionAssignments:i}=Ie({structure:r}),s=i?.filter(c=>c.bye).map(c=>c.drawPosition);return n.drawPositions?.some(c=>s?.includes(c))?(n.matchUpStatus="BYE",n.matchUpStatusCodes=[],gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:n}),{...C}):_({result:{error:aA},info:"matchUp does not include BYE",stack:o})}function Dl(t){let{tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,structure:s,event:a}=t,c="doubleExitAdvancement";if(s.structureType===Ve)return _({result:{...C},stack:c});let{matchUp:u,targetMatchUps:p,targetLinks:m}=i,{loserMatchUp:d,winnerMatchUp:l,loserTargetDrawPosition:f}=p,g=pr(d?.matchUpStatus)&&!d.sides?.map(h=>h.participantId??h.participant).filter(Boolean).length,I=d?.matchUpStatus===oe;if(d&&d.matchUpStatus!=="BYE"){let{loserTargetLink:h}=m;if(r?.progression?.doubleExitPropagateBye||d.feedRound&&d.sides?.[0]?.participantFed){let S=Lx({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:h,drawDefinition:n,loserMatchUp:d,matchUpsMap:o,event:a});if(S.error)return _({result:S,stack:c})}else if(!I){let{feedRound:S,drawPositions:T,matchUpId:y}=d,E=S?2:2-T.indexOf(f);E=g?d.winningSide:E;let P=wx({...t,targetMatchUp:d,walkoverWinningSide:E,tournamentRecord:e,sourceMatchUp:u,matchUpId:y});if(P.error)return _({result:P,stack:c})}}if(l){let h=wx({...t,matchUpId:l.matchUpId,targetMatchUp:l,tournamentRecord:e,sourceMatchUp:u});if(h.error)return _({result:h,stack:c})}return _({result:{...C},stack:c})}function wx(t){let{inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s}=t,a=n.structures.find(({structureId:j})=>j===i.structureId),c=t.matchUpStatus===be?be:oe,u=t.matchUpStatus===be?Gt:Bt,p="conditionallyAdvanceDrawPosition",m=s.drawMatchUps.find(j=>j.matchUpId===i.matchUpId);if(!m)return{error:mr};let d=o?.drawPositions||[],l=m.drawPositions?.filter(Boolean),f=o?.structureId===i.structureId;if(f&&ke(d,l)&&(l=l.filter(j=>!d.includes(j))),f&&l.length>1)return _({result:{error:Xa},stack:p});let{pairedPreviousMatchUpIsDoubleExit:g,pairedPreviousMatchUp:I}=wS(t),h=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:S,targetLinks:T}=h,{loserTargetDrawPosition:y,winnerMatchUp:E,loserMatchUp:P}=S;if(P){let{loserTargetLink:j}=T,V=Lx({loserTargetDrawPosition:y,loserMatchUp:P,tournamentRecord:r,loserTargetLink:j,drawDefinition:n,matchUpsMap:s});if(V.error)return _({result:V,stack:p})}let A=m.drawPositions?.filter(Boolean)||[],U=A.length===1,N=t.walkoverWinningSide||U&&Md({drawPosition:A[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,D=pr(m.matchUpStatus)&&!A.length,M=m.finishingRound===1,R=D&&!M?c:u,b=e.find(j=>j.matchUpId===I.matchUpId),O=[],v;o&&(o?.structureId===b?.structureId?o.roundPosition<I?.roundPosition?v=1:v=2:i.feedRound?o.structureId===i.structureId?v=2:v=1:N&&(v=3-N));let x=t.matchUpStatus,F=I?.matchUpStatus;v===1?O=[{matchUpStatus:$y(x),previousMatchUpStatus:x,sideNumber:1},{matchUpStatus:$y(F),previousMatchUpStatus:F,sideNumber:2}]:v===2&&(O=[{matchUpStatus:$y(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:$y(x),previousMatchUpStatus:x,sideNumber:2}]),O.length&&(O=O.map(j=>nt(j)));let w=Yn({...t,winningSide:N,matchUp:m,matchUpStatusCodes:O,context:p,matchUpStatus:R});if(w.error)return _({result:w,stack:p});if(D)return Dl({...t,matchUpStatus:R,targetData:h});if(!E)return _({result:{...C},stack:p});let L=l.length===2?l[N-1]:l[0],{positionAssignments:k}=Ct({structure:a}),G=k?.find(j=>j.drawPosition===L),H=s.drawMatchUps.find(j=>j.matchUpId===E.matchUpId),K=H?.drawPositions?.filter(Boolean),Y=K.length===1;if(L){if(G?.bye){let j=ur({matchUpId:H.matchUpId,inContextDrawMatchUps:e,drawDefinition:n});if(Y){let V=K.filter(Boolean)[0],$=Md({drawPosition:V,matchUpId:H.matchUpId,inContextDrawMatchUps:e}),X=Yn({appliedPolicies:t.appliedPolicies,matchUpId:H.matchUpId,matchUp:H,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,winningSide:$});return X.error?_({result:X,stack:p}):RS({drawPositionToAdvance:V,matchUpId:H.matchUpId,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}else if(pr(E.matchUpStatus)){let V=Dl({...t,matchUpId:H.matchUpId,matchUpStatus:R,targetData:j});if(V.error)return _({result:V,stack:p})}return _({result:{...C},stack:p})}return wa({matchUpId:E.matchUpId,drawPosition:L,inContextDrawMatchUps:e,drawDefinition:n})}else if(g){if(!H)return{error:mr};if(Y){let $=K[0],X=Md({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawPosition:$});console.log("existing drawPosition is winningSide",{walkoverWinningSide:X})}let j=pr(H.matchUpStatus)?u:c,V=Yn({matchUpId:H.matchUpId,appliedPolicies:t.appliedPolicies,matchUp:H,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,matchUpStatus:j});if(V.error)return _({result:V,stack:p});if(j===c){let $=Dl({...t,matchUpId:i.matchUpId,matchUpStatus:j,targetData:h});if($.error)return $}}return _({result:{...C},stack:p})}function Lx(t){let{loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,matchUpsMap:i,event:s,loserMatchUp:a}=t,c=n?.target?.structureId,{structure:u}=at({drawDefinition:o,structureId:c});return u?Wr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:c,matchUpsMap:i,loserMatchUp:a,event:s}):{error:Si}}function $y(t){return t===oe?Bt:t===be?Gt:t}function Fx(t){let{tournamentRecord:e,drawDefinition:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(h=>h.matchUpId===i.matchUpId).containerStructureId),a="attemptToSetMatchUpStatus",c=n==="BYE",u=i.winningSide,p=[oe,be].includes(n),m=Oa({matchUpStatus:n}),d=gg({matchUpStatus:n}),l=!m&&!d,f=t.matchUpTieId||u&&m&&!p,g=u&&p,I=()=>Yn({...t,removeScore:[po,Bt].includes(n),matchUpStatus:n||Qt});return l&&{error:jI}||f&&Ky(t)||g&&f0(t)||u&&Vc(t)||d&&I()||c&&xx({tournamentRecord:e,drawDefinition:r,structure:o,matchUp:i})||!m&&{error:jI}||p&&g0(t)||s&&Ky(t)||t.propagateExitStatus&&Ky(t)||_({result:{error:Ta,info:"matchUpStatus: "+n},stack:a})}function f0(t){let e=Vc(t);return e.error?e:Dl(t)}function g0(t){let e=Ky({...t,removeScore:!0});return e.error?e:Dl(t)}function Ky(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let i=Vc(t);if(i.error)return _({result:i,stack:e})}let n=!!t.matchUp.collectionId,o=Yn({...t,context:e});if(n){let{matchUpTieId:i,drawDefinition:s,matchUpsMap:a}=t,c=go({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:i,event:t.event,drawDefinition:s,matchUpsMap:a});if(c.error)return _({result:c,stack:e});Object.assign(o,{tieMatchUpResult:c})}return _({result:o,stack:e})}function kx({drawDefinition:t,structure:e,matchUp:r}){let{drawPositions:n}=r,{positionAssignments:o}=Ct({drawDefinition:t,structure:e}),s=o?.filter(({drawPosition:m})=>n?.includes(m))?.map(m=>{let{extension:d}=mt({element:m,name:Lo});return d?.value?.groupOrder}),{containerStructures:a}=fs({drawDefinition:t}),c=a[e.structureId];return{structureIds:Js({drawDefinition:t,structureId:c})?.links?.source?.filter(m=>ke(s,m.source?.finishingPositions||[])).map(m=>m.source.structureId)}}function zy({drawDefinition:t,structure:e,matchUp:r}){let n=[];if(e.finishingPosition===Ei&&Do({drawDefinition:t,structure:e})){let{structureIds:i}=kx({drawDefinition:t,structure:e,matchUp:r});i?.length&&n.push(...i)}return{connectedStructureIds:n}}function Gx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===fn){let a=n.sides.find(({sideNumber:u})=>u!==i).participantId,c=r.find(u=>u.structureId===s.target.structureId&&u.roundNumber===s.target.roundNumber&&u.sides.some(({participantId:p})=>p===a));if(c?.matchUpStatus===Qt){let u=ur({matchUpId:c.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Fi({inContextDrawMatchUps:r,drawDefinition:o,targetData:u})){let{structure:m}=at({structureId:c.structureId,drawDefinition:o}),d=Ct({structure:m}).positionAssignments;for(let l of d||[])if(l.participantId===a){let f=n.sides.find(({sideNumber:g})=>g===i).participantId;if(l.participantId=f,m?.positionAssignments)m.positionAssignments=d;else if(m?.structures){let g=Object.assign({},...(d||[]).map(I=>({[I.drawPosition]:I.participantId})));for(let I of m.structures)I.positionAssignments?.forEach(h=>h.participantId=g[h.drawPosition])}ko({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:m}),e=!0}}}}return{...C,qualifierReplaced:e}}function Vx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===fn){let a=n.sides.find(({sideNumber:p})=>p===i)?.participantId,c=r.filter(p=>p.structureId===s.target.structureId&&p.roundNumber===s.target.roundNumber&&p.sides.some(({participantId:m,qualifier:d})=>d&&!m)),u=Un(c);if(u?.matchUpStatus===Qt){let p=ur({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Fi({inContextDrawMatchUps:r,drawDefinition:o,targetData:p})){let d=u.sides.find(g=>g.qualifier&&!g.participantId)?.drawPosition,{structure:l}=at({structureId:u.structureId,drawDefinition:o});if(!l)return{error:_t};let f=Ct({structure:l}).positionAssignments;for(let g of f||[])if(g.drawPosition===d&&!g.participantId){if(g.participantId=a,l.positionAssignments)l.positionAssignments=f;else if(l.structures){let I=Object.assign({},...(f||[]).map(h=>({[h.drawPosition]:h.participantId})));for(let h of l.structures)h.positionAssignments?.forEach(S=>S.participantId=I[S.drawPosition])}ko({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:l}),e=!0}}}}return{...C,qualifierPlaced:e}}function Bx(t){let e="attemptToSetWinningSide",r,n={},{appliedPolicies:o,disableAutoCalc:i,drawDefinition:s,dualMatchUp:a,winningSide:c,structure:u,matchUp:p}=t;if(a?._disableAutoCalc&&i!==!1)return Fd(t);if(p.winningSide&&p.winningSide!==c){let{connectedStructureIds:f}=zy({drawDefinition:s,structure:u,matchUp:p});f.length&&(console.log({connectedStructureIds:f}),r=!0);let g=Vc(t);if(g.error)return g}let m=uT(t);if(m.context?.progressExitStatus&&Object.assign(n,m.context),m.error)return _({result:m,stack:e});let d,l;return t.qualifierChanging&&o?.[pu]?.autoReplaceQualifiers&&(d=Gx(t).qualifierReplaced),t.qualifierAdvancing&&o?.[pu]?.autoPlaceQualifiers&&(l=Vx(t).qualifierPlaced),_({result:nt({...C,...m,connectedStructures:r,qualifierReplaced:d,qualifierPlaced:l,context:n}),stack:e})}var Qy={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function gM(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,matchUp:s}=t,{matchUpId:a}=s,{iteration:c=0}=t;c+=1;let u="removeDoubleExit";Tn({color:"brightyellow",method:u,matchUpId:a,iteration:c,keyColors:Qy});let{targetMatchUps:{loserMatchUp:p,winnerMatchUp:m,loserTargetDrawPosition:d},targetLinks:{loserTargetLink:l}}=i;if(m&&m.matchUpStatus!=="BYE"){let{stage:I,roundNumber:h,roundPosition:S,structureName:T}=m;Tn({winner:"winner",roundPosition:S,structureName:T,roundNumber:h,keyColors:Qy,stage:I}),Hx({...t,targetMatchUp:m,sourceMatchUp:s,iteration:c})}let f=p?.matchUpStatus==="BYE"&&(p?.feedRound||p?.roundNumber===1),g=i?.targetLinks?.loserTargetLink?.linkCondition===kn;if(f&&g){let I=e.filter(({roundNumber:E,structureId:P})=>P===s.structureId&&E===1),h=I.map(({roundPosition:E})=>E),S=Ae(h.sort(),2).find(E=>E.includes(s.roundPosition));if((I.filter(({roundPosition:E})=>S.includes(E))?.map(({matchUpStatus:E})=>E)).every(E=>[be,oe].includes(E)))return _({result:{...C},stack:u})}if(p&&(p.matchUpStatus!=="BYE"||f)){let I=e.find(({matchUpId:A})=>A===p.matchUpId),{structure:h}=at({drawDefinition:n,structureId:I.structureId}),{stage:S,roundNumber:T,roundPosition:y,feedRound:E,structureName:P}=p;if(Tn({loser:"loser",roundPosition:y,structureName:P,roundNumber:T,keyColors:Qy,feedRound:E,stage:S}),r?.progression?.doubleExitPropagateBye||f)qy({drawPosition:d,targetLink:l,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:o});else{let A=Hx({...t,targetMatchUp:p,structure:h,iteration:c});if(A.error)return _({result:A,stack:u})}}return _({result:{...C},stack:u})}function Hx(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s,structure:a,iteration:c}=t,u="conditionallyRemoveDrawPosition";Tn({method:u,structureName:a?.structureName,iteration:c});let p=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:{winnerMatchUp:m}}=p,d=s?.drawMatchUps.find(y=>y.matchUpId===i.matchUpId),l=[],f,g,I;if(i.feedRound)I=m?.drawPositions?.filter(Boolean)?.find(E=>i.drawPositions.includes(E));else if(!o)I=jt(i?.drawPositions||[],m?.drawPositions||[])?.[0];else if(g=LS({structureId:a.structureId,matchUp:o,matchUpsMap:s})?.pairedPreviousMatchUp,f=[oe,be].includes(g?.matchUpStatus),l=g?.drawPositions?.filter(Boolean)||[],[...ae,"BYE"].includes(g?.matchUpStatus)||g?.winningSide){let E=o.drawPositions||[],P=i.drawPositions?.filter(Boolean);ke(E,P)&&(P=P?.filter(U=>!E.includes(U))),I=E.concat(l).find(U=>P?.includes(U))}if(m&&I){let{stage:y,roundNumber:E,roundPosition:P,structureName:A}=m;Tn({method:"removeDirectedWinner",drawPositionToRemove:I,color:"brightgreen",roundPosition:P,structureName:A,roundNumber:E,keyColors:Qy,stage:y}),fM({winningDrawPosition:I,winnerMatchUp:m,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}let h=gM({targetData:p,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:s,structure:a,iteration:c});if(h.error)return _({result:h,stack:u});let S=I0({pairedPreviousDoubleExit:f,noContextTargetMatchUp:d}),T=!f;return h=Yn({...t,matchUpId:i.matchUpId,matchUp:d,removeWinningSide:!0,matchUpStatusCodes:[],context:u,matchUpStatus:S,removeScore:T,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),h.error?_({result:h,stack:u}):{...C}}function I0({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus==="BYE"?"BYE":t?[be,Gt].includes(e?.matchUpStatus)?Gt:Bt:Qt}function Wx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o}=t,i=t.targetData.targetLinks?.winnerTargetLink;if(i.target.feedProfile===fn){let s=n.sides?.find(({sideNumber:c})=>c===n.winningSide)?.participantId,a=r.find(c=>c.structureId===i.target.structureId&&c.roundNumber===i.target.roundNumber&&c.sides?.some(({participantId:u})=>u===s));if(a&&a.matchUpStatus===Qt){let c=ur({matchUpId:a.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Fi({inContextDrawMatchUps:r,drawDefinition:o,targetData:c})){let{structure:p}=at({structureId:a.structureId,drawDefinition:o}),m=Ct({structure:p}).positionAssignments;for(let d of m||[])if(d.participantId===s){if(d.participantId=void 0,p?.positionAssignments)p.positionAssignments=m;else if(p?.structures){let l=Object.assign({},...(m||[]).map(f=>({[f.drawPosition]:f.participantId})));for(let f of p?.structures||[])f.positionAssignments?.forEach(g=>g.participantId=l[g.drawPosition])}ko({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:p}),e=!0}}}}return{qualifierRemoved:e}}function Yx(t){let{matchUp:e,matchUpStatus:r,score:n,winningSide:o}=t,i="noDownStreamDependencies";if([oe,be].includes(e?.matchUpStatus)&&![oe,be].includes(r)){let h=gM(t);if(h.error)return _({result:h,stack:i})}let a=r===oe,c=he({score:n})&&!a&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!o),u=t?.inContextMatchUp?.collectionId&&_x(t.inContextMatchUp),p=t.removeScore||!u&&![mn,vr].includes(r||mn),m=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!o&&!he({score:n}),d=h=>{let S,{structure:T,drawDefinition:y,dualMatchUp:E,disableAutoCalc:P}=t;if(E?._disableAutoCalc&&P!==!1)return Fd({...t,removeWinningSide:m});let{connectedStructureIds:A}=zy({drawDefinition:y,structure:T,matchUp:e});A.length&&(console.log({connectedStructureIds:A}),S=!0),Object.assign(t,{removeScore:h});let U=Vc(t);if(U.error)return U;if(t.removingQualifier&&t.appliedPolicies?.[pu]?.autoRemoveQualifiers){let N=Wx(t);return{...C,connectedStructures:S,...N}}return{...C,connectedStructures:S}};if(m&&o&&t.isCollectionMatchUp)return jx(t);let l=[po,vr].includes(r)&&t.dualWinningSideChange,f=r&&r!==Qt,g=t.propagateExitStatus&&pr(r),I=(o||l||g)&&Bx(t)||c&&d(p)||f&&Fx(t)||m&&d(p)||e&&jx({...t,removeScore:!0})||{...C};return _({result:I,stack:i})}function jx(t){let e="ndd:scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide&&!t.autoCalcDisabled){let o=Vc(t);if(o.error)return o}let n=Yn({...t,context:e});if(t.isCollectionMatchUp){let{matchUpTieId:o,drawDefinition:i,event:s,matchUpsMap:a}=t,{removeWinningSide:c}=go({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:o,drawDefinition:i,matchUpsMap:a,event:s});c&&console.log("REMOVE WINNING SIDE")}return _({result:n,stack:e})}function fI(t){let e=et(t,[{[ne]:!0,[Ce]:!0,[gn]:!0},{homeParticipantId:!0,[In]:se}]);if(e.error)return e;let r=vs(t,[{[ds]:Gn,attr:{[uu]:!0}}]);if(r.error)return r;let n=r?.matchUp?.matchUp?.sides?.map(m=>m?.participantId);if(t.homeParticipantId&&!n?.includes(t.homeParticipantId))return{error:ln};let{disableNotice:o,homeParticipantId:i,removePriorValues:s,tournamentRecord:a,drawDefinition:c,matchUpId:u}=t;return Zr({duplicateValues:!1,removePriorValues:s,tournamentRecord:a,drawDefinition:c,disableNotice:o,matchUpId:u,timeItem:{itemType:Sd,itemValue:i}})}function IM({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Zo({timeItems:r?.timeItems||[],itemType:Op});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{timeModifiers:n}:e}function ii(t){let e="addMatchUpScheduledTime",r=t.matchUp,{removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,scheduledTime:a,matchUpId:c}=t;if(!c)return _({result:{error:sr},stack:e});if(!Jc(a))return _({result:{error:Co},stack:e});if(!r){let I=Vt({drawDefinition:i,matchUpId:c});if(I.error)return _({result:I,stack:e});r=I.matchUp}let u=Ut(a),p=Xs({matchUp:r}).scheduledDate,m=u&&!p;if((IM({matchUp:r}).timeModifiers||[])?.length){let I=hM({disableNotice:!0,removePriorValues:n,tournamentRecord:o,timeModifiers:[],drawDefinition:i,matchUpId:c,matchUp:r});if(I?.error)return _({result:I,stack:e})}let f=ac(a,!0,m);return Zr({duplicateValues:!1,removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,matchUpId:c,timeItem:{itemType:ts,itemValue:f}})}function hM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,timeModifiers:o,matchUpId:i,matchUp:s}){let a="addMatchUpTimeModifiers";if(!i)return _({result:{error:sr},stack:a});if(o!==void 0&&!Array.isArray(o))return _({info:li("timeModifiers"),result:{error:B},stack:a});if(!s){let l=Vt({drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a});s=l.matchUp}let c=IM({matchUp:s}).timeModifiers||[],u=o.filter(l=>!c.includes(l));if(o.length&&!u.length)return{...C};if(u.some(l=>hS.includes(l))){c=c.filter(f=>!hS.includes(f));let l=ii({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a})}let m=o?.length?[...u,...c]:void 0;return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:Op,itemValue:m}})}function fm({scheduledDate:t,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i}){if(!i)return{error:sr};let s=t&&Oo.test(t);if(t&&!s)return{error:Ye};let c={itemValue:Ut(t),itemType:Zi};return Zr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:c})}function gm({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtIds:a}){if(!r&&!e)return{error:q};if(!s)return{error:sr};let c=Vt({drawDefinition:n,matchUpId:s});if(c.error)return c;if(c?.matchUp?.matchUpType!==xr)return{error:dr};if(!(a===void 0||Array.isArray(a)&&a.length&&a.every(d=>typeof d=="string")))return{error:B,context:{courtIds:a}};let p;if(a){let d=e||r&&{[r.tournamentId]:r},l=Ro({tournamentRecords:d});if(l.error)return l;let f=l.courts?.filter(g=>a.includes(g.courtId));if(f?.length!==a.length)return{error:B,context:{courtIds:a}};p=f?.map(g=>({venueId:g.venueId,courtId:g.courtId}))}return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:lo,itemDate:i,itemValue:p}})}function la({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,venueId:s}){if(!r)return{error:q};if(!i)return{error:sr};if(s){let c=ti({tournamentRecords:e,tournamentRecord:r,venueId:s});if(c.error)return c}return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:Ji,itemValue:s}})}function as({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtId:a}){if(!r&&!e)return{error:q};if(!s)return{error:sr};if(a){let u=hs({tournamentRecords:e,tournamentRecord:r,courtId:a});if(u.error)return u;let p=u.venue?.venueId;la({tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,venueId:p})}return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:Jo,itemDate:i,itemValue:a}})}function xs(t,e){let r=nh.test(t)?t:zt(t),n=Ut(t)||Ut(e)||Kn(new Date);return new Date(`${n}T${r}`).getTime()}function Im(t){let e="addMatchUpScheduleItems",r=et(t,[{drawDefinition:!0,matchUpId:!0},{schedule:!0,[He]:zr}],e);if(r.error)return r;let{matchUpDependencies:n,inContextMatchUps:o}=t,{errorOnAnachronism:i=!1,checkChronology:s=!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,disableNotice:m,drawMatchUps:d,matchUpId:l,schedule:f,event:g}=t,I,h;if(d)I=d.find(v=>v.matchUpId===l);else{let v=Vt({drawDefinition:p,event:g,matchUpId:l});if(v.error)return v;I=v.matchUp}let{endTime:S,courtId:T,courtIds:y,courtOrder:E,resumeTime:P,homeParticipantId:A,scheduledDate:U,scheduledTime:N,startTime:D,stopTime:M,timeModifiers:R,venueId:b}=f;s&&(!n||!o)&&({matchUpDependencies:n,matchUps:o}=an({drawDefinition:p}));let O=n?.[l]?.matchUpIds;if(f.scheduledDate&&s&&O){let v=o?.filter(x=>(x.schedule?.scheduledDate||Ut(x.schedule?.scheduledTime))&&O.includes(x.matchUpId)).map(({schedule:x})=>{let F=Bm(x);return new Date(F).getTime()});if(v?.length){let x=Bm(f),F=new Date(x).getTime();if(Math.max(...v)>=F){if(i)return _({result:{error:VI},stack:e});h=VI}}}if(U!==void 0){let v=fm({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledDate:U,matchUpId:l});if(v?.error)return _({result:v,stack:e,context:{scheduledDate:U}})}if(N!==void 0){let v=ii({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledTime:N,matchUpId:l,matchUp:I});if(v?.error)return _({result:v,stack:e,context:{scheduledTime:N}})}if(D!==void 0){let v=Jy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,startTime:D,event:g});if(v?.error)return _({result:v,stack:e,context:{startTime:D}})}if(M!==void 0){let v=tE({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,stopTime:M,event:g});if(v?.error)return _({result:v,stack:e,context:{stopTime:M}})}if(P!==void 0){let v=eE({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,resumeTime:P,matchUpId:l,event:g});if(v?.error)return _({result:v,stack:e,context:{resumeTime:P}})}if(S!==void 0){let v=Zy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,endTime:S,event:g});if(v?.error)return _({result:v,stack:e,context:{endTime:S}})}if(y!==void 0){let v=gm({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtIds:y});if(v?.error)return _({result:v,stack:e,context:{courtIds:y}})}if(T!==void 0&&U!==void 0){let v=as({courtDayDate:U,disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtId:T});if(v?.error)return _({result:v,stack:e,context:{courtId:T}})}if(b!==void 0){let v=la({disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,venueId:b});if(v?.error)return _({result:v,stack:e,context:{venueId:b}})}if(E!==void 0&&It(E)){let v=Xy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,courtOrder:E,matchUpId:l});if(v?.error)return _({result:v,stack:e,context:{courtOrder:E}})}if(R!==void 0){let v=hM({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,timeModifiers:R,matchUpId:l,matchUp:I});if(v?.error)return _({result:v,stack:e,context:{timeModifiers:R}})}return kt(A)&&fI({disableNotice:!0,homeParticipantId:A,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l}),m||gt({tournamentId:u?.tournamentId,eventId:g?.eventId,context:e,drawDefinition:p,matchUp:I}),h?{...C,warnings:[h]}:{...C}}function Xy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,courtOrder:o,matchUpId:i}){if(!i)return{error:sr};if(o&&!It(o))return{error:B,info:"courtOrder must be numeric"};let s=o&&dt(o);return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:bp,itemValue:s}})}function SM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,participantId:o,officialType:i,matchUpId:s}){if(!s)return{error:sr};if(!o)return{error:se};if(e){let c=Ft({tournamentRecord:e,participantFilters:{participantTypes:[Et],participantRoles:[Sg]}}).participants??[];if(!zo({tournamentParticipants:c,participantId:o}))return{error:re}}let a={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:o};return i&&(a.itemSubTypes=[i]),Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:s,timeItem:a})}function Jy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,startTime:i,event:s}){if(!o)return{error:sr};if(!Jc(i))return{error:Co};let{matchUp:a}=Vt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Xs({matchUp:a}),p=(a?.timeItems??[]).filter(m=>[es,Oi,vi].includes(m?.itemType)).map(m=>xs(m.itemValue,c)).reduce((m,d)=>!m||d<m?d:m,void 0);if(!p||xs(i,c)<p){a?.timeItems&&(a.timeItems=a.timeItems.filter(l=>l.itemType!==Bo));let m=ac(i,!0,!0);return Zr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:{itemType:Bo,itemValue:m}})}else return{error:xA}}function Zy({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,endTime:s,event:a}){if(!i)return{error:sr};if(!Jc(s))return{error:Co};let{matchUp:c}=Vt({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:u}=Xs({matchUp:c}),m=(c?.timeItems??[]).filter(d=>[Bo,Oi,es].includes(d?.itemType)).map(d=>xs(d.itemValue,u)).reduce((d,l)=>!d||l>d?l:d,void 0);if(!t||!m||xs(s,u)>m){c?.timeItems&&(c.timeItems=c.timeItems.filter(f=>f.itemType!==vi));let d=ac(s,!0,!0);return Zr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:vi,itemValue:d}})}else return{error:vA}}function tE({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,stopTime:i,event:s}){if(!o)return{error:sr};if(!Jc(i))return{error:Co};let{matchUp:a}=Vt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Xs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===vi||g,void 0))return{error:JI};let m=u.filter(g=>[Bo,Oi,es].includes(g?.itemType)).sort((g,I)=>xs(g.itemValue,c)-xs(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===es,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>xs(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(xs(i,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:ac(i,!0,!0),itemType:es};return Zr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:I})}else return{error:_A}}function eE({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,resumeTime:o,matchUpId:i,event:s}){if(!i)return{error:sr};if(!Jc(o))return{error:Co};let{matchUp:a}=Vt({drawDefinition:r,event:s,matchUpId:i}),{scheduledDate:c}=Xs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===vi||g,void 0))return{error:JI};let m=u.filter(g=>[Bo,Oi,es].includes(g?.itemType)).sort((g,I)=>xs(g.itemValue,c)-xs(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===Oi,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>xs(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(xs(o,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:ac(o,!0,!0),itemType:Oi};return Zr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:I})}else return{error:xC}}function qx(t){let{targetData:e,matchUpsMap:r}=t,{targetMatchUps:{loserMatchUp:n}}=e,o=pr(n?.matchUpStatus),i=!!r?.drawMatchUps.find(s=>s.loserMatchUpId===n?.matchUpId&&pr(s.matchUpStatus));return i&&n?.matchUpStatus===oe||i&&o}function $x({drawDefinition:t,matchUpStatus:e,matchUpsMap:r,winningSide:n,dualMatchUp:o,tieFormat:i,structure:s,matchUp:a,event:c,score:u}){let p=J(o,void 0,!0);for(let d of p?.tieMatchUps||[])d.matchUpId===a.matchUpId&&(d.winningSide=n,d.score=u,!he({score:u})&&!e?Object.assign(d,{...Gu}):e&&(d.matchUpStatus=e));i=i??We({matchUp:a,structure:s,drawDefinition:t,event:c})?.tieFormat;let{winningSide:m}=vc({matchUp:p,drawDefinition:t,matchUpsMap:r,structure:s,tieFormat:i,event:c});return{projectedWinningSide:m}}function Kx(t){let{tournamentRecord:e,inContextMatchUp:r,structure:n,drawDefinition:o}=t,i=r.roundNumber,s=r.sides.find(P=>P.sideNumber===r.winningSide),a=r.sides.find(P=>P.sideNumber!==r.winningSide),{drawPosition:c,participantId:u}=s,{drawPosition:p,participantId:m}=a,d="swapWinnerLoser",{matchUps:l}=yt(t),f=l.filter(({drawPositions:P,roundNumber:A})=>P?.includes(c)&&A>i);Dr({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:f}),f.forEach(P=>{P.drawPositions=P.drawPositions?.map(A=>A===c?p:A)||[],gt({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:d,drawDefinition:o,matchUp:P})});let{stage:g,stageSequence:I}=n,h=o.structures.filter(({stage:P,stageSequence:A})=>P===g&&A>I).map(({structureId:P})=>P),{targetLinks:{loserTargetLink:S,winnerTargetLink:T}}=t.targetData,y=[S?.target.structureId,T?.target?.structureId].filter(Boolean);return o.structures.filter(({stage:P,structureId:A})=>P!==g&&y.includes(A)).forEach(({stage:P,stageSequence:A,structureId:U})=>{h.includes(U)||h.push(U),o.structures.filter(({stage:N,stageSequence:D})=>N===P&&D>A).forEach(({structureId:N})=>{h.includes(N)||h.push(N)})}),o.structures.filter(({structureId:P})=>h.includes(P)).forEach(P=>{let{positionAssignments:A}=Ct({structure:P}),U=A?.find(({participantId:D})=>D===u),N=A?.find(({participantId:D})=>D===m);U&&(U.participantId=m),N&&(N.participantId=u)}),Yn({...t,context:d})}function ws(t){let e="setMatchUpStatus";t.matchUpStatus&&[Bt,oe].includes(t.matchUpStatus)&&(t.score=void 0);let{allowChangePropagation:r,disableScoreValidation:n,propagateExitStatus:o,tournamentRecords:i,tournamentRecord:s,disableAutoCalc:a,enableAutoCalc:c,drawDefinition:u,matchUpStatus:p,winningSide:m,matchUpId:d,event:l,score:f}=t;if(!u)return{error:Z};if(p&&[po,mn,vr,Qt].includes(p)&&m)return{error:B,winningSide:m,matchUpStatus:p};if(![void 0,...qh].includes(p))return _({result:{error:Ta},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});let g=Pe({drawDefinition:u}),{matchUps:I}=ie({nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:u,matchUpsMap:g,event:l}),h=g.drawMatchUps.find(Y=>Y.matchUpId===d),S=I?.find(Y=>Y.matchUpId===d);if(!h||!I)return{error:we};if((h.winningSide||m)&&p==="BYE")return{context:"Cannot have Bye with winningSide",error:Xl,matchUpStatus:p};let T=S?.structureId,{structure:y}=at({drawDefinition:u,structureId:T}),E=de(Wt)(h.matchUpType),P=S?.drawPositions?.filter(Boolean),A=S?.matchUpTieId,U=ur({matchUpId:A||d,inContextDrawMatchUps:I,drawDefinition:u});Object.assign(t,{inContextDrawMatchUps:I,inContextMatchUp:S,matchUpTieId:A,matchUpsMap:g,targetData:U,structure:y,matchUp:h});let N=p===Qt&&f?.scoreStringSide1===""&&f?.scoreStringSide2===""&&!m;if(qx(t)&&N)return{error:bC};let M=Fi(t),R;if(E){if(a)At({extension:{name:Ua,value:!0},element:h});else if(c){let Y=h.winningSide,{winningSide:j,scoreStringSide1:V,scoreStringSide2:$,set:X}=vc({drawDefinition:u,matchUpsMap:g,structure:y,matchUp:h,event:l}),W={scoreStringSide1:V,scoreStringSide2:$,sets:X?[X]:[]};if(R=j!==Y,M&&R)return _({stack:"winningSideWithDownstreamDependencies",result:{error:xm},context:{winningSide:m,matchUp:h}});Ir({name:Ua,element:h}),Object.assign(t,{winningSide:j,dualWinningSideChange:R,projectedWinningSide:j,score:W})}ka({tournamentId:s?.tournamentId,inContextDualMatchUp:S,eventId:l?.eventId,dualMatchUp:h,drawDefinition:u})}if(E&&p&&[gc].includes(p))return{info:"Not supported for matchUpType: TEAM",error:B};if(f&&!E&&!n){let Y=h.matchUpFormat??y?.matchUpFormat??u?.matchUpFormat??l?.matchUpFormat,j=Qg({existingMatchUpStatus:h.matchUpStatus,matchUpFormat:Y,matchUpStatus:p,winningSide:m,score:f});if(j.error)return j}let b=Tt({policyTypes:[pu,rn],tournamentRecord:s,drawDefinition:u,event:l})?.appliedPolicies??{};ht(t.policyDefinitions)&&Object.assign(b,t.policyDefinitions);let O=S0({assignedDrawPositions:P,propagateExitStatus:o,inContextMatchUp:S,appliedPolicies:b,drawDefinition:u,matchUpStatus:p,structure:y,matchUp:h});if(O?.error)return O;let v=S?.stage===ct&&S.finishingRound===1,x=v&&m,F=v&&h.winningSide&&!m&&(!t.matchUpStatus||t.matchUpStatus&&gg({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!he({outcome:t.outcome})),w=x&&m!==h.winningSide&&h.winningSide;if(Object.assign(t,{qualifierAdvancing:x,qualifierChanging:w,removingQualifier:F,appliedPolicies:b}),A){let{matchUp:Y}=Vt({matchUpId:A,inContext:!0,drawDefinition:u,matchUpsMap:g,event:l});if(Y){let j=We({matchUp:Y,drawDefinition:u,structure:y,event:l})?.tieFormat,{projectedWinningSide:V}=$x({drawDefinition:u,matchUpStatus:p,dualMatchUp:Y,matchUpsMap:g,winningSide:m,tieFormat:j,structure:y,matchUp:h,event:l,score:f}),$=Y.winningSide;R=V!==$;let X=Y._disableAutoCalc;Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:R,projectedWinningSide:V,autoCalcDisabled:X,matchUpTieId:A,dualMatchUp:Y,tieFormat:j})}}let L=Oa({matchUpStatus:p});if(!A){if(M&&!m&&(p&&gg({matchUpStatus:p})||p&&[oe,be].includes(p)))return{error:Xl,activeDownstream:M,winningSide:m};if(m&&m===h.winningSide&&p&&!L)return{context:"winningSide must include directing matchUpStatus",error:Xl,directingMatchUpStatus:L,matchUpStatus:p}}let{schedule:k}=t;if(k){let Y=Im({disableNotice:!0,tournamentRecords:i,tournamentRecord:s,drawDefinition:u,matchUpId:d,schedule:k});if(Y.error)return Y}let G=!E&&!R&&m&&h.winningSide&&h.winningSide!==m;if(r&&G&&h.roundPosition)return Kx(t);let H=m&&!A||t.projectedWinningSide;Tn({activeDownstream:M,matchUpWinner:H,method:e,winningSide:m});let K=!M&&Yx(t)||H&&h0(t)||(L||t.autoCalcDisabled)&&zx(t)||{error:HA};return _({result:K,stack:e})}function h0(t){let{matchUp:e,winningSide:r,matchUpTieId:n,dualWinningSideChange:o}=t;return r===e.winningSide||n&&!o?zx(t):_({stack:"winningSideWithDownstreamDependencies",result:{error:xm},context:{winningSide:r,matchUp:e}})}function zx(t){let{tournamentRecord:e,matchUp:r,event:n}=t,o=t.isCollectionMatchUp&&r.winningSide&&!t.winningSide&&!he({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||o&&Qt||t.winningSide&&ge||mn:t.matchUpStatus||ge,s=t.removeScore||[po,Bt].includes(i)&&![mn,vr].includes(i),a=Yn({...t,matchUpStatus:i,removeWinningSide:o,context:"sms",removeScore:s});if(a.error)return a;if(t.isCollectionMatchUp){let{matchUpTieId:c,drawDefinition:u,matchUpsMap:p}=t,m=go({appliedPolicies:t.appliedPolicies,matchUpId:c,tournamentRecord:e,drawDefinition:u,matchUpsMap:p,event:n});if(m.error)return m;Object.assign(a,{tieMatchUpResult:m})}return a}function S0({assignedDrawPositions:t,propagateExitStatus:e,inContextMatchUp:r,appliedPolicies:n,drawDefinition:o,matchUpStatus:i,structure:s,matchUp:a}){if(n?.[rn]?.requireParticipantsForScoring===!1)return{...C};let c=r?.sides?.map(m=>m.participantId).filter(Boolean).length,u=a?.sides?[]:Ct({structureId:s?.structureId,drawDefinition:o}).positionAssignments,p=c&&c===2||a.collectionId&&cr({structure:s})&&c&&c>=1||t?.length===2&&u?.filter(m=>t.includes(m.drawPosition)).every(m=>m.participantId);return i&&[Bt,Gt,oe].includes(i)&&c===1&&e?{...C}:i&&Yh.includes(i)&&!p?_({info:"matchUpStatus requires assigned participants",context:{matchUpStatus:i,requiredParticipants:p},result:{error:Ta}}):{...C}}function TM({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n}){if(!e)return{error:Z};let{matchUp:o}=Vt({drawDefinition:e,matchUpId:r,event:n});return o?.matchUpType!==xr?{error:dr}:ws({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n})}function yM({drawDefinition:t,event:e,matchUpId:r}){if(!t)return{error:Z};if(!r)return{error:sr};let{matchUp:n}=Vt({drawDefinition:t,event:e,matchUpId:r});return n?Ir({name:Jm,element:n}):{error:we}}function Qx({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:r,drawDefinition:n,sideNumber:o,matchUpId:i,event:s}){let a="substituteParticipant";if(!n)return{error:Z};if(!i)return{error:sr};if(!e||!t)return _({result:{error:se},stack:a});let{matchUp:c}=Vt({drawDefinition:n,matchUpId:i,event:s});if(!c)return{error:we};if(!c.collectionId)return _({result:{error:dr},stack:a});let u=Pe({drawDefinition:n}),{matchUps:p}=ie({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),m=p?.find(g=>g.matchUpId===i),l=p?.find(g=>g.matchUpId===m?.matchUpTieId)?.sides?.find(g=>g.participant.individualParticipants.some(({participantId:I})=>I===e));return!l||o&&l.sideNumber!==o?{error:ln}:l.participant?.individualParticipants?.map(St).filter(g=>g!==e)?.includes(t)?dI({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:r,drawDefinition:n,event:s}):_({result:{error:ln},stack:a})}function EM(t){return Qx(t)}function AM({drawDefinition:t,matchUpId:e,event:r}){if(!t)return{error:Z};let{matchUp:n}=Vt({drawDefinition:t,matchUpId:e,event:r});return At({extension:{name:Ua,value:!0},element:n})}function UM(t){let e="setMatchUpFormat",r=et(t,[{tournamentRecord:!0},{[tr]:E=>Nr({matchUpFormat:E}),[kr]:tc,matchUpFormat:!0}]);if(r.error)return _({result:r,stack:e});let{tournamentRecord:n,drawDefinition:o,scheduledDates:i,stageSequences:s,matchUpFormat:a,structureId:c,eventType:u,matchUpId:p,eventId:m,stages:d,drawId:l,event:f,force:g}=t;if(i&&!Array.isArray(i))return _({result:{error:B,scheduledDates:i},stack:e});if(u&&!Yc([Qn,Kr],u))return _({result:{error:$n},stack:e});let I=0,h=t.structureIds||c&&[c].filter(Boolean)||[],S=t.eventIds||m&&[m].filter(Boolean)||[],T=t.drawIds||l&&[l].filter(Boolean)||[];if((c||h?.length)&&!o)return _({result:{error:Z},stack:e});if(l&&p&&o){let E=el({tournamentRecord:n,drawDefinition:o,matchUpFormat:a,structureIds:h,structureId:c,matchUpId:p});if(E.error)return E;I+=1}let y=E=>{let P=[];for(let A of E.structures||[]){if(Array.isArray(d)&&!d.includes(A.stage)||Array.isArray(s)&&!s.includes(A.stageSequence)||h?.length&&!h.includes(A.structureId))continue;h?.length&&A.matchUpFormat!==a&&(A.matchUpFormat=a,P.push(A.structureId),I+=1);let U=((g||i)&&yt({matchUpFilters:{matchUpStatuses:[Qt]},structure:A}).matchUps)??[],N=(i&&yt({matchUpFilters:{matchUpStatuses:[Qt]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:A}).matchUps)??[];if(U?.length){let D=N?N.map(Ue):U.map(Ue);for(let M of U)D.includes(M.matchUpId)&&(M.matchUpFormat=i?.length?a:void 0,gt({tournamentId:n?.tournamentId,eventId:f?.eventId,context:e,drawDefinition:E,matchUp:M}))}}return!P.length&&E.matchUpFormat!==a&&(E.matchUpFormat=a,I+=1),P};for(let E of n?.events||[])if(!(S?.length&&!S.includes(E.eventId)||u&&u!==E.eventType||u===_e))if(Array.isArray(s)||Array.isArray(d)||h?.length||T?.length)for(let P of E.drawDefinitions||[]){if(Array.isArray(T)&&!T.includes(P.drawId))continue;let A=y(P);bt({structureIds:A,drawDefinition:P})}else E.matchUpFormat!==a&&(E.matchUpFormat=a,I+=1);return I?{...C,modificationsCount:I}:{...C,info:Bs}}function gI({inheritance:t=!0,tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}){if(!r)return{error:Z};let i=Vt({drawDefinition:r,matchUpId:n})?.matchUp;if(!i?.tieMatchUps)return{error:dr};let s=Vt({inContext:!0,drawDefinition:r,matchUpId:n,event:o})?.matchUp,a=0;return(i?.sides||[]).forEach(c=>{c.lineUp&&delete c.lineUp}),(s?.sides||[]).forEach(c=>{if(a+=1,t===!1){let u=s?.tieFormat,p=c.participantId;u&&p&&os({drawDefinition:r,participantId:p,lineUp:[],tieFormat:u})}gt({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:o?.eventId,drawDefinition:r,matchUp:i})}),{...C,modificationsCount:a}}function rE(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o,setTBlast:i}=t;if(!o)return{sets:[]};let s=o.sets||[],a=Mo({winnerFirst:!1,matchUpFormat:e,matchUpStatus:r,setTBlast:i,sets:s}),c=Mo({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:r,setTBlast:i,sets:s}),u=Mo({matchUpFormat:e,matchUpStatus:r,winningSide:n,setTBlast:i,sets:s}),p=a===u?c:a;return n&&(a=n===1?u:p,c=n===2?u:p),{score:{sets:s,scoreStringSide1:a,scoreStringSide2:c}}}function Xx({sourceMatchUpStatusCodes:t,propagateExitStatus:e,sourceMatchUpStatus:r,loserParticipantId:n,tournamentRecord:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,event:c}){let u="progressExitStatus";Tn({matchUpId:s?.matchUpId,matchUpStatus:r,color:"magenta",method:u});let p=pr(r)&&r!==Me&&r||Bt,m=ie({inContext:!0,drawDefinition:i,matchUpsMap:a})?.matchUps,d=p,l=m?.find(f=>f.matchUpId===s?.matchUpId);if(l?.matchUpId&&d){let f,g=l.matchUpStatusCodes?.map(S=>typeof S=="string"?S:"WO")??[],I=l.sides?.find(S=>S.participantId===n);if(I?.sideNumber)if(l?.sides?.reduce((T,y)=>y?.participantId?T+1:T,0)===1&&g.length===0)f=I.sideNumber===1?2:1,g[0]=t[0];else if(!pr(s.matchUpStatus))f=I.sideNumber===1?2:1,g[0]=t[0];else{let T=g[0];g[I.sideNumber-1]=t[0];let y=I.sideNumber===1?2:1;g[y-1]=T,d=oe,f=void 0}let h=ws({matchUpStatus:d,matchUpId:s.matchUpId,matchUpStatusCodes:g,allowChangePropagation:!0,propagateExitStatus:e,tournamentRecord:o,drawDefinition:i,winningSide:f,event:c});return _({result:h,stack:u,context:{progressExitStatus:!0}})}return _({result:{error:mr},stack:u})}function Qu(t){let e=et(t,[{[gn]:!0,[Ce]:!0}]);if(e.error)return e;let r="setMatchUpStatus",n=Rr(t);if(!t.drawDefinition){let E=t.tournamentRecord??(t.tournamentId&&n[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=E);let P=ze({eventId:t.eventId,drawId:t.drawId,tournamentRecord:E});if(P.error)return P;P.drawDefinition&&(t.drawDefinition=P.drawDefinition),t.event=P.event}let{disableScoreValidation:o,propagateExitStatus:i,policyDefinitions:s,tournamentRecord:a,disableAutoCalc:c,enableAutoCalc:u,drawDefinition:p,matchUpId:m,schedule:d,event:l,notes:f}=t,g=t.matchUpFormat||t.outcome?.matchUpFormat,{policy:I}=pi({policyType:rn,tournamentRecord:a,event:l}),h=t.allowChangePropagation!==void 0&&t.allowChangePropagation||I?.allowChangePropagation!==void 0&&I.allowChangePropagation||void 0,{outcome:S,setTBlast:T}=t;if(S?.winningSide&&![1,2].includes(S.winningSide))return{error:_m};if(g){let E=el({tournamentRecord:a,drawDefinition:p,matchUpFormat:g,matchUpId:m,event:l});if(E.error)return E}if(S?.score?.sets&&!S.score.scoreStringSide1){let{score:E}=rE({...S,setTBlast:T});S.score=E,S.score.sets=S.score.sets.filter(P=>P.side1Score||P.side2Score||P.side1TiebreakScore||P.side2TiebreakScore)}let y=ws({matchUpStatusCodes:S?.matchUpStatusCodes,matchUpStatus:S?.matchUpStatus,winningSide:S?.winningSide,allowChangePropagation:h,disableScoreValidation:o,score:S?.score,propagateExitStatus:i,tournamentRecords:n,policyDefinitions:s,tournamentRecord:a,disableAutoCalc:c,enableAutoCalc:u,drawDefinition:p,matchUpFormat:g,matchUpId:m,schedule:d,event:l,notes:f});if(y.context?.progressExitStatus){let E=!0,P=0;for(;E&&P<10;){E=!1,P+=1;let A=Xx({sourceMatchUpStatusCodes:y.context.sourceMatchUpStatusCodes,sourceMatchUpStatus:y.context.sourceMatchUpStatus,loserParticipantId:y.context.loserParticipantId,propagateExitStatus:t.propagateExitStatus,tournamentRecord:t.tournamentRecord,loserMatchUp:y.context.loserMatchUp,matchUpsMap:y.context.matchUpsMap,drawDefinition:t.drawDefinition,event:t.event});A.context?.loserMatchUp&&(Object.assign(y.context,A.context),E=!0)}}return _({result:y,stack:r})}function PM(t){if(!t?.outcomes)return{error:st};if(!Array.isArray(t.outcomes))return{error:st,info:{outcomes:t.outcomes}};let e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},r=t.outcomes??[],n=r.reduce((o,i)=>o.includes(i.tournamentId)?o:o.concat(i.tournamentId),[]);for(let o of n){let i=e[o];if(!i)return{error:q};let s=r.filter(a=>a.tournamentId===o);if(s.length){let a=T0({outcomes:s,tournamentRecord:i});if(a.error)return a}}return{...C}}function T0(t){let{tournamentRecords:e,tournamentRecord:r,outcomes:n,policyDefinitions:o}=t,i={};n.forEach(s=>{let{eventId:a}=s;i[a]||(i[a]=[]),i[a].push(s)});for(let s of Object.keys(i)){let{event:a}=ze({tournamentRecord:r,eventId:s});for(let c of i[s]){let{drawId:u}=c,p=a?.drawDefinitions?.find(m=>m.drawId===u);if(p&&u){let{matchUpFormat:m,matchUpId:d}=c,l=Qu({schedule:c?.schedule,tournamentRecords:e,policyDefinitions:o,tournamentRecord:r,drawDefinition:p,matchUpFormat:m,matchUpId:d,outcome:c,drawId:u,event:a});if(l.error)return l}}}return{...C}}function Jx({drawDefinition:t,matchUpId:e,outcome:r,matchUp:n}){if(!n&&!t)return{error:Z};if(!r)return{error:st,info:"missing outcome"};if(!n&&!e)return{error:mr};if(!n){let i=Vt({drawDefinition:t,matchUpId:e});if(i.error)return i;n=i.matchUp}return typeof r!="object"||!r.score?.scoreStringSide1||!r.score?.scoreStringSide2?{error:B}:At({element:n,extension:{name:Jm,value:r}})}function DM(t){return Jx(t)}function II(t){let e="resetTieFormat",{drawDefinition:r,event:n,uuids:o}=t,i=et(t,[{[ne]:!0,[gn]:!0}],e);if(i.error)return i;let s=vs(t,[{[ds]:Gn}]);if(s[In])return s;let a=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=s?.matchUp??{};if(!c?.tieMatchUps)return _({result:{error:dr},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...C};let p=We({structure:u,drawDefinition:r,event:n})?.tieFormat;if(!p)return _({result:{error:Oe},info:"No inherited tieFormat",stack:e});let m=[],d=[],l=[],f=[];for(let g of p.collectionDefinitions){let{matchUpCount:I,collectionId:h}=g;d.push(h);let S=(c.tieMatchUps||[]).filter(T=>T.collectionId===h);if(S.length>I)S.sort((T,y)=>(T.matchUpStatus===Qt?1:0)-(y.matchUpStatus===Qt?1:0)),l.push(...S.slice(0,I)),m.push(...S.slice(3).map(Ue));else if(l.push(...S),S.length<I){let T=I-S.length,y=wu({collectionDefinition:g,matchUpsLimit:T,matchUp:c,uuids:o});f.push(...y)}}for(let g of c?.tieMatchUps||[])g.collectionId&&!d.includes(g.collectionId)&&m.push(g.matchUpId);return f.length&&(l.push(...f),Fo({eventId:n?.eventId,matchUps:f,drawDefinition:r,tournamentId:a})),m.length&&_n({matchUpIds:m,eventId:n?.eventId,drawDefinition:r,tournamentId:a}),c&&(c.tieMatchUps=l,c.tieFormatId=void 0,c.tieFormat=void 0,gt({structureId:u?.structureId,eventId:n?.eventId,context:e,drawDefinition:r,tournamentId:a,matchUp:c})),{...C,newMatchUps:f,deletedMatchUpIds:m}}function hI(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}=t,i="resetScorecard";if(!r)return _({result:{error:Z},stack:i});if(!n)return _({result:{error:sr},stack:i});if(!kt(n))return _({result:{error:B,matchUpId:n},stack:i});let s=Pe({drawDefinition:r}),{matchUps:a}=ie({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),c=s.drawMatchUps.find(I=>I.matchUpId===n),u=a?.find(I=>I.matchUpId===n);if(!c||!a)return{error:we};if(c.matchUpType!==Or)return{error:dr};let p=ur({inContextDrawMatchUps:a,drawDefinition:r,matchUpId:n}),m=u?.structureId,{structure:d}=at({drawDefinition:r,structureId:m});if(Object.assign(t,{inContextDrawMatchUps:a,inContextMatchUp:u,matchUpsMap:s,targetData:p,structure:d,matchUp:c}),Fi(t))return{error:xm};if(c.tieMatchUps?.length)for(let I of c.tieMatchUps){let h=ws({matchUpId:I.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:r,event:o});if(h.error)return _({result:h,stack:i})}let f=Tt({tournamentRecord:e,drawDefinition:r,event:o})?.appliedPolicies,g=go({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(g.error)return _({result:g,stack:i});if(t.tiebreakReset&&!g.tieFormatRemoved){let I=We({drawDefinition:r,structure:d,event:o})?.tieFormat;if(c.tieFormat&&I){let{matchUpCountDifference:h,descendantDifferences:S,ancestorDifferences:T,valueDifference:y}=ni({descendant:c.tieFormat,ancestor:I});if(S.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&h===1&&y===1){let E=II({tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o});if(E.error)return E}}}return{...C}}function NM(t){let e=et(t,[{[Ce]:!0,[co]:!0},{[Ks]:{[mc]:!1,roundNumbers:!1},[Vh]:"At least one must be provided",[He]:Be}]);if(e.error)return e;let r=mT(t);if(r.error)return r;let{matchUpIds:n}=r,o=de(Or)(t.event.eventType),{tournamentRecord:i,drawDefinition:s,event:a}=t;for(let c of n){if(o){let p=hI({tiebreakReset:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(p.error||t.removeAssignments&&gI({inheritance:!1,drawDefinition:s,matchUpId:c}).error)return p}let u=ws({winningSide:void 0,removeScore:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(u.error)return u;if(t.removeAssignments){let p=lI({...t,matchUpId:c});if(p.error)return p}}return{...C}}function Zx({tournamentRecord:t,drawDefinition:e,finishingOrder:r}){if(!e)return{error:Z};let n="setOrderOfFinish";if(!Array.isArray(r))return _({info:li("finishingOrder"),result:{error:B},stack:n});let{completedMatchUps:o,matchUpsMap:i}=Zs({inContext:!0,drawDefinition:e}),s=o?.map(Ue)??[],a=r.map(Ue),{matchUpTypes:c,roundNumbers:u,structureIds:p,matchUpTieIds:m}=(o??[]).filter(({matchUpId:T})=>a.includes(T)).reduce((T,y)=>{let{matchUpTieId:E,matchUpType:P,roundNumber:A,structureId:U}=y;return T.matchUpTypes.includes(P)||T.matchUpTypes.push(P),T.roundNumbers.includes(A)||T.roundNumbers.push(A),T.structureIds.includes(U)||T.structureIds.push(U),T.matchUpTieIds.includes(E)||T.matchUpTieIds.push(E),T},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||m.length>1||u.length>1||p.length>1)return _({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:B},stack:n});let d,l,f={},g=[],I=[];if(!r.every(({orderOfFinish:T,matchUpId:y})=>(g.push(y),T&&I.push(T),f[y]=T,d=s.includes(y),l=T===void 0||It(T)&&Math.floor(T)>0,d&&l)))return _({result:{error:d?B:Ta},info:!d&&"matchUps must be completed"||!l&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:n});let S=o?.filter(T=>T.structureId===p[0]&&T.roundNumber===u[0]&&T.matchUpType===c[0]&&T.matchUpTieId===m[0]&&!g.includes(T.matchUpId));for(let T of S??[]){let{orderOfFinish:y}=T||{};if(y){if(!It(y))return _({context:{orderOfFinish:y,matchUp:T},result:{error:B},stack:n});I.push(y)}}if(xI(I).length!==I.length||Math.max(...I)>I.length)return _({info:"Values not unique or greater than expected number of values",result:{error:B},stack:n});if(p.length){let T=Mu({matchUpFilters:{matchUpIds:a},structureId:p[0],drawDefinition:e,matchUpsMap:i});if(T.error)return _({result:T,stack:n});T.completedMatchUps?.forEach(y=>{y.orderOfFinish=f[y.matchUpId],gt({tournamentId:t.tournamentId,context:"setOrderOfFinish",drawDefinition:e,matchUp:y})})}return{...C}}function MM(t){return Zx(t)}function RM(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,lineUps:o,event:i}=t,s="applyLineUps",a=et(t,[{[ne]:!0,[Ce]:!0,[gn]:!0},{lineUps:!0,[He]:Be}],s);if(a.error)return a;let c=e.participants||[],u=Vt({tournamentParticipants:c,inContext:!0,drawDefinition:r,matchUpId:n});if(u.error)return u;if(!u.matchUp)return{error:we};let{matchUp:p,structure:m}=u,{drawPositions:d,matchUpType:l}=p;if(l!==Wt)return{error:dr};if(!d?.length)return{error:Ja};let f=We({matchUp:p,drawDefinition:r,structure:m,event:i})?.tieFormat,g={};for(let h of o){if(!Array.isArray(h))return{error:B,lineUp:h};let S={},T=[];for(let U of h){if(typeof U!="object")return{error:B,lineUpAssignment:U};let{participantId:N,collectionAssignments:D=[]}=U;if(!Array.isArray(D))return{error:B,collectionAssignments:D};let M=c.find(b=>b.participantId===N);if(!M)return{error:re};if(M.participantType!==Et)return{error:Pn};let R=p.sides?.find(b=>b.participant?.individualParticipantIds?.includes(N))?.sideNumber;R&&T.push(R);for(let b of D){if(typeof b!="object")return{error:B,collectionAssignment:b};let{collectionId:O,collectionPosition:v}=b,x=f?.collectionDefinitions?.find(L=>L.collectionId===O);if(!x)return{error:B,collectionId:O};let F=`${O}-${v}`;S[F]||(S[F]=[]);let w=S[F].length;if(de(Lt)(x.matchUpType)&&w||x.matchUpType===vt&&w>1)return{info:"Excessive collectionPosition assignments",error:B};S[F].push(N)}}let y=Object.values(S);for(let U of y)if(U.length===2){let{participant:N}=Sn({tournamentParticipants:c,participantIds:U});if(!N){let M=wn({participant:{participantType:ft,participantRole:xe,individualParticipantIds:U},pairOverride:!0,tournamentRecord:e});if(M.error)return M}}let E=Er(T),P=(E[1]||0)>(E[2]||0)&&1||(E[2]||0)>(E[1]||0)&&2||void 0,A=Object.keys(g).map(U=>parseInt(U));P&&!A.includes(P)&&(g[P]=h)}if(!Object.keys(g).length)return{error:ff};if(u=Vt({drawDefinition:r,matchUpId:n}),u.error)return u;if(!u.matchUp)return{error:we};let{matchUp:I}=u;I.sides||(I.sides=[]);for(let h of[1,2]){let S=I.sides.find(y=>y.sideNumber===h),T=g[h];if(T)S?S.lineUp=T:I.sides.push({lineUp:T,sideNumber:h});else continue}return gt({tournamentId:e?.tournamentId,context:s,drawDefinition:r,matchUp:I}),{...C}}var PI={};Xt(PI,{anonymizeTournamentRecord:()=>FM,generate:()=>LM,generateEventWithDraw:()=>Um,generateOutcome:()=>EI,generateOutcomeFromScoreString:()=>SI,generateParticipants:()=>fa,generateTournamentRecord:()=>wM,modifyTournamentRecord:()=>kM,mutate:()=>GM});var LM={};Xt(LM,{generateEventWithDraw:()=>Um,generateOutcome:()=>EI,generateOutcomeFromScoreString:()=>SI,generateParticipants:()=>fa,generateTournamentRecord:()=>wM});function y0(t){let e=t.reduce((n,o)=>((o.side1Score!==void 0||o.side2Score!==void 0)&&(n.side1+=o.side1Score??0,n.side2+=o.side2Score??0),n),{side1:0,side2:0});return e.side1>e.side2?1:e.side2>e.side1?2:t.find(n=>n.side1TiebreakScore!==void 0||n.side2TiebreakScore!==void 0)?.winningSide}function E0(t){let e={side1:0,side2:0};if(t.forEach(r=>{r.winningSide===1?e.side1++:r.winningSide===2&&e.side2++}),e.side1>e.side2)return 1;if(e.side2>e.side1)return 2}function A0(t,e,r){if(t||!e||!r)return t;let n=Ne(e);return n?.setFormat?.based==="A"||n?.finalSetFormat?.based==="A"?y0(r):E0(r)}function U0(t,e,r){let n=nm({scoreString:t,matchUpFormat:e});return{sets:n,scoreStringSide1:Mo({sets:n,matchUpFormat:e,setTBlast:r}),scoreStringSide2:Mo({sets:n,reversed:!0,matchUpFormat:e,setTBlast:r})}}function P0(t,e,r,n){let o=Mo({sets:t,matchUpFormat:r,setTBlast:n}),i=Mo({sets:t,reversed:!0,matchUpFormat:r,setTBlast:n});if(typeof o!="string")return o;if(typeof i!="string")return i;let s=e===2?i:o,a=e===2?o:i;return{sets:nm({scoreString:s,matchUpFormat:r}),scoreStringSide1:s,scoreStringSide2:a}}function SI(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,scoreString:o,setTBlast:i,preserveSideOrder:s=!1}=t;if(!o)return{outcome:{...Gu,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:B,winningSide:n};let a=o&&nm({scoreString:o,matchUpFormat:e}),c=o?.trim().startsWith("["),u=A0(n,e,a),p=Ne(e),m=p?.setFormat?.based==="A"||p?.finalSetFormat?.based==="A",d=s||c||m?U0(o,e,i):P0(a,u,e,i);return nt({outcome:{matchUpStatus:r,winningSide:u,score:d}})}function Nl({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:r,matchUp:n}){let i=(e?.[n.matchUpId]?.matchUpIds||[]).filter(a=>r.includes(a)).filter(a=>!t[a]);return{dependenciesScheduled:!i?.length,remainingDependencies:i}}function Ya({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function tw({individualParticipantProfiles:t,recoveryValue:e,participantId:r,scheduleTime:n,drawId:o}){t[r].potentialRecovery[o]||(t[r].potentialRecovery[o]=[]),t[r].potentialRecovery[o].push(e),t[r].potentialBookings[o]||(t[r].potentialBookings[o]=[]),t[r].potentialBookings[o].push({timeAfterRecovery:e,scheduleTime:n})}function Bc({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:o,matchUpDependencies:i,recoveryMinutes:s=0,scheduleTime:a,matchUp:c}){let u=zt(c?.schedule?.endTime),p=u?$r(u,dt(s)):$r(a,dt(n)+dt(s)),m=r&&(u?$r(zt(u),r):$r(a,dt(n)+dt(r))),d=i?.[c.matchUpId]?.participantIds||[],l=(c.roundPosition&&t[c.matchUpId]||[]).flat();d.forEach(f=>{Ya({individualParticipantProfiles:e,participantId:f});let I=e[f].priorMatchUpType!==c.matchUpType&&m||p;l.includes(f)?tw({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:I,participantId:f,scheduleTime:a}):(e[f].timeAfterRecovery=I,e[f].bookings.push({scheduleTime:a,timeAfterRecovery:I}))}),ua({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:o,timeAfterRecovery:p,matchUp:c})}function nE({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:r,matchUpId:n,details:o}){let i,s=o.minutesMap?.[n]?.recoveryMinutes,c=(o.minutesMap?.[n]?.averageMinutes||0)+(s||0),u=$r(r,c),p=e?.[n]?.dependentMatchUpIds||[];if(p.length){let m=p.reduce((d,l)=>{let f=t[l];if(!f)return d;let g={scheduleTime:f,matchUpId:l};return f&&!d.matchUpId||Yt(f)<Yt(d.scheduleTime)?g:d},{});m.scheduleTime&&Yt(u)>Yt(m.scheduleTime)&&(i=m)}return{scheduledDependent:i}}function ew(t){let{sides:e,matchUpType:r}=t||{};return(e||[]).map(n=>r===vt&&(n?.participant?.individualParticipants||[])||n?.participant&&[n.participant]||[]).flat()}var Hc="DO_NOT_SCHEDULE",rw={DO_NOT_SCHEDULE:Hc};function Ml({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:r=!0,personRequests:n,scheduleTime:o,scheduleDate:i,matchUp:s}){let a=ew(s).map(({person:l})=>l?.personId);if(r){let l=(s?.potentialParticipants||[]).flat().map(({person:f})=>f?.personId);a.push(...l)}let c=a.map(l=>n[l]?.map(f=>({...f,personId:l}))).filter(Boolean).flat().filter(l=>l.requestType===Hc&&zn(i,l.date)),u=[],p=s?.matchUpId,m=Ge(zt(o),Ut(i)),d=zt(Rf(m,t).toISOString());for(let l of c){let{requestId:f,startTime:g,endTime:I}=l;(o>g&&o<I||d>g&&d<I)&&(u.push({matchUpId:p,request:l,scheduleTime:o}),e[f]?(e[f].scheduleTimes.includes(o)||e[f].scheduleTimes.push(o),e[f].matchUpIds.includes(p)||e[f].matchUpIds.push(p)):e[f]={request:l,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:u}}function TI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:r,value:n}){let{matchUpType:o}=r,{individualParticipantIds:i}=Su(r),a=(t[r.matchUpId]||[]).filter(u=>!ke(u,i)).flat();[...i,...a].forEach(u=>{if(Ya({individualParticipantProfiles:e,participantId:u}),!e[u].potentialCounted[r.drawId]){let p=e[u].counters;p[o]?p[o]+=n:n>0&&(p[o]=n),p[fo]?p[fo]+=n:n>0&&(p[fo]=n),a.includes(u)&&(e[u].potentialCounted[r.drawId]=!0)}})}function nw({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,matchUpDependencies:a,clearScheduleDates:c,scheduleDate:u,minutesMap:p,matchUps:m}){let d=[];r||(o=m?.filter(g=>{let I=g.schedule||{},h=g.matchUpStatus==="BYE";return h&&d.push({tournamentId:g.tournamentId,matchUpId:g.matchUpId}),!h&&Ha({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),r=o.map(Ue));let l=Array.isArray(c)?c.includes(u):c,f=l?[]:m.filter(({matchUpId:g})=>r.includes(g));for(let g of f){TI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});let I=g.schedule?.scheduledTime;if(I){s[g.matchUpId]=I;let h=p?.[g.matchUpId]?.recoveryMinutes;Bc({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:a,averageMatchUpMinutes:n,recoveryMinutes:h,scheduleTime:I,matchUp:g})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:d,dateScheduledMatchUps:o,clearDate:l}}function hm({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:o=[],periodLength:i,scheduleDate:s,matchUps:a}){if(typeof n!="object")return{error:xt};if(!Br(a)&&!Array.isArray(r))return{error:no};i=i??zu({recoveryMinutes:t,averageMatchUpMinutes:e});let c=Object.assign({},...Object.values(n).map(d=>(d.events??[]).map(l=>{let{scheduleTiming:f}=Ra({tournamentRecord:d,event:l});return{[l.eventId]:{event:l,scheduleTiming:f}}})).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};r||(r=a?.filter(d=>{let l=d.schedule;return Ha({schedule:l})&&(!s||d.schedule.scheduledDate===s)}));let p=r?.filter(d=>(!o.length||o.includes(d.schedule.venueId))&&d.matchUpStatus!=="BYE");return{bookings:p?.map(({eventId:d,schedule:l,matchUpFormat:f})=>{let{event:g,scheduleTiming:I}=c[d],h=g?.eventType,S={...I,defaultTiming:u,matchUpFormat:f},{averageMinutes:T,recoveryMinutes:y}=xp({timingDetails:S,eventType:h}),{courtId:E,venueId:P}=l,A=zt(l.scheduledTime),U=$r(A,T);return{recoveryMinutes:y,averageMinutes:T,periodLength:i,startTime:A,courtId:E,endTime:U,venueId:P}}).filter(Boolean),relevantMatchUps:p,dateScheduledMatchUps:r}}function ow({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:r,averageMatchUpMinutes:n,clearScheduleDates:o,tournamentRecords:i,tournamentRecord:s,periodLength:a,scheduleDate:c,startTime:u,venueIds:p,matchUps:m,endTime:d}){if(s&&!i&&(i={[s.tournamentId]:s}),typeof i!="object"||!Object.keys(i).length)return{error:xt};a=a??zu({recoveryMinutes:r,averageMatchUpMinutes:n});let{courts:l,venues:f}=Ro({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),g=l?.filter(P=>!p||p.includes(P.venueId))??[];u=u??Gc({courts:g,scheduleDate:c,startTime:!0}),d=d??Gc({courts:g,scheduleDate:c,endTime:!0});let{bookings:I,dateScheduledMatchUps:h}=hm({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:i,scheduleDate:c,periodLength:a,venueIds:p,matchUps:m}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:n,clearScheduleDates:o,date:c,periodLength:a,startTime:u,bookings:I,endTime:d,courts:g},{scheduleTimes:T}=El(S),y=p?.length===1&&p[0]||f?.length===1&&f[0].venueId||void 0;return{dateScheduledMatchUpIds:h?.map(Hr("matchUpId")),dateScheduledMatchUps:h,scheduleTimes:T,venueId:y}}function iw({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:r}){let n=[],o=[],i,s,a,c;for(let u of t.filter(Boolean))c||(c=u.hash),(u.hash===c||r)&&(o=o.concat(u.matchUpIds)),u.hash!==c&&!r&&(c=u.hash,n.push({averageMinutes:a,recoveryMinutes:s,roundPeriodLength:i,matchUpIds:o}),o=u.matchUpIds),a=r?e:u.averageMinutes,s=u.recoveryMinutes,i=u.roundPeriodLength;return o.length&&n.push({matchUpIds:o,roundPeriodLength:i,recoveryMinutes:s,averageMinutes:a}),{groupedRounds:n}}function oE({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,tournamentRecords:c,periodLength:u,scheduleDate:p,useGarman:m,matchUps:d,courts:l,venues:f}){let g={},I=[],h=[],S=[];for(let T of f){let{rounds:y=[],venueId:E}=T,{scheduledRoundsDetails:P,greatestAverageMinutes:A,orderedMatchUpIds:U,minutesMap:N}=$u({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:d,rounds:y});S.push(...U??[]);let{groupedRounds:D}=iw({scheduledRoundsDetails:P,greatestAverageMinutes:A,garmanSinglePass:!0}),M,R=[];m&&({scheduleTimes:R,dateScheduledMatchUpIds:M}=ow({averageMatchUpMinutes:D[0]?.averageMinutes,scheduleDate:Ut(p),venueIds:[T.venueId],clearScheduleDates:a,tournamentRecords:c,periodLength:u,matchUps:d}));let b=nw({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:M,greatestAverageMinutes:A,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,scheduleDate:p,minutesMap:N,matchUps:d});({dateScheduledMatchUpIds:M}=b);let O=b,{byeScheduledMatchUpDetails:v,clearDate:x}=b;v?.length&&h.push(...v);let{matchUpsToSchedule:F,matchUpMap:w}=pl({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:M,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,orderedMatchUpIds:U,clearDate:x,matchUps:d}),L=l.filter(k=>k.venueId===E);g[E]={previousRemainingScheduleTimes:[],courtsCount:L.length,greatestAverageMinutes:A,scheduledRoundsDetails:P,dateScheduledMatchUps:O,matchUpsToSchedule:F,scheduleTimes:R,groupedRounds:D,venueCourts:L,minutesMap:N,matchUpMap:w},a||I.push(...M)}return{allDateScheduledByeMatchUpDetails:h,allDateScheduledMatchUpIds:I,venueScheduledRoundDetails:g,allDateMatchUpIds:S}}function sw(t,e){let r=Yt(t.scheduleTime),n=Yt(t.timeAfterRecovery),o=Yt(e.scheduleTime),i=Yt(e.timeAfterRecovery),s=r===o||n===i,a=r>o&&r<i,c=o>r&&o<n,u=n>o&&n<i,p=i>r&&i<n;return nt({hasOverlap:s||a||u||c||p,startAisContained:a,endAisContained:u,startBisContained:c,endBisContained:p},!0)}function Rl({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:r,scheduleTime:n,matchUp:o,details:i}){let s=(r?.[o.matchUpId]?.participantIds||[]).flat(),a=i?.minutesMap?.[o.matchUpId]?.averageMinutes||0,c=i?.minutesMap?.[o.matchUpId]?.recoveryMinutes||0,u=s.every(f=>{Ya({individualParticipantProfiles:t,participantId:f});let g=t[f];if(!g.timeAfterRecovery)return!0;let I=zt(o?.schedule?.endTime),h=I?$r(I,dt(c)):$r(n,dt(a)+dt(c));return!!![...Object.keys(g.potentialBookings).filter(E=>E!==o.drawId).map(E=>g.potentialBookings[E]).flat(),...g.bookings].find(E=>sw({scheduleTime:n,timeAfterRecovery:h},E).hasOverlap)}),p=e[o.matchUpId],d=(p?ya(Ge(p),Ge(n),!1):0)>=0;return{enoughTime:u&&d}}function iE({autoSchedulingAudit:t,tournamentRecords:e}){lt({topic:Mi,payload:t});let r=s=>s?Object.values(s).reduce((c,u)=>c+u.length||0,0):0,n=(t?.schedulingProfile||[]).reduce((s,a)=>s+a.venues.reduce((c,u)=>c+u.rounds.length,0),0),o={scheduledDatesCount:t.scheduledDates?.length,noTimeMatchUpIdsCount:r(t?.noTimeMatchUpIds),scheduledMatchUpIdsCount:r(t?.scheduledMatchUpIds),overLimitMatchUpIdsCount:r(t?.overLimitMatchUpIds),requestConflictsCount:r(t?.requestConflicts),profileRoundsCount:n},i={itemType:wy,itemValue:o};for(let s of Object.values(e)){let a=s.tournamentId;dp(Mi)?lt({payload:{type:wy,tournamentId:a,detail:o},topic:Mi}):_c({tournamentRecord:s,timeItem:i})}}function Cl({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUpDailyLimits:r={},matchUp:n}){let{enteredIndividualParticipantIds:o}=Su(n),{matchUpId:i,matchUpType:s}=n,a=(n.roundPosition&&t[i]||[]).flat(),c=pt(o.concat(...a));return c.forEach(p=>{Ya({individualParticipantProfiles:e,participantId:p})}),{participantIdsAtLimit:c.filter(p=>{let m=e[p];if(m)return[s,fo].find(d=>{let l=m.counters?.[d]||0,f=r[d]||0;return l&&f&&l>=f})}),relevantParticipantIds:c}}function Xu({scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:e=!1,errorOnAnachronism:r=!1,checkChronology:n=!0,matchUpDependencies:o,removePriorValues:i,tournamentRecords:s,tournamentRecord:a,matchUpDetails:c,matchUpIds:u,schedule:p}){if(!a)return{error:q};if(!c&&(!u||!Array.isArray(u)))return{error:ps};if(!c&&(!p||typeof p!="object"))return{error:LA};let m,d=[],l=0;if(n&&!o){let I=an({tournamentRecords:s,tournamentRecord:a});o=I.matchUpDependencies,m=I.matchUps}m||(m=ye({tournamentRecord:a})?.matchUps??[]);let f=m.reduce((I,h)=>{let{matchUpId:S,drawId:T,matchUpStatus:y}=h;return(e||y!=="BYE")&&(t||!ae.includes(y))&&(I[T]?I[T].push(S):I[T]=[S]),I},{}),g=c?.map(I=>I.matchUpId);for(let I of Object.keys(f)){let{drawDefinition:h}=jo({tournamentRecord:a,drawId:I});if(!h)continue;let S=f[I].filter(y=>u?.includes(y)??g?.includes(y)),T=nr({inContext:!1,drawDefinition:h}).matchUps;for(let y of S){let E=c?.find(A=>A.matchUpId===y)?.schedule||p,P=Im({schedule:E,matchUpDependencies:o,errorOnAnachronism:r,removePriorValues:i,inContextMatchUps:m,tournamentRecords:s,tournamentRecord:a,checkChronology:n,drawDefinition:h,drawMatchUps:T,matchUpId:y});if(P?.warnings?.length&&d.push(...P.warnings),P?.success&&(l+=1),P.error)return P}}return d.length?{...C,scheduled:l,warnings:d}:{...C,scheduled:l}}function Wc(t){let{scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:r=!1,errorOnAnachronism:n,matchUpContextIds:o,removePriorValues:i,tournamentRecords:s,checkChronology:a,matchUpDetails:c,schedule:u}=t;if(t.matchUpIds&&!o)return Xu(t);let p=et(t,[{[Re]:!0},{[Ks]:{matchUpContextIds:!1,matchUpDetails:!1},[kr]:B,[He]:Be}]);if(p.error)return p;if((!c||o)&&!u)return{error:st,info:"schedule is required"};let m=[],d=0,{matchUpDependencies:l}=an({tournamentRecords:s});for(let f of Object.values(s)){let{tournamentId:g}=f,I=o?.filter(S=>S.tournamentId===g).map(Ue),h=c?.filter(S=>S?.tournamentId===g);if(I?.length||h?.length){let S=Xu({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:r,matchUpDependencies:l,errorOnAnachronism:n,removePriorValues:i,tournamentRecords:s,tournamentRecord:f,checkChronology:a,matchUpIds:I,schedule:u});if(S.warnings?.length&&m.push(...S.warnings),S.scheduled&&(d+=S.scheduled),S.error)return S}}return m.length?{...C,scheduled:d,warnings:m}:{...C,scheduled:d}}function aw({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:p,personRequests:m,periodLength:d,matchUps:l,courts:f,dryRun:g}){let I={},h={},S={},T={},y={},E={},P={},A={},U={},N={};for(let R of o){let b=Ut(R?.scheduleDate),O=R?.venues||[],v={},x={},F=(V,$)=>{V.forEach(X=>{let W=x[X].counters;W[$]?W[$]+=1:W[$]=1,W[fo]?W[fo]+=1:W[fo]=1})};S[b]={},T[b]={},I[b]={},h[b]={},P[b]=[],A[b]=[],U[b]=[],N[b]=[];let w={};l.forEach(V=>{V.schedule?.scheduledDate&&zn(b,Ut(V.schedule.scheduledDate))&&ua({matchUpPotentialParticipantIds:v,matchUpNotBeforeTimes:w,matchUp:V})});let{allDateScheduledByeMatchUpDetails:L,venueScheduledRoundDetails:k,allDateMatchUpIds:G}=oE({matchUpPotentialParticipantIds:v,individualParticipantProfiles:x,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:w,matchUpScheduleTimes:E,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:d,scheduleDate:b,matchUps:l,courts:f,venues:O}),H=10,K=0,Y,j=10;for(;!Y;){for(let{venueId:V}of O){let $=0,X=k[V];for(;X.courtsCount&&X.scheduleTimes?.length&&X.matchUpsToSchedule?.length&&$<=X.courtsCount;){let{scheduleTime:W,attempts:it=0}=X.scheduleTimes.shift(),z=X.matchUpsToSchedule.find(Q=>{let{matchUpId:ut,matchUpType:ot}=Q,{participantIdsAtLimit:Dt,relevantParticipantIds:Rt}=Cl({matchUpPotentialParticipantIds:v,individualParticipantProfiles:x,matchUpDailyLimits:a,matchUp:Q});if(Dt.length)return A[b].includes(ut)||A[b].push(ut),!1;let{scheduledDependent:De}=nE({matchUpScheduleTimes:E,matchUpDependencies:s,scheduleTime:W,matchUpId:ut,details:X});if(De)return!1;let{dependenciesScheduled:qt,remainingDependencies:Se}=Nl({matchUpScheduleTimes:E,matchUpDependencies:s,allDateMatchUpIds:G,matchUp:Q});if(!qt)return T[b][ut]||(T[b][ut]=[]),T[b][ut].push({scheduleTime:W,remainingDependencies:Se}),!1;let{enoughTime:_r}=Rl({individualParticipantProfiles:x,matchUpNotBeforeTimes:w,matchUpDependencies:s,scheduleTime:W,details:X,matchUp:Q});if(!_r)return S[b][ut]||(S[b][ut]=[]),S[b][ut].push({scheduleTime:W}),!1;let dn=X.greatestAverageMinutes,{conflicts:hr}=Ml({potentials:e,averageMatchUpMinutes:dn,requestConflicts:N,personRequests:m,scheduleTime:W,scheduleDate:b,matchUp:Q});if(hr?.length)return y[b]||(y[b]=[]),y[b].push(...hr),!1;F(Rt,ot);let Xe=X.minutesMap?.[ut]?.recoveryMinutes;return Bc({matchUpPotentialParticipantIds:v,individualParticipantProfiles:x,matchUpNotBeforeTimes:w,averageMatchUpMinutes:dn,matchUpDependencies:s,recoveryMinutes:Xe,scheduleTime:W,matchUp:Q}),E[ut]=W,!0});X.matchUpsToSchedule=X.matchUpsToSchedule.filter(({matchUpId:Q})=>Q!==z?.matchUpId),z?$+=1:(h[b][V]||(h[b][V]=[]),h[b][V].push({scheduleTime:W,attempts:it+1}))}X.matchUpsToSchedule?.length&&(h[b][V]=h[b][V]?.filter(W=>{let it=W.attempts<H;return it&&X.scheduleTimes.push(W),!it})),(!X.scheduleTimes?.length||!X.matchUpsToSchedule?.length)&&(X.complete=!0)}K+=1,Y=O.every(({venueId:V})=>k[V].complete)||K===j}for(let{venueId:V}of O){let $=k[V].matchUpMap;Object.keys($).forEach(X=>{let W=u[X];W&&Object.keys($[X]).forEach(it=>{let{drawDefinition:z}=jo({tournamentRecord:W,drawId:it});z&&$[X][it].forEach(({matchUpId:ut})=>{let ot=E[ut];if(ot){let Dt=ot.split(":").map(oo).join(":"),Rt=`${Ut(b)}T${Dt}`;g?P[b].push(ut):(ii({drawDefinition:z,scheduledTime:Rt,matchUpId:ut}).success&&P[b].push(ut),V&&la({tournamentRecord:W,drawDefinition:z,matchUpId:ut,venueId:V}))}})})}),U[b]=k[V].matchUpsToSchedule.map(Ue),I[b][V]=k[V].scheduleTimes.sort((X,W)=>Yt(X.scheduleTime)-Yt(W.scheduleTime))}!g&&L?.length&&Wc({matchUpDetails:L,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let V of R.venues)for(let $ of V.rounds){let W=($.matchUps?.map(({matchUpId:z})=>z)||[]).filter(z=>P[b].includes(z));$.canScheduledMatchUpIds=W;let it=Math.round(W.length/$.matchUpsCount*1e4)/100;(it===1/0||isNaN(it))&&(it=0),$.possibleToSchedulePct=it,$.matchUpsCount===W.length&&($.possibleToSchedule=!0)}}let D=o.map(({scheduleDate:R})=>R),M={timeStamp:Date.now(),overLimitMatchUpIds:A,scheduledMatchUpIds:P,schedulingProfile:p,noTimeMatchUpIds:U,requestConflicts:N,scheduledDates:D};return iE({tournamentRecords:u,autoSchedulingAudit:M}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,scheduleTimesRemaining:I,dateSchedulingProfiles:o,skippedScheduleTimes:h,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:E,overLimitMatchUpIds:A,scheduledMatchUpIds:P,noTimeMatchUpIds:U,requestConflicts:N,scheduledDates:D}}function OM({averageMinutes:t,startTime:e,endTime:r,court:n,date:o}){if(!Array.isArray(n.dateAvailability))return{error:st,stack:"getEarliestCourtTime"};let i=Gc({scheduleDate:o,courts:[n],startTime:!0}),s=Gc({scheduleDate:o,courts:[n],endTime:!0});e=e||i,r=r||s;let a=ja({court:n,date:o}),{timeSlots:c}=_s({courtDate:a}),u=Ge(e),p=Ge(r);return{earliestCourtTime:c?.reduce((d,l)=>{let f=Ge(l.startTime),g=Ge(l.endTime);if(f>p||g<u)return d;let I=u>f?u:f;if(ya(I,g)>=t){let T=zt(I.toISOString());(!d||T<d)&&(d=T)}return d},void 0),courtStartTime:i,courtEndTime:s}}function cw({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,periodLength:p=30,schedulingProfile:m,personRequests:d,matchUps:l=[],courts:f,dryRun:g}){let I={},h={},S={},T={},y={},E={},P={},A={},U={};for(let M of o??[]){let R=Ut(M?.scheduleDate),b=M?.venues||[],O={},v={},x=(z,Q)=>{z.forEach(ut=>{let ot=v[ut].counters;ot[Q]?ot[Q]+=1:ot[Q]=1,ot[fo]?ot[fo]+=1:ot[fo]=1})};I[R]={},h[R]={},E[R]=[],P[R]=[],A[R]=[],U[R]=[];let F={};l?.forEach(z=>{z.schedule?.scheduledDate&&zn(R,Ut(z.schedule.scheduledDate))&&ua({matchUpPotentialParticipantIds:O,matchUpNotBeforeTimes:F,matchUp:z})});let{allDateScheduledByeMatchUpDetails:w,allDateScheduledMatchUpIds:L,venueScheduledRoundDetails:k,allDateMatchUpIds:G}=oE({matchUpPotentialParticipantIds:O,individualParticipantProfiles:v,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:y,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,periodLength:p,scheduleDate:R,matchUps:l,courts:f,venues:b}),H=l?.filter(({matchUpId:z})=>L.includes(z)),{bookings:K}=hm({dateScheduledMatchUps:H,tournamentRecords:u,scheduleDate:R,periodLength:p}),{virtualCourts:Y}=mm({scheduleDate:R,periodLength:p,bookings:K,courts:f}),j=Y?.reduce((z,Q)=>{let{earliestCourtTime:ut,courtEndTime:ot}=OM({date:R,averageMinutes:0,court:Q});return(!z.startTime||Ge(ut)<Ge(z.startTime))&&(z.startTime=ut),(!z.endTime||Ge(ot)>Ge(z.endTime))&&(z.endTime=ot),z},{}),V=j.startTime,$=({courtId:z,booking:Q})=>Y?.find(ut=>ut.courtId===z)?.dateAvailability[0].bookings.push(Q),X=10,W=0,it;for(;!it;){for(let{venueId:z}of b){let Q=k[z],ut=Q.matchUpsToSchedule.length,ot=[],Dt=[],Rt,De=0;for(;!Rt;){for(let qt of Q.matchUpsToSchedule){if(Dt.length===Q.courtsCount||ot.length===Q.courtsCount){Rt=!0;break}let{matchUpId:Se,matchUpType:_r}=qt,{participantIdsAtLimit:dn,relevantParticipantIds:hr}=Cl({matchUpPotentialParticipantIds:O,individualParticipantProfiles:v,matchUpDailyLimits:a,matchUp:qt});if(dn.length){P[R].includes(Se)||P[R].push(Se);continue}let{dependenciesScheduled:Xe,remainingDependencies:Zt}=Nl({matchUpScheduleTimes:y,matchUpDependencies:s,allDateMatchUpIds:G,matchUp:qt});if(!Xe){h[R][Se]||(h[R][Se]=[]),h[R][Se].push({remainingDependencies:Zt});continue}let Pt=[],ce=Y?.reduce((ue,Fe)=>{if(Dt.includes(Fe.courtId))return ue;let{earliestCourtTime:te}=OM({averageMinutes:Q.greatestAverageMinutes,startTime:V,date:R,court:Fe});if(ue.scheduleTime&&Yt(te)>=Yt(ue.scheduleTime))return ue;let{scheduledDependent:Je}=nE({matchUpScheduleTimes:y,matchUpDependencies:s,scheduleTime:te,matchUpId:Se,details:Q});if(Je)return ue;let{enoughTime:$t}=Rl({individualParticipantProfiles:v,matchUpNotBeforeTimes:F,matchUpDependencies:s,scheduleTime:te,details:Q,matchUp:qt});if(!$t)return I[R][Se]||(I[R][Se]=[]),I[R][Se].includes(te)||I[R][Se].push(te),ue;let ir=Q.minutesMap?.[Se]?.averageMinutes||Q.greatestAverageMinutes,{conflicts:fr}=Ml({potentials:e,averageMatchUpMinutes:ir,requestConflicts:U,personRequests:d,scheduleTime:te,scheduleDate:R,matchUp:qt});if(fr?.length)return Pt.push(...fr),!1;x(hr,_r);let pe=Q.minutesMap?.[Se]?.recoveryMinutes;return Bc({matchUpPotentialParticipantIds:O,individualParticipantProfiles:v,matchUpNotBeforeTimes:F,averageMatchUpMinutes:ir,matchUpDependencies:s,recoveryMinutes:pe,scheduleTime:te,matchUp:qt}),(!ue.scheduleTime||Yt(te)<Yt(ue.scheduleTime))&&(ue.averageMatchUpMinutes=ir,ue.recoveryMinutes=pe,ue.scheduleTime=te,ue.courtName=Fe.courtName,ue.courtId=Fe.courtId),ue},{});if(ce.scheduleTime){let{averageMatchUpMinutes:ue,recoveryMinutes:Fe,scheduleTime:te,courtId:Je}=ce;y[Se]=te,T[Se]=Je,ot.push(Se),Dt.push(Je);let $t=te,ir=$r($t,ue);$({courtId:Je,booking:{averageMatchUpMinutes:ue,recoveryMinutes:Fe,periodLength:p,matchUpId:Se,startTime:$t,courtId:Je,endTime:ir,venueId:z}}),Q.matchUpsToSchedule=Q.matchUpsToSchedule.filter(pe=>pe.matchUpId!==Se)}else Pt?.length&&(S[R]||(S[R]=[]),S[R].push(...Pt))}(Dt.length===Q.courtsCount||ot.length===Q.courtsCount||!Q.matchUpsToSchedule.length)&&(Rt=!0),Q.matchUpsToSchedule.length&&ot<Q.courtsCount&&(Ge(V)<Ge(j.endTime)?V=$r(V,p):(Rt=!0,Q.complete=!0)),De+=1,!Rt&&De>=ut&&(Rt=!0)}Q.matchUpsToSchedule?.length||(Q.complete=!0)}W+=1,it=b.every(({venueId:z})=>k[z].complete)||W===X}for(let{venueId:z}of b){let Q=k[z].matchUpMap;Object.keys(Q).forEach(ut=>{let ot=u[ut];ot&&Object.keys(Q[ut]).forEach(Dt=>{let{drawDefinition:Rt}=jo({tournamentRecord:ot,drawId:Dt});Rt&&Q[ut][Dt].forEach(({matchUpId:qt})=>{let Se=y[qt],_r=T[qt];if(Se){let dn=Se.split(":").map(oo).join(":"),hr=`${Ut(R)}T${dn}`;g||(ii({drawDefinition:Rt,scheduledTime:hr,matchUpId:qt}),as({courtDayDate:R,tournamentRecords:u,tournamentRecord:ot,drawDefinition:Rt,matchUpId:qt,courtId:_r})),E[R].push(qt)}})})}),A[R]=k[z].matchUpsToSchedule.map(Ue)}!g&&w?.length&&Wc({matchUpDetails:w,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let z of M.venues)for(let Q of z.rounds){let ot=(Q.matchUps??[]).map(({matchUpId:Rt})=>Rt)?.filter(Rt=>E[R].includes(Rt));Q.canScheduledMatchUpIds=ot;let Dt=Math.round((ot?.length||0)/Q.matchUpsCount*1e4)/100;(Dt===1/0||isNaN(Dt))&&(Dt=void 0),Q.possibleToSchedulePct=Dt,Q.matchUpsCount===ot?.length&&(Q.possibleToSchedule=!0)}}let N=(o??[]).map(({scheduleDate:M})=>M),D={timeStamp:Date.now(),overLimitMatchUpIds:P,scheduledMatchUpIds:E,schedulingProfile:m,noTimeMatchUpIds:A,requestConflicts:U,scheduledDates:N};return iE({tournamentRecords:u,autoSchedulingAudit:D}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:I,dependencyDeferredMatchUpIds:h,matchUpScheduleTimes:y,overLimitMatchUpIds:P,scheduledMatchUpIds:E,noTimeMatchUpIds:A,requestConflicts:U,scheduledDates:N}}function Sm(t){let{scheduleAttributes:e=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:r=ae,scheduledDates:n,venueIds:o}=t,i=Rr(t),s=ht(i)?Object.values(i).map(({tournamentId:c})=>c).filter(Boolean):[];if(!s?.length)return{error:xt};let a=0;for(let c of s){let u=i[c],p=D0({ignoreMatchUpStatuses:r,scheduleAttributes:e,tournamentRecord:u,scheduledDates:n,venueIds:o});if(p.error)return p;a+=p.clearedScheduleCount??0}return{...C,clearedScheduleCount:a}}function D0({scheduleAttributes:t=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:e=ae,tournamentRecord:r,scheduledDates:n,venueIds:o=[]}){if(typeof r!="object")return{error:q};if(!Array.isArray(e)||!Array.isArray(o))return{error:B};o.length&&t.push("venueId");let i=ye({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[],s={};i.forEach(({matchUpStatus:u,schedule:p,drawId:m,matchUpId:d})=>{(!u||!e.includes(u))&&Ha({schedule:p,scheduleAttributes:t})&&(!o?.length||o.includes(p.venueId))&&(s[m]||(s[m]=[]),s[m].push(d))});let a=r.tournamentId,c=0;for(let u in s){let{event:p,drawDefinition:m}=ze({tournamentRecord:r,drawId:u}),d=nr({drawDefinition:m,matchUpFilters:{matchUpIds:s[u]}}).matchUps??[];for(let l of d){let f=!1;l.timeItems=(l.timeItems??[]).filter(g=>{let I=g?.itemType&&![lo,Jo,Ji,bp,Zi,ts].includes(g?.itemType);return I||(f=!0),I}),f&&(gt({context:"clear schedules",eventId:p?.eventId,drawDefinition:m,tournamentId:a,matchUp:l}),c+=1)}}return{...C,clearedScheduleCount:c}}function Tm(t){let{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,periodLength:s,useGarman:a,dryRun:c,pro:u}=t,p=et(t,[{[Re]:!0},{[tr]:N=>!N||Array.isArray(N)&&N.every(Mr),[wh]:!1,[He]:Be}]);if(p.error)return p;let m=oi({tournamentRecords:i});if(m.error)return m;if(!m.schedulingProfile.length)return{...C};let{modifications:d,issues:l=[],schedulingProfile:f=[]}=m,g=Object.assign({},...Object.values(i).map(N=>fs({tournamentRecord:N}).containedStructures)),I=o.map(N=>{if(Mr(N))return Ut(N)}).filter(Boolean),h=f.map(N=>N.scheduleDate).map(N=>Mr(N)&&Ut(N)).filter(N=>N&&(!o.length||I.includes(N)));if(!h.length)return{error:lA};if(n&&!c){let N=Array.isArray(n)?n:[];Sm({tournamentRecords:i,scheduledDates:N})}let S=Ro({ignoreDisabled:!1,tournamentRecords:i}).courts,{matchUps:T}=Mn({matchUpFilters:{matchUpTypes:[Lt,vt]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:i}),{matchUpDependencies:y}=an({includeParticipantDependencies:!0,tournamentRecords:i,matchUps:T}),{matchUpDailyLimits:E}=Sl({tournamentRecords:i}),{personRequests:P}=ki({requestType:Hc,tournamentRecords:i}),A=f.filter(N=>{let D=Ut(N?.scheduleDate);return h.includes(D)}).sort((N,D)=>new Date(N.scheduleDate).getTime()-new Date(D.scheduleDate).getTime()),U={schedulingProfileModifications:d,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:l,dateSchedulingProfiles:A,containedStructureIds:g,matchUpDependencies:y,matchUpDailyLimits:E,clearScheduleDates:n,tournamentRecords:i,schedulingProfile:f,personRequests:P,periodLength:s,useGarman:a,matchUps:T,dryRun:c,courts:S};return u?cw(U):aw(U)}function ym(t){let{tournamentRecord:e,tournamentRecords:r,activeTournamentId:n,...o}=t||{};return o.tournamentId||(o.tournamentId=Nt()),o.startDate&&!sc(o.startDate)&&!Vm.test(o.startDate)?{error:Ye}:o.endDate&&!sc(o.endDate)&&!Vm.test(o.endDate)?{error:Ye}:(o.extensions&&(o.extensions=o.extensions.filter(Bn)),{...o})}function yI({addParticipants:t=!0,participantAttribute:e,tournamentRecord:r,personAttribute:n,teamNames:o,accessor:i,uuids:s}){if(!r)return{error:q};let a={},c=(r.participants??[]).filter(({participantType:f,participantRole:g})=>f===Et&&g===xe),u=0;for(let f of c){let I=i&&ys({element:f,accessor:i})?.value||n&&f.person?.[n]||e&&f[e];if(I){if(!Object.keys(a).includes(I)){a[I]={participantName:o?.[u]??I,participantId:s?.pop()??Nt(),individualParticipantIds:[],participantRole:xe,participantType:wt};let h={value:n??e,name:Hh};At({element:a[I],extension:h}),u+=1}a[I].individualParticipantIds.push(f.participantId)}}let p=Object.keys(a),m=(r.participants??[]).map(f=>{if(f.participantType!==wt||f.participantRole!==xe)return;let{extension:g}=mt({name:Hh,element:f}),I=g?.value;if(p.includes(I))return f.participantId}).filter(Boolean),d=0,l=[];return Object.keys(a).forEach(f=>{let g=a[f],{participantId:I}=g;m.includes(I)||(r.participants||(r.participants=[]),t&&r.participants.push(g),l.push(g),d++)}),t&&d?(lt({payload:{tournamentId:r.tournamentId,participants:l},topic:ci}),{...C,participantsAdded:d}):l.length?{...C,newParticipants:l}:{error:OC}}var uw=[{AA:"Annexia"},{BA:"Bacteria"},{BO:"Borduria"},{BM:"Bensalem"},{BS:"Basenji"},{BI:"Balnibarbi"},{BV:"Bartovia"},{BZ:"Berzerkistan"},{CA:"Caldonia"},{CC:"Concordia"},{CH:"Chula"},{DA:"Deltora"},{DW:"Discworld"},{EA:"Eastasia"},{EP:"Ecotopia"},{ER:"Erewhon"},{FA:"Freedonia"},{FN:"Florin"},{FG:"Fogg"},{FK:"Fourecks"},{GA:"Genovia"},{GL:"Gilead"},{GD:"Gilead"},{GL:"Gondal"},{GO:"Gondor"},{GR:"Gruzinia"},{GT:"Goritania"},{GU:"Guilder"},{HA:"Heldscalla"},{HO:"Hidalgo"},{IL:"Illyria"},{KA:"Kinakuta"},{KG:"Kangan"},{KN:"Kreplachistan"},{KS:"Kallipolis"},{LH:"Lugash"},{LI:"Listenbourg"},{LT:"Lilliput"},{LU:"Luggnagg"},{LV:"Lichtenslava"},{MR:"Moher"},{NA:"Narnia"},{NV:"Novaria"},{OA:"Oceania"},{OS:"Orsinia"},{OV:"Octavia"},{PA:"Palombia"},{PG:"Penguina"},{QA:"Qasha"},{PM:"Panem"},{SA:"Solymbria"},{SD:"Syldavia"},{SG:"San Glucose"},{SL:"San Lorenzo"},{SR:"Sontar"},{SY:"Sylvania"},{TF:"Tralfamadore"},{TH:"Themyscira"},{UA:"Utopia"},{VA:"Vespugia"},{WA:"Wakanda"},{WX:"Wessex"},{ZA:"Zamunda"},{ZK:"Zubrowka"}];var pw=["Amber","Ansul","Atlantis","Braavos","Busytown","Castle Rock","Centralia","Coober Pedy","Chefchaouen","Chronopolis","Damanhur","Diaspar","Dictionopolis","Diomira","El Dorado","Elista","Ephesus","Gotham","Hadleyburg","Hallstatt","Hierusalem","Ilium","Inverness","Kowloon","Laputa","Longyearbyen","Lys","Matmata","Maycomb","Metropolis","Miyake-jima","Monowi","Nagoro","Navarre","New New York","Nimbin","Pemberley","Pseudopolis","Rivendell","Roswell","Shangri-La","Springfield","Supilinn","Thneedville","Trantor","Wobegon","Yonwood","Xanadu","Xylar","Zion"];function sE({count:t=1,participantsCount:e=32}={}){let r=Tr(pw),n=r.slice(0,t);return{cities:tt(0,e).map(i=>i<Math.min(t,r.length)?n[i]:Un(n))}}function aE({count:t=1,participantsCount:e=32}={}){let r=Tr(uw),n=r.slice(0,t).map(i=>Object.keys(i)).flat();return{states:tt(0,e).map(i=>i<Math.min(t,r.length)?n[i]:Un(n))}}function cE({count:t=1,participantsCount:e=32}={}){let r=tt(0,t).map(()=>tt(0,5).map(()=>Io(0,9)).join(""));return{postalCodes:tt(0,e).map(o=>o<t?r[o]:Un(r))}}function Em({idPrefix:t,participantType:e,index:r,uuids:n}){let o=kt(e)?e[0]:"X";return t?`${t}-${o}-${r}`:n?.pop()||Nt()}function uE(t){let{cities:e,states:r,postalCodes:n,nationalityCode:o,participantIndex:i}=t;return{postalCode:n?.[i],state:r?.[i],city:e?.[i],countryCode:o}}var mw={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brewer","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carlin","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Ellul","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","McLuhan","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood","Zecic"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","Jacques","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Marhsall","Masanobu","Maurits","Michael","Miro","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function pE(t){let{count:e=100,sex:r}=t||{};if(!e||r&&!Dn(r))return{personData:[],error:B};let n=Math.ceil(e*1.3),{lastNames:o,firstFemale:i,firstMale:s}=mw,a=ui.map(({iso:I})=>I).filter(Boolean),c=Math.ceil(n/o.length),u=Math.ceil(n/i.length),p=Math.ceil(n/s.length),m=tt(0,c).flatMap(()=>{let I=J(o,!1,!0);return tt(0,o.length).map(()=>tn(I))}),d=tt(0,u).flatMap(()=>{let I=J(i,!1,!0);return tt(0,i.length).map(()=>tn(I))}),l=tt(0,p).flatMap(()=>{let I=J(s,!1,!0);return tt(0,s.length).map(()=>tn(I))}),f={};for(let I=0;I<n;I++){let h=m.pop(),S=r||Un([Le,lr]),T=S===Le?l.pop():d.pop(),y=Un(a);f[`${T}${h}`]={nationalityCode:y,sex:S,firstName:T,lastName:h}}return{personData:Object.values(f).slice(0,e)}}function mE(t){let e=t?.count||1,{personExtensions:r,consideredDate:n,isMock:o=!0,gendersCount:i,personData:s,category:a,sex:c}=t||{};if(isNaN(e))return{error:B};let u=i?.[Le]||Hs(c)&&e||0,p=i?.[lr]||$i(c)&&e||0;e=Math.max(e,u+p);let m=e-(u+p),d=u&&pE({count:u,sex:Le}).personData||[],l=p&&pE({count:p,sex:lr}).personData||[],f=[...d,...l,...m&&pE({count:m}).personData||[]],g=f.filter(U=>!c||u&&p||U.sex===c),I=[];if(Array.isArray(s)){let U=s.filter(N=>typeof N.firstName!="string"||typeof N.lastName!="string"||N.sex&&![Le,lr].includes(N.sex)||N.nationalityCode&&(typeof N.nationalityCode!="string"||N.nationalityCode.length>3||!ui.find(({iso:D,ioc:M})=>[D,M].includes(N.nationalityCode)))?!1:(N.nationalityCode&&I.push(N.nationalityCode),!0));if(U.length)g=U;else return{error:B}}let h=s?g:Tr(g);if(h.length<e){let{maleFirstNames:U,maleLastNames:N,femaleFirstNames:D,femaleLastNames:M,nationalityCodes:R}=f.reduce((b,O)=>{let{firstName:v,lastName:x,nationalityCode:F}=O;return O.sex===Le?(b.maleFirstNames.includes(v)||b.maleFirstNames.push(v),b.maleLastNames.includes(x)||b.maleLastNames.push(x)):(b.femaleFirstNames.includes(v)||b.femaleFirstNames.push(v),b.femaleLastNames.includes(x)||b.femaleLastNames.push(x)),b.nationalityCodes.includes(F)||b.nationalityCodes.push(F),b},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});tt(0,e-h.length).forEach(()=>{let b=c||Un([Le,lr]),O=Un(R),v=b===Le?Un(U):Un(D),x=b===Le?Un(N):Un(M),F={firstName:v,lastName:x,sex:b,nationalityCode:O};h.push(F)})}let{ageMinDate:S,ageMaxDate:T}=Ys({consideredDate:n,category:a}),y=dt(S?.slice(0,4)||0)||dt(T?.slice(0,4)||0)-3,E=dt(T?.slice(0,4)||0)||dt(S?.slice(0,4)||0)+3,P=(S||T)&&[y,E],A=h.slice(0,e).map((U,N)=>{let[D,M]=P||[],R=P&&tn(tt(D,M)),b=tn(tt(0,365)),O=R&&ZC(R,b);return Object.assign(nt({extensions:r||[{name:"regionCode",value:N+1}],birthDate:O,isMock:o}),U)});return{persons:A.length&&A||h[0],nationalityCodes:I}}var dw=["Ace Academy","Avengers","Ball Bouncers","Baseliners","Captivators","Civil Disobedients","Continentals","Court Royal","Court Sharks","Diamond Dogs","Danger Zone","Doubles Dominators","Double Faults","Tricksters","Eliminators","Court Crusaders","Fuzz Busters","Game Changers","Goal Gurus","Good Volley","Green Machine","Hawk Eyes","Inside Outers","Killer Instinct","Line Toers","Masters of Mayhem","Matter Catchers","Cheap Shot","Mean Machines","Mindspace Invaders","Net Centric","Net Positive","Smash Mullet","Over Your Head","Spin Meisters","Aggressors","Racket Machine","Slice Happy","Refs Nightmare","Sandeaters","Sun Seekers","Slicer Dicers","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Unreturnables","Upside Downers","Vertically Challenged","Visual Spectacle"];function Am({nameRoot:t="TEAM",count:e=1}={}){let n=Tr(dw).slice(0,e);return n.length<e&&tt(0,e-n.length).forEach(o=>n.push(`${t} ${o+1}`)),{names:n}}function fa(t){let{scaledParticipantsCount:e,rankingRange:r}=t,{ratingsParameters:n=je,valuesInstanceLimit:o,ratingsValues:i=[],consideredDate:s,categories:a,category:c,nationalityCodesCount:u,nationalityCodeType:p,nationalityCodes:m,participantsCount:d=32,participantType:l,teamSize:f=8,personIds:g,idPrefix:I,uuids:h,personExtensions:S,addressProps:T,gendersCount:y,matchUpType:E,personData:P,sex:A,inContext:U,withISO2:N,withIOC:D,scaleAllParticipants:M}=t,R=l===ft||E===Gi,b=l===wt||E===wt;r&&(!Array.isArray(r)||!r.every(Zt=>Jt(Zt))||r.length!==2)&&(r=void 0),e=M?d:e;let O=1e3,v=e&&e>O?e:O;r=r||[1,v],r[1]+=1;let x=d*(R&&2||b&&(f??8)||1),F=mE({count:x,personExtensions:S,consideredDate:s,gendersCount:y,personData:P,category:c,sex:A});if(F.error)return F;let{nationalityCodes:w,persons:L}=F,k={},G={},H={},K={},Y=Zt=>{Object.assign(k,Zt.doublesRankings),Object.assign(G,Zt.singlesRankings),Object.assign(K,Zt.doublesRatings),Object.assign(H,Zt.singlesRatings)};if(ht(c)){let Zt=lw({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:c});Y(Zt)}Array.isArray(a)&&a.forEach(Zt=>{let Pt=lw({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:Zt});Y(Pt)});let j=ui.filter(Zt=>p==="IOC"&&Zt.ioc||Zt.iso);function V(Zt){let Pt=Math.ceil(x/Zt);return o&&Pt>o?Math.ceil(x/o):Zt}let{postalCodesProfile:$,postalCodesCount:X,statesProfile:W,citiesProfile:it,citiesCount:z,statesCount:Q}=T||{},ut=Zt=>Object.keys(Zt).map(Pt=>tt(0,W[Pt]).map(()=>Pt)).flat(),ot=it&&ut(it)||T?.cities||sE({count:z||x,participantsCount:x}).cities,Dt=W&&ut(W)||T?.states||aE({count:Q||x,participantsCount:x}).states,Rt=$&&ut($)||T?.postalCodes||cE({count:X||x,participantsCount:x}).postalCodes,De={cities:ot,states:Dt,postalCodes:Rt},qt=V(u),Se=qt?Tr(j).slice(0,u):m&&j.filter(Zt=>m.includes(Zt.iso))||j,_r=Tr(tt(0,Math.ceil(x/(qt||1))).map(()=>Se).flat(1/0)),dn=Am({count:d}).names;return{participants:tt(0,d).map(Zt=>{let Pt=R&&2||b&&(f??8)||1,ce=tt(0,Pt).map($t=>{let ir=Zt*Pt+$t;return Xe(ir)}),ue=ce.map($t=>$t.participantId),Fe=ce.map($t=>$t.person.standardFamilyName).join("/"),te=R?ft:wt,Je={participantId:Em({participantType:te,index:Zt,idPrefix:I,uuids:h}),participantName:R?Fe:dn[Zt],participantRole:xe,individualParticipantIds:ue,participantType:te};return U&&(Je.individualParticipants=ce),R||b?[Je,...ce]:ce}).flat(),...C};function Xe(Zt){let Pt=L[Zt],{nationalityCode:ce,participantExtensions:ue,participantTimeItems:Fe,extensions:te,firstName:Je,birthDate:$t,lastName:ir,personId:fr,sex:pe}=Pt||{},me=Je||"GivenName",Sr=ir||"FamilyName",jr=`${me} ${Sr}`,Kt=_r[Zt],Te=w?.length&&ce||Kt&&(p==="IOC"?Kt.ioc||Kt.iso:Kt.iso||Kt.ioc)||ce;_r?.length&&!Te&&!ce&&console.log("%c Invalid Nationality Code",{participantIndex:Zt,country:Kt});let gr=uE({...De,participantIndex:Zt,nationalityCode:Te}),Ee=nt({participantId:Em({participantType:Et,index:Zt,idPrefix:I,uuids:h}),extensions:ue,timeItems:Fe,participantRole:xe,participantType:Et,participantName:jr,person:{personId:fr||g?.length&&g[Zt]||Nt(),birthDate:Mr($t)?$t:void 0,addresses:[gr],standardFamilyName:Sr,standardGivenName:me,nationalityCode:Te,extensions:te,sex:pe}});if(D&&Te){let ee=ui.find(({iso:Ur})=>Ur===Te);ee?.ioc&&(Ee.person.iocNationalityCode=ee.ioc),ee?.label&&(Ee.person.countryName=ee.label)}if(N&&Te){let ee=ui.find(({iso:Ur})=>Ur===Te);ee?.iso2&&(Ee.person.iso2NationalityCode=ee.iso2),ee?.label&&(Ee.person.countryName=ee.label)}let Rn=ee=>{let Ur=ee.categoryName||ee.ratingType||ee.ageCategoryCode,Cn=G[Ur]?.[Zt],An=k[Ur]?.[Zt];dE({scaleValue:Cn,eventType:qs,scaleType:Ai,participant:Ee,category:ee}),dE({scaleValue:An,eventType:Ko,scaleType:Ai,participant:Ee,category:ee});let hi=H[Ur]?.[Zt],ga=K[Ur]?.[Zt];dE({scaleValue:hi,eventType:qs,scaleType:Ui,participant:Ee,category:ee}),dE({scaleValue:ga,eventType:Ko,scaleType:Ui,participant:Ee,category:ee})};return Array.isArray(a)?a.forEach(ee=>Rn(ee)):c&&Rn(c),Ee}}function dE({scaleValue:t,participant:e,eventType:r,scaleType:n,category:o}){let i=o.categoryName||o.ratingType||o.ageCategoryCode,s=[Pi,n,r,i].join("."),a={itemValue:t,itemType:s};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(a))}function lw(t){let{category:e,scaledParticipantsCount:r,ratingsParameters:n,participantType:o,ratingsValues:i=[]}=t,s=e.rankingRange||t.rankingRange||[1,1e3],a={},c={},u={},p={},{categoryName:m,ageCategoryCode:d,ratingType:l}=e,f=e.categoryName||e.ratingType||e.ageCategoryCode;if((m||d)&&!l){let[g,I]=s||[];if(c[f]=Tr(tt(g,I)).slice(0,r||Io(20,30)),[ft,wt].includes(o)){let[h,S]=s||[];a[f]=Tr(tt(h,S)).slice(0,r||Io(20,30))}}if(l&&n[l]){let{ratingMax:g,ratingMin:I,ratingAttributes:h}=e,S={...n[l],...h||{}},{attributes:T={},decimalsCount:y,accessors:E,range:P,step:A}=S,U=v=>{let x={},F=Object.keys(v||{});for(let w of F){let L=v[w];if(typeof L=="object"&&L.generator){let{range:k}=L,[G,H]=k.slice().sort();x[w]=Io(G,H)}else x[w]=L}return x},D=P[0]>P[1]?2:.7,[M,R]=P.slice().sort(),O=tt(0,2e3).map(()=>wE(M,R,D,A,y)).filter(x=>(!g||x<=g)&&(!I||x>=I)).slice(0,r||Io(20,30)).map(x=>E?Object.assign({},...E.map(F=>({[F]:x})),U(T)):x);u[f]=[...i,...O],[ft,wt].includes(o)&&(p[f]=[...i,...O])}return{singlesRankings:c,doublesRankings:a,singlesRatings:u,doublesRatings:p}}function bl(t){let{alternatesCount:e=0,tieFormatName:r,drawSize:n}=t,o=0,i=0,s=0,a=0,c={},u={[Le]:0,[lr]:0,[qi]:0,[$o]:0,ANY:0};(ht(t.tieFormat)?t.tieFormat:io({namedFormat:r}))?.collectionDefinitions?.filter(Boolean).forEach(f=>{let{category:g,collectionId:I,matchUpType:h,matchUpCount:S,gender:T}=f;if(Dn(T)){let y=yr(T),E=S*(h===vt?2:1);y&&u[y]<E&&(u[y]=E)}else en(T)&&(u[Le]<S&&(u[Le]=S),u[lr]<S&&(u[lr]=S));if(g){let y=JSON.stringify(g);c[y]=g}if(I||(f.collectionId=Nt()),de(vt)(h)){let y=S;a+=S,o=Math.max(o,y)}if(de(Lt)(h)){let y=S;s+=S,i=Math.max(i,y)}});let m=Object.keys(c).length?Math.max(s,a*2):Math.max(i,o*2),d=o*(n+e),l=i*(n+e);return{maxDoublesDraw:d,maxSinglesDraw:l,teamSize:m,genders:u}}function fw({participantsProfile:t,eventProfiles:e,drawProfiles:r}){let{participantsCount:n,participantType:o=Et}=t||{},i=n||0,s={[lr]:0,[qi]:0,[$o]:0,[Le]:0,ANY:0},a=0,c=0,u=0,p=0,m=0,d=({alternatesCount:f=0,uniqueParticipants:g,tieFormatName:I,drawSize:h=0,eventType:S,tieFormat:T,category:y,gender:E,stage:P})=>{let A=S===Kr,U=S===_e,N=!!(g||P===ct||y||E);if(U){p=Math.max(p,h+f),T=typeof T=="object"?T:io({namedFormat:I});let{teamSize:D,maxDoublesDraw:M,maxSinglesDraw:R,genders:b}=bl({alternatesCount:f,tieFormatName:I,tieFormat:T,drawSize:h});u=Math.max(u,D),c=Math.max(c,R),N||(a=Math.max(a,M)),Object.keys(b).forEach(O=>s[O]+=b[O])}else if(A)if(N){let D=(h+f)*2;m+=D,E&&(s[E]+=D)}else h+f&&h+f>a&&(a=h+f);else if(N){let D=h+f;E&&(s[E]+=D),m+=D}else h&&h>c&&(c=h+f)};if(e?.forEach(f=>{let{tieFormatName:g,tieFormat:I,drawProfiles:h,eventType:S,category:T,gender:y}=f;if(h)for(let E of h){let{tieFormatName:P,tieFormat:A}=E;d({...E,tieFormatName:P||g,tieFormat:A||I,eventType:S,category:T,gender:y})}}),Array.isArray(r))for(let f of r)d(f);let l=Math.max(p*u,a*2,c);return a&&(o=ft),(n||i)<l&&(n=l),n&&a&&[ft,_e].includes(o)&&(c&&Math.floor(c/2)>a?n=Math.floor(c/2):(!c||a*2>=c)&&(n=Math.ceil(n/2))),n===void 0&&(n=!e?.length&&!r?.length?32:0),n<i&&(n=i),{uniqueParticipantsCount:m,participantsCount:n,largestTeamDraw:p,largestTeamSize:u,participantType:o,gendersCount:s}}function lE({participantsProfile:t,tournamentRecord:e,eventProfiles:r,drawProfiles:n,startDate:o,uuids:i}){if(t?.participantsCount===0)return{addedCount:0,...C};let{participantsCount:s,participantType:a,largestTeamDraw:c,largestTeamSize:u,gendersCount:p}=fw({participantsProfile:t,eventProfiles:r,drawProfiles:n}),m=t?.teamKey,d=fa({consideredDate:o,...t,participantsCount:s,participantType:a,gendersCount:p,uuids:i}).participants,l=0,f=En({tournamentRecord:e,participants:d});if(f.error)return f;if(l+=f.addedCount,m){let S=yI({tournamentRecord:e,...m});if(S.error)return S}let g=d.filter(({participantType:S})=>S===Et).map(St),I=t?.idPrefix?`${wt}-${t.idPrefix}`:void 0,h=tt(0,c).map(S=>{let T=g.slice(S*u,(S+1)*u),y=Em({index:S,participantType:a,idPrefix:I,uuids:i});return{participantName:`Team ${S+1}`,participantRole:xe,individualParticipantIds:T,participantType:wt,participantId:y}});return f=En({participants:h,tournamentRecord:e}),f.error?f:(l+=f.addedCount,{addedCount:l,...C})}function fE({drawProfiles:t,category:e,gender:r}){let n={},o=t?.reduce((s,a)=>{let{qualifyingPositions:c=0,participantsCount:u=0,uniqueParticipants:p,stage:m=rt,drawSize:d=0}=a||{};Object.keys(s).includes(m)||(s[m]=0);let l=(u||d)-c;return p||r||e||m===ct?(Object.keys(n).includes(m)||(n[m]=0),n[m]+=l):s[m]=Math.max(s[m],l),s},{}),i=Object.keys(n);return i.forEach(s=>o[s]+=n[s]),{stageParticipantsCount:o,uniqueParticipantsCount:n,uniqueParticipantStages:i}}function gE({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:r,targetParticipants:n}){let o=e[rt]||0,i=e[ct]||0;return{stageParticipants:{QUALIFYING:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(0,i),MAIN:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(i,i+o)}}}var b0={[Bt]:2,[oe]:1,[be]:1,[Me]:1,[Gt]:4};function EI(t){let{defaultWithScorePercent:e=2,winningSide:r}=t,{matchUpStatusProfile:n=b0,matchUpFormat:o=bn,pointsPerMinute:i=1,sideWeight:s=4}=t;if(!Nr({matchUpFormat:o}))return{error:Jl};if(typeof n!="object")return{error:B};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(s))return{error:B};let a=Object.keys(n).filter(b=>Object.keys(Qh).includes(b)&&b!==ge);if(Object.keys(a).reduce((b,O)=>b+n[O],0)>100)return{error:B,matchUpStatusProfile:n};let u=a.reduce((b,O)=>(b.pointer=b.pointer+n[O],b.valueMap.push([b.pointer,O]),b),{pointer:0,valueMap:[]}),p=Io(1,100),m=(u.valueMap.find(b=>p<=b[0])??[100,ge])[1],d={sets:[],scoreStringSide1:"",side2ScoreString:""};if(pr(m)){r=r||Io(1,2);let b={score:d,matchUpStatus:m,winningSide:r};if(!(m===Gt&&Io(1,100)>100-e))return{outcome:b}}else if([oe,be].includes(m))return{outcome:{score:d,matchUpStatus:m}};let l=Ne(o),{bestOf:f=1,exactly:g,setFormat:I,finalSetFormat:h}=l??{},S=[],T=Io(0,1),y=r?[r-1]:[...tt(0,s).map(()=>T),1-T],P=[Me,Gt,mn,ls].includes(m)&&(tn(tt(1,g||f))||1),A,U=tt(1,(g??f)+1);for(let b of U){let O=b===(g??f),{set:v,incomplete:x,winningSideNumber:F}=O0({setFormat:O&&h||I,incomplete:P===b,pointsPerMinute:i,matchUpStatus:m,weightedRange:y,setNumber:b});if(S.push(v),x){A=F;break}if(cm({matchUp:{score:{sets:S},matchUpFormat:o}}).calculatedWinningSide)break}let N=cm({matchUp:{score:{sets:S},matchUpFormat:o,winningSide:r}}),D=A?r||A:N.calculatedWinningSide,{score:M}=rE({winningSide:D,score:{sets:S},matchUpStatus:m});return{outcome:{winningSide:D,matchUpStatus:m,score:M}}}function O0({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:r,incomplete:n,setFormat:o,setNumber:i}){let s={setNumber:i},{setTo:a,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:p,timed:m,minutes:d}=o,l=Io(0,t.length-1),f=t[l],g;if(m){let I=d*e,h=Math.round(I*.2),S=I+tn([1,-1])*h,T=SC(S,2),y=[T,S-T];f&&y.reverse(),g=t[l]+1;let E=y[0]>y[1]&&1||y[1]>y[0]&&2||0;if(n){let[U,N]=y;return Object.assign(s,{side1Score:U,side2Score:N}),ae.includes(r)?{set:s,incomplete:n,winningSideNumber:g}:{set:s,incomplete:n}}E||(y[Io(0,1)]+=1),E=y[0]>y[1]?1:2,E!==g&&y.reverse();let[P,A]=y;return Object.assign(s,{side1Score:P,side2Score:A,winningSide:g}),{set:s}}else{if(n)return s.side1Score=Io(0,u),s.side2Score=Io(0,u),ae.includes(r)&&(g=t[l]+1),{set:s,incomplete:n,winningSideNumber:g};{let I=tt(1,a+1).map(A=>tt(0,a+2-A).map(()=>A)).flat(),h=I[Io(0,I.length-1)],S=a&&Xg({isSide1:!0,tiebreakAt:u,lowValue:h,setTo:a}),T=!S,y=t.length===1&&t[l]+1;if(!T){y?(S[0]>S[1]?1:2)!==y&&S.reverse():f&&S.reverse();let[A,U]=S;Object.assign(s,{side1Score:A,side2Score:U})}let E=qu({matchUpScoringFormat:{setFormat:o},setObject:s}),P;if(E.hasTiebreakCondition||T){let{NoAD:A,tiebreakTo:U}=c||p||{},N=tt(1,U+1).map(R=>tt(0,U+2-R).map(()=>R)).flat(),D=N[Io(0,N.length-1)],M=rm({isSide1:!0,tiebreakNoAd:A,tiebreakTo:U,lowValue:D});if(M)if(T){let R=M[0]>M[1]?1:2;y?R!==y&&M.reverse():f&&M.reverse(),[s.side1TiebreakScore,s.side2TiebreakScore]=M,P=M[0]>M[1]&&1||M[1]>M[0]&&2||void 0}else E.leadingSide===2?[s.side1TiebreakScore,s.side2TiebreakScore]=M:[s.side2TiebreakScore,s.side1TiebreakScore]=M}s.winningSide=E.winningSide||E.leadingSide||y||P}}return{set:s}}function Ol(t){let{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:o,completionGoal:i,drawDefinition:s,event:a}=t;if(!s)return{error:Z};let c=t.matchUpFormat||s.matchUpFormat||a?.matchUpFormat,u=s.structures.slice().sort(Ni),p=0,{matchUps:m,matchUpsMap:d}=ie({matchUpFilters:{matchUpTypes:[Wt],roundNumbers:[1]},contextFilters:{stages:[rt,ct]},inContext:!0,drawDefinition:s});if(m?.length){let h=a?.category?.ageCategoryCode||a?.category?.categoryName;if(h){let T=By({singlesOnly:!0,tournamentRecord:o,drawDefinition:s,scaleAccessor:{scaleName:h,sortOrder:"ASC",scaleType:Ai},event:a});if(T.error)return T;let{lineUps:y,participantsToAdd:E}=T;En({tournamentRecord:o,participants:E}),At({element:s,extension:{name:wo,value:y}})}else{let S=m[0]?.structureId,{positionAssignments:T}=Ct({drawDefinition:s,structureId:S});if(T?.length){let{participants:y}=Ft({participantFilters:{participantTypes:[Wt]},tournamentRecord:o}),E=P=>{let A=P.tieMatchUps.filter(de(Lt)),U=P.tieMatchUps.filter(de(vt));A.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,O=y?.find(v=>{let{participantId:x}=v;return T.find(w=>w.participantId===x)?.drawPosition===b});if(O){let v=O.individualParticipantIds?.[D];v&&Pl({teamParticipantId:O.participantId,participantId:v,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})}})}),U.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,O=y?.find(v=>{let{participantId:x}=v;return T.find(w=>w.participantId===x)?.drawPosition===b});O&&O.individualParticipantIds?.slice(D*2,D*2+2)?.forEach(x=>{Pl({teamParticipantId:O.participantId,participantId:x,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})})})})};m.forEach(E)}}}let l=typeof r=="string"&&r,f=l&&ge,g=u.length===2&&u[0].finishingPosition===Ei&&jt(u.map(({stage:h})=>h),[rt,fe]).length===2,I=u.map(({structureId:h})=>h);for(let h of I){if(p>=i)break;let S=s.structures.find(E=>E.structureId===h),T=yt({contextFilters:{matchUpTypes:[vt,Lt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}).matchUps;T.length;let y=T.filter(({winningSide:E})=>!E).sort(xi).map(Ue);for(let E of y){if(!isNaN(i)&&p>=i)break;let{matchUps:P}=yt({matchUpFilters:{matchUpTypes:[vt,Lt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}),A=P.find(N=>N.matchUpId===E),U=[oe,be].includes(A.matchUpStatus);if(A?.readyToScore&&!U){let D=_0({matchUpStatusProfile:e,tournamentRecord:o,drawDefinition:s,targetMatchUp:A,matchUpFormat:c,matchUpStatus:f,scoreString:l,winningSide:!n&&1,event:a});if(D?.error)return D;p+=1}}g&&S.finishingPosition===Ei&&t.completeRoundRobinPlayoffs&&na({structureId:S.structureId,applyPositioning:!0,drawDefinition:s})}return{...C,completedCount:p}}function vM(t){let{matchUpStatusCodes:e,policyDefinitions:r,tournamentRecord:n,drawDefinition:o,targetMatchUp:i,matchUpStatus:s,matchUpFormat:a,scoreString:c,winningSide:u,event:p}=t;if(!i||i.matchUpStatus==="BYE")return;let{matchUpId:m}=i||{},{outcome:d}=SI({matchUpFormat:a,matchUpStatus:s,scoreString:c,winningSide:u});return e&&(d.matchUpStatusCodes=e),Qu({tournamentRecord:n,policyDefinitions:r,drawDefinition:o,matchUpFormat:a,matchUpId:m,outcome:d,event:p})}function _0(t){let{matchUpStatusProfile:e={},tournamentRecord:r,policyDefinitions:n,drawDefinition:o,matchUpStatus:i,matchUpFormat:s,targetMatchUp:a,scoreString:c,winningSide:u,event:p}=t;if(c||i)return vM(t);let{matchUpId:m}=a||{},{outcome:d}=EI({matchUpStatusProfile:e,matchUpFormat:s,winningSide:u});return Qu({policyDefinitions:n,tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:m,outcome:d,event:p})}function IE({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfiles:o,isMock:i,event:s}){let a=Ht({event:s}).flightProfile,{eventName:c,eventType:u,category:p}=s,{startDate:m}=n,d=[],l=p?.categoryName||p?.ageCategoryCode||p?.ratingType,f=s.drawDefinitions?.map(({drawId:g})=>g);if(Array.isArray(a?.flights))for(let[g,I]of a.flights.entries()){let{drawId:h,stage:S,drawName:T,drawEntries:y}=I;d.push(I.drawId);let E=o[g],{seedsCount:P,generate:A=!0}=E||{};if(A){let U=y.filter(Hr(ao)).map(Hr(ao)),N=l||c;if(n&&P&&P<=U.length&&tt(1,P+1).forEach((x,F)=>{let w={scaleValue:x,scaleName:N,scaleType:Ao,eventType:u,scaleDate:m},L=U[F];xc({tournamentRecord:n,participantId:L,scaleItem:w})}),f?.includes(h))break;let D=Wa({...E,matchUpType:u,seedingScaleName:N,tournamentRecord:n,drawEntries:y,drawName:T,drawId:h,isMock:i,event:s,stage:S});if(D.error)return{error:D.error,drawIds:[]};let{drawDefinition:M}=D;if(!M)return{error:br};let R=o[g]?.drawExtensions;if(Array.isArray(R)&&R.filter(Bn).forEach(v=>At({element:M,extension:v})),D=kc({suppressNotifications:!0,tournamentRecord:n,drawDefinition:M,event:s}),D.error)return{error:D.error,drawIds:[]};if(E?.withPlayoffs){let v=M.structures?.[0].structureId,x=Kp({idPrefix:E.idPrefix,...E.withPlayoffs,tournamentRecord:n,drawDefinition:M,structureId:v,isMock:i,event:s});if(x?.error)return x}let b=E?.completionGoal;if(!(E?.automated===!1)&&(e||b)){let v=E?.matchUpFormat,x=Ol({completeAllMatchUps:!b&&e,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,completionGoal:b,drawDefinition:M,matchUpFormat:v,event:s});if(x.error)return{error:x.error,drawIds:[]};let F=x.completedCount;if(E?.drawType===Eo){let w=M.structures?.find(G=>G.stage===rt);if(!w)return{error:_t};let L=na({structureId:w.structureId,tournamentRecord:n,drawDefinition:M,event:s});if(L.error)return{error:L.error,drawIds:[]};let k=b?b-(F??0):void 0;if(L=Ol({completeAllMatchUps:!b&&e,completionGoal:b?k:void 0,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:M,matchUpFormat:v,event:s}),L.error)return{error:L.error,drawIds:[]}}}}}return{...C,drawIds:d}}function hE(t){let{participantsProfile:e={},uniqueParticipantsCount:r,ratingsParameters:n,tournamentRecord:o,eventProfile:i,eventIndex:s,event:a,uuids:c}=t,{category:u,gender:p,eventType:m}=a,d=de(Qn)(m)&&Et||de(Kr)(m)&&ft||m,l=r[rt]||0,f=r[ct]||0,g=i.drawProfiles?.length?l+f:i.participantsProfile?.participantsCount??0,I=Dn(p)?p:void 0,h=e?.idPrefix?`E-${s}-${e?.idPrefix}`:void 0,{participants:S}=fa({uuids:i.uuids||c,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:o?.startDate,rankingRange:i.rankingRange,participantType:d,participantsCount:g,ratingsParameters:n,category:u,idPrefix:h,sex:I}),y=En({tournamentRecord:o,participants:S});if(y.error)return y;let E=S?.filter(({participantType:A})=>A===d),P=S?.map(St);return{uniqueDrawParticipants:E,uniqueParticipantIds:P}}function gw({autoEntryPositions:t,tournamentRecord:e,drawParticipants:r,drawProfile:n,event:o}){let{drawType:i=yo,qualifyingPositions:s=0,stage:a=rt,drawSize:c=0,drawName:u,drawId:p}=n,m=c-s,d=r.slice(0,m).map(St);if(d.length){let g=Wn({participantIds:d,autoEntryPositions:t,entryStage:a,tournamentRecord:e,event:o});if(g.error)return g}let l=d.map(g=>({entryStatus:Gr,entryStage:a,participantId:g})),f=pm({drawName:u||i,qualifyingPositions:s,drawEntries:l,drawId:p,event:o,stage:a});return f.error?f:{...C}}function SE({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:r,tournamentRecord:n,drawProfiles:o,category:i,gender:s,event:a}){let c=0;for(let u of o){let{qualifyingPositions:p=0,uniqueParticipants:m,stage:d=rt,drawSize:l=0}=u,f=l-p,g=m||s||i||d===ct,I=g?t.slice(c,c+f):r[d||rt]||[];g&&(c+=f);let h=gw({autoEntryPositions:e,drawParticipants:I,tournamentRecord:n,drawProfile:u,event:a});if(h.error)return h}return{...C}}function TE(t){let{allUniqueParticipantIds:e,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,publish:d,isMock:l,uuids:f}=t,g=p.gender,I=p.eventName,{eventType:h=Qn,policyDefinitions:S,drawProfiles:T=[],eventExtensions:y,surfaceCategory:E,tieFormatName:P,processCodes:A,discipline:U,eventLevel:N,timeItems:D,ballType:M,category:R}=p,b=p.eventId||Nt(),O=p.tieFormat||(h===_e?io({namedFormat:P,event:{eventId:b,category:R,gender:g},hydrateCollections:s,isMock:l}):void 0),v=u.participants;for(let W of T)!g&&W.gender&&(g=W?.gender);let{stageParticipantsCount:x,uniqueParticipantsCount:F,uniqueParticipantStages:w}=fE({drawProfiles:T,category:R,gender:g}),L=de(Qn)(h)&&Et||de(Kr)(h)&&ft||h,{uniqueDrawParticipants:k=[],uniqueParticipantIds:G=[]}=w?hE({event:{eventType:h,category:R,gender:g},uniqueParticipantsCount:F,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,uuids:f}):{},{eventAttributes:H}=p;typeof H!="object"&&(H={});let K=R?.categoryName||R?.ageCategoryCode||R?.ratingType;I=I||K||"Generated Event";let Y={...H,surfaceCategory:E,processCodes:A,discipline:U,eventLevel:N,eventName:I,eventType:h,tieFormat:O,ballType:M,category:R,eventId:b,gender:g};if(y?.length&&Array.isArray(y)){let W=y.filter(Bn);W?.length&&Object.assign(Y,{extensions:W})}if(Array.isArray(D)&&D.forEach(W=>is({event:$,timeItem:W})),typeof S=="object")for(let W of Object.keys(S))ss({policyDefinitions:{[W]:S[W]},event:Y});Y.category&&(Y.category.categoryName=K);let j,V=pa({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:Y});if(V.error)return V;let $=V?.event,{stageParticipants:X}=gE({allUniqueParticipantIds:e,stageParticipantsCount:x,eventParticipantType:L,targetParticipants:v});if(T?.length){let W=SE({uniqueDrawParticipants:k,autoEntryPositions:i,stageParticipants:X,tournamentRecord:u,drawProfiles:T,category:R,gender:g,event:$});if(W.error)return W;let it=IE({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:T,isMock:l,event:$});if(it.error)return it;j=it.drawIds}else if(p?.participantsProfile?.participantsCount){let W=k.map(St);if(W.length){let it=Wn({participantIds:W,autoEntryPositions:i,tournamentRecord:u,entryStage:rt,event:$});if(it.error)return it}}return d&&da({tournamentRecord:u,event:$}),{drawIds:j,eventId:b,uniqueParticipantIds:G}}function AI({tournamentRecords:t,scheduleDate:e,venueId:r,round:n}){if(!Mr(e))return{error:Ye};let o="addSchedulingProfileRound",{extension:i}=mt({name:Na,tournamentRecords:t,discover:!0}),s=i?.value||[],a=s.find(l=>zn(e,l.scheduleDate));if(!a){let{startDate:l,endDate:f}=ol({tournamentRecords:t}),g=new Date(e);if(l&&g<new Date(l)||f&&g>new Date(f))return{error:Ye};a={scheduleDate:e,venues:[]},s.push(a)}let c=a.venues.find(l=>l.venueId===r);c||(c={venueId:r,rounds:[]},a.venues.push(c));let u=["notBeforeTime"],p=l=>Object.keys(l).filter(f=>!u.includes(f)).sort().map(f=>ht(l[f])?p(l[f]):l[f]).flat().join("|");if(c.rounds.find(l=>p(l)===p(n)))return _({result:{error:ZE},stack:o});c.rounds.push(n);let d=Lc({tournamentRecords:t,schedulingProfile:s});return d.error?d:{...C}}function Iw({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:B};let r=fs({tournamentRecord:e}).containedStructures,n=ye({tournamentRecord:e}).matchUps??[],{tournamentId:o}=e,i=[];for(let s of t){let{scheduleDate:a,venues:c=[]}=s;for(let u of c){let{rounds:p,venueId:m}=u;for(let d of p){let{drawId:l,winnerFinishingPositionRange:f,roundSegment:g}=d,h=n.filter(S=>{let T=f?.indexOf("-")>0&&f.split("-").map(E=>+E),y=S.finishingPositionRange?.winner;return S.drawId===l&&(!d.roundNumber||S.roundNumber===d.roundNumber)&&(!y||!T||jt(y,T).length===2||pt(y).length===pt(T).length&&jt(y,T).length===pt(y).length)})[0];if(h){let{eventId:S,roundNumber:T,drawName:y,structureName:E,roundName:P}=h,A=h.structureId;T&&!f&&(A=Object.keys(r).find(D=>r[D].includes(A))??A);let U={tournamentId:o,structureId:A,roundNumber:T,roundSegment:g,eventId:S,drawId:l},N=AI({tournamentRecords:{[o]:e},round:U,scheduleDate:a,venueId:m});if(N.error)return N;i.push({structureName:E,roundName:P,drawName:y,...U})}}}}return{scheduledRounds:i}}function Um(t){let e=et(t,[{drawProfile:!0,_ofType:zr}]);if(e.error)return e;let{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:o,completeAllMatchUps:i,autoEntryPositions:s,hydrateCollections:a,randomWinningSide:c,ratingsParameters:u,tournamentRecord:p,isMock:m=!0,drawProfile:d,startDate:l,drawIndex:f,uuids:g}=t,I=J(d,!1,!0),{excessParticipantAlternates:h=!0,matchUpFormat:S=bn,drawType:T=yo,tournamentAlternates:y=0,alternatesCount:E=0,qualifyingPositions:P,qualifyingProfiles:A,generate:U=!0,eventExtensions:N,drawExtensions:D,completionGoal:M,tieFormatName:R,buildTeams:b,seedsCount:O,timeItems:v,drawName:x,category:F,idPrefix:w,publish:L,gender:k,stage:G}=I,H=I.drawSize||(I.ignoreDefaults?void 0:32),K=I.eventId||Nt(),Y=d.eventType||d.matchUpType||Qn,j=Y===Kr?ft:Et,V=ht(d.tieFormat)&&d.tieFormat||Y===wt&&io({event:{eventId:K,category:F,gender:k},namedFormat:R,hydrateCollections:a,isMock:m})||void 0,$=F?.categoryName||F?.ageCategoryCode||F?.ratingType,X=d.eventName||$||`Generated ${Y}`,W=p?.participants||[],it=(A?.map(Pt=>Pt.structureProfiles||[]).flat().reduce((Pt,ce)=>{let ue=!ce.participantsCount||ce.participantsCount>ce.drawSize?ce.drawSize:ce.participantsCount||0;return Pt+ue},0)||0)*(j===ft?2:1),z=(!d.participantsCount||d.participantsCount>H?H:d.participantsCount)||0,Q={eventName:X,eventType:Y,tieFormat:V,category:F,eventId:K,gender:k};Array.isArray(v)&&v.forEach(Pt=>is({event:Q,timeItem:Pt}));let{eventAttributes:ut}=d;if(typeof ut!="object"&&(ut={}),Object.assign(Q,ut),N?.length&&Array.isArray(N)){let Pt=N.filter(Bn);Pt?.length&&Object.assign(Q,{extensions:Pt})}let ot=[];if(n?.participantsCount===0||d.uniqueParticipants||it||!p||k||F){let Pt=(z||0)+E+it,ce=Pt,ue={[Le]:0,[lr]:0},Fe,te;Y===wt&&({teamSize:Fe,genders:te}=bl({alternatesCount:E,tieFormatName:R,tieFormat:V,drawSize:H}),Object.keys(te).forEach(fr=>{let pe=yr(fr);pe&&Dn(fr)&&te[pe]&&(ue[pe]=H*te[pe])}),ce=Fe*((H||0)+it));let Je=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,ir=fa({...n,scaledParticipantsCount:d.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:ce,consideredDate:p?.startDate,sex:k||n?.sex,rankingRange:d.rankingRange,uuids:d.uuids||g,ratingsParameters:u,participantType:j,gendersCount:ue,idPrefix:Je,category:F}).participants;if(Q.category&&(Q.category.categoryName=$),p){let fr=En({participants:ir,tournamentRecord:p});if(fr.error)return fr}if(ir.forEach(({participantId:fr})=>ot.push(fr)),W=ir,Y===wt){let fr=te[Le]?ir.filter(({participantType:ee,person:Ur})=>ee===Et&&Ur?.sex===Le).map(St):[],pe=te[lr]?ir.filter(({participantType:ee,person:Ur})=>ee===Et&&$i(Ur?.sex)).map(St):[],me=ir.filter(({participantType:ee})=>ee===Et).map(St).filter(ee=>!fr.includes(ee)&&!pe.includes(ee)),Sr=[...I.teamNames??[],...Am({count:Pt}).names],jr=Fe-(te[Le]+te[lr]),Kt=0,Te=0,gr=0,Ee=tt(0,Pt).map(ee=>{let Ur=pe.slice(Kt,Kt+te[lr]),Cn=fr.slice(Te,Te+te[Le]),An=me.slice(gr,gr+jr);Kt+=te[lr],Te+=te[Le],gr+=jr;let hi=b!==!1?[...Ur,...Cn,...An]:[];return{participantName:Sr[ee]||`Team ${ee+1}`,participantOtherName:`TM${ee+1}`,participantRole:xe,individualParticipantIds:hi,participantType:wt,participantId:Nt()}}),Rn=En({participants:Ee,tournamentRecord:p});if(!Rn.success)return Rn;W=Ee}}let Dt=Pt=>{let{participantType:ce}=Pt;return de(Qn)(Y)&&ce===Et||de(Kr)(Y)&&ce===ft?!0:Y===wt&&ce===wt},Rt=Pt=>!d.gender||Pt.person?.sex===d.gender?!0:Pt.individualParticipantIds?.some(ce=>{let ue=W.find(Fe=>Fe.participantId===ce);return ue&&Rt(ue)}),De=W.filter(Dt).filter(Rt).filter(({participantId:Pt})=>!r.includes(Pt)),qt=De.slice(0,z).map(Pt=>Pt.participantId);if(m&&qt?.length){let Pt=Wn({autoEntryPositions:s,entryStage:G,tournamentRecord:p,participantIds:qt,event:Q});if(Pt.error)return Pt}let Se=it?De.slice(z,z+it).map(Pt=>Pt.participantId):0;if(m&&Se?.length){let Pt=0,ce=1,ue=(te,Je)=>te.stageSequence-Je.stageSequence,Fe=(te,Je)=>te.roundTarget-Je.roundTarget;for(let te of A.sort(Fe)){ce=te.roundTarget||ce;let Je=1,$t;for(let ir of te.structureProfiles.sort(ue)){let pe=(ir.drawSize||Rm(ir.participantsCount))-($t||0),me=Se.slice(Pt,Pt+pe),Sr=Wn({entryStage:ct,entryStageSequence:Je,autoEntryPositions:s,tournamentRecord:p,participantIds:me,roundTarget:ce,event:Q});if(Sr.error)return Sr;$t=ir.qualifyingPositions,Pt+=pe,Je+=1}ce+=1}}let _r=h&&p?.participants?.filter(({participantId:Pt})=>!qt.includes(Pt)).filter(Dt).filter(Rt).slice(0,E||H-z||y).map(Pt=>Pt.participantId);if(m&&_r?.length){let Pt=Wn({participantIds:_r,autoEntryPositions:!1,entryStatus:on,tournamentRecord:p,event:Q});if(Pt.error)return Pt.error}let dn=$||X;p&&O&&O<=qt.length&&tt(1,O+1).forEach((ce,ue)=>{let Fe={scaleName:dn,scaleDate:l,scaleType:lg,scaleValue:ce,eventType:Y},te=qt[ue];xc({tournamentRecord:p,participantId:te,scaleItem:Fe})});let hr=Wa({...J(d,!1,!0),tournamentRecord:p,seedingScaleName:dn,matchUpFormat:S,eventId:K,isMock:m,event:Q});if(hr.error)return hr;if(!hr.drawDefinition)return{error:br};let{drawDefinition:Xe}=hr,Zt=Xe.drawId;if(Array.isArray(D)&&D.filter(Bn).forEach(Pt=>At({element:Xe,extension:Pt})),U){if(kc({drawDefinition:Xe,event:Q,suppressNotifications:!0}),d.withPlayoffs){let ce=Xe.structures?.[0].structureId,ue=Kp({...d.withPlayoffs,tournamentRecord:p,drawDefinition:Xe,structureId:ce,idPrefix:w,isMock:m,event:Q});if(ue?.error)return ue}let Pt=d.automated===!1;if(m&&!Pt){let ce=ue=>{let Fe=Ol({completeAllMatchUps:ue.completeAllMatchUps,completionGoal:ue.completionGoal,matchUpStatusProfile:o,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:Q});if(Fe.error)return Fe;let te=Fe.completedCount;if(T===Eo){let Je=Xe.structures?.find(fr=>fr.stage===rt);if(!Je)return{error:_t};na({structureId:Je.structureId,tournamentRecord:p,drawDefinition:Xe,event:Q});let $t=M?M-(te??0):void 0,ir=Ol({completionGoal:M?$t:void 0,matchUpStatusProfile:o,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:Q});if(ir.error)return ir}};if(M&&ce({completionGoal:M}),d.outcomes){let{matchUps:ue}=nr({inContext:!0,drawDefinition:Xe,event:Q});for(let Fe of d.outcomes){let{matchUpStatus:te=ge,matchUpStatusCodes:Je,stageSequence:$t=1,matchUpIndex:ir=0,structureOrder:fr,matchUpFormat:pe,drawPositions:me,roundPosition:Sr,stage:jr=rt,roundNumber:Kt,winningSide:Te,scoreString:gr}=Fe,Ee=ue?.reduce((An,hi)=>{let{structureId:ga,matchUpId:ep}=hi;return An[ga]?An[ga].push(ep):An[ga]=[ep],An},{})??[],Rn=Object.assign({},...Object.keys(Ee).map((An,hi)=>({[An]:hi+1}))),Ur=ue?.filter(An=>(!jr||An.stage===jr)&&(!$t||An.stageSequence===$t)&&(!Kt||An.roundNumber===Kt)&&(!Sr||An.roundPosition===Sr)&&(!fr||Rn[An.structureId]===fr)&&(!me||jt(me,An.drawPositions).length===2))?.[ir],Cn=vM({matchUpStatusCodes:Je,tournamentRecord:p,drawDefinition:Xe,targetMatchUp:Ur,matchUpFormat:pe,matchUpStatus:te,scoreString:gr,winningSide:Te});if(Cn?.error)return Cn}}i&&ce({completeAllMatchUps:i})}L&&da({tournamentRecord:p,event:Q})}else{let Pt=pm({drawEntries:Xe.entries,drawName:x||T,qualifyingPositions:P,drawId:Zt,event:Q,stage:G});if(Pt.error)return Pt}return{...C,event:nt(Q),uniqueParticipantIds:ot,targetParticipants:W,drawDefinition:Xe,eventId:K,drawId:Zt}}var _M=()=>({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}),hw=_M;function yE(t){return parseInt(t)}function xM({startTime:t="",endTime:e=""}={}){if(!t||!e||!Ws.test(t)||!Ws.test(e))return!1;let[r,n]=t.split(":").map(yE),[o,i]=e.split(":").map(yE);return o<r?!1:!(r===o&&i<n)}function Sw(t,e){let[r,n]=t.startTime.split(":").map(yE),[o,i]=e.startTime.split(":").map(yE);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function EE({dateAvailability:t}){if(!t)return{error:fA};if(!Array.isArray(t))return{error:rf};let e="Dates must be formated => YYYY-MM-DD",r="Times must be 24 hour => 00:00";for(let n of t){if(typeof n!="object")return{error:rf};let{date:o,startTime:i,endTime:s,bookings:a=[]}=n;if(!i||!s)return{error:rf};if(o&&!Oo.test(o))return{error:Ye,dateAvailability:{date:o},info:e};if(!Ws.test(i))return{error:Co,dateAvailability:{startTime:i},info:r};if(!Ws.test(s))return{error:Co,dateAvailability:{endTime:s},info:r};if(i===s)return{error:Co,dateAvailability:{startTime:i,endTime:s},info:"startTime and endTime are equivalent"};if(!xM({startTime:i,endTime:s}))return{error:Co,dateAvailability:{startTime:i,endTime:s},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:vm};for(let c of a){if(typeof c!="object")return{error:vm};let{startTime:u,endTime:p}=c;if(!Ws.test(u))return{error:Co,booking:{startTime:u},info:r};if(!Ws.test(p))return{error:Co,booking:{endTime:p},info:r};if(u===p)return{error:Co,dateAvailability:{startTime:u,endTime:p},info:"startTime and endTime are equivalent"};if(!xM({startTime:u,endTime:p}))return{error:Co,dateAvailability:{startTime:u,endTime:p},info:"endTime must be after startTime"}}}}return{valid:!0}}function vl({tournamentRecord:t,disableNotice:e,venueId:r,courtId:n,court:o}){let{venue:i}=ti({tournamentRecord:t,venueId:r});if(!i)return{error:ji};i.courts||(i.courts=[]);let s={..._M(),venueId:r,courtId:n};if(s.courtId||(s.courtId=Nt()),i.courts.some(c=>c.courtId===s.courtId))return{error:bA};{let c=(o?.dateAvailability||[]).map(m=>({...m,date:Ut(m.date),startTime:zt(m.startTime),endTime:zt(m.endTime),bookings:m.bookings?.map(({startTime:d,endTime:l,bookingType:f})=>({startTime:zt(d),endTime:zt(l),bookingType:f}))})),u=Object.keys(s);for(let m of u)if(o?.[m])if(m==="dateAvailability"){let d=EE({dateAvailability:c});if(!d.valid&&d.error)return d;s.dateAvailability=c}else s[m]=o[m];let p=s;return i.courts.push(p),e||lt({payload:{venue:i,tournamentId:t.tournamentId},topic:Ri,key:i.venueId}),{...C,court:J(s),venueId:r}}}function UI(t){let{tournamentRecord:e,venueId:r}=t;if(typeof r!="string"||!r)return{error:ai};let n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o=[],i;for(let s of Object.values(n)){let{venue:a}=ti({tournamentRecord:s,venueId:r});if(a){let c=x0({...t,tournamentRecord:s});for(let u of c?.courts??[])o.push(u?.courtId);if(c.error)return c;i=!0}}return i?{...C,courtIds:o}:{error:ji}}function x0({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:r,tournamentRecord:n,courtNames:o=[],courtTimings:i,courtsCount:s,startTime:a,courtIds:c,endTime:u,idPrefix:p,venueId:m,dates:d}){if(!m)return{error:ai};let l=ti({tournamentRecord:n,venueId:m});if(l.error)return l;let{venue:f}=l;if(!Jt(s)||!o)return{error:CA};s=s??o.length;let h=tt(0,s).map(S=>{let T=i?.[S],y=T?d.map(E=>({date:Kn(E),startTime:a,endTime:u,...T})):e;return T&&a&&u&&y.push({startTime:a,endTime:u}),{courtName:o[S]||r&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:y}}).map((S,T)=>{let y=c?.pop()||p&&`${p}-${T+1}`;return vl({disableNotice:!0,tournamentRecord:n,courtId:y,venueId:m,court:S})}).map(S=>S.court).filter(Boolean);return h.length!==s?_({info:"not all courts could be generated",result:{error:B}}):(f&<({payload:{venue:f,tournamentId:n.tournamentId},topic:Ri,key:f.venueId}),{...C,courts:J(h)})}function _l({tournamentRecord:t,ignoreExistingVenues:e,venueProfiles:r,uuids:n}){let{startDate:o,endDate:i}=t,s=[];for(let[a,c]of r.entries()){let{venueAbbreviation:u,venueId:p=n?.pop()??Nt(),dateAvailability:m,startTime:d="07:00",endTime:l="19:00",courtTimings:f,courtsCount:g,courtNames:I,venueName:h,idPrefix:S,courtIds:T}=c,y={venueName:h||`Venue ${a+1}`,venueAbbreviation:u,venueId:p},E=Ec({tournamentRecord:t,venue:y});if(E.error){if(e)continue;return E}s.push(p);let P=js(o,i),A=!Array.isArray(m)&&[{startTime:d,endTime:l}].concat(P.map(U=>({date:Kn(U),startTime:d,endTime:l})));if(g||I){let U=UI({dateAvailability:m||A,tournamentRecord:t,courtTimings:f,courtsCount:g,courtNames:I,startTime:d,idPrefix:S,courtIds:T,endTime:l,venueId:p,dates:P});if(U.error)return U}}return s}function Tw(t){let{tournamentRecord:e,leagueProfiles:r,eventIds:n,venueIds:o,drawIds:i,allUniqueParticipantIds:s,uuids:a}=t,c=0;for(let p of r){let m=[],{tieFormatName:d=Hm,teamProfiles:l=[],teamsCount:f=0,category:g,idPrefix:I,gender:h}=p,S=p.leagueName??p.eventName??`League ${c+1}`,T=p.leagueId??p.eventId??a?.pop()??Nt();n.push(T);let y=ht(p.tieFormat)&&p.tieFormat||io({event:{eventId:T,category:g,gender:h},namedFormat:d,isMock:t.isMock})||void 0;if(!y)return{error:ks};let E=Math.max(f,l.length),P=tt(0,E),{genders:A,teamSize:U}=bl({tieFormat:y,drawSize:E}),N={[lr]:0,[qi]:0,[$o]:0,[Le]:0,ANY:0};Object.keys(A).forEach(R=>N[R]+=A[R]);for(let R of P){let b=l?.[R]?.teamName??`Team ${R+1}`,O=l?.[R]?.teamId||a?.pop()||Nt(),v=p.startDate??t.startDate,x=fa({...p?.participantsProfile,participantsCount:U,consideredDate:v,gendersCount:N,category:g,gender:h,uuids:a}).participants,F=x.map(K=>K.participantId),w=wt,L=O??Em({participantType:w,idPrefix:I,index:R,uuids:a});m.push({participantId:L,entryStatus:Gr,entryStage:rt});let k=l?.[R]?.venueIds??[],G={participantId:L,participantRole:xe,participantName:b,individualParticipantIds:F,participantType:w,homeVenueIds:k};k.forEach(K=>!o.includes(K)&&o.push(K)),s.push(...F,L);let H=En({participants:[G,...x],tournamentRecord:e});if(H.error)return H}let M={eventName:S,entries:m,eventType:wt,tieFormat:y,category:g,eventId:T,gender:h};if(e.events||(e.events=[]),e.events.push(M),m.length){let R=(Jt(p.roundsCount)&&p.roundsCount)??p.roundsCount===ub?(E-1)*2:E-1,b=Wa({automated:p.automated,tournamentRecord:e,drawType:Fr,roundsCount:R,drawSize:E,event:M});if(b.error)return b;let{drawDefinition:O}=b;if(O){let v=O?.drawId;kc({drawDefinition:O,event:M,suppressNotifications:!0}),i.push(v)}}c++}let u=o.map(p=>({venueId:p}));_l({tournamentRecord:e,ignoreExistingVenues:!0,venueProfiles:u,uuids:a})}var w0=["Generated Tournament","CourtHive Challenge","Replication Crisis","Open Competition","Factory Follies","Mock Tournament","Atomic Culture","Racket Rally","Stats Fail"];function wM(t){let{startDate:e,endDate:r}=t??{},{tournamentName:n=tn(w0),ratingsParameters:o=je,tournamentExtensions:i,policyDefinitions:s,schedulingProfile:a,venueProfiles:c,uuids:u}=t??{},p=t?.isMock===!1?void 0:!0;if(e&&!Mr(e)||r&&!Mr(r))return{error:Ye};if(t.leagueProfiles&&!Array.isArray(t.leagueProfiles)||t.eventProfiles&&!Array.isArray(t.eventProfiles)||t.drawProfiles&&!Array.isArray(t.drawProfiles))return{error:B};if(!e){let S=new Date;e=Kn(r??S),r=Kn(S.setDate(S.getDate()+7))}if(!r){let S=new Date(e);r=Kn(S.setDate(S.getDate()+7))}let m=ym({...t.tournamentAttributes??{},tournamentName:n,startDate:e,endDate:r,isMock:p}),d=c?.length?_l({tournamentRecord:m,venueProfiles:c,uuids:u}):[];if(i?.length&&Array.isArray(i)){let S=i.filter(T=>Bn({extension:T}));S?.length&&Object.assign(m,{extensions:S,isMock:p})}if(typeof s=="object")for(let S of Object.keys(s))ss({policyDefinitions:{[S]:s[S]},tournamentRecord:m});if(!t?.leagueProfiles?.length||t.eventProfiles?.length||t.drawProfiles?.length||t.participantsProfile){let S=lE({tournamentRecord:m,...t});if(!S.success)return S}let l=[],f=[],g=[];if(t.leagueProfiles){let S=Tw({allUniqueParticipantIds:l,tournamentRecord:m,...t,eventIds:f,venueIds:d,drawIds:g});if(S?.error)return S}if(t.drawProfiles){let S=L0({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}if(t.eventProfiles){let S=F0({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}let{scheduledRounds:I=void 0,schedulerResult:h={}}=a?k0({...t,tournamentRecord:m}):{};return Tf(),nt({...C,tournamentRecord:m,scheduledRounds:I,schedulerResult:h,eventIds:f,venueIds:d,drawIds:g})}function L0(t){let{tournamentRecord:e,drawProfiles:r,allUniqueParticipantIds:n,eventIds:o,drawIds:i}=t,s=0;for(let a of r){let c=Um({allUniqueParticipantIds:n,tournamentRecord:e,drawProfile:a,drawIndex:s,...t});if(c.error)return c;let{drawId:u,eventId:p,event:m,uniqueParticipantIds:d}=c;if(a?.addEvent!==!1){if(c=pa({suppressNotifications:!1,internalUse:!0,tournamentRecord:e,event:m}),c.error)return c;u&&i.push(u),o.push(p)}d?.length&&n.push(...d),s+=1}}function F0(t){let{eventProfiles:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o}=t,i=0;for(let s of e){let a=TE({...t,eventIndex:i,eventProfile:s});if(a.error)return a;let{eventId:c,drawIds:u,uniqueParticipantIds:p}=a;u&&o.push(...u),n.push(c),p?.length&&r.push(...p),i+=1}}function k0(t){let{schedulingProfile:e,tournamentRecord:r,autoSchedule:n,periodLength:o,scheduleCompletedMatchUps:i}=t,s=Iw({schedulingProfile:e,tournamentRecord:r});if(s.error)return s;let a=s.scheduledRounds;if(n){let{tournamentId:c}=r,u={[c]:r};return{schedulerResult:Tm({scheduleCompletedMatchUps:i,tournamentRecords:u,periodLength:o}),scheduledRounds:a}}return{scheduledRounds:a}}var GM={};Xt(GM,{anonymizeTournamentRecord:()=>FM,modifyTournamentRecord:()=>kM});function FM({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:r,tournamentName:n,personIds:o=[],tournamentId:i}){if(!r)return{error:q};let s=Array.isArray(t)?vU.concat(...t):vU,a=L=>Array.isArray(t)?L?.extensions?.filter(k=>s.includes(k.name)):L?.extensions,c={};r.extensions=a(r);let u=i||Nt();c[r.tournamentId]=u,r.tournamentId=u,r.createdAt=new Date().toISOString(),r.tournamentName=n||`Anonymized: ${Kn(new Date)}`,r.isMock=!0,delete r.parentOrganisation;for(let L of r.participants||[]){L.extensions=a(L),L.onlineResources=[];let k=Nt();c[L.participantId]=k,L.participantId=k}for(let L of r.participants||[])Array.isArray(L.individualParticipantIds)&&(L.individualParticipantIds=L.individualParticipantIds.map(k=>c[k]));let p=0;for(let L of r.venues||[]){L.venueAbbreviation=`V${p}`,L.extensions=a(L),L.venueName=`Venue #${p}`,L.onlineResources=[],L.addresses=[];let k=Nt();c[L.venueId]=k,L.isMock=!0,p+=1;let G=0;for(let H of L.courts||[])H.courtName=`V${p}C${G}`,H.extensions=a(H),H.onlineResources=[],H.isMock=!0,G+=1}let m=1;for(let L of r.events||[]){L.extensions=a(L),L.onlineResources=[],L.isMock=!0;let k=Nt();c[L.eventId]=k,L.eventId=k;let G=L.category?.categoryName||L.category?.ageCategoryCode||L.category?.ratingType||L.gender;if(L.eventName=`Event ${m} ${G}`,Array.isArray(L.entries))for(let K of L.entries)K.participantId=c[K.participantId];for(let K of L.drawDefinitions||[]){K.extensions=a(K);let Y=Nt();if(c[K.drawId]=Y,K.drawId=Y,K.isMock=!0,Array.isArray(K.entries))for(let V of K.entries)V.participantId=c[V.participantId];let j=V=>{V.extensions=a(V);let $=Nt();c[V.structureId]=$,V.structureId=$;for(let X of V.positionAssignments||[])X.participantId&&(X.participantId=c[X.participantId]);for(let X of V.seedAssignments||[])X.participantId&&(X.participantId=c[X.participantId]);for(let X of V.matchUps||[]){X.isMock=!0;for(let W of X.sides||[])W.lineUp&&(W.lineUp=W.lineUp.map(({participantId:it,collectionAssignments:z})=>({participantId:c[it],collectionAssignments:z})))}};for(let V of K.structures||[])if(j(V),Array.isArray(V.structures))for(let $ of V.structures)j($);for(let V of K.links||[])V.source.structureId=c[V.source.structureId],V.target.structureId=c[V.target.structureId]}let{extension:H}=mt({name:pn,element:L});Array.isArray(H?.value?.flights)&&H?.value.flights?.forEach(K=>{if(K.drawId=c[K.drawId],Array.isArray(K.drawEntries))for(let Y of K.drawEntries)Y.participantId=c[Y.participantId]}),m+=1}let d=r.startDate||Kn(new Date),l=(r.participants||[]).filter(({participantType:L})=>L===Et),f=l.reduce((L,k)=>{let G=k.person?.sex,H=yr(G);return H&&Dn(G)?L[H]+=1:L[$o]+=1,L},{[Le]:0,[lr]:0,[$o]:0}),g=Object.assign({},...Object.keys(f).map(L=>({[L]:mE({category:{ageCategoryCode:"O18"},count:f[L],addressProps:{citiesCount:10},personExtensions:[],consideredDate:d,sex:L})?.persons||[]}))),I={[Le]:0,[lr]:0,[$o]:0},h=l.length,S=l.reduce((L,k)=>{let G=k.person?.addresses?.[0]||{},{city:H,state:K,postalCode:Y}=G;return L.cities.includes(H)||L.cities.push(H),L.states.includes(K)||L.states.push(K),L.postalCodes.includes(Y)||L.postalCodes.push(Y),L},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,y=S.cities.length,E=S.states.length,{cities:P}=sE({count:y||h,participantsCount:h}),{states:A}=aE({count:E||h,participantsCount:h}),{postalCodes:U}=cE({count:T||h,participantsCount:h}),N={cities:P,states:A,postalCodes:U};l.forEach((L,k)=>{let G=L?.person,H=G?.sex||$o,K=Ut(G?.birthDate)?.split("-")[0],Y=I[H],j=g[H][Y];if(I[H]+=1,K){let[,V,$]=j?.birthDate?.split("-")||[],X=[K,V,$].join("-");j.birthDate=X}if(G?.addresses){let V=uE({...N,participantIndex:k,nationalityCode:j.nationalityCode});j.addresses=[V]}j.personId=o?.[k]||Nt(),e?(j.standardFamilyName=j.lastName,j.standardGivenName=j.firstName,L.participantName=`${j.standardGivenName} ${j.standardFamilyName}`):(j.standardFamilyName=G?.standardFamilyName,j.standardGivenName=G?.standardGivenName),delete j.firstName,delete j.lastName,j.extensions=a(G),L.person=j,c[G?.personId]=j.personId}),(r.participants||[]).filter(({participantType:L})=>L===ft).forEach(L=>{let{individualParticipantIds:k}=L;L.participantName=G0({individualParticipantIds:k,individualParticipants:l})});let M=(r.participants||[]).filter(({participantType:L})=>L===wt),R=M.length,b=Am({count:R}).names;M.forEach((L,k)=>{L.participantName=b[k]});let O=(r.participants||[]).filter(({participantType:L})=>L===Qr),v=O.length,x=Am({count:v,nameRoot:"Group"}).names;O.forEach((L,k)=>{L.participantName=x[k]});let{extension:F}=mt({element:r,name:Na});Array.isArray(F?.value)&&F?.value.forEach(L=>{L.tournamentId=c[L.tournamentId],L.structureId=c[L.structureId],L.eventId=c[L.eventId],L.drawId=c[L.drawId]});let{extension:w}=mt({element:r,name:Da});return Array.isArray(w?.value)&&w?.value.forEach(L=>{L.personId=c[L.personId]}),{...C}}function G0({individualParticipantIds:t,individualParticipants:e}){let r=e.filter(({participantId:n})=>t.includes(n)).map(({person:n})=>n?.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(r+="/Unknown"),r}function V0({event:t,eventProfile:e,tournamentRecord:r,allUniqueParticipantIds:n,drawIds:o}){let{gender:i,category:s,eventType:a}=t,{drawProfiles:c,publish:u}=e,p=de(Qn)(a)&&Et||de(Kr)(a)&&ft||a;if(c){let{stageParticipantsCount:m,uniqueParticipantsCount:d,uniqueParticipantStages:l}=fE({drawProfiles:c,category:s,gender:i}),{uniqueDrawParticipants:f=[],uniqueParticipantIds:g=[]}=l?hE({event:{eventType:a,category:s,gender:i},uniqueParticipantsCount:d,participantsProfile:e.participantsProfile,ratingsParameters:e.ratingsParameters,tournamentRecord:r,eventProfile:e,uuids:e.uuids}):{};n.push(...g);let{stageParticipants:I}=gE({targetParticipants:r.participants||[],allUniqueParticipantIds:n,stageParticipantsCount:m,eventParticipantType:p}),h=SE({uniqueDrawParticipants:f,autoEntryPositions:e.autoEntryPositions,stageParticipants:I,tournamentRecord:r,drawProfiles:c,category:s,gender:i,event:t});if(h.error||(h=IE({matchUpStatusProfile:e.matchUpStatusProfile,completeAllMatchUps:e.completeAllMatchUps,randomWinningSide:e.randomWinningSide,tournamentRecord:r,drawProfiles:c,isMock:e.isMock,event:t}),h.error))return h;o.push(...h.drawIds)}return u&&da({tournamentRecord:r,event:t}),C}function yw(t,e){return t?.find((r,n)=>e.eventIndex!==void 0&&n===e.eventIndex||e.eventName&&r.eventName===e.eventName||e.eventId&&r.eventId===e.eventId)}function B0({eventProfiles:t,tournamentRecord:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o,params:i}){let s=e.events?.length||0;for(let a of t){let c=yw(e.events,a);if(c){let u=V0({event:c,eventProfile:{...a,...i},tournamentRecord:e,allUniqueParticipantIds:r,drawIds:o});if(u.error)return u}else{let u=TE({startDate:e.startDate,allUniqueParticipantIds:r,matchUpStatusProfile:i.matchUpStatusProfile,participantsProfile:i.participantsProfile,completeAllMatchUps:i.completeAllMatchUps,autoEntryPositions:i.autoEntryPositions,randomWinningSide:i.randomWinningSide,ratingsParameters:a.ratingsParameters,tournamentRecord:e,eventProfile:a,eventIndex:s,uuids:i.uuids});if(u.error)return u;let{eventId:p,drawIds:m,uniqueParticipantIds:d}=u;m&&o.push(...m),n.push(p),d?.length&&r.push(...d),s+=1}}return C}function H0({drawProfiles:t,tournamentRecord:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o,params:i}){let s=(e.events||[]).flatMap(a=>a.drawDefinitions?.map(()=>1)||[]).reduce((a,c)=>a+c,0);for(let a of t){let c=Um({startDate:e.startDate,allUniqueParticipantIds:r,matchUpStatusProfile:i.matchUpStatusProfile,participantsProfile:i.participantsProfile,completeAllMatchUps:i.completeAllMatchUps,autoEntryPositions:i.autoEntryPositions,hydrateCollections:i.hydrateCollections,randomWinningSide:i.randomWinningSide,ratingsParameters:i.ratingsParameters,tournamentRecord:e,drawProfile:a,drawIndex:s,uuids:i.uuids});if(c.error)return c;let{drawId:u,eventId:p,event:m,uniqueParticipantIds:d}=c;if(c=pa({tournamentRecord:e,event:m,internalUse:!0}),c.error)return c;u&&o.push(u),n.push(p),d?.length&&r.push(...d),s+=1}return C}function W0({schedulingProfile:t,autoSchedule:e,periodLength:r,tournamentRecord:n}){let o,i={};if(t?.length){let s={[n.tournamentId]:n},a=Lc({tournamentRecords:s,schedulingProfile:t});if(a.error)return a;if(e){let{tournamentId:c}=n,u={[c]:n};i=Tm({tournamentRecords:u,periodLength:r})}}return{scheduledRounds:o,schedulerResult:i}}function kM(t){let{participantsProfile:e={},schedulingProfile:r,tournamentRecord:n,autoSchedule:o,eventProfiles:i,periodLength:s,venueProfiles:a,drawProfiles:c,uuids:u}=t;if(!n)return{error:q};let p=[],m=[],d=[];i?.forEach(y=>{let E=yw(n.events,y);E?.gender&&(y.gender=E.gender)});let l=n.participants?.length||void 0;l&&e?.idPrefix&&(e.idPrefix=`${e.idPrefix}-${l}`);let f=lE({startDate:n.startDate,participantsProfile:e,tournamentRecord:n,eventProfiles:i,drawProfiles:c,uuids:u});if(!f.success)return f;if(i){let y=B0({eventProfiles:i,tournamentRecord:n,allUniqueParticipantIds:p,eventIds:m,drawIds:d,params:t});if(y.error)return y}if(c){let y=H0({drawProfiles:c,tournamentRecord:n,allUniqueParticipantIds:p,eventIds:m,drawIds:d,params:t});if(y.error)return y}let g=a?.length?_l({tournamentRecord:n,venueProfiles:a}):[],I=W0({schedulingProfile:r,autoSchedule:o,periodLength:s,tournamentRecord:n});if(I.error)return I;let{scheduledRounds:h,schedulerResult:S}=I;return{totalParticipantsCount:n.participants.length,scheduledRounds:h,schedulerResult:S,...C,eventIds:m,venueIds:g,drawIds:d}}var sR={};Xt(sR,{addDynamicRatings:()=>Yg,addIndividualParticipantIds:()=>dm,addParticipant:()=>wn,addParticipants:()=>En,addPenalty:()=>nR,addPersonRequests:()=>HM,addPersons:()=>oR,createGroupParticipant:()=>zM,createTeamsFromParticipantAttributes:()=>yI,deleteParticipants:()=>ns,filterParticipants:()=>bu,findParticipant:()=>KM,getCompetitionParticipants:()=>QT,getPairedParticipant:()=>Sn,getParticipantEventDetails:()=>XT,getParticipantMembership:()=>JT,getParticipantScaleItem:()=>wc,getParticipantSchedules:()=>ZT,getParticipantSignInStatus:()=>ty,getParticipantTimeItem:()=>sS,getParticipants:()=>Ft,getScaleValues:()=>Aa,mergeParticipants:()=>rR,modifyIndividualParticipantIds:()=>WM,modifyParticipant:()=>lm,modifyParticipantName:()=>QM,modifyParticipantOtherName:()=>YM,modifyParticipantsSignInStatus:()=>jM,modifyPenalty:()=>tR,modifyPersonRequests:()=>VM,mutate:()=>iR,participantScaleItem:()=>Po,query:()=>hN,regenerateParticipantNames:()=>$M,removeIndividualParticipantIds:()=>Tg,removeParticipantIdsFromAllTeams:()=>kp,removePenalty:()=>ZM,removePersonRequests:()=>BM,removeRatings:()=>JM,scaledTeamAssignment:()=>XM,setParticipantScaleItem:()=>xc,setParticipantScaleItems:()=>DD,validateLineUp:()=>Cd});var iR={};Xt(iR,{addDynamicRatings:()=>Yg,addIndividualParticipantIds:()=>dm,addParticipant:()=>wn,addParticipants:()=>En,addPenalty:()=>nR,addPersonRequests:()=>HM,addPersons:()=>oR,createGroupParticipant:()=>zM,createTeamsFromParticipantAttributes:()=>yI,deleteParticipants:()=>ns,findParticipant:()=>KM,mergeParticipants:()=>rR,modifyIndividualParticipantIds:()=>WM,modifyParticipant:()=>lm,modifyParticipantName:()=>QM,modifyParticipantOtherName:()=>YM,modifyParticipantsSignInStatus:()=>jM,modifyPenalty:()=>tR,modifyPersonRequests:()=>VM,regenerateParticipantNames:()=>$M,removeIndividualParticipantIds:()=>Tg,removeParticipantIdsFromAllTeams:()=>kp,removePenalty:()=>ZM,removePersonRequests:()=>BM,removeRatings:()=>JM,scaledTeamAssignment:()=>XM,setParticipantScaleItem:()=>xc,setParticipantScaleItems:()=>DD});function AE(t=0){(typeof t!="number"||isNaN(t))&&(t=0);let e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function UE({personRequests:t,personId:e,requests:r}){t[e]||(t[e]=[]);let n=r.filter(({requestType:o})=>o).map(o=>{let{date:i,startTime:s,endTime:a}=o;return o.requestType===Hc&&(i=Ut(i),s=zt(s),a=zt(a),i&&s&&a)?{date:i,startTime:s,endTime:a,requestType:o.requestType}:o}).filter(Boolean);for(let o of n)o.requestId=AE(),t[e].push(o);return{mergeCount:n.length}}function xl(t){let{tournamentRecords:e,personRequests:r}=t,n=et(t,[{[Re]:!0}]);if(n.error)return n;if(!r)return{...C};let o=Object.values(e);for(let i of o){let s=i.participants??[],a=[];for(let c of Object.keys(r))if(zo({tournamentParticipants:s,personId:c})){let u=r[c];u.length&&a.push({personId:c,requests:u})}Object.keys(a).length&&At({element:i,extension:{value:a,name:Da}})}return{...C}}function VM(t){let{tournamentRecords:e,requests:r,personId:n}=t,o=et(t,[{[Re]:!0},{requests:!0,[He]:Be,[kr]:B}]);if(o.error)return o;let i=r.map(({requestId:u})=>u).filter(Boolean),{personRequests:s}=ki({tournamentRecords:e}),a=u=>{s&&(s[u]=s[u].map(p=>{if(!i.includes(p.requestId))return p;let m=r.find(d=>d.requestId===p.requestId);if(m.requestType)return Object.assign(p,m)}).filter(Boolean))};if(n&&s?.[n])a(n);else if(s)for(let u of Object.keys(s))a(u);let c=r.filter(u=>!u.requestId);return c.length&&UE({personRequests:s,personId:n,requests:c}),xl({tournamentRecords:e,personRequests:s})}function BM(t){let{tournamentRecords:e,requestType:r,requestId:n,personId:o,date:i}=t,s=et(t,[{[Re]:!0}]);if(s.error)return s;let{personRequests:a}=ki({tournamentRecords:e}),c=p=>{a&&(a[p]=a[p].filter(m=>(!r||m.requestType!==r)&&(!n||m.requestId!==n)&&(!i||m.date!==i)),a?.[p]?.length||delete a[p])},u=!r&&!n&&!o&&!i;if(!u){if(o&&a?.[o])c(o);else if(a)for(let p of Object.keys(a))c(p)}return u||!a||!Object.keys(a).length?Ir({name:Da,tournamentRecords:e,discover:!0}):xl({tournamentRecords:e,personRequests:a})}function HM(t){let{tournamentRecords:e,personId:r,requests:n}=t,o=et(t,[{[Re]:!0,[gb]:!0},{requests:!0,[He]:Be,[kr]:B}]);if(o.error)return o;let{personRequests:i}=ki({tournamentRecords:e}),{mergeCount:s}=UE({personRequests:i,personId:r,requests:n});return s&&i?xl({tournamentRecords:e,personRequests:i}):{error:B}}function WM({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n="modifyIndividualParticipantIds";if(!r)return _({result:{error:q},stack:n});if(!e||!t)return _({result:{error:st},stack:n});let o=r.participants||[],i=o.find(l=>l.participantId===e);if(!i)return _({result:{error:re},stack:n});if(![wt,Qr].includes(i.participantType))return _({result:{error:Pn},context:{participantType:i.participantType},stack:n});let s=t.filter(l=>o.find(g=>g.participantId===l)?.participantType!==Et);if(s.length)return _({result:{error:wr,invalidParticipantIds:s},stack:n});let a=i.individualParticipantIds||[],c=t.filter(l=>!a.includes(l)),u=a.filter(l=>!t.includes(l)),p=dm({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:r});if(p.error)return _({result:p,stack:n});let m=Tg({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:r});if(m.error)return _({result:m,stack:n});let{topics:d}=Lr();if(d.includes(rr)){let l=o.find(({participantId:f})=>f===e);lt({topic:rr,payload:{tournamentId:r.tournamentId,participants:[l]}})}return{...p,...m}}function jM({tournamentRecord:t,participantIds:e,signInState:r}){if(!t)return{error:q};if(!Array.isArray(e))return{error:st};if(![Tu,zU].includes(r))return{error:B,signInState:r};let o=t.participants||[];if(!o.length)return{error:ec};let i=o.map(St),s=e.filter(p=>!i.includes(p));if(s.length)return{error:B,context:{invalidParticipantIds:s}};let a=[],c=new Date().toISOString();for(let p of o){let{participantId:m}=p;if(e.includes(m)){let l=Gg({duplicateValues:!1,tournamentRecord:t,participantId:m,timeItem:{itemType:Ic,itemValue:r,createdAt:c}});if(l.error)return l;a.push(p)}}let{topics:u}=Lr();return a.length&&u.includes(rr)&<({topic:rr,payload:{tournamentId:t.tournamentId,participants:a}}),{...C}}function YM({tournamentRecord:t,participantId:e,participantOtherName:r}){if(!t)return{error:q};if(!e)return{error:se};let{participant:n}=Uo({tournamentRecord:t,participantId:e});if(!n)return{error:re};n.participantOtherName=r;let{topics:o}=Lr();return o.includes(rr)&<({topic:rr,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function qM({personFormat:t,person:e}){let r=g=>g.replace(/\W/g,""),n=g=>/^[a-z]*$/.test(r(g)),o=g=>/^[A-Z]*$/.test(r(g)),i=g=>/^[LAST]{4}/.test(r(g)),s=g=>g.toLowerCase().indexOf("l")<g.toLowerCase().indexOf("f"),a=g=>g.indexOf(",")>=0,c=g=>g.toLowerCase().indexOf("f.")>=0,u=g=>g.toLowerCase().indexOf("f")<0,p=g=>g.indexOf(" ")>0;if(!e)return;let m=p(t)?" ":"",d=vS(e?.standardGivenName??""),l=vS(e?.standardFamilyName??"");if(!t)return`${d}${m}${l}`;c(t)&&!a(t)&&!s(t)&&(d=`${d[0]}.`),n(t)?(d=d.toLowerCase(),l=l.toLowerCase()):o(t)?(d=d.toUpperCase(),l=l.toUpperCase()):i(t)&&(l=l.toUpperCase());let f=`${d}${m}${l}`;return u(t)?f=l:s(t)&&(a(t)?f=`${l},${m}${d}`:f=`${l}${m}${d}`),f}function Ew({participantMap:t,participant:e,formats:r}){let{participantType:n,individualParticipantIds:o,person:i}=e,s=n&&r[n];if(n!==Ar&&s){let{personFormat:a,doublesJoiner:c}=s;n===Et&&(e.participantName=qM({person:i,personFormat:a})),n===ft&&(e.participantName=o?.map(u=>{let p=t[u]?.person;return qM({person:p,personFormat:a})}).filter(Boolean).join(c??"/"))}}function $M({tournamentRecord:t,formats:e}){if(!t)return{error:q};if(!ht(e))return{error:st};let r=t.participants??[],n=kI(r,"participantId");for(let o of r)Ew({participant:o,participantMap:n,formats:e});return{...C}}function KM(t){let{tournamentRecord:e,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}=t,s=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="string"&&typeof i!="string")return{error:st,stack:"publicFindParticipant"};let a,c;for(let u of Object.values(s)){c=u.tournamentId;let p=u.participants||[];if(a=zo({tournamentParticipants:p,internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}),a)break}return{participant:a,tournamentId:c,...C}}function zM({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:r=yP,tournamentRecord:n,participantId:o,groupName:i}){if(!n)return{error:q};if(!i)return{error:st,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:B};let a=(Ft({participantFilters:{participantTypes:[Et]},tournamentRecord:n}).participants??[]).map(m=>m.participantId);for(let m of t)if(!a.includes(m))return{error:Pn,participantId:m};let c=nt({participantId:o||Nt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:Qr,participantRole:r}),u=wn({participant:c,tournamentRecord:n});if(u.error)return u;let{topics:p}=Lr();return p.includes(ci)&<({topic:ci,payload:{tournamentId:n.tournamentId,participants:[c]}}),{...C,participant:J(c)}}function QM({tournamentRecord:t,participantName:e,participantId:r}){if(!t)return{error:q};if(!r)return{error:se};if(!e)return{error:st,info:"Missing participantName"};let{participant:n}=Uo({tournamentRecord:t,participantId:r});if(!n)return{error:re};n.participantName=e;let{topics:o}=Lr();return o.includes(rr)&<({topic:rr,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function XM({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:r,initialTeamIndex:n=0,scaledParticipants:o=[],teamParticipantIds:i,tournamentRecord:s,scaleAttributes:a,teamNameBase:c,teamsCount:u,eventId:p,event:m}){if(!s)return{error:q};if(!Array.isArray(i)&&!It(u)&&!p||!It(n)||o&&!Array.isArray(o)||a&&(typeof a!="object"||!Object.keys(a).length))return{error:B};if(!a&&!o.length||!o&&!(e&&a))return{error:st,info:"Missing scaling details"};if(p&&!i){if(m?.eventType!==Or)return{error:$n};i=m?.entries?.filter(({entryStatus:h})=>h===Gr).map(St)}if(!i?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:st};let d=e??o.map(({participantId:h})=>h);r&&(i?.reverse(),n+=1),n>(i?.length||0)-1&&(n=0);let l=i?.slice(n).concat(...i.slice(0,n))??[],f=[];for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(l.includes(S)){if(T!==Ar)return{error:Pn,participant:h};f.push(h)}}if(u&&f.length<u){let h=u-(f?.length||0),S=c??"Team",T=tt(0,h).map(A=>({participantName:`${S} ${A+1}`,participantType:Ar,participantRole:xe})),{participants:y=[]}=En({participants:T,returnParticipants:!0,tournamentRecord:s}),E=y.map(St),P=s.participants?.filter(({participantId:A})=>E.includes(A))??[];f.push(...P)}if(!f.length)return{error:lf};if(t)for(let h of f)h.individualParticipantIds=[];else{let h=f.map(S=>S).flat();e?.length?d=d.filter(S=>!h.includes(S)):o=o?.filter(({participantId:S})=>!h.includes(S))}if(!e?.length&&!o?.length)return{error:ap,info:"Nothing to be done"};if(!o.length){for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(!d.includes(S))continue;if(T!==Et)return{error:Pn,participant:h};let y=Po({scaleAttributes:a,participant:h})?.scaleItem,E=a?.accessor?y?.scaleValue?.[a?.accessor]:y?.scaleValue,P={participantId:S,scaleValue:E};o.push(P)}if(!o.length)return{error:re}}o.sort((h,S)=>a?.sortOrder?(S?.scaleValue||0)-(h?.scaleValue||0):(h?.scaleValue||1/0)-(S?.scaleValue||1/0));for(let h of o)if(!h.participantId)return{error:B,scaledParticipant:h};let g=0;for(;g<o.length;){for(let h of f){if(g+1>o.length)break;let S=o[g];h.individualParticipantIds.push(S.participantId),g++}f.reverse()}let I=f.map(St);for(let h of s.events??[]){if(h.eventType!==Or)continue;let S=(h.entries??[]).filter(T=>I.includes(T.participantId));for(let T of S){let y=T.participantId,P=f.find(U=>U.participantId===y)?.individualParticipantIds;h.entries=(h.entries??[]).filter(U=>!P.includes(U.participantId)),(h.drawDefinitions??[]).forEach(U=>{U.entries=(U.entries??[]).filter(N=>!P.includes(N.participantId))});let{flightProfile:A}=Ht({event:h});(A?.flights||[]).forEach(U=>{U.drawEntries=(U.drawEntries||[]).filter(N=>!P.includes(N.participantId))})}}return{...C,scaledParticipants:o}}function JM(t){let e=et(t,[{[ne]:!0,[wf]:!0},{ratingType:!1,[tr]:s=>je[s]}]);if(e.error)return e;let r=`${t.ratingType}.${Qm}`,n=t.asDynamic?r:t.ratingType,o=[Pi,Ui,t.eventType,n].join("."),i=t.tournamentRecord.participants??[];for(let s of i)s.timeItems&&(s.timeItems=s.timeItems.filter(a=>a.itemType!==o));return{...C}}function ZM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=j0({...t,tournamentRecord:r});if(n.error&&n.error!==$c)return n}return{...C}}function j0({tournamentRecord:t,penaltyId:e}){if(!t)return{error:q};if(!e)return{error:uf};let r=t?.participants??[],n=[],o=!1,i;return r.forEach(s=>{let a=!1;s.penalties=(s.penalties??[]).filter(c=>(c.penaltyId===e&&(a=!0,o||(i=c,o=!0)),a&&n.push(s),c.penaltyId!==e))}),i&<({topic:rr,payload:{tournamentId:t.tournamentId,participants:n}}),i?{...C,penalty:i}:{error:$c}}var Y0=({penaltyId:t=Nt()}={})=>({refereeParticipantId:void 0,penaltyCode:void 0,penaltyType:void 0,extensions:void 0,matchUpId:void 0,createdAt:void 0,issuedAt:void 0,notes:void 0,penaltyId:t}),PE=Y0;function tR(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=q0({...t,tournamentRecord:r});if(n.error&&n.error!==$c||n.success)return n}return{error:$c}}function q0({tournamentRecord:t,modifications:e,penaltyId:r}){if(!t)return{error:q};if(!e)return{error:B,modifications:e};if(!r)return{error:uf};let n=t?.participants??[],o=Object.keys(PE()).filter(c=>c!=="penaltyId"),i=Object.keys(e).filter(c=>o.includes(c));if(!i.length)return{error:up};let s,a=[];return n.forEach(c=>{let u=!1;c.penalties=(c.penalties??[]).map(p=>(p.penaltyId===r&&(u=!0,i.forEach(m=>Object.assign(p,{[m]:e[m]})),s||(s=p)),p)),u&&a.push(c)}),s&<({topic:rr,payload:{tournamentId:t.tournamentId,participants:a}}),s?{...C,penalty:s}:{error:$c}}function eR(t,e,r){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:pt(Object.keys(t).concat(Object.keys(e))).reduce((o,i)=>{if(!e[i])o[i]=t[i];else if(!t[i])o[i]=e[i];else if(typeof t[i]!=typeof e[i])o[i]=e[i];else if(Array.isArray(t[i]))if(r===!0||Array.isArray(r)&&r.includes(i)){let s=pt(t[i].map(a=>JSON.stringify(a)).concat(e[i].map(a=>JSON.stringify(a)))).map(a=>JSON.parse(a));o[i]=s}else o[i]=e[i];else typeof t[i]=="object"?o[i]=eR(t[i],e[i],r):o[i]=e[i];return o},{})}function rR({participants:t=[],tournamentRecord:e,arraysToMerge:r}){if(!e)return{error:q};e.participants||(e.participants=[]);let n=t.filter(Hr(ao)).map(u=>({[u.participantId]:u})),o=Object.assign({},...n),i=[];e.participants=e.participants.map(u=>{if(o[u.participantId]){let p=eR(u,o[u.participantId],r);return i.push(p),p}return u});let s=e.participants.map(Hr(ao))||[],a=t.filter(({participantId:u})=>!s.includes(u)),{topics:c}=Lr();return a.length&&(e.participants=e.participants.concat(...a),c.includes(ci)&<({topic:ci,payload:{participants:a}})),i.length&&c.includes(rr)&<({topic:rr,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:a.length,...C}}function nR(t){let{tournamentRecord:e,participantIds:r}=t,n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o;for(let i of Object.values(n)){let a=(Ft({tournamentRecord:i}).participants??[])?.map(St).filter(c=>r.includes(c));a.length&&(o=$0({...t,penaltyId:t.penaltyId??o,tournamentRecord:i,participantIds:a}).penaltyId)}return o?{...C,penaltyId:o}:{error:re}}function $0({refereeParticipantId:t,tournamentRecord:e,participantIds:r,penaltyCode:n,penaltyType:o,extensions:i,penaltyId:s,matchUpId:a,issuedAt:c,notes:u}){if(!e)return{error:q};if(!r)return{error:se};if(!o)return{error:RA};let m=(e?.participants??[]).filter(f=>r.includes(f.participantId));if(!m.length)return{error:re};let d=new Date().toISOString(),l=Object.assign(PE({penaltyId:s}),{refereeParticipantId:t,penaltyCode:n,penaltyType:o,matchUpId:a,createdAt:d,issuedAt:c,notes:u});return Array.isArray(i)&&i.forEach(f=>At({element:l,extension:f})),m.forEach(f=>{f.penalties||(f.penalties=[]),f.penalties.push(l)}),lt({topic:rr,payload:{tournamentId:e.tournamentId,participants:m}}),{...C,penaltyId:l.penaltyId}}function oR({participantRole:t=xe,tournamentRecord:e,persons:r}){if(!e)return{error:q};if(!Array.isArray(r))return{error:B};if(!Object.keys(Dd).includes(t))return{error:SA};let n=(e.participants||[]).map(({person:f})=>f?.personId).filter(Boolean),o=[],i=r.filter(f=>f&&(!f.personId||!n.includes(f.personId))).map(f=>(f.personId||(f.personId=Nt()),o.push(f.personId),f)),s=(f,g)=>Object.assign({},...Object.keys(f).filter(I=>!g.includes(I)).map(I=>({[I]:f[I]}))),a=i.map(f=>nt({extensions:f.participantExtensions,timeItems:f.participantTimeItems,participantType:Et,participantRole:t,person:s(f,["participantExtensions","participantTimeItems","pairedPersons"])})),c=0,u=0,p=En({participants:a,tournamentRecord:e});if(p.error)return p;u=p.addedCount||0;let m=[],d=Ft({participantFilters:{participantTypes:[Et]},tournamentRecord:e})?.participants??[];if(t===xe&&r.filter(({pairedPersons:f})=>f).forEach(({personId:f,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{let h=[f,I.personId].map(S=>zo({tournamentParticipants:d,personId:S})).filter(Boolean);if(h.length===2){let S=h.map(St);m.push(nt({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:xe,individualParticipantIds:S,participantType:ft}))}})}),m.length){if(p=En({participants:m,tournamentRecord:e}),p.error)return p;c=p.addedCount||0}let l=u+c;return{...C,addedCount:l,newPersonIds:o}}var gR={};Xt(gR,{bulkUpdatePublishedEventIds:()=>cy,getAllEventData:()=>uy,getCourtInfo:()=>Td,getDrawData:()=>cl,getEventData:()=>ul,getEventPublishStatus:()=>Jr,getPublishState:()=>As,getTournamentPublishStatus:()=>Ru,getVenueData:()=>Ac,mutate:()=>fR,publishEvent:()=>da,publishEventSeeding:()=>aR,publishOrderOfPlay:()=>dR,publishParticipants:()=>mR,query:()=>DN,setEventDisplay:()=>yl,unPublishEvent:()=>lR,unPublishEventSeeding:()=>cR,unPublishOrderOfPlay:()=>pR,unPublishParticipants:()=>uR});var fR={};Xt(fR,{publishEvent:()=>da,publishEventSeeding:()=>aR,publishOrderOfPlay:()=>dR,publishParticipants:()=>mR,setEventDisplay:()=>yl,unPublishEvent:()=>lR,unPublishEventSeeding:()=>cR,unPublishOrderOfPlay:()=>pR,unPublishParticipants:()=>uR});function aR({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:r,tournamentRecord:n,status:o=Cr,drawIds:i=[],event:s}){if(!n)return{error:q};if(!s)return{error:Ot};let a=Jr({event:s,status:o}),c=(a?.seeding?.seedingScaleNames||r)&&{...a?.seeding?.seedingScaleNames,...r},u=(a?.seeding?.stageSeedingScaleNames||e)&&{...a?.seeding?.stageSeedingScaleNames,...e},p=nt({stageSeedingScaleNames:u,seedingScaleNames:c,published:!0,drawIds:i});return ma({statusObject:{seeding:p},removePriorValues:t,status:o,event:s}),lt({topic:YU,payload:{tournamentId:n.tournamentId,eventId:s.eventId,drawIds:i}}),{...C}}function cR({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:r,status:n=Cr,drawIds:o,stages:i,event:s}){if(!r)return{error:q};if(!s)return{error:Ot};let a=Jr({event:s});if(a){let c=a.seeding;if(Array.isArray(i)&&c.stageSeedingScaleNames)for(let u of i)c.stageSeedingScaleNames[u]&&delete c.stageSeedingScaleNames[u];Array.isArray(e)&&c?.seedingScaleNames&&(c.seedingScaleNames=c.seedingScaleNames.filter(u=>!e.includes(u))),Array.isArray(o)&&c?.drawIds&&(c.drawIds=c.drawIds.filter(u=>!o.includes(u))),(!Object.values(c.stageSeedingScaleNames??{}).length&&!c.seedingScaleNames?.length&&!c.drawIds?.length||!i&&!e&&!o?.length)&&(delete c.stageSeedingScaleNames,delete c.seedingScaleNames,delete c.drawIds,c.published=!1),ma({statusObject:{seeding:c},removePriorValues:t,status:n,event:s})}return lt({topic:eg,payload:{tournamentId:r.tournamentId,eventId:s.eventId}}),{...C}}function uR(t){let e=Rr(t);if(!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=K0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function K0({removePriorValues:t=!0,tournamentRecord:e,status:r=Cr}){if(!e)return{error:q};let n=`${Ho}.${Wo}`,{timeItem:o}=nn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].participants,ro({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({payload:{tournamentId:e.tournamentId},topic:Mb}),{...C}}function pR(t){let e=Rr(t);if(!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=z0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function z0({removePriorValues:t=!0,tournamentRecord:e,status:r=Cr}){if(!e)return{error:q};let n=`${Ho}.${Wo}`,{timeItem:o}=nn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].orderOfPlay,ro({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({topic:rg,payload:{tournamentId:e.tournamentId}}),{...C}}function mR(t){let e=Rr(t);if(!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=Q0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function Q0({removePriorValues:t,tournamentRecord:e,status:r=Cr}){if(!e)return{error:q};let n=`${Ho}.${Wo}`,{timeItem:o}=nn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r].participants={published:!0},ro({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),lt({payload:{tournamentId:e.tournamentId},topic:$U}),{...C}}function dR(t){let e=Rr(t);if(!Object.keys(e).length)return{error:xt};for(let r of Object.values(e)){let n=X0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function X0({scheduledDates:t=[],removePriorValues:e,tournamentRecord:r,status:n=Cr,eventIds:o=[]}){if(!r)return{error:q};let i=`${Ho}.${Wo}`,{timeItem:s}=nn({element:r,itemType:i}),a=s?.itemValue||{[n]:{}};return a[n].orderOfPlay={published:!0,scheduledDates:t,eventIds:o},ro({timeItem:{itemValue:a,itemType:i},element:r,removePriorValues:e}),lt({topic:qU,payload:{tournamentId:r.tournamentId,scheduledDates:t,eventIds:o}}),{...C}}function lR({removePriorValues:t=!0,tournamentRecord:e,status:r=Cr,event:n}){if(!e)return{error:q};if(!n)return{error:Ot};let o=`${Ho}.${Wo}`,{timeItem:i}=Au({itemType:o,event:n}),s=i?.itemValue||{[r]:{}};return delete s[r].structureIds,delete s[r].drawDetails,delete s[r].drawIds,is({event:n,timeItem:{itemValue:s,itemType:o},removePriorValues:t}),ma({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:r,event:n}),lt({topic:tg,payload:{tournamentId:e.tournamentId,eventId:n.eventId}}),{eventId:n.eventId,...C}}var IR={};Xt(IR,{getEntryStatusReports:()=>Uw,getParticipantStats:()=>Aw,getStructureReports:()=>Dw,getVenuesReport:()=>Nw});function Aw({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:r,teamParticipantId:n,tournamentRecord:o,withScaleValues:i,tallyPolicy:s,matchUps:a}){if(!o)return{error:q};if(a&&!Array.isArray(a))return{error:dr};if(a=a??ye({tournamentRecord:o,participantsProfile:i?{withScaleValues:i}:void 0}).matchUps,!a?.length)return{error:no};let u=[];e&&u.push(e),n&&u.push(n);let p=u.length?{participantIds:u}:{participantTypes:[Ar]},m=Ft({participantFilters:p,tournamentRecord:o}).participants??[];if(!m.every(({participantType:U})=>U===Ar))return{error:wr};u.length||u.push(...m.map(St));let d=new Map,l=new Map,f=new Map,g=new Map,I=(U,N="")=>l.get(U)||l.set(U,{participantName:N,participantId:U,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(U);for(let U of m){let{participantId:N,individualParticipantIds:D}=U;g.set(N,D??[]),I(N,U.participantName)}if(n&&!g.get(n))return _({result:{error:re},context:{teamParticipantId:n}});if(e&&!g.get(e))return _({result:{error:re},context:{opponentParticipantId:e}});let h=[],S=U=>{let N=[[],[]];for(let M of U){let R=M.participant;if(R?.participantName){d.set(R.participantId,{participantName:R.participantName,ratings:R.ratings});let b=l.get(R.participantId);b&&(b.participantName=R.participantName)}}let D=({side:M,individualParticipantIds:R})=>M.participantId&&(!R?.length||R.includes(M.participantId))&&[M.participantId]||M.participant?.individualParticipantIds?.length&&(!R?.length||jt(R,M.participant?.individualParticipantIds).length===M.participant?.individualParticipantIds?.length)&&M.participant.individualParticipantIds;if(g.size){let M=(R,b)=>{for(let O of U){if(!O.participant)continue;let v=D({individualParticipantIds:b,side:O});if(v?.length){let x=O.sideNumber;if(!x)continue;let F=[R];r&&F.push(...v),N[x-1]=F;let w=l.get(R);for(let L of v.filter(Boolean))w&&!w.competitorIds.includes(L)&&w.competitorIds.push(L)}}};if(n)(!e||U.every(b=>b.participant&&(D({individualParticipantIds:g.get(n),side:b})||D({individualParticipantIds:g.get(e),side:b}))))&&M(n,g.get(n));else for(let[R,b]of g)M(R,b)}else if(r)for(let M of U){if(!M.participant)continue;let R=D({individualParticipantIds:[],side:M}),b=M.sideNumber;b&&(N[b-1]=R)}return N};for(let U of a){if(!ht(U))return{error:dr};let{matchUpStatus:N,matchUpFormat:D,matchUpType:M,winningSide:R,score:b,sides:O}=U;if(!O||!b||M===xr||N==="BYE")continue;let v=S(O);if(!v.filter(Boolean).length)continue;let x=t&&R&&Du({matchUp:U})?.competitiveness;h.push(U);let F=Lg({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),w=nT({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),{pointsTally:L,tiebreaksTally:k}=oT({matchUpFormat:D,score:b});v.forEach((G,H)=>{for(let K of G){let Y=d.get(K)?.participantName,j=I(K,Y);if(j){let V=(z,Q)=>Q.forEach((ut,ot)=>j[z][ot]+=ut),$=H?[...k].reverse():k,X=H?[...L].reverse():L,W=H?[...w].reverse():w,it=H?[...F].reverse():F;if(V("tiebreaks",$),V("points",X),V("games",W),V("sets",it),R){let z=R-1===H?0:1;j.matchUps[z]+=1}if(x){let z=x.toLowerCase();j.competitiveness[z]||(j.competitiveness[z]=[0,0]),j.competitiveness[z][H]+=1}if(N){let z=N.toLowerCase();j.matchUpStatuses[z]||(j.matchUpStatuses[z]=0),j.matchUpStatuses[z]+=1}}}})}let T=["tiebreaks","matchUps","points","games","sets"],y=["competitive","routine","decisive"],E=new Map,P=(U,N)=>(U??0)+(N??0);for(let[U,N]of l.entries()){for(let D of T){let M=N[D].reduce(P);if(M){let R=N[D][0]/M,b=`${D}Ratio`,O=parseFloat(R.toFixed(2));N[b]=O,f.set(U,!0),E.has(b)||E.set(b,[]),E.get(b)?.push(O)}}for(let D of y){let M=N.competitiveness?.[D]?.reduce(P);if(M){let R=N.competitiveness[D][0]/M,b=`${D}Ratio`,O=parseFloat(R.toFixed(2));N[b]=O}}}if(!n){let U=(N,D)=>D-N;for(let N of l.values())for(let D of T){let M=`${D}Ratio`;if(typeof N[M]=="number"){let R=E.get(M)?.sort(U).indexOf(N[M]);if(typeof R=="number"&&R>=0){let b=`${D}Rank`;N[b]=R+1}}}}let A={relevantMatchUps:h,...C};return n?(A.teamStats=l.get(n),e&&(A.opponentStats=l.get(e))):A.participatingTeamsCount=f.size,A.allParticipantStats=[...l.values()],A}function Pm({participant:t,eventType:e}){let r=t?.person?.personId,n=t?.person?.personOtherIds?.[0],o=t?.person?.tennisId,i=t?.ratings?.[e]?.find(({scaleName:u})=>u==="WTN"),s=i?.scaleValue,{wtnRating:a,confidence:c}=s||{};return{timeStamp:i?.scaleDate,personOtherId:n,confidence:c,wtnRating:a,personId:r,tennisId:o}}function Uw({tournamentRecord:t}){if(!t)return{error:q};let e=t.tournamentId,{participantMap:r}=Ft({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(ye({matchUpFilters:{matchUpTypes:[Ia,Gi]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:f,matchUpType:g})=>f?.flatMap(I=>g===Gi?I?.participant?.individualParticipantIds:I?.participant?.participantId||I.participantId).filter(Boolean)).filter(Boolean),i=[],s={},a={},c={},u=0,p=({id:f,entry:g,eventId:I,eventType:h})=>{let{qualifyingSeeding:S,mainSeeding:T,entryStatus:y,entryStage:E,drawId:P}=g;s[f]||(s[f]=[]);let{participant:A,events:U}=r?.[f]??{},N=Pm({participant:A,eventType:h}),D=U?.[I]?.ranking;y===xg&&i.push(f),s[f].push({participantType:A?.participantType,participantId:f,tournamentId:e,eventType:h,eventId:I,drawId:P,entryStatus:y,entryStage:E,...N,ranking:D,mainSeeding:T,qualifyingSeeding:S})};for(let f of t.events??[]){let g={},I=N=>{g[N]||(g[N]={count:0}),g[N].count+=1},{drawDefinitions:h=[],eventType:S,eventId:T}=f,y=h.flatMap(N=>{let{drawId:D,entries:M}=N;u+=1;let R=({stage:F,stageSequence:w})=>F===rt&&w===1||F===ct,O=(N.structures??[]).filter(R).flatMap(({positionAssignments:F})=>F).filter(Boolean).map(({participantId:F})=>F),v=({participantId:F})=>O.includes(F),x=F=>{let{participantId:w,entryStatus:L,entryStage:k}=F;I(L);let G=r?.[w]?.draws?.[D]?.seedAssignments?.[rt];return{qualifyingSeeding:r?.[w]?.draws?.[D]?.seedAssignments?.[ct],participantId:w,mainSeeding:G,entryStatus:L,entryStage:k,drawId:D}};return M?.filter(v).map(x)}),E=N=>{let D=N.participantId,M=r?.[D].participant.individualParticipantIds?.filter(R=>o.includes(R));return D&&{[D]:{individualParticipantIds:M}}};S===Ko?(()=>{let N=Object.assign({},...y.map(E).filter(Boolean)),D=M=>{N[M.participantId].individualParticipantIds.forEach(R=>{p({id:R,eventType:S,eventId:T,entry:M})})};y.forEach(D)})():y.forEach(N=>{p({id:N?.participantId,eventType:S,eventId:T,entry:N})});let A=Object.values(g).reduce((N,D)=>N+D.count,0);Object.keys(g).forEach(N=>{g[N].pct=g[N].count/A*100}),c[T]={tournamentId:e,eventId:T,entries:y,entryStatuses:g};let U=Object.assign({},...Xr.flatMap(N=>[{[N+"_count"]:g[N]?.count},{[N+"_pct"]:g[N]?.pct}]));a[T]={tournamentId:e,eventId:T,...U}}let m=Object.values(r??{}).filter(({participant:{participantType:f,participantRole:g}})=>f===Et&&g===xe),d=m.filter(({participant:f})=>!o.includes(f.participantId)).map(({participant:f})=>f.participantId),l={nonParticipatingEntriesCount:d.length,individualParticipantsCount:m.length,eventsCount:Object.values(c).length,nonParticipatingParticipantIds:d,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(a).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(c).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}}function Pw({eventType:t,matchUps:e,eventId:r,drawId:n}){let o={},i=g=>{let I=g?.matchUpFormat;I&&(o[I]||(o[I]=0),o[I]+=1)},s=e.filter(g=>r?g.eventId===r:g.drawId===n).reduce((g,I)=>(i(I),(I.sides??[]).flatMap(h=>(h?.participant?.individualParticipants||[h?.participant]).filter(Boolean)).forEach(h=>g[h.participantId]=h),g),{}),a=Object.values(s),c=a.map(g=>Pm({participant:g,eventType:t})).filter(({wtnRating:g})=>g),u=(a.length-c.length)/a.length*100,p=c.reduce((g,I)=>{let{wtnRating:h,confidence:S}=I;return g.totalWTN+=h,g.totalConfidence+=S,g},{totalWTN:0,totalConfidence:0}),m=c?.length?p.totalWTN/c.length:0,d=c?.length?p.totalConfidence/c.length:0,f=Object.values(o).reduce((g,I)=>g+(I||0),0);return{matchUpFormatCounts:o,matchUpsCount:f,avgConfidence:d,pctNoRating:u,avgWTN:m}}function Dw(t){let{tournamentRecord:e,extensionProfiles:r,firstFlightOnly:n,firstStageSequenceOnly:o=!0}=t;if(!e)return{error:ha};let i=[],s={},a={},c=[],u=Object.assign({},...(r??[]).map(({name:I,label:h,accessor:S})=>{let T=mt({element:e,name:I})?.extension?.value,y=S?ys({element:T,accessor:S})?.value:T;return{[h??I]:y}})),p=e?.tournamentId,d=ye({participantsProfile:{withScaleValues:!0},tournamentRecord:e}).matchUps??[],l=I=>nn({itemType:Yf,itemSubTypes:[Ao],element:{timeItems:I}})?.timeItem?.itemValue?.scaleBasis,f=({positionManipulations:I})=>{I?.forEach(h=>{let{structureId:S,name:T}=h,y=h.drawPositions??[h.drawPosition];s[S]??=[],s[S].push(`${T}: ${y.join("/")}`)})},g=e?.events?.flatMap(({timeItems:I,drawDefinitions:h=[],extensions:S,eventType:T,eventName:y,eventId:E,category:P})=>{let U=S?.find(x=>x.name===pn)?.value?.flights?.map(x=>({[x.drawId]:x.flightNumber})),N=U&&Object.assign({},...U),D=S?.find(x=>x.name===Pa),M=I?.find(x=>x.itemType===Pa),R=D?.value?.length??M?.itemValue??0,b=Object.values(N??{}),O=N&&Math.min(...b),v=l(I);return a[E]={seedingBasis:v?JSON.stringify(v):void 0,totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:R,tournamentId:p,eventId:E},h.filter(x=>!n||!U||N[x.drawId]===O).flatMap(x=>{let{matchUpFormat:F,tieFormat:w,timeItems:L,extensions:k,structures:G,drawName:H,drawType:K,drawId:Y}=x,{matchUpFormatCounts:j,matchUpsCount:V,avgConfidence:$,pctNoRating:X,avgWTN:W}=Pw({eventType:T,matchUps:d,drawId:Y}),it=l(L)??v,z=J0({extensions:k}),Q=z?.length??0;return f({positionManipulations:z}),a[E].totalPositionManipulations+=Q,a[E].generatedDrawsCount+=1,Q>a[E].maxPositionManipulations&&(a[E].maxPositionManipulations=Q),G?.filter(ut=>(ut.stageSequence===1||!o)&&[ct,rt,qe,fe].includes(ut.stage)).map(ut=>{let ot=[rt,fe].includes(ut.stage)?d.find(Cn=>Cn.structureId===ut.structureId&&Cn.finishingRound===1&&Cn.winningSide):void 0;ut.stage===rt&&i.push({eventName:y,drawName:H,structureId:ut.structureId});let Rt=ot?.sides?.find(Cn=>Cn.sideNumber===ot.winningSide)?.participant,De=Rt?.participantType===Ar&&Rt.participantId,qt=Rt?.participantType===ft?Rt.individualParticipants:[],Se=Pm({participant:qt?.[0]??Rt,eventType:T}),{personId:_r,personOtherId:dn,tennisId:hr,confidence:Xe,wtnRating:Zt}=Se||{},Pt=Pm({participant:qt?.[1],eventType:T}),{personId:ce,personOtherId:ue,tennisId:Fe,confidence:te,wtnRating:Je}=Pt||{},{ageCategoryCode:$t,categoryName:ir,subType:fr}=P??{},pe=ut.matchUpFormat??F,Sr=(j[pe]??0)/V*100,{tieFormatName:jr,tieFormatDesc:Kt}=sl(w),{tieFormatName:Te,tieFormatDesc:gr}=sl(ut.tieFormat),Ee=Kt===gr,Rn=!Ee&&Te,ee=ut.tieFormat&&!Ee&&gr,Ur=z?.filter(Cn=>Cn.structureId===ut.structureId)?.length??0;return{...u,tournamentId:p,eventId:E,structureId:ut.structureId,drawId:Y,eventType:T,category:fr,categoryName:ir,ageCategoryCode:$t,flightNumber:N?.[Y],drawType:K,stage:ut.stage,seedingBasis:it?JSON.stringify(it):void 0,winningPersonId:_r,winningPersonOtherId:dn,winningPersonTennisId:hr,winningPersonWTNrating:Zt,winningPersonWTNconfidence:Xe,winningPerson2Id:ce,winningPerson2OtherId:ue,winningPerson2TennisId:Fe,winningPerson2WTNrating:Je,winningPerson2WTNconfidence:te,winningTeamId:De,positionManipulations:Ur,pctNoRating:X,matchUpFormat:pe,pctInitialMatchUpFormat:Sr,matchUpsCount:V,drawTieFormatName:jr,drawTieFormatDesc:Kt,tieFormatName:Rn,tieFormatDesc:ee,avgConfidence:$,avgWTN:W}})})});return i.forEach(({eventName:I,drawName:h,structureId:S})=>{s[S]?.length&&c.push({eventName:I,drawName:h,actions:s[S]})}),{eventStructureReports:Object.values(a),structureReports:g,flightReports:c}}function J0({extensions:t}){return t?.find(({name:e})=>e===lc)?.value?.slice(1)}function Nw({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:r,venueIds:n=[],dates:o=[]}){if(!Array.isArray(o))return{error:B,dates:o};if(!Array.isArray(n))return{error:B,venueIds:n};if(!(e&&Object.keys(e).filter(l=>!r||l===r)||[]).length)return{error:xt};if(!o.every(Mr))return{error:Ye};let a=Ro({tournamentRecords:e,ignoreDisabled:t,dates:o});if(a.error)return a;let c=a?.venues?.filter(({venueId:l})=>!n?.length||n.includes(l)),u=a.courts?.reduce((l,f)=>(f.dateAvailability?.forEach(g=>{let I=g.date;l.includes(I)||l.push(I)}),l),[]).filter(l=>!o.length||o.includes(l)),p={venueIds:c?.map(({venueId:l})=>l)},{matchUps:m}=Mn({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:p});return{venuesReport:c?.map(l=>Z0(u,l,m))}}function Z0(t,e,r){let{venueId:n,courts:o,venueName:i}=e,s={};return t.forEach(a=>{let c=0,u=0,p=0;for(let l of o){let f=l.dateAvailability.find(h=>h.date===a),I=(f&&_s({courtDate:f}).timeSlots)?.reduce((h,S)=>{let{startTime:T,endTime:y}=S,E=Yt(y)-Yt(T);return h+E},0);I&&(p+=1),c+=I}let m=r.filter(({schedule:l})=>l.venueId===n&&zn(a,l.scheduledDate));m.forEach(({schedule:l})=>{let f=zt(l.scheduledTime),g=$r(f,l.averageMinutes),I=Yt(g)-Yt(f);u+=I});let d=c?(u/c*100).toFixed(2):"100";s[a]={scheduledMatchUpsCount:m.length,availableCourts:p,availableMinutes:c,scheduledMinutes:u,percentUtilization:d}}),{venueId:n,venueName:i,venueReport:s}}var RR={};Xt(RR,{addMatchUpCourtOrder:()=>Xy,addMatchUpEndTime:()=>Zy,addMatchUpOfficial:()=>SM,addMatchUpResumeTime:()=>eE,addMatchUpScheduleItems:()=>Im,addMatchUpScheduledDate:()=>fm,addMatchUpScheduledTime:()=>ii,addMatchUpStartTime:()=>Jy,addMatchUpStopTime:()=>tE,addSchedulingProfileRound:()=>AI,allocateTeamMatchUpCourts:()=>gm,assignMatchUpCourt:()=>as,assignMatchUpVenue:()=>la,bulkRescheduleMatchUps:()=>UR,bulkScheduleMatchUps:()=>Wc,bulkScheduleTournamentMatchUps:()=>Xu,bulkUpdateCourtAssignments:()=>TR,calculateScheduleTimes:()=>DI,clearMatchUpSchedule:()=>DR,clearScheduledMatchUps:()=>Sm,courtGridRows:()=>dl,findMatchUpFormatTiming:()=>im,findVenue:()=>ti,generateBookings:()=>hm,generateVirtualCourts:()=>mm,getMatchUpsToSchedule:()=>pl,getPersonRequests:()=>ki,getProfileRounds:()=>ml,getScheduledRoundsDetails:()=>$u,getSchedulingProfile:()=>oi,getSchedulingProfileIssues:()=>my,matchUpScheduleChange:()=>PR,modifyMatchUpFormatTiming:()=>nI,mutate:()=>MR,proAutoSchedule:()=>SR,proConflicts:()=>ER,publicFindCourt:()=>PS,query:()=>CN,removeEventMatchUpFormatTiming:()=>Tl,removeMatchUpCourtAssignment:()=>hR,reorderUpcomingMatchUps:()=>AR,scheduleMatchUps:()=>yR,scheduleProfileRounds:()=>Tm,setMatchUpDailyLimits:()=>NR,setMatchUpHomeParticipantId:()=>fI,setSchedulingProfile:()=>Lc,toggleParticipantCheckInState:()=>Al,validateSchedulingProfile:()=>sm});var MR={};Xt(MR,{addMatchUpCourtOrder:()=>Xy,addMatchUpEndTime:()=>Zy,addMatchUpOfficial:()=>SM,addMatchUpResumeTime:()=>eE,addMatchUpScheduleItems:()=>Im,addMatchUpScheduledDate:()=>fm,addMatchUpScheduledTime:()=>ii,addMatchUpStartTime:()=>Jy,addMatchUpStopTime:()=>tE,addSchedulingProfileRound:()=>AI,allocateTeamMatchUpCourts:()=>gm,assignMatchUpCourt:()=>as,assignMatchUpVenue:()=>la,bulkRescheduleMatchUps:()=>UR,bulkScheduleMatchUps:()=>Wc,bulkScheduleTournamentMatchUps:()=>Xu,bulkUpdateCourtAssignments:()=>TR,calculateScheduleTimes:()=>DI,clearMatchUpSchedule:()=>DR,clearScheduledMatchUps:()=>Sm,findMatchUpFormatTiming:()=>im,generateBookings:()=>hm,generateVirtualCourts:()=>mm,matchUpScheduleChange:()=>PR,modifyMatchUpFormatTiming:()=>nI,proAutoSchedule:()=>SR,proConflicts:()=>ER,removeEventMatchUpFormatTiming:()=>Tl,removeMatchUpCourtAssignment:()=>hR,reorderUpcomingMatchUps:()=>AR,scheduleMatchUps:()=>yR,scheduleProfileRounds:()=>Tm,setMatchUpDailyLimits:()=>NR,setMatchUpHomeParticipantId:()=>fI,setSchedulingProfile:()=>Lc,toggleParticipantCheckInState:()=>Al,validateSchedulingProfile:()=>sm});function DI({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:r=90,remainingScheduleTimes:n,clearScheduleDates:o,tournamentRecords:i,periodLength:s,scheduleDate:a,startTime:c,venueIds:u,endTime:p}){if(typeof i!="object"||!Object.keys(i).length)return{error:xt};s=s??zu({recoveryMinutes:e,averageMatchUpMinutes:r});let{courts:m,venues:d}=Ro({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),l=m?.filter(M=>!u||u.includes(M.venueId));c||(c=l?.reduce((M,R)=>{let O=R.dateAvailability?.find(v=>!v.date||zn(a,v.date))?.startTime??R.startTime;return O&&(!M||Yt(O)<Yt(M))?O:M},void 0)),p||(p=l?.reduce((M,R)=>{let O=R.dateAvailability?.find(v=>!v.date||zn(a,v.date))?.endTime??R.endTime;return O&&(!M||Yt(O)>Yt(M))?O:M},void 0));let f=Object.values(i),g=Object.assign({},...f.map(M=>(M.events??[]).map(R=>{let{scheduleTiming:b}=Ra({tournamentRecord:M,event:R});return{[R.eventId]:{event:R,scheduleTiming:b}}})).flat()),h=Ku({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:a,venueIds:u}}),S=h?.dateMatchUps??[],T=h?.completedMatchUps??[],y=[];y.push(...S),y.push(...T);let E={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:e}}]},P=y?.map(({eventId:M,schedule:R,matchUpFormat:b})=>{let{event:O,scheduleTiming:v}=g[M],x=O?.eventType,F={...v,defaultTiming:E,matchUpFormat:b},{averageMinutes:w,recoveryMinutes:L}=xp({eventType:x,timingDetails:F}),{courtId:k,venueId:G}=R,H=zt(R.scheduledTime),K=$r(H,w);return{recoveryMinutes:L,averageMinutes:w,periodLength:s,startTime:H,endTime:K,courtId:k,venueId:G}}),A={calculateStartTimeFromCourts:t,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:a,clearScheduleDates:o,periodLength:s,startTime:c,endTime:p,bookings:P,courts:l},{scheduleTimes:U}=El(A),N=u?.length===1&&u[0]||d?.length===1&&d[0].venueId||void 0,D=y.map(Ue);return{venueId:N,scheduleTimes:U,dateScheduledMatchUpIds:D}}function hR(t){let e=et(t,[{[Re]:!0}]);if(e.error)return e;let{removePriorValues:r,tournamentRecords:n,tournamentId:o,courtDayDate:i,matchUpId:s,courtId:a,drawId:c}=t,u=n[o];if(!u)return{error:q};let{drawDefinition:p,event:m}=jo({tournamentRecord:u,drawId:c});if(!p)return{error:Z};let d=Vt({drawDefinition:p,event:m,matchUpId:s});if(d.error)return d;if(d?.matchUp?.matchUpType===xr){let{itemValue:l}=Zo({timeItems:d.matchUp.timeItems??[],itemType:lo}),f=a&&l.filter(I=>I.courtId!==a);return Zr({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:p,matchUpId:s,timeItem:{itemType:lo,itemValue:f}})}else return as({tournamentRecord:u,drawDefinition:p,courtDayDate:i,courtId:"",matchUpId:s})}function SR({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:r,matchUps:n}){if(!Br(n))return{error:B};if(n.some(({hasContext:g})=>!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Kc};let i=Ku({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(i.error)return i;let{rows:s}=i,a=[],c=g=>[(g.sides||[]).map(I=>[I.participantId,I.participant?.individualParticipantIds]),(g.potentialParticipants||[]).flat().map(I=>[I.participantId,I.individualParticipantIds])].flat(1/0).filter(Boolean),u=s?.reduce((g,I)=>{let h=[],S=[];Object.values(I).forEach(y=>{if(ht(y)&&(y.matchUpId&&(h.push(y.matchUpId),a.push(y)),y.sides)){let E=c(y);S.push(...E)}});let T=Object.values(I).filter(y=>ht(y)&&!y.matchUpId);return g.concat({matchUpIds:h,availableCourts:T,rowId:I.rowId,participantIds:S})},[]);n.filter(({matchUpStatus:g})=>g&&g!=="BYE"&&(t||!ae.includes(g))).sort(xi);let p=an({matchUps:n.concat(a),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,m=[],d=[];for(;n.length&&u.length;){let g=u.shift(),I=[];for(;n.length&&g.availableCourts.length;){let h=n.concat(I).map(D=>D.matchUpId),S=n.shift(),T=S?.matchUpId,y=T&&p[T].matchUpIds.concat(p[T].dependentMatchUpIds),E=T&&h.some(D=>p[T].matchUpIds.includes(D)),P=T&&d.some(D=>p[T].dependentMatchUpIds.includes(D)),A=g.matchUpIds.some(D=>y.includes(D)),U=c(S),N=g.participantIds.some(D=>U.includes(D));if(S&&!A&&!E&&!N&&!P){let D=g.availableCourts.shift();Object.assign(S.schedule,D.schedule),Object.assign(D,S),m.push(S),g.participantIds.push(...U),g.matchUpIds.push(T)}else S&&I.push(S)}n.push(...I),d.push(...g.matchUpIds)}let l=m.map(({matchUpId:g,tournamentId:I,schedule:h,drawId:S})=>({tournamentId:I,matchUpId:g,drawId:S,schedule:{...h,scheduledDate:r}}));return i=Wc({tournamentRecords:e,matchUpDetails:l}),{...i,scheduled:m,notScheduled:n}}function TR(t){let{courtDayDate:e}=t,r=et(t,[{courtAssignments:!0,[He]:Be,[kr]:st},{[Re]:!0}]);if(r.error)return r;let n=t.courtAssignments.reduce((s,a)=>{let{tournamentId:c}=a;return s[c]||(s[c]=[]),s[c].push(a),s},{}),o;return Object.keys(n).every(s=>{let a=t[Re][s];if(!a)return o={error:q},!1;let c=n[s].reduce((p,m)=>{let{drawId:d}=m;return p[d]||(p[d]=[]),p[d].push(m),p},{});Object.keys(c).every(p=>{let{drawDefinition:m}=ze({tournamentRecord:a,drawId:p});return m?(c[p].every(d=>{let{matchUpId:l,courtId:f}=d,g=as({tournamentRecord:a,drawDefinition:m,courtDayDate:e,matchUpId:l,courtId:f});if(g.success)return g?.success;o={error:kA}}),!0):(o={error:Z},!1)})}),o||C}function yR(t){let{tournamentRecords:e,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:o=0,recoveryMinutesMap:i,matchUpPotentialParticipantIds:s={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:p=!0,remainingScheduleTimes:m,clearScheduleDates:d,periodLength:l=30,scheduleDate:f,matchUpIds:g,venueIds:I,startTime:h,endTime:S,dryRun:T}=t,y=et(t,[{[Re]:!0,[mc]:!0},{[tr]:Mr,[kr]:Ye,[db]:!0},{[tr]:V=>!V||!isNaN(V),[Ib]:!1,[kr]:B,[hb]:!1,[Sb]:!1}]);if(y.error)return y;let E=t.competitionMatchUps??Mn({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],P=t.matchUpDependencies??an({includeParticipantDependencies:!0,matchUps:E,tournamentRecords:e}).matchUpDependencies;E.forEach(V=>{V.schedule?.scheduledDate&&zn(f,Ut(V.schedule.scheduledDate))&&ua({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:V})});let A=g.map(V=>E.find($=>$.matchUpId===V)).filter(Boolean),{venueId:U,scheduleTimes:N,dateScheduledMatchUpIds:D}=DI({tournamentRecords:e,remainingScheduleTimes:m,startTime:zt(h),endTime:zt(S),scheduleDate:Ut(f),averageMatchUpMinutes:n,clearScheduleDates:d,periodLength:l,venueIds:I}),M={},R=[],b={},O={},v={};E.filter(({matchUpId:V})=>D?.includes(V)).forEach(V=>{TI({matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUp:V,value:1});let $=V.schedule?.scheduledTime;if($){b[V.matchUpId]=$;let X=i?.[V.matchUpId];Bc({recoveryMinutes:X||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:P,scheduleTime:$,matchUp:V})}});let F=A.filter(V=>{let $=D?.includes(V.matchUpId),X=["BYE",Gt,ge,vr,Me,Bt].includes(V?.matchUpStatus);return!$&&!V.winningSide&&!X}),{matchUpMap:w,overLimitMatchUpIds:L,participantIdsAtLimit:k}=F.reduce((V,$)=>{let{drawId:X,tournamentId:W,matchUpType:it}=$,{participantIdsAtLimit:z,relevantParticipantIds:Q}=Cl({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,matchUpDailyLimits:u,matchUp:$});return z?.length?(V.overLimitMatchUpIds.push($.matchUpId),V.participantIdsAtLimit.push(...z),V):(Q.forEach(ut=>{Ya({individualParticipantProfiles:a,participantId:ut});let ot=a[ut].counters;ot[it]?ot[it]+=1:ot[it]=1,ot[fo]?ot[fo]+=1:ot[fo]=1}),V.matchUpMap[W]||(V.matchUpMap[W]={}),V.matchUpMap[W][X]?V.matchUpMap[W][X].push($):V.matchUpMap[W][X]=[$],ua({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:$}),V)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter(({matchUpId:V})=>!L.includes(V));let G=0,H=N?.length??0,{personRequests:K}=ki({tournamentRecords:e,requestType:Hc});for(;N?.length&&F.length&&G<=H;){G++;let{scheduleTime:V}=N.shift(),$=F.find(X=>{let{matchUpId:W}=X,{dependenciesScheduled:it,remainingDependencies:z}=Nl({matchUpScheduleTimes:b,matchUpDependencies:P,allDateMatchUpIds:r,matchUp:X});if(!it)return v[W]||(v[W]=[]),v[W].push({scheduleTime:V,remainingDependencies:z}),!1;let{enoughTime:Q}=Rl({individualParticipantProfiles:a,matchUpNotBeforeTimes:c,matchUpDependencies:P,scheduleTime:V,matchUp:X});if(!Q)return O[W]||(O[W]=[]),O[W].push({scheduleTime:V}),!1;let{conflicts:ut}=Ml({potentials:p,averageMatchUpMinutes:n,requestConflicts:M,personRequests:K,scheduleTime:V,scheduleDate:f,matchUp:X});if(ut?.length)return!1;let ot=i?.[X.matchUpId];return Bc({recoveryMinutes:ot||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:P,scheduleTime:V,matchUp:X}),b[X.matchUpId]=V,!0});F=F.filter(({matchUpId:X})=>X!==$?.matchUpId),$||R.push(V)}F.forEach(V=>{TI({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,value:-1,matchUp:V})});let Y=[];Object.keys(w).forEach(V=>{let $=e[V];$&&Object.keys(w[V]).forEach(X=>{let{drawDefinition:W}=jo({tournamentRecord:$,drawId:X});W&&w[V][X].forEach(({matchUpId:z})=>{let Q=b[z];if(Q){let ut=Q.split(":").map(oo).join(":"),ot=`${Ut(f)}T${ut}`;T?Y.push(z):(ii({drawDefinition:W,matchUpId:z,scheduledTime:ot}).success&&Y.push(z),U&&la({tournamentRecords:e,tournamentRecord:$,drawDefinition:W,matchUpId:z,venueId:U}))}})})});let j=od(F);return{...C,requestConflicts:Object.values(M),remainingScheduleTimes:N?.map(({scheduleTime:V})=>V),individualParticipantProfiles:a,matchUpNotBeforeTimes:c,participantIdsAtLimit:k,skippedScheduleTimes:R,overLimitMatchUpIds:L,scheduledMatchUpIds:Y,noTimeMatchUpIds:j,recoveryTimeDeferred:O,dependencyDeferred:v}}function ER({tournamentRecords:t,matchUps:e}){if(!Br(e))return{error:no};if(e.some(({matchUpId:f,hasContext:g})=>f&&!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Kc};let r=Math.max(...e.map(({schedule:f})=>f?.courtOrder||1).map(f=>dt(f))),n=tt(1,r+1).map(f=>e.filter(g=>dt(g.schedule?.courtOrder)===f)),o={},i={},s={};n.flat().filter(Boolean).sort(xi).forEach(({schedule:f})=>delete f[fg]);let c=pt(e.map(({drawId:f})=>f)),u=an({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:c}).matchUpDependencies,p=n.map((f,g)=>f.reduce((I,h)=>{if(!h.matchUpId)return I;let{matchUpId:S,winnerMatchUpId:T,loserMatchUpId:y,schedule:E,sides:P,potentialParticipants:A}=h,U=E?.courtId;o[S]=g,i[U]=[],I.matchUpIds.push(S),s[S]=h;let N=u[S].matchUpIds;N.length&&I.sourceMatchUpIds.push(...N);let D=P?.map(R=>[R.participant?.individualParticipantIds,R.participantId]).flat().filter(Boolean)??[],M=A?.flat().map(({individualParticipantIds:R,participantId:b})=>[R,b]).flat().filter(Boolean)||[];return I.participantIds.push(...M,...D),T&&I.targetMatchUpIds.push(T),y&&I.targetMatchUpIds.push(y),I},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),m=(f,g)=>u[f].sources.reduce((I,h,S)=>h.includes(g)&&S+1||I,0),d=p.map(()=>[]),l=(f,g,I,h)=>{if(!s[f].schedule[fg]){s[f].schedule[fg]=g,s[f].schedule[iP]=h,d[o[f]].push({matchUpId:f,issueType:I,issueIds:h,issue:g});let S=s[f].schedule.courtId;i[S]||(i[S]=[]),i[S].push({matchUpId:f,issue:g,issueType:I,issueIds:h})}};return p.forEach((f,g)=>{let I=g?p[g-1]:void 0,h=p.slice(g+1),S={},T=Er(f.participantIds),y=Object.keys(T).filter(A=>T[A]>1),E=f.matchUpIds.filter(A=>u[A].participantIds.some(U=>y.includes(U)));E.forEach(A=>{S[A]||(S[A]={}),S[A][Tc]||(S[A][Tc]=E.filter(U=>U!==A))});let P=I&&f.participantIds.filter(A=>I.participantIds.includes(A));P&&P.forEach(A=>{let U=f.matchUpIds.concat(I.matchUpIds).filter(N=>u[N].participantIds.includes(A));U.forEach(N=>{S[N]||(S[N]={}),S[N][yc]||(S[N][yc]=U.filter(D=>D!==N))})}),f.matchUpIds.forEach(A=>{let U=u[A].matchUpIds;for(let D of h){let M=D.matchUpIds.filter(R=>U.includes(R));M?.length&&(M.forEach(R=>l(R,yS,Ca,[A])),l(A,yS,Ca,M))}if(S[A]?.[Tc]&&l(A,Tc,TS,S[A][Tc]),f.sourceMatchUpIds.includes(A)){let D=f.matchUpIds.filter(M=>u[M].matchUpIds.includes(A));l(A,Tc,Ca,D),f.matchUpIds.filter(M=>u[M].matchUpIds.includes(A)).forEach(M=>l(M,Tc,Ca,[A]))}let N=I?.matchUpIds?.filter(D=>m(A,D)>1);if(N?.length&&(l(A,ES,Ca,N),N.forEach(D=>l(D,ES,Ca,[A]))),S[A]?.[yc]&&l(A,yc,TS,S[A][yc]),I?.targetMatchUpIds?.includes(A)){let D=s[A].schedule.courtId,M=U.filter(b=>I.matchUpIds.includes(b));M.some(b=>s[b].schedule.courtId===D)||(M.forEach(b=>l(b,yc,Ca,[A])),l(A,yc,Ca,M))}})}),{courtIssues:i,rowIssues:d}}function AR(t){let e="reorderUpcomingMatchUps",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return _({result:{error:xt},stack:e});let{matchUpsContextIds:n,firstToLast:o}=t;if(!n)return _({result:{error:st},stack:e});let i=n?.length;if(!i)return{...C};let s=0;return n.forEach((c,u)=>{let{tournamentId:p,drawId:m,matchUpId:d}=c,l=u+(o?-1:1);l<0&&(l=i-1),l===i&&(l=0);let f=n[l].schedule.scheduledTime,g=a({tournamentId:p,scheduledTime:f,matchUpId:d,drawId:m});if(g.success)s++;else return g}),s===i?C:_({result:{error:FA},stack:e});function a({tournamentId:c,scheduledTime:u,matchUpId:p,drawId:m}){let d=r[c],{drawDefinition:l}=jo({tournamentRecord:d,drawId:m});return l?ii({drawDefinition:l,scheduledTime:u,matchUpId:p}):{error:br}}}function UR(t){let{scheduleChange:e,matchUpIds:r,dryRun:n}=t;if(!r||!Array.isArray(r))return{error:ps};if(typeof e!="object")return{error:B};let o=Rr(t),i=[],s=[];for(let c of Object.values(o)){let u=tB({tournamentRecord:c,scheduleChange:e,matchUpIds:r,dryRun:n});if(u.error)return u;Array.isArray(u.notRescheduled)&&s.push(...u.notRescheduled);let p=od(u.notRescheduled),m=[];u.rescheduled?.forEach(d=>{let{matchUpId:l}=d;p.includes(l)&&m.push(l),i.push(d)}),m.length&&(s=u?.notRescheduled?.filter(({matchUpId:d})=>!m.includes(d))||[])}let a=!!(i.length&&!s.length);return{...C,rescheduled:i,notRescheduled:s,allRescheduled:a}}function tB({tournamentRecord:t,scheduleChange:e,matchUpIds:r,dryRun:n}){if(!t)return{error:q};if(!r||!Array.isArray(r))return{error:ps};if(typeof e!="object")return{error:B};let o=[],i=[],{minutesChange:s,daysChange:a}=e;if(!s&&!a)return{...C};if(s&&isNaN(s))return{error:B};if(a&&isNaN(a))return{error:B};let{matchUps:c}=ye({matchUpFilters:{matchUpIds:r},tournamentRecord:t}),u=({matchUpStatus:y})=>!ae.includes(y),p=c?.filter(y=>Ha({schedule:y.schedule})).filter(y=>u({matchUpStatus:y.matchUpStatus}));if(!p?.length)return{...C};let{tournamentInfo:m}=bs({tournamentRecord:t}),{startDate:d,endDate:l}=m,f=p?.reduce((y,E)=>{let{matchUpId:P,drawId:A}=E;return y[A]?y[A].push(P):y[A]=[P],y},{}),g=1440;for(let y of Object.keys(f)){let E=jo({tournamentRecord:t,drawId:y});if(E.error)return E;let P=E.drawDefinition,A=f[y].filter(U=>r.includes(U));for(let U of A)if(U&&P){let D=p.find(x=>x.matchUpId===U)?.schedule,{scheduledTime:M,scheduledDate:R}=D,b,O,v;if(!b&&a&&R){let x=Ut(R);v=Ip(x,a),b=new Date(v)<new Date(d)||new Date(v)>new Date(l)}if(s&&M){let x=Ut(M),w=Yt(zt(M))+s;if(b=w<0||w>g,!b){let L=$r(M,s),k=x&&v||R===x&&x;O=k?`${k}T${L}`:L}}if(b)i.push(U);else{if(!n){if(O){let x=ii({scheduledTime:O,drawDefinition:P,matchUpId:U});if(x.error)return x}if(v){let x=fm({scheduledDate:v,drawDefinition:P,matchUpId:U});if(x.error)return x}}(O||v)&&o.push(U)}}}let I=ye({matchUpFilters:{matchUpIds:r},tournamentRecord:t}).matchUps??[],h=I.filter(({matchUpId:y})=>o.includes(y)),S=I.filter(({matchUpId:y})=>i.includes(y)),T=h.length&&!S.length;return{...C,rescheduled:h,notRescheduled:S,allRescheduled:T}}function PR(t){let e="matchUpScheduleChange",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return{error:xt};let{sourceMatchUpContextIds:n,targetMatchUpContextIds:o,sourceCourtId:i,targetCourtId:s,courtDayDate:a}=t||{},{drawId:c,matchUpId:u,tournamentId:p}=n||{},{drawId:m,matchUpId:d,tournamentId:l}=o||{};if(!u&&!d)return _({result:{error:st},stack:e});let{matchUps:f}=Mn({matchUpFilters:{matchUpIds:[u,d].filter(Boolean),drawIds:[c,m].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=f?.find(({matchUpId:y})=>y===u),I=f?.find(({matchUpId:y})=>y===d),h=0;if(s&&u&&!d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y?.success&&h++,y.error)return _({result:y,stack:e})}else if(i&&s&&u&&d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y.success&&h++,y.error)return _({result:y,stack:e,info:"source"});let E=S({tournamentId:l,sourceCourtId:s,matchUpId:d,matchUp:I,courtId:i,drawId:m,tournamentRecords:r,courtDayDate:a});if(E.success&&h++,E.error)return _({result:E,stack:e,info:"target"})}else return{error:st};return h?C:_({result:{error:Bs},stack:e});function S(y){let{tournamentRecords:E,tournamentId:P,matchUp:A,drawId:U}=y,N=E[P],{drawDefinition:D}=jo({tournamentRecord:N,drawId:U});return A.matchUpType===Wt?T({...y,tournamentRecord:N,drawDefinition:D}):as({...y,tournamentRecord:N,drawDefinition:D})}function T({removePriorValues:y,tournamentRecords:E,tournamentRecord:P,drawDefinition:A,sourceCourtId:U,courtDayDate:N,matchUpId:D,matchUp:M,courtId:R}){let b=[R].concat(M.schedule.allocatedCourts.map(({courtId:O})=>O).filter(O=>O!==U));return gm({removePriorValues:y,tournamentRecords:E,tournamentRecord:P,drawDefinition:A,courtDayDate:N,matchUpId:D,courtIds:b})}}function DR({scheduleAttributes:t=[lo,Jo,Ji,Zi,ts,Bo,vi,Oi,es],tournamentRecord:e,drawDefinition:r,matchUpId:n}){let o="clearMatchUpSchedule",i=r?nr({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:ye({matchUpFilters:{matchUpIds:[n]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:we};let s=(i.timeItems??[]).filter(a=>a?.itemType&&!t.includes(a?.itemType));return i.timeItems=s,gt({tournamentId:e.tournamentId,context:o,drawDefinition:r,matchUp:i}),{...C}}function NR(t){let{tournamentRecord:e,tournamentId:r,dailyLimits:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="object"||!Object.keys(o).length)return{error:xt};if(typeof n!="object")return{error:So};let i=Object.keys(o).filter(s=>!r||r===s);if(r&&!i.includes(r))return{error:B};for(let s of i){let a=o[s],c=At({extension:{name:lu,value:{dailyLimits:n}},element:a});if(c.error)return c}return{...C}}var kR={};Xt(kR,{addCollectionDefinition:()=>RI,addCollectionGroup:()=>_R,aggregateTieFormats:()=>LR,compareTieFormats:()=>ni,getTieFormat:()=>al,modifyCollectionDefinition:()=>NI,modifyTieFormat:()=>wR,mutate:()=>FR,orderCollectionDefinitions:()=>vR,query:()=>EN,removeCollectionDefinition:()=>MI,removeCollectionGroup:()=>bR,tieFormatGenderValidityCheck:()=>km,validateCollectionDefinition:()=>eu});var FR={};Xt(FR,{addCollectionDefinition:()=>RI,addCollectionGroup:()=>_R,aggregateTieFormats:()=>LR,modifyCollectionDefinition:()=>NI,modifyTieFormat:()=>wR,orderCollectionDefinitions:()=>vR,removeCollectionDefinition:()=>MI,removeCollectionGroup:()=>bR});function Ii({drawDefinition:t,structureId:e,matchUpId:r,structure:n,matchUp:o,eventId:i,event:s}){let a="getTieFormat",c;if(e=n?.structureId??e,r=o?.matchUpId??r,(r||e)&&!t)return{error:Z};if(i&&s)c=di(s);else if(r){if(t&&(!o||!n)){let u=Vt({drawDefinition:t,matchUpId:r});if(u.error)return u;if(u.matchUp?.matchUpType!==xr)return _({result:{error:dr},stack:a});n||(n=u.structure),o||(o=u.matchUp)}c=Cp({item:o,drawDefinition:t,structure:n,event:s})||Cp({item:n,drawDefinition:t,structure:n,event:s})||di(t)||di(s)}else if(t&&e){if(!n){let u=at({drawDefinition:t,structureId:e});if(u.error)return u;n=u?.structure}c=Cp({item:n,drawDefinition:t,structure:n,event:s})||di(t)||di(s)}else c=di(t)||di(s);return c?{...C,structure:n,tieFormat:c,matchUp:o}:_({result:{error:ks},stack:a})}function wl({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![ae].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Hn&&!he(t))}function CR({from:t,to:e}){let r=Object.keys(t),n=jt(r,Object.keys(e)).length===r.length,i=r.filter(c=>t[c]!==e[c]).map(c=>({countChange:e[c]-t[c],collectionId:c})),s=r.every(c=>t[c]===e[c]);return{equivalent:n&&s,matchUpsCountChanges:i}}function Rw({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,structure:n,tieFormat:o,eventId:i,matchUp:s,event:a,uuids:c}){let u="updateTieFormat",p=e?.tournamentId,m=0,d=0,l=0,f=0,g=o?.collectionDefinitions.reduce((P,A)=>(P[A.collectionId]=(P[A.collectionId]||0)+A.matchUpCount,P),{}),I=({tieFormat:P})=>{let A=P?.collectionDefinitions.reduce((U,N)=>(U[N.collectionId]=(U[N.collectionId]||0)+N.matchUpCount,U),{});return CR({from:A,to:g}).equivalent},h=Ii({drawDefinition:r})?.tieFormat,S=Ii({event:a})?.tieFormat;if(a&&i){for(let P of a.drawDefinitions??[])T({drawDefinition:P});a.tieFormat=or(o),f+=1}else if(s){if(!s.tieMatchUps)return _({result:{error:dr},stack:u});let P=Er(s.tieMatchUps?.map(({collectionId:M})=>M)),A=CR({to:g,from:P}),{changes:U,changesArePossible:N,cannotChangeReaon:D}=Mw({matchUp:s,check:A});if(A.equivalent)if(wl({matchUp:s,updateInProgressMatchUps:t}))s.tieFormat=or(o),f+=1;else return _({result:{error:nf},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});else if(N)E({tieFormat:o,matchUp:s,changes:U,uuids:c});else return _({context:{collectionMap:g,matchUpMap:P},result:{error:Yo},info:D||"specified changes not possible",stack:u});d+=1,gt({eventId:a?.eventId,context:u,drawDefinition:r,tournamentId:p,matchUp:s})}else if(n){let A=y({inheritedTieFormat:h??S,structure:n})?.modifiedMatchUpsCount;A&&(d+=A,m+=1,f+=1);let U=!n.tieFormat||ni({ancestor:n.tieFormat,descendant:o}).different;U&&(n.tieFormat=or(o),m+=1,f+=1),(A||U)&&r&&bt({structureIds:[n.structureId],eventId:a?.eventId,drawDefinition:r})}else if(r)T({drawDefinition:r}),r.tieFormat=or(o),f+=1;else return{error:Z};return{modifiedStructuresCount:m,modifiedMatchUpsCount:d,addedMatchUpsCount:l,modifiedCount:f,...C,tieFormat:o};function T({drawDefinition:P}){let A=P.structures||[],U=[];for(let N of A){if(N.tieFormat)continue;let M=y({inheritedTieFormat:S,structure:N})?.modifiedMatchUpsCount;if(M){m+=1,d+=M;let R=N.structureId;U.push(R)}}return bt({structureIds:U,eventId:a?.eventId,drawDefinition:P}),U.length}function y({inheritedTieFormat:P,structure:A}){let U=0,N=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:A})?.matchUps||[];for(let D of N){let M=wl({matchUp:D,updateInProgressMatchUps:t}),R=!1,b=Er(D.tieMatchUps?.map(({collectionId:v})=>v)),O=CR({from:b,to:g});if(O.equivalent)D.tieFormat&&I(D)&&M&&(D.tieFormat=or(o),R=!0);else{let{changes:v,changesArePossible:x}=Mw({matchUp:D,check:O});if(x&&!D.tieFormat)E({changes:v,matchUp:D,tieFormat:o,uuids:c});else if(P)(!D.tieFormat||ni({ancestor:P,descendant:D.tieFormat}).different)&&(D.tieFormat=P,R=!0);else return _({result:{error:ks},stack:u})}R&&(U+=1,gt({tournamentId:e?.tournamentId,drawDefinition:r,context:u,eventId:i,matchUp:D}))}return{modifiedMatchUpsCount:U}}function E({uuids:P,matchUp:A,tieFormat:U,changes:N}){A.tieFormat=or(U);let D=[],M=[];return N.forEach(R=>{if(R.countChange>0){let b=Math.max(0,...A.tieMatchUps.filter(x=>x.collectionId===R.collectionId).map(Hr("collectionPosition"))),O=U.collectionDefinitions.find(x=>x.collectionId===R.collectionId),v=wu({matchUpsLimit:R.countChange,collectionPositionOffset:b,collectionDefinition:O,matchUp:A,uuids:P});M.push(...J(v,!1,!0)),l+=M.length,A.tieMatchUps.push(...v)}else{let b=R.toBePlayedTieMatchUpIds.slice(0,Math.abs(R.countChange));console.log("remove",b.length),D.push(...b),A.tieMatchUps=A.tieMatchUps.filter(({matchUpId:O})=>!b.includes(O))}}),M.length&&Fo({matchUps:M,drawDefinition:r,tournamentId:p,eventId:i}),D.length&&_n({matchUpIds:D,action:"updateTieFormat",drawDefinition:r,tournamentId:p,eventId:i}),{matchUpIdsRemoved:D,matchUpsAdded:M}}}function Mw({check:t,matchUp:e}){let r="",n=[];return{changesArePossible:t.matchUpsCountChanges.every(({collectionId:i,countChange:s})=>{let a=e.tieMatchUps.filter(u=>u.collectionId===i&&u.matchUpStatus===Qt).map(Hr("matchUpId")),c=a.length+s>=0||s>0;return!c&&s<0&&(r="Insufficient TO_BE_PLAYED matchUps"),n.push({toBePlayedTieMatchUpIds:a,collectionId:i,countChange:s}),c}),changes:n,cannotChangeReaon:r}}function Ju({appliedPolicies:t,drawDefinition:e,auditData:r}){if(!t?.audit?.[nd])return;let{extension:n}=mt({name:nd,element:e}),o={value:Array.isArray(n?.value)?n?.value.concat(r):[r],name:nd};At({element:e,extension:o})}function NI({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:r,collectionName:n,tieFormatName:o,drawDefinition:i,matchUpFormat:s,matchUpCount:a,collectionId:c,matchUpType:u,structureId:p,matchUpId:m,category:d,eventId:l,gender:f,event:g,collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y}){let E="modifyCollectionDefinition";if(s&&!Nr({matchUpFormat:s}))return _({result:{error:B},context:{matchUpFormat:s},stack:E});if(n&&typeof n!="string")return _({result:{error:B},context:{collectionName:n},stack:E});if(f&&!Object.values(Fm).includes(f))return _({result:{error:B},context:{gender:f},stack:E});if(d&&typeof d!="object")return _({result:{error:B},context:{category:d},stack:E});let P={collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y};if(!Object.values(P).filter(Boolean).length&&!r&&!n&&!s&&!a&&!u)return _({result:{error:st},stack:E});if(Object.values(P).filter(Boolean).length>1)return _({info:"Only one value assignment allowed per collectionDefinition",result:{error:B},stack:E});let A=Ii({drawDefinition:i,structureId:p,matchUpId:m,eventId:l,event:g});if(A.error)return _({result:A,stack:E});let{matchUp:U,structure:N,tieFormat:D}=A,M=or(D),R=D?.collectionDefinitions.find(Y=>Y.collectionId===c),b=M?.collectionDefinitions.find(Y=>Y.collectionId===c);if(!R)return _({info:"source collectionDefinition",result:{error:Oe},context:{collectionId:c},stack:E});let O=h??S??T??y;if(I?.length){let Y=GI({matchUpCount:a??R?.matchUpCount??0,collectionValueProfiles:I});if(Y.errors)return _({result:{error:B},info:Y.errors,stack:E})}else if(O&&!It(O))return _({result:{error:B},info:"value is not an integer",context:{value:O},stack:E});let v=(Y,j)=>jt(Object.keys(Y),Object.keys(j)).length===Object.keys(Y).length&&jt(Object.values(Y),Object.values(j)).length===Object.values(Y).length,x=I&&(!R.collectionValueProfiles||!v(R.collectionValueProfiles,I)),F=It(h)&&R.collectionValue!==h||It(S)&&R.matchUpValue!==S||It(T)&&R.scoreValue!==T||It(y)&&R.setValue!==y||x,w=[];if(F&&(b.collectionValueProfiles=void 0,b.collectionValue=void 0,b.matchUpValue=void 0,b.scoreValue=void 0,b.setValue=void 0,Object.assign(b,P),w.push({collectionId:c,...nt(P)})),(It(T)||It(y))&&b.collectionGroupNumber){let Y=b.collectionGroupNumber;M.collectionDefinitions=M.collectionDefinitions.map(j=>{let{collectionGroupNumber:V,...$}=j;return V===Y?$:j}),M.collectionGroups=M.collectionGroups.filter(({groupNumber:j})=>j!==Y),w.push({collectionId:c,change:"collectionGroupNumber removed"})}let{aggregateValue:L,valueGoal:k}=Os(M),G=nt({aggregateValue:L,valueGoal:k});if((G.aggregateValue!==D?.winCriteria.aggregateValue||G.valueGoal!==D?.winCriteria.valueGoal)&&(M.winCriteria=G,w.push({collectionId:c,winCriteria:G})),It(r)&&R.collectionOrder!==r&&(b.collectionOrder=r,w.push({collectionId:c,collectionOrder:r})),n&&R.collectionName!==n&&(b.collectionName=n,w.push({collectionId:c,collectionName:n})),s&&R.matchUpFormat!==s&&(b.matchUpFormat=s,w.push({collectionId:c,matchUpFormat:s})),It(a)&&R.matchUpCount!==a&&(b.matchUpCount=a,w.push({collectionId:c,matchUpCount:a})),u&&R.matchUpType!==u)return _({result:{error:pp},context:{matchUpType:u},stack:E});d&&R.category!==d&&(b.category=d,w.push({collectionId:c,category:d})),f&&R.gender!==f&&(b.gender=f,w.push({collectionId:c,gender:f}));let H=nt(M);if(A=ar({tieFormat:H}),A.error)return _({result:A,stack:E});if(!w.length)return _({result:{...C,modifications:w}});if(D?.tieFormatName!==o?(H.tieFormatName=o,w.push({tieFormatName:o})):w.length&&(delete H.tieFormatName,w.push("tieFormatName removed: modifications without new tieFormatName")),A=Rw({tieFormat:H,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:i,structure:N,eventId:l,matchUp:U,event:g}),!A.error){let{appliedPolicies:Y}=Tt({tournamentRecord:e}),j=nt({collectionDefinition:b,drawId:i?.drawId,action:E,structureId:p,matchUpId:m,eventId:l});Ju({appliedPolicies:Y,drawDefinition:i,auditData:j})}return _({result:{...A,modifications:w},stack:E})}function Cw({updateInProgressMatchUps:t,drawDefinition:e,structureId:r,structure:n,matchUpId:o,matchUp:i}){let s=[];return o&&i?s=[i]:r&&n?s=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:n})?.matchUps??[]:e&&(s=nr({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:s.filter(c=>!c.winningSide&&c.matchUpStatus!==ge&&(t||c.matchUpStatus!==Hn&&!he(c)))}}function bw({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUps:n,tieFormat:o,event:i}){for(let s of n){let a=!!s.tieFormat;a&&(s.tieFormat=or(o));let c;if(t){let u=Tt({tournamentRecord:e,drawDefinition:r,event:i}).appliedPolicies,p=go({matchUpId:s.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:u,drawDefinition:r,event:i});if(p.error)return p;c=p.score}a&&!c&>({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:i?.eventId,matchUp:s,drawDefinition:r})}return{...C}}function DE({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:r,wasAggregateValue:n,tieFormatName:o,drawDefinition:i,structureId:s,structure:a,tieFormat:c,matchUpId:u,matchUp:p,eventId:m,event:d}){let{aggregateValue:l,valueGoal:f}=Os(c);c.winCriteria=nt({aggregateValue:l,valueGoal:f}),(e&&e!==f||l&&!n)&&(o?c.tieFormatName=o:delete c.tieFormatName);let{targetMatchUps:g}=Cw({updateInProgressMatchUps:t,drawDefinition:i,structureId:s,structure:a,matchUpId:u,matchUp:p});bw({updateInProgressMatchUps:t,tournamentRecord:r,targetMatchUps:g,drawDefinition:i,tieFormat:c,event:d});let I=nt(c),h=ar({tieFormat:I});if(h.error)return h;if(m&&d)d.tieFormat=I;else if(u&&p)p.tieFormat=c;else if(a)a.tieFormat=I;else if(i)i.tieFormat=I;else if(!p||!i)return{error:Z};return bt({drawDefinition:i,eventId:d?.eventId}),{...C}}function bR({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,matchUpId:s,matchUp:a,eventId:c,event:u}){if(!e)return{error:st};if(isNaN(e))return{error:B};let p="removeCollectionGroup",m=a?void 0:Ii({drawDefinition:n,structureId:i,matchUpId:s,eventId:c,event:u});if(m?.error)return _({result:m,stack:p});let d=m?.structure;a=a??m?.matchUp;let l=m?.tieFormat,f=l?.winCriteria.valueGoal,g=l?.winCriteria.aggregateValue,I=or(l);if(m=ar({tieFormat:I}),m.error)return _({result:m,stack:p});let h=[];if(I.collectionDefinitions=I.collectionDefinitions.map(S=>{let{collectionGroupNumber:T,...y}=S;return T!==e?S:(h.push(S.collectionId),y)}),I.collectionGroups=I.collectionGroups.filter(({groupNumber:S})=>S!==e),m=DE({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:g,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,structure:d,tieFormat:I,matchUpId:s,matchUp:a,eventId:c,event:u}),!m.error){let{appliedPolicies:S}=Tt({tournamentRecord:r}),T=nt({drawId:n?.drawId,collectionGroupNumber:e,action:p,structureId:i,matchUpId:s,eventId:c});Ju({appliedPolicies:S,drawDefinition:n,auditData:T})}return _({result:{...m,modifiedCollectionIds:h},stack:p})}function Ll({tieFormat:t,orderMap:e}){let r=or(t);return r.collectionDefinitions?.forEach(n=>{let o=e[n.collectionId];o&&(n.collectionOrder=o)}),r.collectionDefinitions?.sort((n,o)=>za(n.collectionOrder)-za(o.collectionOrder)),r}function vR({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,orderMap:o,eventId:i,matchUp:s,event:a}){if(typeof o!="object"||!Object.values(o).every(p=>It(p)))return _({result:{error:B},context:{orderMap:o}});let c=r?at({drawDefinition:e,structureId:r}):void 0;if(c?.error)return c;let u=c?.structure;if(i&&a?.tieFormat)Ow({tournamentRecord:t,event:a,orderMap:o});else if(n){let p=e&&Vt({drawDefinition:e,matchUpId:n});if(p?.error)return p;if(s=p.matchUp,!s)return{error:mr};let m=al({tournamentRecord:t,matchUpId:n,structure:u,drawDefinition:e,event:a})?.tieFormat;s.tieFormat=Ll({tieFormat:m,orderMap:o}),gt({tournamentId:t?.tournamentId,eventId:a?.eventId,drawDefinition:e,matchUp:s})}else if(r)if(u?.tieFormat)u.tieFormat=Ll({tieFormat:u.tieFormat,orderMap:o}),vw({eventId:a?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:o}),bt({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)OR({structureIds:[r],tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else if(a?.tieFormat)Ow({structureIds:[r],tournamentRecord:t,orderMap:o,event:a});else return{error:Oe};else if(e?.tieFormat)OR({tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else return{error:Oe};return{...C}}function Ow({tournamentRecord:t,structureIds:e,orderMap:r,event:n}){let o=Ll({tieFormat:n.tieFormat,orderMap:r});e?.length||(n.tieFormat=o);for(let i of n.drawDefinitions??[])OR({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:r,event:n})}function OR({tournamentRecord:t,drawDefinition:e,structureIds:r,orderMap:n,event:o}){let i=e.tieFormat??o?.tieFormat,s=Ll({tieFormat:i,orderMap:n});r?.length||(e.tieFormat=s);let a=[];for(let c of e.structures??[])r?.length&&!r.includes(c.structureId)||((c.tieFormat||r?.includes(c.structureId))&&(c.tieFormat=Ll({tieFormat:c.tieFormat??e.tieFormat??o?.tieFormat,orderMap:n})),vw({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,structure:c,orderMap:n}),a.push(c.structureId));bt({drawDefinition:e,structureIds:a})}function vw({tournamentRecord:t,drawDefinition:e,structure:r,orderMap:n,eventId:o}){let i=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:r})?.matchUps;for(let s of i)s.tieFormat&&(s.tieFormat=Ll({tieFormat:s.tieFormat,orderMap:n}),gt({tournamentId:t?.tournamentId,drawDefinition:e,eventId:o,matchUp:s}))}function MI({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,collectionId:i,structureId:s,matchUpId:a,eventId:c,matchUp:u,event:p}){let m="removeCollectionDefinition",d=u?void 0:Ii({drawDefinition:n,structureId:s,matchUpId:a,eventId:c,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;u=u??d?.matchUp;let f=d?.tieFormat,g=or(f);if(d=ar({tieFormat:g}),d.error)return _({result:d,stack:m});let I=g?.collectionDefinitions?.find(M=>M.collectionId===i);if(!I)return _({result:{error:Oe,collectionId:i}});g.collectionDefinitions=g.collectionDefinitions.filter(M=>M.collectionId!==i),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(M=>{let{collectionGroupNumber:R,...b}=M;return b}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:M})=>M!==I.collectionGroupNumber));let{aggregateValue:h,valueGoal:S}=Os(g);g.winCriteria=nt({aggregateValue:h,valueGoal:S});let T=f?.winCriteria.valueGoal,y=f?.winCriteria.aggregateValue;(T&&T!==S||h&&!y)&&(o?g.tieFormatName=o:delete g.tieFormatName);let E=[];a&&u?E=[u]:s&&l?E=yt({matchUpFilters:{matchUpTypes:[Wt]},structure:l})?.matchUps??[]:n?E=nr({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:n})?.matchUps??[]:p&&(E=to({matchUpFilters:{matchUpTypes:[Wt]},drawDefinition:n})?.matchUps??[]);let P=(E||[]).filter(M=>{let b=M.tieMatchUps?.filter(v=>v.collectionId===i)?.some(he),O=e&&M.tieFormat?ni({descendant:M.tieFormat,ancestor:g})?.different:!1;return t&&!b||!M.winningSide&&M.matchUpStatus!==ge&&(t||M.matchUpStatus!==Hn&&!he(M)&&!O)});if(!P.length)return{error:Bs};let{appliedPolicies:A}=Tt({tournamentRecord:r});if(a&&u&&t){let M=u.tieMatchUps?.filter(R=>R.collectionId===i);for(let R of M??[]){let b=ws({matchUpId:R.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:r,appliedPolicies:A,drawDefinition:n,event:p});if(b.error||(b=Vt({drawDefinition:n,matchUpId:a}),b.error))return b;u=b?.matchUp}}let U=[];for(let M of P){for(let R of M?.sides??[])R.lineUp=(R.lineUp??[]).map(b=>({participantId:b.participantId,collectionAssignments:(b?.collectionAssignments??[]).filter(O=>O.collectionId!==i)}));if(M.tieMatchUps=(M.tieMatchUps??[]).filter(R=>{let b=R.collectionId===i;return b&&U.push(R.matchUpId),!b}),M.tieFormat&&(M.tieFormat=or(g)),t){let R=go({matchUpId:M.matchUpId,exitWhenNoValues:!0,tournamentRecord:r,appliedPolicies:A,drawDefinition:n,event:p});if(R.error)return R}gt({tournamentId:r?.tournamentId,eventId:p?.eventId,drawDefinition:n,context:m,matchUp:M})}U.length&&_n({tournamentId:r?.tournamentId,matchUpIds:U,eventId:p?.eventId,drawDefinition:n});let N=nt(g);if(d=ar({tieFormat:N}),d.error)return _({result:d,stack:m});if(c&&p)p.tieFormat=N;else if(a&&u)u.tieFormat=N;else if(l)l.tieFormat=N;else if(n)n.tieFormat=N;else if(!u||!n)return{error:Z};bt({drawDefinition:n,eventId:p?.eventId});let D=nt({drawId:n?.drawId,action:m,collectionId:i,structureId:s,matchUpId:a,eventId:c});return Ju({appliedPolicies:A,drawDefinition:n,auditData:D}),{tieFormat:N,deletedMatchUpIds:U,targetMatchUps:P,...C}}function _R({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:r,drawDefinition:n,collectionIds:o,tieFormatName:i,structureId:s,matchUpId:a,matchUp:c,eventId:u,event:p}){let m="addCollectionGroup";if(!Array.isArray(o))return _({result:{error:st},stack:m});let d=c?void 0:Ii({drawDefinition:n,structureId:s,matchUpId:a,eventId:u,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;c=c||d?.matchUp;let f=d?.tieFormat,g=f?.winCriteria.valueGoal,I=or(f);if(d=ar({tieFormat:I}),d.error)return _({result:d,stack:m});for(let T of I.collectionDefinitions){let{collectionId:y,collectionGroupNumber:E}=T;if(E&&o.includes(y))return _({info:"collectionIds cannot be part of other collectionGroups",result:{error:B},stack:m})}let S=(I.collectionGroups||[]).reduce((T,y)=>y.groupNumber>T?y.groupNumber:T,0)+1;return r.groupNumber=S,I.collectionDefinitions=I.collectionDefinitions.map(T=>o.includes(T.collectionId)?{...T,collectionGroupNumber:S}:T),I.collectionGroups=[...I.collecitonGroups||[],r],DE({updateInProgressMatchUps:t,originalValueGoal:g,tournamentRecord:e,drawDefinition:n,tieFormatName:i,structureId:s,structure:l,tieFormat:I,matchUpId:a,matchUp:c,eventId:u,event:p})}function RI({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:r,tournamentRecord:n,policyDefinitions:o,enforceCategory:i,referenceGender:s,drawDefinition:a,tieFormatName:c,enforceGender:u,structureId:p,matchUpId:m,matchUp:d,eventId:l,uuids:f,event:g}){let I="addCollectionDefinition",h=Tt({tournamentRecord:n,drawDefinition:a,event:g}).appliedPolicies??{},S=o?.[er]??h?.[er];i=i??S?.participants?.enforceCategory;let T=(u??S?.participants?.enforceGender)!==!1,y=!!((r??g?.category)&&i!==!1),E=!!((s??g?.gender)&&T),P=eu({referenceCategory:r??g?.category,collectionDefinition:e,referenceGender:s,checkCategory:y,checkGender:E,event:g});if(P.error)return _({result:P,stack:I});let A=d?.tieFormat?void 0:Ii({drawDefinition:a,structureId:p,matchUpId:m,eventId:l,event:g});if(A?.error)return _({result:{error:A.error},stack:I});let U=A?.structure;d=d??A?.matchUp;let N=d?.tieFormat??A?.tieFormat,D=or(N);if(A=ar({tieFormat:D}),A?.error)return _({result:{error:A.error},stack:I});if(!e.collectionId)e.collectionId=Nt();else if(D.collectionDefinitions.map(({collectionId:G})=>G).includes(e.collectionId))return _({context:{collectionId:e.collectionId},result:{error:BA}});D.collectionDefinitions.push(e),D.collectionDefinitions.sort((k,G)=>(k.collectionOrder||0)-(G.collectionOrder||0)).forEach((k,G)=>k.collectionOrder=G+1);let{aggregateValue:M,valueGoal:R}=Os(D);D.winCriteria=nt({aggregateValue:M,valueGoal:R});let b=N?.winCriteria.valueGoal,O=N?.winCriteria.aggregateValue;(b&&b!==R||M&&!O)&&(c?D.tieFormatName=c:delete D.tieFormatName);let v=[],x=[],F=[],w=nt(D);if(A=ar({tieFormat:w}),A?.error)return _({result:{error:A.error},stack:I});if(l&&g){g.tieFormat=w;for(let k of g.drawDefinitions??[])if(!k.tieFormat)for(let G of k.structures??[]){if(G.tieFormat)continue;let H=xR({updateInProgressMatchUps:t,collectionDefinition:e,structure:G,uuids:f});x.push(...H.newMatchUps),F.push(...H.targetMatchUps),v.push(G.structureId)}NE({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:v,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(p&&U){U.tieFormat=w;let k=xR({updateInProgressMatchUps:t,collectionDefinition:e,structure:U,uuids:f});x.push(...k.newMatchUps),F=k.targetMatchUps,NE({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:v,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(m&&d){if(!wl({matchUp:d,updateInProgressMatchUps:t}))return _({result:{error:nf},stack:I});d.tieFormat=w;let k=wu({collectionDefinition:e,matchUp:d,uuids:f});Array.isArray(d.tieMatchUps)||(d.tieMatchUps=[]),d.tieMatchUps.push(...k),x.push(...k),NE({modifiedMatchUps:[d],eventId:g?.eventId,modifiedStructureIds:v,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(a){a.tieFormat=w;for(let k of a.structures??[]){let G=xR({updateInProgressMatchUps:t,collectionDefinition:e,structure:k,uuids:f});v.push(k.structureId),x.push(...G.newMatchUps),F.push(...G.targetMatchUps)}NE({modifiedMatchUps:F,eventId:g?.eventId,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else return{error:Z};let L=nt({drawId:a?.drawId,collectionDefinition:e,action:I,structureId:p,matchUpId:m,eventId:l});return Ju({appliedPolicies:h,drawDefinition:a,auditData:L}),{tieFormat:w,targetMatchUps:F,addedMatchUps:x,...C}}function xR({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:n}){let o=[],s=(yt({matchUpFilters:{matchUpTypes:[Wt]},structure:r})?.matchUps).filter(a=>wl({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat);for(let a of s){let c=wu({collectionDefinition:e,matchUp:a,uuids:n});Array.isArray(a.tieMatchUps)||(a.tieMatchUps=[]),a.tieMatchUps.push(...c),o.push(...c)}return{newMatchUps:o,targetMatchUps:s}}function NE({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:o,eventId:i,stack:s}){Fo({tournamentId:e?.tournamentId,matchUps:o,drawDefinition:n,eventId:i}),r?.forEach(a=>{gt({tournamentId:e?.tournamentId,drawDefinition:n,context:s,matchUp:a,eventId:i})}),bt({structureIds:t,drawDefinition:n,eventId:i})}function wR({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:r,tournamentRecord:n,considerations:o,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,uuids:u,event:p}){let m="modifyTieFormat";if(!ar({tieFormat:r}).valid)return _({result:{error:Yo},info:"falied validation",stack:m});let d=Ii({drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(d.error)return _({result:d,stack:m});let{matchUp:l,tieFormat:f}=d,g=or(f),I=ni({descendant:r,ancestor:g,considerations:o});if(I.invalid)return _({context:{invalid:I.invalid},result:{error:Yo},stack:m});if(!I?.different)return _({result:{...C},info:"Nothing to do",stack:m});let h=g.collectionDefinitions.map(({collectionId:D})=>D),S=r.collectionDefinitions.map(({collectionId:D})=>D),T=h.filter(D=>!S.includes(D)),y=r.collectionDefinitions.filter(({collectionId:D})=>!h.includes(D)),E=y.map(Hr("collectionId")),P=[],A,U=r.tieFormatName;for(let D of r.collectionDefinitions){if(E.includes(D.collectionId))continue;let M=NI({updateInProgressMatchUps:t,...D,tournamentRecord:n,tieFormatName:U,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(M.modifications&&P.push(...M.modifications),M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}for(let D of y){let M=RI({updateInProgressMatchUps:t,collectionDefinition:D,tournamentRecord:n,drawDefinition:i,tieFormatName:U,structureId:s,matchUpId:a,matchUp:l,eventId:c,uuids:u,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}for(let D of T){let M=MI({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:n,drawDefinition:i,tieFormatName:U,collectionId:D,structureId:s,matchUpId:a,eventId:c,matchUp:l,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(A=M.tieFormat)}return f?.tieFormatName!==U?(A.tieFormatName=U,P.push({tieFormatName:U})):(P.length||E.length||T.length)&&(delete A.tieFormatName,P.push("tieFormatName removed: modifications without new tieFormatName")),A.collectionDefinitions=A.collectionDefinitions.sort((D,M)=>za(D.collectionOrder)-za(M.collectionOrder)).map((D,M)=>({...D,collectionOrder:M+1})),{processedTieFormat:or(A),modifications:P,...C}}function LR({tournamentRecord:t}){if(!t)return{error:q};let e=0;for(let r of t.events??[]){let n=r.tieFormats??[],o=p=>{if(!p.tieFormat)return;let m;for(let d of n)ni({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);if(m)p.tieFormatId=m,delete p.tieFormat;else{let d=J(p.tieFormat,void 0,!0);d.tieFormatId||(d.tieFormatId=Nt()),p.tieFormatId=d.tieFormatId,delete p.tieFormat,n.push(d),e+=1}},i=r.eventType;o({tieFormat:r.tieFormat,eventType:i});for(let p of r.drawDefinitions??[]){o({tieFormat:p.tieFormat,eventType:i});for(let m of p.structures??[])o({tieFormat:m.tieFormat,eventType:i})}let s=(p,m)=>{let d=c.matchUps?.find(l=>l.matchUpId===p);d&&(d.tieFormatId=m,delete d.tieFormat,gt({tournamentId:t?.tournamentId,eventId:r.eventId,matchUp:d}))},a=p=>{let m=J(p.tieFormat,void 0,!0);m.tieFormatId||(m.tieFormatId=Nt()),n.push(m),e+=1,s(p.matchUpId,m.tieFormatId)},c=to({matchUpFilters:{matchUpTypes:[xr]},event:r}),u=c.matchUps??[];for(let p of u){let m;for(let d of n)p.tieFormat&&ni({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);m?s(p.matchUpId,m):a(p)}n.length&&(r.tieFormats=n)}return{...C,addedCount:e}}var XR={};Xt(XR,{addDrawDefinitionExtension:()=>Pp,addEventExtension:()=>xo,addEventTimeItem:()=>is,addExtension:()=>At,addNotes:()=>$p,addOnlineResource:()=>jR,addParticipantExtension:()=>RU,addParticipantTimeItem:()=>Gg,addTimeItem:()=>ro,addTournamentExtension:()=>Vf,addTournamentTimeItem:()=>_c,analyzeDraws:()=>Vu,analyzeTournament:()=>sy,copyTournamentRecord:()=>GR,createTournamentRecord:()=>ym,generate:()=>VR,getAggregateTeamResults:()=>iy,getAllowedDrawTypes:()=>rl,getAllowedMatchUpFormats:()=>ey,getAppliedPolicies:()=>Tt,getCompetitionDateRange:()=>ol,getCompetitionPenalties:()=>ry,getPolicyDefinitions:()=>Go,getTournamentInfo:()=>bs,getTournamentPenalties:()=>nl,getTournamentPersons:()=>oy,getTournamentPoints:()=>il,getTournamentStructures:()=>HS,getTournamentTimeItem:()=>cd,hydrateTournamentRecord:()=>BR,mutate:()=>QR,query:()=>TN,removeDrawDefinitionExtension:()=>CU,removeEventExtension:()=>Dp,removeExtension:()=>Ir,removeNotes:()=>Fg,removeOnlineResource:()=>WR,removeParticipantExtension:()=>bU,removeTournamentExtension:()=>Bf,setTournamentCategories:()=>$R,setTournamentDates:()=>CI,setTournamentEndDate:()=>zR,setTournamentName:()=>YR,setTournamentNotes:()=>qR,setTournamentStartDate:()=>KR,setTournamentStatus:()=>HR});var VR={};Xt(VR,{copyTournamentRecord:()=>GR,createTournamentRecord:()=>ym});function GR(t){let e=et(t,[{tournamentRecord:!0,startDate:!0,endDate:!1,tournamentName:!0}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord,o=1440*60*1e3,s=(r&&n?new Date(Ut(n)).getTime()-new Date(Ut(r)).getTime():0)/o,a=t.endDate||ch(t.startDate,s),c=l=>l?.filter(({itemType:f})=>t.itemTypeList?.includes(f)),u=l=>l?.filter(({name:f})=>t.extensionList?.includes(f)),p=l=>{let{timeItems:f,extensions:g,...I}=l;return J({...I,timeItems:c(f),extensions:u(g)},!1,!0)},m=l=>{let{drawDefinitions:f,timeItems:g,extensions:I,startDate:h,endDate:S,...T}=l;return J({extensions:u(I),timeItems:c(g),startDate:t.startDate,endDate:a,...T},!1,!0)},d={participants:t.copyParticipants?t.tournamentRecord.participants?.map(p)??[]:[],parentOrganisation:J({...t.tournamentRecord.parentOrganisation},!1,!0),venues:J(t.tournamentRecord.venues??[],!1,!0),extensions:u(t.tournamentRecord.extensions),timeItems:c(t.tournamentRecord.timeItems),events:t.tournamentRecord.events?.map(m)??[],weekdays:[...t.tournamentRecord.weekdays??[]],tournamentName:t.tournamentName,startDate:t.startDate,tournamentId:Nt(),endDate:a};return{...C,tournamentRecord:d}}var QR={};Xt(QR,{addDrawDefinitionExtension:()=>Pp,addEventExtension:()=>xo,addEventTimeItem:()=>is,addExtension:()=>At,addNotes:()=>$p,addOnlineResource:()=>jR,addParticipantExtension:()=>RU,addParticipantTimeItem:()=>Gg,addTimeItem:()=>ro,addTournamentExtension:()=>Vf,addTournamentTimeItem:()=>_c,hydrateTournamentRecord:()=>BR,removeDrawDefinitionExtension:()=>CU,removeEventExtension:()=>Dp,removeExtension:()=>Ir,removeNotes:()=>Fg,removeOnlineResource:()=>WR,removeParticipantExtension:()=>bU,removeTournamentExtension:()=>Bf,setTournamentCategories:()=>$R,setTournamentDates:()=>CI,setTournamentEndDate:()=>zR,setTournamentName:()=>YR,setTournamentNotes:()=>qR,setTournamentStartDate:()=>KR,setTournamentStatus:()=>HR});function BR(t){let{tournamentRecord:e,eventProfiles:r=[],directives:n,policyDefinitions:o}=t;return e?((e.events||[]).forEach(s=>{let a=r.find(c=>c.eventId&&c.eventId===s.eventId);(a?.directives?.hydrateRoundNames||n?.hydrateRoundNames)&&s.drawDefinitions?.forEach(c=>{(a?.policyDefinitions?.[vo]||o?.[vo])&&by({drawDefinition:c,appliedPolicies:o})})}),{tournamentRecord:e}):{error:q}}var eB="ABANDONED",rB="ACTIVE",nB="CANCELLED",oB="COMPLETED",iB="IN_PROGRESS",ME={ABANDONED:eB,ACTIVE:rB,CANCELLED:nB,COMPLETED:oB,IN_PROGRESS:iB};function HR({tournamentRecord:t,status:e}){return t?e&&!Object.keys(ME).includes(e)?{error:B,info:"Unknown status"}:(t.tournamentStatus=e,{...C}):{error:q}}function WR(t){let e=et(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:Oe}});Fl({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:Oe}}):_({result:{error:re}});if(s){if(u.person?.personId!==s)return _({result:{error:Hi}});Fl({element:u.person,onlineResource:n})}else Fl({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:Vs}});Fl({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:ji}});Fl({element:u,onlineResource:n})}else Fl({element:r,onlineResource:n}),lt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Xi});return{...C}}function Fl({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>!(n?.[cc]===e[cc]&&n?.[uc]===e[uc]&&n?.[pc]===e[pc]));t.onlineResources=r}function jR(t){let e=et(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:Oe}});kl({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:Oe}}):_({result:{error:re}});if(s){if(u.person?.personId!==s)return _({result:{error:Hi}});kl({element:u.person,onlineResource:n})}else kl({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:Vs}});kl({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:ji}});kl({element:u,onlineResource:n})}else kl({element:r,onlineResource:n}),lt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Xi});return{...C}}function kl({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>n?.[cc]!==e[cc]&&n?.[uc]!==e[uc]&&n?.[pc]!==e[pc]);return r.push(e),t.onlineResources=r,{...C}}function YR({tournamentRecord:t,promotionalName:e,tournamentName:r,formalName:n}){if(!t)return{error:q};let o=t.tournamentId,i={tournamentId:o};return r&&r!==t.tournamentName&&(t.tournamentName=r,i.tournamentName=r),e&&e!==t.promotionalName&&(t.promotionalName=e,i.promotionalName=e),n&&n!==t.formalName&&(t.formalName=n,i.formalName=n),t.promotionalName===t.tournamentName&&(delete t.promotionalName,i.promotionalName=""),t.formalName===t.tournamentName&&(delete t.formalName,i.formalName=""),Object.keys(i).length>1&<({topic:Xi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:o,...i}}),{...C}}function qR({tournamentRecord:t,notes:e}){if(!t)return{error:q};let r=e?$p({element:t,notes:e}):Fg({element:t});return r.error?r:(lt({topic:Xi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,notes:e??""}}),{...C})}function $R({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(r=>r.categoryName&&r.type),t.tournamentCategories=e,lt({topic:Xi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,categories:e}}),{...C}):{error:q}}function _w({tournamentRecord:t}){if(!t)return{error:q};let{startDate:e,endDate:r}=t,n=js(e,r),o=[];for(let i of t.venues||[])i?.courts?.length&&o.push(...i.courts);for(let i of o){let{startTime:s,endTime:a}=(i.dateAvailability??[]).reduce((p,m)=>{let d=Yt(p.startTime),l=Yt(p.endTime);return m.startTime&&Yt(m.startTime)<d&&(p.startTime=m.startTime),m.endTime&&Yt(m.endTime)>l&&(p.endTime=m.endTime),p},{startTime:"08:00",endTime:"18:00"}),c=n.map(p=>i.dateAvailability?.find(d=>d.date===p)??{date:p,startTime:s,endTime:a}),u=i.dateAvailability?.find(p=>!p.date);u&&c.unshift(u),i.dateAvailability=c}return{...C}}function CI(t){let{tournamentRecord:e,startDate:r,endDate:n,weekdays:o}=t,i=t.activeDates?.filter(Boolean),s=et(t,[{tournamentRecord:!0},{[tr]:l=>Oo.test(l),[kr]:Ye,startDate:!1,endDate:!1},{[tr]:l=>l.filter(Boolean).every(f=>Oo.test(f)),[kr]:Ye,activeDates:!1},{[tr]:Fy,weekdays:!1}]);if(s.error)return s;if(n&&r&&new Date(n)<new Date(r))return{error:B};if(n&&r&&new Date(r)>new Date(n))return{error:B};if(i?.length){let l=r||e.startDate,f=n||e.endDate,g=!l||i.every(h=>new Date(h)>=new Date(l)),I=!f||i.every(h=>new Date(h)<=new Date(f));if(!g||!I)return{error:Ye}}let a;(r&&e.startDate&&new Date(r)>new Date(e.startDate)||n&&e.endDate&&new Date(n)<new Date(e.endDate))&&(a=!0);let c=js(e.startDate,e.endDate);r&&(e.startDate=r),n&&(e.endDate=n);let u=js(e.startDate,e.endDate),p=c.filter(l=>!u.includes(l)),m=u.filter(l=>!c.includes(l));for(let l of e.events??[])r&&l.startDate&&new Date(l.startDate)<new Date(r)&&(l.startDate=r),n&&l.startDate&&new Date(l.startDate)>new Date(n)&&(l.startDate=r??n),n&&l.endDate&&new Date(l.endDate)>new Date(n)&&(l.endDate=n),r&&l.endDate&&new Date(l.endDate)<new Date(r)&&(l.endDate=n??r);r&&e.endDate&&new Date(r)>new Date(e.endDate)&&(e.endDate=r),n&&e.startDate&&new Date(n)<new Date(e.startDate)&&(e.startDate=n),i&&(e.activeDates=i),o&&(e.weekdays=o);let d=a&&sB({tournamentRecord:e})?.unscheduledMatchUpIds;return _w({tournamentRecord:e}),lt({payload:nt({parentOrganisation:e.parentOrganisation,tournamentId:e.tournamentId,activeDates:i,startDate:r,weekdays:o,endDate:n}),topic:Xi}),{...C,unscheduledMatchUpIds:d,datesAdded:m,datesRemoved:p}}function KR({tournamentRecord:t,startDate:e}){return e?CI({tournamentRecord:t,startDate:e}):{error:Ye}}function zR({tournamentRecord:t,endDate:e}){return e?CI({tournamentRecord:t,endDate:e}):{error:Ye}}function sB({tournamentRecord:t}){let e=ye({tournamentRecord:t}).matchUps??[],r=t.startDate&&new Date(t.startDate),n=t.endDate&&new Date(t.endDate),o=[],i=[];for(let s of e){let{schedule:a,matchUpId:c}=s;if(a&&a.scheduledDate){let u=new Date(a.scheduledDate);(r&&u<r||n&&u>n)&&(i.push(c),o.includes(a.scheduledDate)||o.push(a.scheduledDate))}}return o.length&&!Sm({scheduledDates:o,tournamentRecord:t}).clearedScheduleCount?{error:WE}:{unscheduledMatchUpIds:i}}var aC={};Xt(aC,{addCourt:()=>vl,addCourts:()=>UI,addVenue:()=>Ec,deleteCourt:()=>oC,deleteVenue:()=>CE,deleteVenues:()=>ZR,disableCourts:()=>tC,disableVenues:()=>eC,enableCourts:()=>rC,enableVenues:()=>nC,generate:()=>JR,generateCourts:()=>uI,getCompetitionVenues:()=>om,getCourts:()=>Ny,getVenuesAndCourts:()=>Ro,modifyCourt:()=>OI,modifyCourtAvailability:()=>bI,modifyVenue:()=>iC,mutate:()=>sC,publicFindVenue:()=>US,query:()=>wN});var JR={};Xt(JR,{generateCourts:()=>uI});var sC={};Xt(sC,{addCourt:()=>vl,addCourts:()=>UI,addVenue:()=>Ec,deleteCourt:()=>oC,deleteVenue:()=>CE,deleteVenues:()=>ZR,disableCourts:()=>tC,disableVenues:()=>eC,enableCourts:()=>rC,enableVenues:()=>nC,modifyCourt:()=>OI,modifyCourtAvailability:()=>bI,modifyVenue:()=>iC});function Gl(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:q};if(!t?.courtId)return{error:Bi};let{scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n,venueMatchUps:o,courtId:i}=t,{schedulingProfile:s}=oi({tournamentRecord:r});if(Array.isArray(o))return{matchUps:u({matchUps:o,courtId:i})};let{matchUps:a}=ye({scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n});return{matchUps:u({matchUps:a,courtId:i})};function u({matchUps:p,courtId:m}){let d=p.filter(l=>{let f=l.schedule?.allocatedCourts?.map(({courtId:g})=>g);return l.schedule?.courtId===m||f?.includes(m)});return gl({matchUps:d,schedulingProfile:s})}}function xw({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r,venueId:n}){if(!e)return{error:q};if(!n)return{error:ai};let{schedulingProfile:o}=oi({tournamentRecord:e}),{matchUps:i}=ye({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r});return{matchUps:a({matchUps:i,venueId:n})};function a({matchUps:c,venueId:u}){let p=c.filter(m=>{let d=m.schedule?.allocatedCourts?.map(({venueId:l})=>l);return m.schedule?.venueId===u||d?.includes(u)});return gl({matchUps:p,schedulingProfile:o})}}function bI({tournamentRecord:t,dateAvailability:e,disableNotice:r,venueMatchUps:n,courtId:o,force:i}){if(!t)return{error:q};if(!o)return{error:Bi};let s=EE({dateAvailability:e});if(s.error)return s;let{updatedDateAvailability:a,totalMergeCount:c}=aB(e);e=a;let u=hs({tournamentRecord:t,courtId:o});if(u.error)return u;let{court:p,venue:m}=u,{matchUps:d}=Gl({tournamentRecord:t,venueMatchUps:n,courtId:o});if(d?.length){let l=Tt({tournamentRecord:t})?.appliedPolicies,f=i??l?.[_o]?.allowDeletionWithScoresPresent?.courts,g=[];g.length&&(f||console.log("throw error: scheduled court matchUps",g.length))}return p&&(p.dateAvailability=e,!r&&m&<({payload:{venue:m,tournamentId:t.tournamentId},topic:Ri,key:m.venueId})),{...C,totalMergeCount:c}}function aB(t){let e=0,r=t.reduce((o,i)=>{let{date:s,startTime:a,endTime:c,bookings:u}=i;return o[s]||(o[s]=[]),o[s].push({startTime:a,endTime:c,bookings:u}),o},{}),n=[];return Object.keys(r).forEach(o=>{r[o].sort(Sw);let{mergedAvailability:i,mergeCount:s}=cB(r[o]);n.push(...i.map(a=>({date:o,...a}))),e+=s}),{updatedDateAvailability:n,totalMergeCount:e}}function cB(t){let e,r,n,o=t.length,i=0,s=[];for(;t.length&&o;){let c=t.shift(),{startTime:u,endTime:p,bookings:m}=c;if(o-=1,!e)e=u,n=m,r=p;else if(ya(Ge(r),Ge(u),!1)>0){let l={startTime:e,endTime:r};n?.length&&(l.bookings=n),s.push(l),e=u,n=m,r=p}else m&&(n?n.push(m):n=m),r=p,i+=1}let a={startTime:e,endTime:r};return n?.length&&(a.bookings=n),s.push(a),{mergedAvailability:s,mergeCount:i}}function Vl({matchUpsCount:t=0}){let r=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:qA,info:r}}function RE({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:n}){let o="removeCourtAssignment";if(!r)return{error:sr};if(!e&&!n)return{error:cn};let i;if(!e){if(!t)return{error:q};({drawDefinition:e}=ze({tournamentRecord:t,drawId:n}))}if(e)({matchUp:i}=Vt({drawDefinition:e,matchUpId:r}));else{if(!t)return{error:q};let s=ye({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=sT({matchUps:s,matchUpId:r}))}return i?(i.timeItems&&i.timeItems.find(a=>[Jo,lo].includes(a.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:a})=>![Jo,lo].includes(a)),gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:i})),{...C}):{error:we}}function CE(t){if(typeof t?.venueId!="string")return{error:ai};let{tournamentRecord:e,venueId:r,force:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(o).length)return{error:q};let s=Mn({tournamentRecords:o,contextFilters:{venueIds:[r]}}).matchUps??[],a=Tt({tournamentRecord:e})?.appliedPolicies,c=n??a?.[_o]?.allowDeletionWithScoresPresent?.venues;if(!s.length||c)for(let u of Object.values(o)){for(let m of s){let d=RE({matchUpId:m.matchUpId,drawId:m.drawId,tournamentRecord:u});if(d.error)return d}let p;u.venues=(u.venues??[]).filter(m=>m?.venueId!==r?!0:(p=!0,!1)),p&<({payload:{venueId:r,tournamentId:u.tournamentId},topic:$f,key:r})}else return Vl({matchUpsCount:s.length});return Fc({tournamentRecords:o}),{...C}}function ZR({tournamentRecord:t,venueIds:e,force:r}){if(!t)return{error:q};if(!Array.isArray(e))return{error:B};for(let n of t.venues||[]){let{venueId:o}=n;if(e.includes(o)){let{venueId:i}=n,s=CE({tournamentRecord:t,venueId:i,force:r});if(s.error)return s}}return{...C}}function tC(t){let{courtIds:e,dates:r}=t,n=Rr(t),o=[{[Re]:!0,[Ap]:!0}],i=et(t,o);if(i.error)return i;for(let s of Object.values(n))uB({tournamentRecord:s,courtIds:e,dates:r});return{...C}}function uB({tournamentRecord:t,courtIds:e,dates:r}){let n=Array.isArray(r)&&r.length?{dates:r}:!0,o=i=>At({extension:{value:n,name:uo},creationTime:!1,element:i});for(let i of t.venues||[])for(let s of i.courts||[])if(e?.includes(s.courtId)){let a=o(s);if(a.error)return a}return{...C}}function eC(t){let{tournamentRecords:e,tournamentId:r,venueIds:n}=t,o=[{[Re]:!0,[Up]:!0}],i=et(t,o);if(i.error)return i;let s=Object.keys(e).filter(a=>!r||a===r);for(let a of s){let c=e[a];pB({tournamentRecord:c,venueIds:n})}return{...C}}function pB({tournamentRecord:t,venueIds:e}){for(let r of t.venues||[])if(e?.includes(r.venueId)){let n=At({creationTime:!1,element:r,extension:{name:uo,value:!0}});if(n.error)return n}return{...C}}function rC(t){let e=Rr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[Ap]:!0});let n=et(t,r);if(n.error)return n;let{enableAll:o,courtIds:i,dates:s}=t;for(let a of Object.values(e))mB({tournamentRecord:a,courtIds:i,enableAll:o,dates:s});return{...C}}function mB({tournamentRecord:t,courtIds:e,enableAll:r,dates:n}){for(let o of t.venues||[])for(let i of o.courts||[])if(r||e?.includes(i.courtId))if(Array.isArray(n)){let{extension:s}=mt({element:i,name:uo});if(s){let a=s.value;Array.isArray(a.dates)&&(a.dates=a.dates.filter(c=>!n.includes(c))),At({extension:{name:uo,value:a},creationTime:!1,element:i})}}else Ir({element:i,name:uo});return{...C}}function nC(t){let e=Rr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[Up]:!0});let n=et(t,r);if(n.error)return n;let{venueIds:o,enableAll:i}=t;for(let s of Object.values(e))for(let a of s.venues||[])(i||o?.includes(a.venueId))&&Ir({element:a,name:uo});return{...C}}function oC(t){let{courtId:e,disableNotice:r,force:n}=t,o=Rr(t),i=et(t,[{[Re]:!0,[Fh]:!0}]);if(i.error)return i;let s,a;for(let c of Object.values(o)){if(a=dB({tournamentRecord:c,disableNotice:r,courtId:e,force:n}),a.error&&a.error!==Vs)return a;a.success&&(s=!0)}return s?{...C}:a}function dB({tournamentRecord:t,disableNotice:e,courtId:r,force:n}){let o=hs({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.venue,{matchUps:s}=Gl({tournamentRecord:t,courtId:r}),a=Tt({tournamentRecord:t})?.appliedPolicies,c=n??a?.[_o]?.allowDeletionWithScoresPresent?.courts;if(!s?.length||c){for(let u of s??[]){let p=RE({matchUpId:u.matchUpId,drawId:u.drawId,tournamentRecord:t});if(p.error)return p}i&&(i.courts=(i.courts??[]).filter(u=>u.courtId!==r),e||lt({payload:{venue:i,tournamentId:t.tournamentId},topic:Ri,key:i.venueId}))}else return Vl({matchUpsCount:s.length});return{...C}}function OI(t){let{disableNotice:e,modifications:r,courtId:n,force:o,venueMatchUps:i}=t,s=Rr(t);if(!Object.keys(s).length)return{error:xt};let a,c;for(let u of Object.values(s)){let p=lB({tournamentRecord:u,disableNotice:e,venueMatchUps:i,modifications:r,courtId:n,force:o});if(p?.error)return p;a=!0}return a?{...C}:c}function lB({tournamentRecord:t,disableNotice:e,venueMatchUps:r,modifications:n,courtId:o,force:i}){if(!t)return{error:q};if(!o)return{error:Bi};if(!n||typeof n!="object")return{error:So};let s=hs({tournamentRecord:t,courtId:o});if(s.error)return s;let{venue:a,court:c}=s,u=Object.keys(hw()).filter(l=>l!=="courtId");if(!Object.keys(n).filter(l=>u.includes(l)).length)return{error:up};let m=u.filter(l=>!["dateAvailability"].includes(l)),d=Object.keys(n).filter(l=>m.includes(l));if(c&&d.forEach(l=>Object.assign(c,{[l]:n[l]})),n.dateAvailability){let l=bI({dateAvailability:n.dateAvailability,tournamentRecord:t,venueMatchUps:r,disableNotice:e,courtId:o,force:i});if(l.error)return l}return e||lt({payload:{venue:a,tournamentId:t.tournamentId},topic:Ri,key:a?.venueId}),{...C,court:J(c)}}var fB=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]}),ww=fB;function iC(t){let{modifications:e,venueId:r,force:n}=t,o=Rr(t);if(!Object.keys(o).length)return{error:xt};if(typeof r!="string")return{error:ai};let i,s;for(let a of Object.values(o)){let c=gB({tournamentRecord:a,modifications:e,venueId:r,force:n});if(c.success&&(s=!0),c.error&&(i=c.error),c.error&&c.error!==ji)return c}return Fc({tournamentRecords:o}),s?{...C}:{error:i}}function gB({tournamentRecord:t,modifications:e,venueId:r,force:n}){if(!t)return{error:q};if(!e||typeof e!="object")return{error:So};if(!r)return{error:ai};let o=Tt({tournamentRecord:t})?.appliedPolicies,i=n??o?.[_o]?.allowDeletionWithScoresPresent?.venues,{matchUps:s}=xw({tournamentRecord:t,venueId:r}),a=ti({tournamentRecord:t,venueId:r});if(a.error)return a;let c=a.venue,u=Object.keys(ww()).filter(h=>h!=="venueId");if(!Object.keys(e).filter(h=>u.includes(h)).length)return{error:up};let m=u.filter(h=>!["courts","onlineResources"].includes(h)),d=Object.keys(e).filter(h=>m.includes(h));c&&d.forEach(h=>Object.assign(c,{[h]:e[h]}));let l=c?.courts?.map(h=>h.courtId)??[],f=e.courts?.map(h=>h.courtId)||[],g=f.length?l.filter(h=>!f.includes(h)):e?.courts&&l,I=[];if(g?.length){let S=c?.courts?.filter(T=>g.includes(T.courtId))?.map(T=>{let y=Gl({courtId:T.courtId,tournamentRecord:t,venueMatchUps:s});for(let E of y.matchUps??[])I.push({matchUpId:E.matchUpId,drawId:E.drawId});return y.matchUps?.length??0}).reduce((T,y)=>T+y);if(c&&(!S||i))c.courts=c.courts?.filter(T=>f.includes(T.courtId)),Xu({schedule:{courtId:"",scheduledDate:""},matchUpDetails:I,removePriorValues:!0,tournamentRecord:t});else return Vl({matchUpsCount:S})}if(e.courts)for(let h of e.courts){let{courtId:S}=h||{},T=OI({modifications:h,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:S,force:n});if(T.error===Vs&&(T=vl({disableNotice:!0,tournamentRecord:t,venueId:r,court:h})),T.error)return T}return Fc({tournamentRecord:t}),c&<({payload:{venue:c,tournamentId:t.tournamentId},topic:Ri,key:c?.venueId}),{...C,venue:J(c)}}var cC={};Xt(cC,{JSON2CSV:()=>Bw,UUID:()=>Nt,UUIDS:()=>ph,allNumeric:()=>wI,attributeFilter:()=>Qi,chunkArray:()=>Ae,chunkByNth:()=>Wl,chunkSizeProfile:()=>kE,constantToString:()=>Qe,countValues:()=>yC,createMap:()=>kI,dateTime:()=>uh,definedAttributes:()=>nt,dehydrateMatchUps:()=>Vw,extractAttributes:()=>uP,flattenJSON:()=>OE,generateDateRange:()=>js,generateHashCode:()=>MC,generateRange:()=>tt,generateTimeCode:()=>AE,groupValues:()=>LE,hasAttributeValues:()=>NC,instanceCount:()=>Er,intersection:()=>jt,isConvertableInteger:()=>It,isNumeric:()=>Jt,isOdd:()=>_I,isPowerOf2:()=>Ln,makeDeepCopy:()=>J,matchUpScheduleSort:()=>Gw,matchUpSort:()=>xi,nearestPowerOf2:()=>Cm,nextPowerOf2:()=>us,noNulls:()=>TC,noNumeric:()=>LI,numericSort:()=>le,occurrences:()=>EC,overlap:()=>ke,randomMember:()=>Un,randomPop:()=>tn,shuffleArray:()=>Tr,structureSort:()=>Ni,subSort:()=>AC,undefinedToNull:()=>FI,unique:()=>pt,visualizeScheduledMatchUps:()=>Lw});function Lw({scheduledMatchUps:t,showGlobalLog:e}){dO();let r=t?.reduce((o,{structureId:i})=>o.includes(i)?o:o.concat(i),[]),n=Array.isArray(r)&&{...r.map(o=>{let{structureName:i,matchUpType:s}=t.find(a=>a.structureId===o);return{[o]:`${i} ${s}`}})};r?.forEach(o=>{Tn({color:"blue",method:"draw",structure:n[o],keyColors:{structure:"magenta"}},!0);let i=t.filter(a=>a.structureId===o),s=Ke({matchUps:i})?.roundMatchUps||[];Object.keys(s).forEach(a=>{Tn({roundNumber:a,keyColors:{roundNumber:"brightcyan"}},!0),s[a].forEach(({matchUpId:c,schedule:u})=>{let p=zt(u.scheduledTime);Tn({matchUpId:c,time:p,date:u.scheduledDate,venue:u.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&mO()}var{extractTime:Fw,timeStringMinutes:kw}=uh;function Gw(t,e){let r=t.schedule??{},n=e.schedule??{};if(r.scheduledDate&&!n.scheduledDate)return 1;if(n.scheduledDate&&!r.scheduledDate)return-1;if(r.scheduledDate&&n.scheduledDate){if(r.scheduledDate===n.scheduledDate){if(r.scheduledTime&&!n.scheduledTime)return 1;if(n.scheduledTime&&!r.scheduledTime)return-1;if(r.scheduledTime&&n.scheduledTime){let o=kw(Fw(r.scheduledTime)),i=kw(Fw(n.scheduledTime));return o-i}}return new Date(r.scheduledDate).getTime()-new Date(n.scheduledDate).getTime()}return 0}function Vw({tournamentRecord:t}){if(!t)return{error:q};if(typeof t!="object"||!t.tournamentId)return{error:B};let{matchUps:e}=ye({tournamentRecord:t,inContext:!1});if(e?.length){let r=IB({tournamentRecord:t});SB(e,r)}return{...C}}function IB({tournamentRecord:t}){let e={};for(let r of t.events||[]){r.matchUpFormat&&(e[r.eventId]=r.matchUpFormat);for(let n of r.drawDefinitions||[]){n.matchUpFormat&&(e[n.drawId]=n.matchUpFormat);for(let o of n.structures||[]){o.matchUpFormat&&(e[o.structureId]=o.matchUpFormat);for(let i of o.structures||[])i.matchUpFormat&&(e[i.structureId]=i.matchUpFormat)}}}return e}var hB=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function SB(t,e={}){for(let r of t){let{structureId:n,drawId:o,eventId:i}=r,s=e[n]||e[o]||e[i],a=r.matchUpFormat===s?void 0:r.matchUpFormat;for(let c of Object.keys(r))hB.includes(c)||delete r[c];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,a&&(r.matchUpFormat=a)}}function Bw(t,e){if(e&&typeof e!="object")return{error:B};let{columnTransform:r={}}=e||{},{includeTransformAccessors:n,includeHeaderRow:o=!0,returnTransformedJSON:i,removeEmptyColumns:s,onlyHeaderRow:a,columnAccessors:c=[],functionMap:u={},columnMap:p={},valuesMap:m={},context:d={},delimiter:l='"',columnJoiner:f=",",rowJoiner:g=`\r
|
|
27
27
|
`,keyJoiner:I="."}=e||{};if(!Array.isArray(t)||!Array.isArray(c)||typeof d!="object"||typeof p!="object"||typeof r!="object"||typeof u!="object"||typeof m!="object"||typeof f!="string"||typeof g!="string"||typeof I!="string"||typeof l!="string")return{error:B};r=Object.assign({},...Object.keys(r).reverse().map(O=>({[O]:Array.isArray(r[O])?r[O]:[typeof r[O]=="string"&&r[O]].filter(Boolean)})));let h=t.filter(Boolean).map(O=>OE(O,I)),S=Object.values(r).flat();n&&c.push(...S);let T=h.reduce((O,v)=>Object.keys(v).every(x=>!O.includes(x)&&O.push(x)||!0)&&O,[]).filter(O=>!c?.length||c.includes(O)),y=Object.assign({},...Object.keys(r).reverse().map(O=>r[O].map(v=>({[v]:O})).flat()).flat()),E=(O,v)=>e?.sortOrder?e.sortOrder.includes(O)&&e.sortOrder.includes(v)&&e.sortOrder.indexOf(O)-e.sortOrder.indexOf(v)||!e.sortOrder.includes(v)&&-1:0,P=T.reduce((O,v)=>{let x=y[v];return x?O.includes(x)||O.push(x):O.push(v),O},[]).sort(E);Object.keys(p).forEach(O=>!P.includes(O)&&P.unshift(O)),Object.keys(r).forEach(O=>!P.includes(O)&&P.unshift(O)),typeof d=="object"&&Object.keys(d).forEach(O=>!P.includes(O)&&P.unshift(O));let A=P.map(O=>p[O]||O);if(a)return[A];let U=O=>`${l}${O}${l}`,N=[],D=O=>Object.values(P.reduce((v,x,F)=>{let w=r[x],L=(w?.length?O[w.find(H=>O[H])]:O[x])||d?.[x]||"",k=m[x]?.[L]||L,G=Yr(u[x])?u[x](k):k;return v[x]=U(G),G&&(N[F]=(N[F]||0)+1),v},{})),M=h.map(D),R=s&&[...N].map((O,v)=>!O&&v).filter(Jt).reverse();if(R){let O=v=>v.filter((x,F)=>!R.includes(F));M=M.map(O),A=O(A)}let b=M.map(O=>O.join(f));return i?b.map(O=>{let v=O.split(f);return Object.assign({},...v.map((x,F)=>({[A[F]]:x})))}):o?[A.map(U).join(f),...b].join(g):b.join(g)}function OE(t,e=".",r=[]){return typeof t=="object"&&Object.keys(t).reduce((n,o)=>typeof t[o]!="object"?(n[r.concat(o).join(e)]=t[o],n):Object.assign(n,OE(t[o],e,r.concat(o))),{})}var TB={};var{FACTORY:Hw}=jh;function Ww({tournamentRecord:t,value:e}){let{extension:r}=mt({element:t,name:Hw}),n={name:Hw,value:{...r?.value,...e}};At({element:t,extension:n})}function Zu({timeStamp:t}){let e=qo(),r=Tf();return r&&Object.values(e).forEach(n=>{Ww({tournamentRecord:n,value:{version:Ka(),timeStamp:t}})}),r}function vE({engineType:t,methodName:e,elapsed:r,params:n,result:o}){let i=Dr();if(typeof i!="object")return;let s={method:e},a=o?.error&&(i.errors===!0||Array.isArray(i.errors)&&i.errors.includes(e)),c=Array.isArray(i.params)&&i.params?.includes(e),u=i.params&&!Array.isArray(i.params)||c,p=Array.isArray(i.exclude)&&i.exclude.includes(e);!p&&![void 0,!1].includes(i.perf)&&!isNaN(i.perf)&&r>=i.perf&&(s.elapsed=r),!p&&(a||u)&&(s.params=n),!p&&(a||i.result&&!Array.isArray(i.result)&&(!Array.isArray(i.params)||c)||Array.isArray(i.result)&&i.result?.includes(e))&&(s.result=o),Object.keys(s).length>1&&JA(s,t)}function qa({methodName:t,params:e,start:r}){let n={error:nc,methodName:t},o=r?Date.now()-r:0;return vE({result:n,methodName:t,elapsed:o,params:e,engineType:"sync"}),n}function jw(t,e){if(e._middleware===!1)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:q};let r=e.drawId||e.matchUp?.drawId;if(r){let{event:i,drawDefinition:s,tournamentId:a}=ze({tournamentRecords:t,drawId:r});s&&(e.drawDefinition=s),a&&(e.tournamentId=a),i&&(e.event=i)}if(e.eventId&&!e.event){let{event:i,tournamentId:s}=ze({eventId:e.eventId,tournamentRecords:t});if(!i)return{error:qr};e.tournamentId=s,e.event=i}let n=e.tournamentId??ms();if(!n&&e)return e;let o=t[n];return n&&!o?{error:q}:(o&&(e.tournamentRecord=o),e)}function $a(t,e,r,n,o){delete t.success,delete t.error;let i=Date.now(),s=ms();r&&(r.activeTournamentId=s);let a=r?.tournamentRecord||Ef(s),c=typeof r?.tournamentRecord=="object"&&{[r?.tournamentRecord.tournamentId]:r.tournamentRecord}||qo(),u=r?J(r,void 0,!0):void 0,p=r?jw(c,r):void 0;if(p?.error)return p;let m=yB({params:p,tournamentRecords:c,tournamentRecord:a,methodName:n,method:e}),d=Date.now()-i;return vE({result:m,methodName:n,elapsed:d,params:u,engineType:o}),m}function yB({tournamentRecords:t,tournamentRecord:e,params:r,methodName:n,method:o}){if(Dr())return o({tournamentRecords:t,tournamentRecord:e,...r});try{return o({tournamentRecords:t,tournamentRecord:e,...r})}catch(i){return fp({engineName:"engine",methodName:n,params:r,err:i})}}function tp(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Lr();for(let s of[...i].sort(qw)){let a=th({topic:s});a?.length&&wm({topic:s,notices:a})}e&&o&&i.includes(sd)&&wm({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:sd})}async function _E(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Lr();for(let s of[...i].sort(qw)){let a=th({topic:s});a&&await wm({topic:s,notices:a})}e&&o&&i.includes(sd)&&wm({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:sd})}var Yw={[eg]:5,[tg]:5,[rg]:5,[Zf]:5,[Jf]:5,[Qf]:5,[WU]:5,[jU]:5,[Xf]:1,[Rp]:1,[rr]:5,[Ri]:5,[zf]:4,[qf]:4,[$f]:4,[Kf]:4,[Mp]:3,[jf]:2};function qw(t,e){return(Yw[e]||0)-(Yw[t]||0)}function $w({convertExtensions:t,removeExtensions:e}){let r=qo();return{tournamentId:ms(),tournamentRecords:J(r,t,!1,e)}}function Kw(t){let{convertExtensions:e=!1,removeExtensions:r=!1}=t??{},n=t?.tournamentId??ms();if(typeof n!="string")return{};let o=Ef(n);return{tournamentRecord:J(o,e,!1,r)}}function zw(){let t=qo(),{extension:e}=mt({name:Qs,tournamentRecords:t,discover:!0}),r=e?.value?.tournamentIds||[];return Object.keys(t).forEach(n=>{r.includes(n)||delete t[n]}),Lm(t)}function uC(t,e=!0){return typeof t!="object"||Array.isArray(t)?{error:So}:t?.tournamentId?QA(e?J(t):t):{error:B}}function cs(t,e=!0){if(typeof t!="object")return{error:So};if(lp(),Array.isArray(t)){if(!(t.filter(n=>n?.tournamentId).length===t.length))return{error:BI};t=Object.assign({},...t.map(n=>({[n.tournamentId]:n})))}else if(t?.tournamentId)t={[t.tournamentId]:t},lp(t.tournamentId);else if(!Object.keys(t).every(n=>t[n].tournamentId===n))return{error:BI};return Lm(e?J(t):t)}async function Qw(t,e,r){if(!Array.isArray(e))return{error:B,message:"directives must be an array"};let n=yf(),o=Date.now(),i=r&&J(qo(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:B,message:"directive must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return qa({methodName:m,start:o,params:l});if(d){let g=s.at(-1),I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=$a(t,n[m],l,m,"async");if(f?.error)return i&&cs(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=Zu({timeStamp:a});return await _E({directives:e,mutationStatus:c,timeStamp:a}),Yi(),{success:s.every(p=>p.success),results:s}}async function pC(t,e){if(!ht(e))return{error:B,message:"args must be an object"};let r=Object.values(e).filter(Yr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:B};let n=r?Object.keys(e).find(l=>Yr(e[l])):kt(e.method)&&e.method;if(!n)return{error:nc};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(qo(),!1,!0),c=o||t[n]||mp()[n];if(!c)return qa({methodName:n,params:s});let u=await $a(t,c,s,n,"async")??{};u?.error&&a&&cs(a);let p=Date.now(),m=Zu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&await _E({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&Yi(),u}function Xw(t,e,r,n,o,i){let s=ZA(r,n,o,i);if(s.error)return s;let a=s.methods??[];return Object.keys(a).filter(u=>Yr(a[u])).forEach(u=>{t[u]=p=>{let m=()=>e(t,{[u]:a[u],...p});if(Dr())return m();try{return m()}catch(d){fp({engineName:"engine",methodName:u,params:p,err:d})}}}),{...C,...t}}function Dm(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function Bl(t,e){t.importMethods=(r,n,o,i)=>Xw(t,e,r,n,o,i),t.getTournament=r=>Kw(r),t.getState=r=>$w({convertExtensions:r?.convertExtensions,removeExtensions:r?.removeExtensions}),t.version=()=>Ka(),t.reset=()=>(Lm({}),Dm(t)),t.devContext=r=>(Qc(r),Dm(t)),t.getDevContext=r=>Dr(r),t.newTournamentRecord=(r={})=>{let n=ym(r),o=n.tournamentId;return n.error?n:(uC(n),lp(o),{...C,tournamentId:o})},t.setState=(r,n,o)=>{Xc(n,o);let i=cs(r,n);return Dm(t,i)},t.setTournamentId=r=>lp(r),t.getTournamentId=()=>ms(),t.setTournamentRecord=(r,n,o)=>{Xc(n,o);let i=uC(r,n);return Dm(t,i)},t.removeTournamentRecord=r=>{let n=XA(r);return Dm(t,n)},t.removeUnlinkedTournamentRecords=()=>{let r=zw();return Dm(t,r)}}function EB(t){let e=KA();if(e.error&&!t)return e;let r={executionQueue:(n,o)=>Qw(r,n,o),execute:n=>pC(r,n)};return Bl(r,pC),r}function Jw(t,e,r){if(!Array.isArray(e))return{error:B,message:"directives must be an array"};let n=yf(),o=Date.now(),i=r&&J(qo(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:B,message:"directive must be an object"};if(p.params&&typeof p.params!="object")return{error:B,message:"params must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return qa({methodName:m,start:o,params:l});if(d){let g=s.at(-1),I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=$a(t,n[m],l,m,"sync");if(f?.error)return i&&cs(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=Zu({timeStamp:a});return tp({directives:e,mutationStatus:c,timeStamp:a}),Yi(),{success:s.every(p=>p.success),results:s}}function mC(t,e){if(!ht(e))return{error:B,message:"args must be an object"};let r=Object.values(e).filter(Yr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:B};let n=r?Object.keys(e).find(l=>Yr(e[l])):kt(e.method)&&e.method;if(!n)return{error:nc};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(qo(),!1,!0),c=o||t[n]||mp()[n];if(!c)return qa({methodName:n,params:s});let u=$a(t,c,s,n,"sync")??{};u?.error&&a&&cs(a);let p=Date.now(),m=Zu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&tp({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&Yi(),u}var Zw=(()=>{let t={executionQueue:(e,r)=>Jw(t,e,r),execute:e=>mC(t,e)};return Bl(t,mC),t})(),Nm=Zw;function dC(t,e){if(!ht(e))return{error:B,message:"args must be an object"};let r=Object.values(e).filter(Yr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:B};let n=r?Object.keys(e).find(c=>Yr(e[c])):kt(e.method)&&e.method;if(!n)return{error:nc};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=o||t[n]||mp()[n];return a?$a(t,a,s,n,"ask"):qa({methodName:n,params:s})}var AB=(()=>{let t={execute:e=>dC(t,e)};return Bl(t,dC),t})();var Mm={},jc;function lC(t,e=!0){if(!t)return{error:st};if(typeof t!="object")return{error:So};if(t.matchUpId)jc=t.matchUpId,Mm[jc]=e?J(t):t;else if(Array.isArray(t))for(let r of t.reverse())r.matchUpId&&(Mm[r.matchUpId]=e?J(r):r,jc||(jc=r.matchUpId));else for(let r of Object.values(t))r.matchUpId&&(Mm[r.matchUpId]=e?J(r):r,jc||(jc=r.matchUpId));return e?J(t):t}function tL(){return Mm[jc]}function eL(){return Object.values(Mm)}function rL(){jc=void 0,Mm={}}function nL(t){return J(Mm[jc],t?.convertExtensions,!1,t?.removeExtensions)}var UB=(()=>{let t={getState:r=>nL(r),version:()=>Ka(),reset:()=>(rL(),{...C}),drawId:void 0,error:void 0,success:!1,devContext:r=>(Qc(r),t),setState:(r,n,o)=>{Xc(n,o);let i=lC(r);return e(i)}};function e(r){return r?.error?(t.error=r.error,t.success=!1):(t.error=void 0,t.success=!0,t.drawId=r.drawId),t}return PB(t,[Jg]),t})();function PB(t,e){e.forEach(r=>{Object.keys(r).forEach(n=>{t[n]=o=>{if(Dr())return oL(t,{params:o,governor:r,methodName:n});try{return oL(t,{params:o,governor:r,methodName:n})}catch(i){fp({engineName:"matchUpEngine",methodName:n,params:o,err:i})}}})})}function oL(t,{params:e,governor:r,methodName:n}){t.error=void 0,t.success=!1;let o=e?.matchUp||tL(),i=e?.matchUps||eL(),s=e?.rollbackOnError&&J(o,!1,!0);e={...e,matchUpId:o?.matchUpId,matchUps:i,matchUp:o};let a=r[n](e);if(a?.error)return s&&lC(s),{...a,rolledBack:!!s};let c=a?.success&&e?.delayNotify!==!0&&e?.doNotNotify!==!0;return c&&tp(),(c||!a?.success||e?.doNotNotify)&&Yi(),a}var fC=!1,DB=(()=>{let t={version:()=>Ka(),setDeepCopy:(n,o)=>(Xc(n,o),t),devContext:n=>(Qc(n),fC=!0,t)};return r([PI]),t;function e(n,o){let i=n({...o});return i?.error||tp(),Yi(),fC&&(Qc(!1),fC=!1),i}function r(n){n.forEach(o=>{Object.keys(o).forEach(i=>{t[i]=s=>{if(Dr()){let a=e(o[i],s);return!a?.error&&s?.setState&&a?.tournamentRecord&&cs(a.tournamentRecord),a}else try{let a=e(o[i],s);return!a?.error&&s?.setState&&a?.tournamentRecord&&cs(a.tournamentRecord),a}catch(a){let c;typeof a=="string"?c=a.toUpperCase():a instanceof Error&&(c=a.message),console.log("ERROR",{params:JSON.stringify(s),method:i,error:c})}}})})}})();Nm.importMethods(bE,!0,1);var NB=Nm,MB=Nm;var RB={getTournamentPoints:il},iL=RB;var CB={calculateNewRatings:xT,generateDynamicRatings:wT},sL=CB;var bB={...iL,...sL};Nm.importMethods(bB);var OB=Nm;var aL={[mu]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}};var cL={[Jn]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[oa,jp]}};var uL={[Jn]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[oa,xu,ia],disabledActions:[]}]}};var pL={[Jn]:{policyName:"positionActionsDisabled",enabledStructures:!1}};var mL={[zs]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,rankings:!0,ratings:!0,representing:!0,participantRoleResponsibilities:!1,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}},individualParticipantIds:!0,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,rankings:!0,ratings:!0,representing:!0,participantRoleResponsibilities:!1,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}}}};var dL={[rn]:{processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},defaultMatchUpFormat:bn,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireParticipantsForScoring:!1,requireAllPositionsAssigned:void 0,allowChangePropagation:!1,stage:{[rt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},matchUpFormats:[],matchUpStatusCodes:{[vr]:[],[po]:[],[Gt]:[],[mn]:[],[Me]:[],[Bt]:[]}}};var gC="Personal circumstance",lL={[rn]:{requireAllPositionsAssigned:!1,stage:{[rt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:bn,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:bn,categoryNames:[],categoryTypes:[]},{description:"Two tiebreak sets, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB7"},{description:"Two tiebreak sets, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB10"},{description:"One standard tiebreak set to 6, 7-point tiebreak at 6 games all",matchUpFormat:"SET1-S:6/TB7"},{description:"Best of 3 sets to 4",matchUpFormat:"SET3-S:4/TB7"},{description:"Two out of three short sets to 4 with 5-point tiebreak at 3 games all",matchUpFormat:"SET3-S:4/TB5@3"},{description:"One short set to 4, 7-point tiebreak at 4 games all",matchUpFormat:"SET1-S:4/TB7"},{description:"One short set to 4, 5-point tiebreak at 3 games all",matchUpFormat:"SET1-S:4/TB5@3"},{description:"Two short sets to 4, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB10"},{description:"Two short sets to 4, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB7"},{description:"One no advantage set to 5, tiebreak to 9 at 4-4",matchUpFormat:"SET1-S:5/TB9@4"},{description:"One set to 6 with deciding game at 5 games all",matchUpFormat:"SET1-S:6NOAD"},{description:"One short set to 4, deciding game is played at 3 games all",matchUpFormat:"SET1-S:4NOAD"},{description:"Two short sets to 4 with deciding game at 3-3, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4NOAD-F:TB7"},{description:"8 game pro-set with 7 point tiebreak at 8 games all",matchUpFormat:"SET1-S:8/TB7"},{description:"8 game pro-set with 7 point tiebreak at 7 games all",matchUpFormat:"SET1-S:8/TB7@7"},{description:"Best of 3 10-point tiebreak games",matchUpFormat:"SET3-S:TB10"},{description:"One 10-point tiebreak game",matchUpFormat:"SET1-S:TB10"},{description:"Timed 20 minute game - game based",matchUpFormat:"SET1-S:T20"}],matchUpStatusCodes:{[vr]:[{matchUpStatusCodeDisplay:"Abandoned",label:"Abandoned match",matchUpStatusCode:"OA"}],[po]:[{matchUpStatusCodeDisplay:"Unplayed or Cancelled",label:"Cancelled match",matchUpStatusCode:"OC"}],[mn]:[{matchUpStatusCodeDisplay:"Incomplete",label:"Incomplete match",matchUpStatusCode:"OI"}],[Gt]:[{description:"Disqualification for cause or ineligibility",label:"Disqualification (ineligibility)",matchUpStatusCodeDisplay:"Def [dq]",matchUpStatusCode:"DQ"},{description:"Misconduct before or between matches",label:"Misconduct",matchUpStatusCodeDisplay:"Def [cond]",matchUpStatusCode:"DM"},{description:"Failure to start match because of adult discipline",label:"Fail. (adult discipline)",matchUpStatusCodeDisplay:"Def [ad]",matchUpStatusCode:"D5"},{description:"Refusal to start match for reason other than adult discipline, injury, illness, or personal circumstance. (After the Referee has conclusively confirmed that a player refuses to play a match, the Referee need not wait until the scheduled time of the match to records the result.)",label:"Refusal to start match",matchUpStatusCodeDisplay:"Def [refsl]",matchUpStatusCode:"D4"},{label:"Not showing up",matchUpStatusCodeDisplay:"Def [ns]",matchUpStatusCode:"D6"},{description:"Lateness for match including, but not limited to, intending to play but mistakenly arriving at the wrong time, location, or without proper equipment",label:"Lateness for match",matchUpStatusCodeDisplay:"Score + Def [late]",matchUpStatusCode:"D7"},{label:"Double default",matchUpStatusCodeDisplay:"Def/Def",matchUpStatusCode:"DD"},{description:"Refusal to continue playing a match for reason other than injury, illness, personal circumstance, or adult discipline",label:"Refusal to continue match",matchUpStatusCodeDisplay:"Def [refsl]",matchUpStatusCode:"D9"},{description:"Default for receiving an injection, IV, or supplemental oxygen",label:"Default (PEDs)",matchUpStatusCodeDisplay:"Def [med]",matchUpStatusCode:"DI"},{description:"Default under Point Penalty System",label:"Default (Point Penalty System)",matchUpStatusCodeDisplay:"Def [pps]",matchUpStatusCode:"DP"}],[Bt]:[{matchUpStatusCodeDisplay:"Wo [inj]",matchUpStatusCode:"W1",label:"Injury"},{matchUpStatusCodeDisplay:"Wo [ill]",matchUpStatusCode:"W2",label:"Illness"},{matchUpStatusCodeDisplay:"Wo [pc]",label:gC,matchUpStatusCode:"W3"},{matchUpStatusCodeDisplay:"Wo/Wo",matchUpStatusCode:"WOWO",label:"Double walkover"},{matchUpStatusCodeDisplay:"Wo [Tae]",label:"Tournament Administrative Error",matchUpStatusCode:"W4"},{matchUpStatusCodeDisplay:"Wo/Withdrawn",matchUpStatusCode:"W5",label:"Withdrawn"}],[Me]:[{matchUpStatusCodeDisplay:"Ret [inj]",matchUpStatusCode:"RJ",label:"Injury"},{matchUpStatusCodeDisplay:"Ret [ill]",matchUpStatusCode:"RI",label:"Illness"},{matchUpStatusCodeDisplay:"Ret [pc]",label:gC,matchUpStatusCode:"RC"},{description:"Retirement because of adult discipline",label:"Ret. (adult discipline)",matchUpStatusCodeDisplay:"Ret [ad]",matchUpStatusCode:"RD"},{description:"A player who retires from a match remains eligible for consolations, place playoffs, doubles and subsequent round robin matches",matchUpStatusCodeDisplay:"Ret [elg]",label:"Ret. (eligible)",matchUpStatusCode:"RU"}],[mo]:[{matchUpStatusCodeDisplay:"Wd [inj]",matchUpStatusCode:"WD.INJ",label:"Injury"},{matchUpStatusCodeDisplay:"Wd [ill]",matchUpStatusCode:"WD.ILL",label:"Illness"},{matchUpStatusCodeDisplay:"Wd [pc]",label:gC,matchUpStatusCode:"WD.PC"},{matchUpStatusCodeDisplay:"Wd/Wd",matchUpStatusCode:"WD.WD",label:"Double withdrawal"},{label:"Tournament Administrative Error",matchUpStatusCodeDisplay:"Wd [Tae]",matchUpStatusCode:"WD.TAE"}]}}};var fL={[Vn]:{seedingProfile:{positioning:nu},validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,policyName:"ITF 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:97,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}};var gL={POLICY_AVOIDANCE_COUNTRY:aL,POLICY_POSITION_ACTIONS_DEFAULT:IT,POLICY_POSITION_ACTIONS_DISABLED:pL,POLICY_POSITION_ACTIONS_NO_MOVEMENT:uL,POLICY_POSITION_ACTIONS_UNRESTRICTED:cL,POLICY_PRIVACY_DEFAULT:mL,POLICY_ROUND_NAMING_DEFAULT:mg,POLICY_SCHEDULING_DEFAULT:_N,POLICY_SCORING_DEFAULT:dL,POLICY_SCORING_USTA:lL,POLICY_SEEDING_ITF:fL,POLICY_SEEDING_DEFAULT:IN};var vB={ratingsParameters:je,matchUpFormats:eb,countryToFlag:QU,tieFormats:xy,countries:ui,policies:gL,flagIOC:vb};var TL={};Xt(TL,{activeMatchUpStatuses:()=>id,auditConstants:()=>gx,completedMatchUpStatuses:()=>ae,directingMatchUpStatuses:()=>$h,displayConstants:()=>tx,drawDefinitionConstants:()=>NU,entryStatusConstants:()=>xb,errorConditionConstants:()=>wC,eventConstants:()=>ib,extensionConstants:()=>jh,flightConstants:()=>yx,genderConstants:()=>Fm,keyValueConstants:()=>u_,matchUpActionConstants:()=>wv,matchUpStatusConstants:()=>Qh,matchUpTypes:()=>IC,nonDirectingMatchUpStatuses:()=>Kh,particicipantsRequiredMatchUpStatuses:()=>Yh,participantConstants:()=>Ob,participantRoles:()=>Dd,participantTypes:()=>yu,penaltyConstants:()=>IL,policyConstants:()=>Ub,positionActionConstants:()=>uv,ratingConstants:()=>Iv,recoveryTimeRequiredMatchUpStatuses:()=>Nb,requestConstants:()=>rw,resourceContants:()=>tb,resultConstants:()=>RC,scaleConstants:()=>Ab,scheduleConstants:()=>Qb,sortingConstants:()=>Nx,surfaceConstants:()=>hL,tieFormatConstants:()=>rb,timeItemConstants:()=>$b,topicConstants:()=>Rb,tournamentConstants:()=>ME,upcomingMatchUpStatuses:()=>zh,validMatchUpStatuses:()=>qh,venueConstants:()=>SL,weekdayConstants:()=>Ly});var _B="Coaching",xB="Ball Abuse",wB="Racket Abuse",LB="Verbal Abuse",FB="INELIGIBILITY",kB="Physical Abuse",GB="Unsportmanlike Conduct",VB="Dress Code Violation",BB="Equipment Violation",HB="Leaving the court",WB="Failure to complete",jB="No Show",YB="Other",qB="REFUSAL_TO_PLAY",$B="PROHIBITED_SUBSTANCE",KB="Puncuality",zB="Failure to sign in",IL={COACHING:_B,BALL_ABUSE:xB,RACKET_ABUSE:wB,VERBAL_ABUSE:LB,PHYSICAL_ABUSE:kB,INELIGIBILITY:FB,UNSPORTSMANLIKE_CONDUCT:GB,PROHIBITED_SUBSTANCE:$B,DRESS_CODE_VIOLATION:VB,EQUIMENT_VIOLATION:BB,LEAVING_THE_COURT:HB,REFUSAL_TO_PLAY:qB,FAILURE_TO_COMPLETE:WB,NO_SHOW:jB,OTHER:YB,PUNCTUALITY:KB,FAILUIRE_TO_SIGN_IN:zB};var QB="CLAY",XB="HARD",JB="GRASS",ZB="CARPET",t2="ARTIFICIAL",hL={CLAY:QB,HARD:XB,GRASS:JB,CARPET:ZB,ARTIFICIAL:t2};var e2="INDOOR",r2="OUTDOOR",SL={INDOOR:e2,OUTDOOR:r2};export{id as activeMatchUpStatuses,AB as askEngine,EB as asyncEngine,gx as auditConstants,NB as competitionEngine,kU as competitionGovernor,ae as completedMatchUpStatuses,$h as directingMatchUpStatuses,tx as displayConstants,NU as drawDefinitionConstants,GN as drawsGovernor,qN as entriesGovernor,xb as entryStatusConstants,wC as errorConditionConstants,ib as eventConstants,iM as eventGovernor,jh as extensionConstants,TL as factoryConstants,vB as fixtures,yx as flightConstants,TB as forge,Fm as genderConstants,pM as generationGovernor,BC as globalState,bE as governors,u_ as keyValueConstants,wv as matchUpActionConstants,UB as matchUpEngine,jy as matchUpFormatCode,jy as matchUpFormatGovernor,bM as matchUpGovernor,Qh as matchUpStatusConstants,IC as matchUpTypes,DB as mocksEngine,PI as mocksGovernor,Kh as nonDirectingMatchUpStatuses,Yh as particicipantsRequiredMatchUpStatuses,Ob as participantConstants,sR as participantGovernor,Dd as participantRoles,yu as participantTypes,IL as penaltyConstants,Ub as policyConstants,gN as policyGovernor,uv as positionActionConstants,gR as publishingGovernor,FN as queryGovernor,Iv as ratingConstants,Nb as recoveryTimeRequiredMatchUpStatuses,IR as reportGovernor,rw as requestConstants,tb as resourceContants,RC as resultConstants,Ab as scaleConstants,OB as scaleEngine,Qb as scheduleConstants,RR as scheduleGovernor,Jg as scoreGovernor,Nx as sortingConstants,hL as surfaceConstants,Zw as syncEngine,rb as tieFormatConstants,kR as tieFormatGovernor,$b as timeItemConstants,cC as tools,Rb as topicConstants,ME as tournamentConstants,MB as tournamentEngine,XR as tournamentGovernor,zh as upcomingMatchUpStatuses,cC as utilities,qh as validMatchUpStatuses,SL as venueConstants,aC as venueGovernor,Ka as version,Ly as weekdayConstants};
|