tods-competition-factory
Version:
Create and mutate TODS compliant tournament objects
3 lines • 1.02 MB
JavaScript
"use strict";function t(){return"2.2.28"}Object.defineProperty(exports,"__esModule",{value:!0});const e="SINGLES",n="SINGLES",r="DOUBLES",i="DOUBLES",a="TEAM",o="TEAM",s={SINGLES_MATCHUP:e,SINGLES:n,DOUBLES_MATCHUP:r,DOUBLES:i,TEAM_MATCHUP:a,TEAM:o},c={[n]:[n,"S"],[i]:[i,"D"],[o]:[o,"T"],S:[n,"S"],D:[i,"D"],T:[o,"T"]};function u(t,e){return(t??0)-(e??0)}function d(t){return"number"==typeof t?parseInt(t.toString()):"string"==typeof t?parseInt(t):0}function p(t){return!isNaN(t)&&(t&&!(t&t-1))}function l(t){if(!t.length)return;const e=[...t].sort(u),n=Math.floor(e.length/2);return e.length%2?e[n]:(e[n-1]+e[n])/2}function m(t){return isNaN(t)?0:t%2&&t+1||t}function f(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function h(t){return!isNaN(parseFloat(t))}function g(t){const e=d(t);if(!isNaN(e))return 0!==e&&1==(e&-e)}function I(t){if(isNaN(t))return!1;for(;!p(t);)t++;return t}function U(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function y(t){return Number.isSafeInteger("string"==typeof t?+t:t)}function S(t,e,n,r,i=2){const a=1-Math.random(),o=1-Math.random();let s=Math.sqrt(-2*Math.log(a))*Math.cos(2*Math.PI*o);return s=s/10+.5,s>1||s<0?s=S(t,e,n):(s=Math.pow(s,n),s*=e-t,s+=t),r&&(s=function(t,e){e||(e=1);const n=1/e;return Math.round(t*n)/n}(s,r)),parseFloat(s.toFixed(i))}function v(t,e=2){return parseFloat(Number(Math.round(1e3*t)/1e3).toFixed(e))}function w(t){return Array.isArray(t)?t?.filter(((t,e,n)=>n.lastIndexOf(t)===e)):[]}function P(t){return Array.isArray(t)?t.map((t=>[Math.random(),t])).sort(((t,e)=>t[0]-e[0])).map((t=>t[1])):[]}function D(t){return y(t)?t:1/0}function T(t){return Array.isArray(t)?t.reduce(((t,e)=>(t[e]||(t[e]=0),t[e]++,t)),{}):{}}function b(t){return Object.keys(t).reduce(((e,n)=>{const r=t[n];return e[r]?e[r].push(n):e[r]=[n],e}),{})}function R(t,e,n){return n.indexOf(t)===e}function M(t){return t.filter(R)}function N(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function A(t){return t[Math.floor(Math.random()*t.length)]}function E(t,e){return Array.from({length:e-t},((e,n)=>n+t))}function C(t,e){return e.reduce(((e,n,r)=>(n===t&&e.push(r),e)),[])}function O(t,e){return Array.isArray(t)&&Array.isArray(e)?t.filter((t=>-1!==e.indexOf(t))).filter(((t,e,n)=>n.indexOf(t)===e)):[]}function F(t,e){return Array.isArray(t)&&Array.isArray(e)?t.filter((t=>!e.includes(t))):[]}function k(t,e){return!(!Array.isArray(t)||!Array.isArray(e))&&t.some((t=>e.includes(t)))}function x(t,e){return Array.isArray(t)?t.reduce(((t,n,r)=>{const i=Math.floor(r/e);return t[i]=[].concat(t[i]||[],n),t}),[]):[]}function _(t){return!!Array.isArray(t)&&t.reduce(((t,e)=>!isNaN(parseInt(e))&&t),!0)}function L(t){return!!Array.isArray(t)&&t.reduce(((t,e)=>isNaN(parseInt(e))&&t),!0)}function B(t,e,n){return Array.isArray(t)?t.reduce(((t,r,i)=>{const a=!!n&&!!(Math.floor(i/e)%2),o=i%e,s=a?e-1-o:o;return t[s]||(t[s]=[]),t[s].push(r),t}),[]):[]}function V(t){return"function"==typeof t}function j(t){return"string"==typeof t}function G(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function q(t,e){if(!G(t)||!G(e))return!1;const n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(const r of n)if(t[r]!==e[r])return!1;return!0}function $(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(G).map((t=>t[e]&&{[t[e]]:t})).filter(Boolean)):{}}function W(t){return Array.isArray(t)?t.length+t.map(W).reduce(((t,e)=>t+e),0):G(t)&&null!==t?Object.keys(t).length+Object.keys(t).map((e=>W(t[e]))).reduce(((t,e)=>t+e),0):0}function H(t,e){return!(!Array.isArray(t)||!j(e))&&O(t,c[e]).length}const z={success:!0},Y="error",K={SUCCESS:z,ERROR:Y};function Q({collectionValueProfiles:t,matchUpCount:e}){const n=[];if(!Array.isArray(t))return n.push(`collectionValueProfiles is not an array: ${t}`),{errors:n};if(t.length&&t.length!==e)return n.push("collectionValueProfiles do not align with matchUpsCount"),{errors:n};for(const r of t){if("object"!=typeof r)return n.push(`valueProfile is not type object: ${r}`),{errors:n};const{matchUpValue:t,collectionPosition:i}=r;if("number"!=typeof t||"number"!=typeof i||i>e||i<1)return n.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:n}}const r=t.map((t=>t.collectionPosition));return r.length!==w(r).length?(n.push("collectionPositions are not unique"),{errors:n}):{...z}}const J={message:"Chronological error; time violation.",code:"ANACHRONISM"},Z={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},X={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},tt={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},et={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},nt={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},rt={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},it={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},at={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},ot={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},st={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},ct={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},ut={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},dt={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},pt={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},lt={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},mt={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},ft={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},ht={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},gt={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},It={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Ut={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},yt={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},St={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},vt={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},wt={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},Pt={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Dt={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Tt={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},bt={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},Rt={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},Mt={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},Nt={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},At={message:"Invalid action",code:"ERR_INVALID_ACTION"},Et={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},Ct={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},Ot={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},Ft={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},kt={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},xt={message:"Existing round",code:"ERR_EXISTING_ROUND"},_t={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Lt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Bt={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Vt={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},jt={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},Gt={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},qt={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"},$t={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Wt={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},Ht={message:"Event exists",code:"ERR_EXISTING_EVENT"},zt={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},Yt={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Kt={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Qt={message:"Missing stage",code:"ERR_MISSING_STAGE"},Jt={message:"Invalid stage",code:"ERR_INVALID_STAGE"},Zt={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},Xt={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},te={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},ee={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},ne={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},re={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},ie={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ae={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},oe={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},se={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},ce={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},ue={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},de={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},pe={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},le={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},me={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},fe={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},he={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},ge={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Ie={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},Ue={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},ye={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},Se={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},ve={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},we={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},Pe={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},De={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},Te={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},be={message:"Missing value",code:"ERR_MISSING_VALUE"},Re={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},Me={message:"Missing date",code:"ERR_MISSING_DATE"},Ne={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Ae={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Ee={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},Ce={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},Oe={message:"Invalid Date",code:"ERR_INVALID_DATE"},Fe={message:"Invalid time",code:"ERR_INVALID_TIME"},ke={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},xe={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},_e={message:"Invalid score",code:"ERR_INVALID_SCORE"},Le={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"},Be={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Ve={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},je={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Ge={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},qe={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},$e={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},We={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},He={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},ze={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},Ye={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Ke={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},Qe={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Je={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Ze={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},Xe={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},tn={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},en={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},nn={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},rn={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},an={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},on={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},sn={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},cn={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},un={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},dn={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},pn={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},ln={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},mn={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},fn={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},hn={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},gn={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},In={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},Un={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},yn={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Sn={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},vn={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},wn={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Pn={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},Dn={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Tn={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},bn={message:"Court exists",code:"ERR_EXISTING_COURT"},Rn={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Mn={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Nn={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},An={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},En={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},Cn={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},On={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},Fn={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},kn={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},xn={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},_n={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},Ln={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Bn={message:"Missing context",code:"ERR_MISSING_CONTEXT"},Vn={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},jn={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},Gn={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},qn={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},$n={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Wn={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},Hn={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},zn={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},Yn={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Kn={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Qn={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},Jn={message:"Invalid values",code:"ERR_INVALID_VALUES"},Zn={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},Xn={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},tr={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},er={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},nr={message:"Value unchanged",code:"ABORT_UNCHANGED"},rr={message:"Not found",code:"ERR_NOT_FOUND"},ir={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},ar={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},or={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},sr={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},cr={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},ur={message:"Existing stage",code:"ERR_EXISTING_STAGE"},dr={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},pr={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},lr={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},mr={message:"Scores present",code:"ERR_SCORES_PRESENT"},fr={ANACHRONISM:J,CANNOT_CHANGE_WINNING_SIDE:$e,CANNOT_MODIFY_TIEFORMAT:Ve,CANNOT_MODIFY_PARTICIPANT_TYPE:je,CANNOT_REMOVE_MAIN_STRUCTURE:X,CANNOT_REMOVE_PARTICIPANTS:Ge,CATEGORY_MISMATCH:qe,COURT_EXISTS:bn,COURT_NOT_FOUND:Tn,DRAW_DEFINITION_NOT_FOUND:ct,DRAW_ID_EXISTS:bt,DRAW_POSITION_ACTIVE:It,DRAW_POSITION_ASSIGNED:lt,DRAW_POSITION_NOT_CLEARED:ft,DRAW_POSITION_NOT_FOUND:{message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},DRAW_SIZE_MISMATCH:Pt,DUPLICATE_ENTRY:Z,DUPLICATE_VALUE:Zn,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:In,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:gn,EVENT_EXISTS:Ht,EVENT_NOT_FOUND:Wt,EXISTING_DRAW_DEFINITIONS:st,EXISTING_END_TIME:En,EXISTING_FLIGHT:ar,EXISTING_MATCHUP_ID:cr,EXISTING_OUTCOME:sr,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:un,EXISTING_PARTICIPANT:dn,EXISTING_POLICY_TYPE:ve,EXISTING_PROFILE:or,EXISTING_ROUND:xt,EXISTING_STAGE:ur,EXISTING_STRUCTURE:dr,INCOMPATIBLE_MATCHUP_STATUS:re,INCOMPLETE_SOURCE_STRUCTURE:dt,INSUFFICIENT_DRAW_POSITIONS:Sn,INVALID_ACTION:At,INVALID_ASSIGNMENT:Et,INVALID_BOOKINGS:Ae,INVALID_CATEGORY:Qn,INVALID_COLLECTION_DEFINITION:zn,INVALID_CONFIGURATION:Hn,INVALID_DATE_AVAILABILITY:Ee,INVALID_DATE:Oe,INVALID_DRAW_DEFINITION:at,INVALID_DRAW_POSITION_FOR_SEEDING:pt,INVALID_DRAW_POSITION:yt,INVALID_DRAW_SIZE:wt,INVALID_END_TIME:An,INVALID_ENTRIES:Yt,INVALID_EVENT_TYPE:qt,INVALID_GAME_SCORES:xe,INVALID_GENDER:Kn,INVALID_MATCHUP_FORMAT:oe,INVALID_MATCHUP_STATUS:ie,INVALID_MATCHUP_STATUS_BYE:te,INVALID_MATCHUP:he,INVALID_OBJECT:Yn,INVALID_PARTICIPANT_ID:He,INVALID_PARTICIPANT_IDS:ze,INVALID_PARTICIPANT_ROLE:Ye,INVALID_PARTICIPANT_SEEDING:Rt,INVALID_PARTICIPANT_TYPE:Ke,INVALID_PARTICIPANT:We,INVALID_POLICY_DEFINITION:Se,INVALID_RECORDS:tt,INVALID_SCALE_ITEM:jn,INVALID_SEED_NUMBER:Ot,INVALID_SEED_POSITION:Ft,INVALID_SET_NUMBER:{message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},INVALID_SIDE_NUMBER:Pe,INVALID_SCORE:_e,INVALID_STAGE:Jt,INVALID_START_TIME:On,INVALID_STRUCTURE:ut,INVALID_STOP_TIME:Cn,INVALID_TIE_FORMAT:ae,INVALID_TIME:Fe,INVALID_TIME_ITEM:kn,INVALID_TOURNAMENT_DATES:ke,INVALID_TOURNAMENT_RECORD:rt,INVALID_VALUES:Jn,INVALID_WINNING_SIDE:Le,MATCHUP_NOT_FOUND:le,METHOD_NOT_FOUND:pr,MISSING_ASSIGNMENTS:Kt,MISSING_ASYNC_STATE_PROVIDER:xn,MISSING_AVOIDANCE_POLICY:Ue,MISSING_BIRTH_DATE:Re,MISSING_COLLECTION_DEFINITION:ce,MISSING_COURT_ID:Te,MISSING_COURTS_INFO:Dn,MISSING_DATE_AVAILABILITY:Ce,MISSING_DATE:Me,MISSING_DRAW_DEFINITION:ot,MISSING_DRAW_ID:Tt,MISSING_DRAW_POSITION:St,MISSING_DRAW_POSITIONS:gt,MISSING_DRAW_SIZE:Dt,MISSING_ENTRIES:zt,MISSING_EVENT:$t,MISSING_QUALIFIED_PARTICIPANTS:tn,MISSING_MATCHUP_FORMAT:se,MISSING_MATCHUP_ID:de,MISSING_MATCHUP_IDS:pe,MISSING_MATCHUP:fe,MISSING_MATCHUPS:me,MISSING_PARTICIPANT_COUNT:on,MISSING_PARTICIPANT_ID:Xe,MISSING_PARTICIPANT_IDS:an,MISSING_PARTICIPANT_ROLE:Qe,MISSING_PARTICIPANT:Je,MISSING_PARTICIPANTS:Ze,MISSING_PENALTY_ID:wn,MISSING_PENALTY_TYPE:vn,MISSING_PERSON_DETAILS:cn,MISSING_POLICY_ATTRIBUTES:ye,MISSING_POLICY_DEFINITION:Ie,MISSING_POLICY_TYPE:ge,MISSING_POSITION_ASSIGNMENTS:Xt,MISSING_ROUND_NUMBER:{message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},MISSING_SCHEDULE:Vn,MISSING_SCORING_POLICY:{message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},MISSING_SEED_ASSIGNMENTS:Ct,MISSING_SEEDCOUNT_THRESHOLDS:Nt,MISSING_SEEDING_POLICY:{message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},MISSING_SET_NUMBER:{message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},MISSING_SET_OBJECT:De,MISSING_SIDE_NUMBER:{message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},MISSING_STAGE:Qt,MISSING_STRUCTURE_ID:_t,MISSING_STRUCTURE:Vt,MISSING_MAIN_STRUCTURE:jt,MISSING_STRUCTURES:Bt,MISSING_TARGET_LINK:kt,MISSING_TIE_FORMAT:ue,MISSING_TIME_ITEM:_n,MISSING_TIME_ITEMS:Ln,MISSING_TOURNAMENT_ID:it,MISSING_TOURNAMENT_RECORD:nt,MISSING_TOURNAMENT_RECORDS:et,MISSING_VALUE:be,MISSING_VENUE_ID:Nn,MODIFICATIONS_FAILED:Gn,NO_CANDIDATES:Wn,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:yn,NO_MODIFICATIONS_APPLIED:qn,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:Un,NO_PARTICIPANT_REMOVED:rn,NO_VALID_ACTIONS:tr,NO_VALID_ATTRIBUTES:er,NO_VALID_DATES:Ne,NOT_FOUND:rr,NOT_IMPLEMENTED:ir,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:pn,PARTICIPANT_ID_EXISTS:nn,PARTICIPANT_NOT_CHECKED_IN:sn,PARTICIPANT_NOT_FOUND:en,PARTICIPANT_PAIR_EXISTS:{message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},PENALTY_NOT_FOUND:Pn,POLICY_NOT_ATTACHED:{message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},POLICY_NOT_FOUND:we,SCHEDULE_NOT_CLEARED:mt,SCHEDULED_MATCHUPS:lr,SCORES_PRESENT:mr,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:Mt,STAGE_SEQUENCE_LIMIT:Zt,STRUCTURE_NOT_FOUND:Lt,TEAM_NOT_FOUND:Xn,UNABLE_TO_ASSIGN_COURT:$n,UNLINKED_STRUCTURES:Gt,UNRECOGNIZED_DRAW_TYPE:ht,UNRECOGNIZED_MATCHUP_FORMAT:ne,UNRECOGNIZED_MATCHUP_STATUS:ee,VALUE_UNCHANGED:nr,VENUE_EXISTS:Rn},hr={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]};var gr={addNotice:function({topic:t,payload:e,key:n},r){if("string"!=typeof t||"object"!=typeof e)return;hr.disableNotifications||(hr.modified=!0);if(hr.disableNotifications||!hr.subscriptions[t]&&!r)return;n&&(hr.notices=hr.notices.filter((e=>!(e.topic===t&&e.key===n))));return hr.notices.push({topic:t,payload:e,key:n}),{...z}},callListener:function({topic:t,notices:e},n){const r=hr.subscriptions[t];r&&"function"==typeof r&&r(e);const i=n?.[t];i&&"function"==typeof i&&i(e)},cycleMutationStatus:function(){const t=hr.modified;return hr.modified=!1,t},deleteNotice:function({topic:t,key:e}){hr.notices=hr.notices.filter((n=>(!t||n.topic===t)&&n.key!==e))},deleteNotices:function(){hr.notices=[]},disableNotifications:function(){hr.disableNotifications=!0},enableNotifications:function(){hr.disableNotifications=!1},getMethods:Ur,getNotices:function({topic:t}){return hr.notices.filter((e=>e.topic===t)).map((t=>t.payload))},getTopics:function(){return{topics:Object.keys(hr.subscriptions)}},getTournamentId:Ir,getTournamentRecord:function(t){return hr.tournamentRecords[t]},getTournamentRecords:function(){return hr.tournamentRecords},removeTournamentRecord:function(t){if("string"!=typeof t)return{error:Jn};if(!hr.tournamentRecords[t])return{error:rr};delete hr.tournamentRecords[t];const e=Object.keys(hr.tournamentRecords);1===e.length?hr.tournamentId=e[0]:e.length||(hr.tournamentId=void 0);return{success:!0}},setMethods:function(t){return"object"!=typeof t?{error:Jn}:(Object.keys(t).forEach((e=>{"function"==typeof t[e]&&(hr.methods[e]=t[e])})),{...z})},setSubscriptions:function(t){return"object"!=typeof t.subscriptions?{error:Jn}:(Object.keys(t.subscriptions).forEach((e=>{"function"==typeof t.subscriptions[e]?hr.subscriptions[e]=t.subscriptions[e]:delete hr.subscriptions[e]})),{...z})},setTournamentId:function(t){if(!t)return hr.tournamentId=void 0,{success:!0};return hr.tournamentRecords[t]?(hr.tournamentId=t,{success:!0}):{error:nt}},setTournamentRecord:function(t){const e=t?.tournamentId;return e?(hr.tournamentRecords[e]=t,{success:!0}):{error:rt}},setTournamentRecords:function(t){hr.tournamentRecords=t;const e=Object.keys(t);1===e.length?hr.tournamentId=e[0]:e.length||(hr.tournamentId=void 0)},handleCaughtError:function({engineName:t,methodName:e,params:n,err:r}){let i;"string"==typeof r?i=r.toUpperCase():r instanceof Error&&(i=r.message);return console.log("ERROR",{tournamentId:Ir(),params:JSON.stringify(n),engine:t,methodName:e,error:i}),{error:i}}};function Ir(){return hr.tournamentId}function Ur(){return hr.methods??{}}const yr={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0};let Sr=gr;const vr=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function wr(){if(Sr.createInstanceState){try{Sr.createInstanceState()}catch(t){return{error:t}}return{success:!0}}return{error:xn}}function Pr(t){return t&&"object"==typeof t?"object"==typeof yr.devContext&&(Object.keys(t).every((e=>yr.devContext?.[e]===t[e]))&&yr.devContext):yr.devContext??!1}function Dr(t){V(t)?yr.globalLog=t:delete yr.globalLog}function Tr(t){yr.devContext=t}function br(){Sr.disableNotifications()}function Rr(){Sr.enableNotifications()}function Mr(t,e){"boolean"==typeof t&&(yr.deepCopy=t),"object"==typeof e&&(Array.isArray(e.ignore)&&(yr.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(yr.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(yr.deepCopyAttributes.stringify=e.stringify),e.threshold&&(yr.deepCopyAttributes.threshold=e.threshold))}function Nr(){return{enabled:yr.deepCopy,...yr.deepCopyAttributes}}function Ar(t){return t?"object"!=typeof t?{error:Jn}:(Object.keys(t).forEach((e=>{V(t[e])&&(yr.globalMethods[e]=t[e])})),{...z}):{error:be,info:"missing method declarations"}}function Er(t){return t?"object"!=typeof t?{error:Jn}:Sr.setMethods(t):{error:be,info:"missing method declarations"}}function Cr(){return Sr.cycleMutationStatus()}function Or(t){if("string"!=typeof t?.topic)return;const e=yr.globalSubscriptions[t.topic];return Sr.addNotice(t,e)}function Fr(){return{...yr.globalMethods,...Sr.getMethods()}}function kr(t){return Sr.getNotices(t)}function xr({key:t,topic:e}){return Sr.deleteNotice({key:t,topic:e})}function _r(){return Sr.deleteNotices()}function Lr(){return Sr.getTopics()}function Br(t){return Lr()?.topics?.includes(t)}async function Vr(t){return Sr.callListener(t,yr.globalSubscriptions)}function jr(){return Sr.getTournamentId()}function Gr(t){return Sr.getTournamentRecord(t)}function qr(){return Sr.getTournamentRecords()}function $r(t){return Sr.setTournamentRecord(t)}function Wr(t){return Sr.setTournamentRecords(t)}function Hr(t){return Sr.setTournamentId(t)}function zr(t){return Sr.removeTournamentRecord(t)}function Yr(){return Sr}function Kr({engineName:t,methodName:e,params:n,err:r}){const i=V(Sr.handleCaughtError)&&Sr.handleCaughtError||gr.handleCaughtError,{tournamentRecord:a,...o}=n;return i({params:o,engineName:t,methodName:e,err:r})}function Qr(t,e){if(yr.globalLog)try{yr.globalLog({log:t,engine:e})}catch(n){console.log("globalLog error",n),console.log(e,t),Dr()}else console.log(e,t)}function Jr(t,e,n,r){if(!G(t))return{error:Jn};h||(n=1);const i=Array.isArray(e)?e:[],a={},o=(t,r=0)=>{Object.keys(t).forEach((s=>{V(t[s])?a[s]=t[s]:G(t[s])&&(!0===e||i?.includes(s))&&(void 0===n||r<n)&&o(t[s],r+1)}))};return o(t),r?Ar(a):Er(a),{methods:a}}var Zr={__proto__:null,addNotice:Or,callListener:Vr,createInstanceState:wr,cycleMutationStatus:Cr,deepCopyEnabled:Nr,deleteNotice:xr,deleteNotices:_r,disableNotifications:br,enableNotifications:Rr,getDevContext:Pr,getMethods:Fr,getNotices:kr,getProvider:Yr,getTopics:Lr,getTournamentId:jr,getTournamentRecord:Gr,getTournamentRecords:qr,globalLog:Qr,handleCaughtError:Kr,hasTopic:Br,removeTournamentRecord:zr,setDeepCopy:Mr,setDevContext:Tr,setGlobalLog:Dr,setGlobalMethods:Ar,setGlobalSubscriptions:function(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach((e=>{yr.globalSubscriptions[e]=t.subscriptions[e]})),{...z}):{error:be,info:"missing subscriptions"}},setMethods:Er,setStateMethods:Jr,setStateProvider:function(t){if("object"!=typeof t)throw new Error("Global state provider can not be undefined or null");if(O(Object.keys(t),vr).length!==vr.length)throw new Error("Global state provider is missing required methods");return Sr=t,{success:!0}},setSubscriptions:function(t){return t?.subscriptions?Sr.setSubscriptions({subscriptions:t.subscriptions}):{error:be,info:"missing subscriptions"}},setTournamentId:Hr,setTournamentRecord:$r,setTournamentRecords:Wr,timeKeeper:function(t="reset",e="default"){const n=Date.now();if("report"===t){if("allTimers"===e){return Object.keys(yr.timers).filter((t=>"default"!==t||yr.timers[t].startTime)).map((t=>{const e=yr.timers[t],r="stopped"===e.state?0:(n-(e?.startTime??0))/1e3,i=e.elapsedTime+r;return{state:yr.timers[t].state,elapsedTime:i.toFixed(2),timer:t}}))}{const t="stopped"===yr.timers[e].state?0:(n-(yr.timers[e]?.startTime??0))/1e3,r=yr.timers[e].elapsedTime+t;return{state:yr.timers[e].state,elapsedTime:r.toFixed(2),timer:e}}}if(!yr.timers[e]||"reset"===t){if("allTimers"===e)return yr.timers={default:{elapsedTime:0}},!0;yr.timers[e]={startTime:n,state:"active",elapsedTime:0}}return yr.timers[e].elapsedTime||(yr.timers[e].elapsedTime=0),"stop"===t&&"stopped"!==yr.timers[e].state&&(yr.timers[e].state="stopped")&&(yr.timers[e].elapsedTime+=(n-(yr.timers[e]?.startTime??0))/1e3),"start"===t&&(yr.timers[e].startTime=n)&&(yr.timers[e].state="active"),yr.timers[e]}};function Xr(t,e,n,r){if("object"!=typeof t||null===t)return t;const i=Nr();i?.enabled||(r=!0);const a=["",void 0,null];e&&a.push(!1);const o=function(t,e,n){return Object.keys(t).filter((r=>!e.includes(t[r])&&(!n||!Array.isArray(t[r])||t[r].length)))}(t,a,n);return Object.assign({},...o.map((e=>Array.isArray(t[e])?{[e]:r?t[e]:t[e].map((t=>Xr(t)))}:{[e]:r?t[e]:Xr(t[e])})))}function ti({context:t,result:e,stack:n,info:r}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&"string"==typeof n&&e.stack.push(n),e&&r&&(e.info=r),e&&"object"==typeof t&&Object.keys(t).length&&Object.assign(e,Xr(t)),!e||e?.error||e?.success||Object.assign(e,{...z}),e??{success:!0}}const ei="ANY",ni="MALE",ri="MIXED",ii="OTHER",ai="FEMALE",oi={ANY:ei,MALE:ni,FEMALE:ai,MIXED:ri,OTHER:ii};function si(t){const e="tieFormatGenderValidityCheck",{referenceGender:n,matchUpType:r,gender:a}=t;return n&&a&&[ni,ai].includes(n)&&n!==a?ti({result:{valid:!1,error:Kn},context:{gender:a},stack:e}):n===ri&&(a===ei||a===ri&&r!==i)?ti({result:{error:Kn,valid:!1},info:"MIXED events can not contain mixed singles or { gender: ANY } collections",stack:e}):n===ei&&a===ri&&r!==i?ti({result:{error:Kn,valid:!1},info:"events with { gender: ANY } can not contain MIXED singles collections",stack:e}):{valid:!0}}const ci="timed",ui="NOAD",di="SET",pi={S:"normal",F:"final"};function li(t,e){if((t?.bestOf||t?.exactly)&&t?.setFormat)return function(t,e){const n=mi(t.bestOf)||void 0,r=mi(t.exactly)||void 0,i=n||r;if(t.setFormat?.timed&&t.simplified&&1===i)return fi(t.setFormat);const a=i&&`${di}${i}`||"",o=hi(t.setFormat,e),s=o&&`S:${o}`||"",c=hi(t.finalSetFormat,e),u=i&&i>1&&c&&o!==c&&`F:${c}`||"";if(a&&o)return[a,s,u].filter((t=>t)).join("-");return}(t,e)}function mi(t){return!isNaN(Number(t))&&Number(t)}function fi(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function hi(t,e){if("object"==typeof t&&Object.keys(t).length){if(t.timed)return fi(t);if(t.tiebreakSet)return gi(t.tiebreakSet);const n=mi(t.setTo);if(n){const r=t.NoAD&&ui||"",i=gi(t.tiebreakFormat),a=i&&`/${i}`||"",o=mi(t.tiebreakAt);if(!1!==i)return`${n}${r}${a}${o&&(o!==n||e)&&`@${o}`||""}`}}}function gi(t){if(t){if("object"!=typeof t||t.tiebreakTo){if("object"==typeof t&&mi(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?ui:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}return!1}return""}}function Ii(t){if(j(t)){const e=t.startsWith("T")&&ci||t.startsWith(di)&&di||"";if(e===ci){const e=vi(t);if(e)return{simplified:!0,setFormat:e,bestOf:1}}if(e===di)return function(t){const e=t.split("-"),n=Pi(e[0].slice(3)),r=1===n||n%2!=0?n:void 0,i=1!==n&&n%2==0?n:void 0,a=e&&Ui(e[1]),o=e&&Ui(e[2]),s=a&&a.timed||o&&o.timed,c=r&&r<6||s&&i,u=!e[2]||o,d=a,p=Xr({setFormat:a,exactly:i,bestOf:r});o&&(p.finalSetFormat=o);if(c&&d&&u)return p}(t)}}function Ui(t){if(":"===t?.[1]){const e=t.split(":"),n=pi[e[0]],r=e[1];if(n&&r){if(r.startsWith("TB")){const t=Si(r);return!1!==t&&("object"==typeof t?{tiebreakSet:t}:void 0)}if(r.startsWith("T"))return vi(r);const e=t.match(/^[FS]:(\d+)([A-Za-z]*)/),n=e&&wi(e[2])||!1,i=!e?.[2]||n,a=e?Pi(e[1]):void 0,o=yi(r),s=!1!==o,c=s&&o||a,u=Si(r.split("/")[1]),d=!1!==u,p={setTo:a};return n&&(p.NoAD=!0),u?(p.tiebreakFormat=u,p.tiebreakAt=c):p.noTiebreak=!0,a&&i&&d&&s&&p||!1}}}function yi(t,e=!0){const n=t?.indexOf("@")>0&&t.split("@");if(n){return(e?Pi(n[1]):n[1])||!1}}function Si(t){if(t){if(t.startsWith("TB")){const e=yi(t,!1),n=t.match(/^TB(\d+)([A-Za-z]*)/),r=n?.[1],i=n&&wi(n[2]),a=!n?.[2]||i,o=Pi(r);if(o&&a){const t={tiebreakTo:o};return e&&"string"==typeof e&&!y(e)&&(t.modifier=e),i&&(t.NoAD=!0),t}return!1}return!1}}function vi(t){const e=t.slice(1),n=e.match(/^(\d+)(@?[A-Za-z]*)/),r=Pi(n?.[1]);if(!r)return;const i={timed:!0,minutes:r},a=n?.[2],o=[void 0,"P","G"].includes(a);if(a&&!o){const t=e.match(/^(\d+)(@)([A-Za-z]+)$/)?.[3];return t?(i.modifier=t,i):void 0}return a&&(i.based=n[2]),i}function wi(t){return t&&t.indexOf(ui)>=0}function Pi(t){return isNaN(Number(t))?0:Number(t)}function Di({matchUpFormat:t}){if(!j(t)||""===t)return!1;const e=Ii(t),n=t.match(/-S:([1-9])+\/TB(\d{1,2})@?([1-9]?)*/),r=n?.[1],i=n?.[2],a=n?.[3],o=t.match(/-F:([1-9])+\/TB(\d{1,2})@?([1-9]?)*/),s=o?.[1],c=o?.[2],u=o?.[3];return li(e,!!(n&&i&&r===a||o&&c&&s===u))===t}const Ti=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,bi=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Ri=/^([\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?$/,Mi=/^([\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 Ni(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=$i(t.scheduledTime)),!e)return;const n=qi(t.scheduledTime);let r=$i(e);return r&&n&&(r+=`T${n}`),r}function Ai(t){if("object"!=typeof t||Array.isArray(t))return!1;return"[object Date]"===Object.prototype.toString.call(t)}function Ei(t){const e="string"==typeof t?t?.split(" "):[];return!(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))&&!(t&&!Mi.test(zi(t,!0,!0)))}function Ci(t){return Bi(t)||Ti.test(t)}const Oi=t=>{const e=xi(t)||Bi(t)?new Date(t):new Date,n=e.getUTCMonth()+1,r=n<10?`0${n}`:`${n}`;return`${e.getUTCFullYear()}-${ta(r)}-${ta(e.getUTCDate())}`};function Fi(t,e="-",n="YMD"){if(!t)return"";"string"==typeof t&&t.indexOf("T")<0&&(t+="T00:00");const r=new Date(t);let i=""+(r.getMonth()+1),a=""+r.getDate();const o=r.getFullYear();return i.length<2&&(i="0"+i),a.length<2&&(a="0"+a),"DMY"===n?[a,i,o].join(e):"MDY"===n?[i,a,o].join(e):"YDM"===n?[o,a,i].join(e):"DYM"===n?[a,o,i].join(e):"MYD"===n?[i,o,a].join(e):[o,i,a].join(e)}function ki(t){const e=t?new Date(t):new Date,n=e.getTimezoneOffset();return new Date(e.getTime()-60*n*1e3)}function xi(t){if("boolean"==typeof t)return!1;const e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function _i(t,e){if(!Ci(t)||!Ci(e))return[];const n=$i(t)+"T00:00",r=$i(e)+"T00:00",i=new Date(n),a=new Date(r);const o=[];let s=0;if(xi(a)&&xi(i)&&i<=a){const t=i;let e=t.getTime();for(;e<=a.getTime()&&s<300;)s+=1,o.push(new Date(t)),e=t.setDate(t.getDate()+1)}return o.map((t=>Fi(t)))}const Li=/^([+-]?\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 Bi(t){return"string"==typeof t&&Li.test(t)}function Vi(t){if("string"!=typeof t)return!1;const e=t.split("Z")[0].split(":"),n=e.every((t=>!isNaN(parseInt(t))));return!(e.length<2||!n||parseInt(e[0])>23||parseInt(e[1])>60)}function ji(t){const e=qi(t);if(!e)return 0;const[n,r]=e.split(":").map((t=>parseInt(t)));return 60*n+r}function Gi(t){return Vi(t)?t.split(":").slice(0,2).map(ta).join(":"):void 0}function qi(t){return Bi(t)&&t.indexOf("T")>0?Gi(t.split("T").reverse()[0]):Gi(t)}function $i(t){return Bi(t)||Ri.test(t)?t.split("T")[0]:void 0}function Wi(t,e){const n=new Date(t);return n.setDate(n.getDate()+e),$i(n.toISOString())}function Hi(t){t="string"!=typeof t?"00:00":t;const e={},n={};return({0:e.time,1:e.ampm}=t.split(" ")||[]),({0:n.hours,1:n.minutes}=e.time.split(":")||[]),n.ampm=e.ampm,isNaN(n.hours)||isNaN(n.minutes)||n.ampm&&!["AM","PM"].includes(n.ampm.toUpperCase())?{}:n}function zi(t,e,n){const r=$i(t),i=qi(t),a=r?i:t;return t?e&&(r&&n&&t||function(t){const e=Hi(t);return e.ampm&&e.hours&&("pm"===e.ampm.toLowerCase()&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),"am"===e.ampm.toLowerCase()&&"12"===e.hours&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(ta).join(":")}(a))||function(t){const e=Hi(t);if("object"!=typeof e||Object.keys(e).length)return e.ampm?t:(e.hours>12?(e.hours-=12,e.ampm="PM"):"12"===e.hours?e.ampm="PM":"00"===e.hours?(e.hours="12",e.ampm="AM"):e.ampm="AM","0"===e.hours?.[0]&&(e.hours=e.hours.slice(1)),`${e.hours||"12"}:${e.minutes||"00"} ${e.ampm}`)}(a):void 0}function Yi(t,e){const n=Hi(t),r=Hi(e);if(parseInt(n.hours)<parseInt(r.hours))return-1;if(parseInt(n.hours)>parseInt(r.hours))return 1;if(n.hours===r.hours){if(parseInt(n.minutes)<parseInt(r.minutes))return-1;if(parseInt(n.minutes)>parseInt(r.minutes))return 1}return 0}function Ki(t,e=7){const n=$i(t)+"T00:00",r=new Date(n);return Fi(new Date(r.setDate(r.getDate()+e)))}function Qi(t,e=void 0){const[n,r]=(t||"00:00").split(":").map(ta),i=ki(e).setHours(n,r,0,0);return ki(i)}function Ji(t,e,n=!0){const r=new Date(t),i=(new Date(e).getTime()-r.getTime())/1e3/60;return n?Math.abs(Math.round(i)):Math.round(i)}function Zi(t,e){const n=qi(t);if(!n)return"00:00";const r=isNaN(e)?0:e;return qi(Xi(Qi(n),r).toISOString())}function Xi(t,e){const n=new Date(t);return new Date(n.getTime()+6e4*e)}function ta(t){return t.toString()[1]?t:"0"+t}function ea(t,e){const n=new Date(t),r=new Date(e);return n.getFullYear()===r.getFullYear()&&n.getMonth()===r.getMonth()&&n.getDate()===r.getDate()}const na={addDays:Ki,addWeek:function(t){return Ki(t)},addMinutesToTimeString:Zi,convertTime:zi,getIsoDateString:Ni,getUTCdateString:Oi,DateHHMM:function(t){const e=new Date(t);return function(t,e){const n=parseInt(t,10),r=Math.floor(n/3600),i=Math.floor((n-3600*r)/60),a=n-3600*r-60*i;return(!e||e?.displaySeconds?r+":"+i+":"+a:r+":"+i).split(":").map(ta).join(":")}(e.getSeconds()+60*e.getMinutes()+3600*e.getHours(),{displaySeconds:!1})},extractDate:$i,extractTime:qi,formatDate:Fi,getDateByWeek:function(t,e,n,r=!1){const i=new Date(e,0,1+7*(t-1)),a=r?0:1;return i.setDate(i.getDate()+(a-i.getDay())),Fi(i,n)},isISODateString:Bi,isDate:xi,isTimeString:Vi,offsetDate:ki,offsetTime:function(t){return ki(t).getTime()},sameDay:ea,timeStringMinutes:ji,timeToDate:Qi,timeUTC:function(t){const e=xi(t)||Bi(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())},validTimeValue:Ei,validDateString:Ti,timeValidation:Mi,dateValidation:Ri};function ra(t){const e=t.category;if("object"!=typeof e)return{error:Qn};let{ageCategoryCode:n,ageMaxDate:r,ageMinDate:i,ageMax:a,ageMin:o}=e;const s=e.categoryName;let c;var u;if(!(u="string",[n,r,i,s].filter(Boolean).every((t=>typeof t===u))&&(t=>t.filter(Boolean).every(h))([a,o])&&[r,i].filter(Boolean).every(Ci)))return{error:Qn};const d=t.consideredDate??$i((new Date).toLocaleDateString("sv"));if(!Ci(d))return{error:Oe};const[p]=d.split("-").slice(0,3).map((t=>parseInt(t))),l=Wi(d,-1),[m,f]=l.split("-").slice(1,3).map((t=>parseInt(t))),g=`${ta(m)}-${ta(f)}`,I=Wi(d,1),[U,y]=I.split("-").slice(1,3).map((t=>parseInt(t))),S=`${ta(U)}-${ta(y)}`;let v=o&&Wi(d,-365*o),w=a&&Wi(d,-365*a);const P=[],D=t=>!P.includes(t)&&P.push(t);n=n??s;const T=/^([UO]?)(\d{1,2})([UO]?)$/,b=/^C(\d{1,2})-(\d{1,2})$/,R=n?.includes("-"),M=R&&n?.match(b),N=n?.match(T),A=(t,e)=>`${t}-${e}`,E=t=>{const r=A(p-t-1,S);e.ageMin&&e.ageMin>t&&D(`Invalid submitted ageMin: ${o}`),e.ageMax&&e.ageMax>t&&D(`Invalid submitted ageMax: ${a}`),e.ageMinDate&&e.ageMinDate!==r&&D(`Invalid submitted ageMinDate: ${i}`),i=r,n&&(e.ageMax&&e.ageMax!==t&&(D(`Invalid submitted ageMax: ${a}`),v=void 0),a=t)},C=t=>{const i=A(p-t,g);e.ageMaxDate&&e.ageMaxDate!==i&&D(`Invalid submitted ageMaxDate: ${r}`),r=i,n&&(e.ageMin&&e.ageMin!==t+1&&(D(`Invalid submitted ageMin: ${o}`),v=void 0),o=t+1)},O=t=>{const[s,c,u]=(t.match(T)||[]).slice(1),d=parseInt(c);"U"===s?(e.ageMaxDate&&e.ageMaxDate!==r&&D(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),(t=>{const r=A(p-t,S);e.ageMinDate&&e.ageMinDate!==r&&D(`Invalid submitted ageMinDate: ${i}`),i=r,n&&(e.ageMax&&e.ageMax!==t-1&&(D(`Invalid submitted ageMax: ${a}`),w=void 0),a=t-1)})(d)):"O"===s&&C(d),"U"===u?(e.ageMaxDate&&e.ageMaxDate!==r&&D(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),E(d)):"O"===u&&(t=>{const i=A(p-t-1,g);e.ageMaxDate&&e.ageMaxDate!==i&&D(`Invalid submitted ageMaxDate: ${r}`),r=i,n&&(e.ageMin&&e.ageMin!==t&&(D(`Invalid submitted ageMin: ${o}`),v=void 0),o=t)})(d),r=r??v,i=i??w};if(M){if(r=void 0,i=void 0,a=void 0,o=void 0,e.ageMin){const t=p-e.ageMin;r=A(t,g)}if(e.ageMax){const t=p-e.ageMax-1;i=A(t,S)}const[t,s]=(n?.match(b)??[]).slice(1).map((t=>parseInt(t)));t<=s?(o=t,a=s,c=!0):D(`Invalid combined age range ${n}`)}else R?n?.split("-").forEach(O):N?O(n):(o&&C(o),a&&E(a));a&&e.ageMin&&e.ageMin>a&&(D(`Invalid submitted ageMin: ${e.ageMin}`),o=void 0);const F=Xr({consideredDate:d,combinedAge:c,ageMaxDate:r,ageMinDate:i,ageMax:a,ageMin:o});return P.length&&(F.errors=P),F}function ia({category:t}){if(!G(t))return{error:Jn};const e=ra({category:t});if(e.error)return{error:e};const{ratingMax:n,ratingMin:r}=t;return n&&!h(n)?ti({result:{error:Jn},context:{ratingMax:n}}):r&&!h(r)?ti({result:{error:Jn},context:{ratingMin:r}}):{...e}}function aa({childCategory:t,withDetails:e,category:n}){const r=ia({category:n}),i=ia({category:t}),a=i.ageMin&&(r.ageMin&&i.ageMin<r.ageMin||r.ageMax&&i.ageMin>r.ageMax),o=i.ageMax&&(r.ageMax&&i.ageMax>r.ageMax||r.ageMin&&i.ageMax<r.ageMin),s=i.ageMinDate&&r.ageMaxDate&&new Date(i.ageMinDate)>new Date(r.ageMaxDate),c=i.ageMaxDate&&r.ageMinDate&&new Date(i.ageMaxDate)<new Date(r.ageMinDate),u=n?.ratingType&&t?.ratingType&&n.ratingType===t.ratingType&&(n.ratingMin&&t.ratingMin&&t.ratingMin<n.ratingMin||n.ratingMax&&t.ratingMax&&t.ratingMax>n.ratingMax||n.ratingMin&&t.ratingMax&&t.ratingMax<n.ratingMin||n.ratingMax&&t.ratingMin&&t.ratingMin>n.ratingMax),d=n?.ballType&&t?.ballType&&n.ballType!==t.ballType,p=Xr({invalidRatingRange:u,invalidAgeMinDate:s,invalidAgeMaxDate:c,invalidBallType:d,invalidAgeMax:o,invalidAgeMin:a,valid:!(u||s||c||d||o||a)},!0);return e&&Object.assign(p,{categoryDetails:r,childCategoryDetails:i}),p}function oa({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:a=!0,referenceCategory:o,referenceGender:s,event:c}){s=s??c?.gender;const u="validateCollectionDefinition",d=[];if("object"!=typeof e)return d.push(`collectionDefinition must be an object: ${e}`),ti({result:{errors:d,error:Yn},stack:u});const{collectionValueProfiles:p,collectionGroupNumber:l,collectionValue:m,collectionId:f,matchUpCount:h,matchUpFormat:g,matchUpValue:I,matchUpType:U,scoreValue:S,setValue:v,category:w,gender:P}=e;r&&"string"!=typeof f&&d.push(`collectionId is not type string: ${f}`),"number"!=typeof h&&d.push(`matchUpCount is not type number: ${h}`),U&&!H([n,i],U)&&d.push(`matchUpType must be SINGLES or DOUBLES: ${U}`);if(1!==[!!p?.length].concat([I,m,S,v].map(y)).filter(Boolean).length&&d.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),I&&"number"!=typeof I&&d.push(`matchUpValue is not type number: ${I}`),m&&"number"!=typeof m&&d.push(`collectionValue is not type number: ${m}`),p&&h){const t=Q({collectionValueProfiles:p,matchUpCount:h});t.errors&&d.push(...t.errors)}if(l&&"number"!=typeof l&&d.push(`collectionGroupNumber is not type number: ${m}`),g&&!Di({matchUpFormat:g})&&d.push(`Invalid matchUpFormat: ${g}`),a){const t=si({referenceGender:s,matchUpType:U,gender:P});if(t.error)return ti({context:{referenceGender:s,gender:P},result:t,stack:u})}if(t&&o&&w){const t=aa({category:o,childCategory:w});if(!t.valid)return ti({result:{error:Qn},context:t,stack:u})}return d.length?ti({result:{errors:d,error:zn},stack:u}):{valid:!0}}function sa(t){const e=!(!1===t?.enforceCategory||!t?.category),n=!(!1===t?.enforceGender||!t?.gender),r=t?.checkCollectionIds,i=t?.tieFormat,a=t?.event,o="validateTieFormat",s=[],c=function(t){const{tieFormat:e,stack:n}=t;if(!t||!e||!G(e))return ti({result:{error:ae},context:{tieFormat:e,message:"tieformat must be an object"},stack:n});if(!G(e.winCriteria))return ti({result:{error:ae},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:n});if(!Array.isArray(e.collectionDefinitions))return ti({result:{error:ae},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:n});return{...z}}({...t,stack:o});if(c?.error)return c;let u;const d=i.collectionDefinitions.every((i=>{const{setValue:o,scoreValue:c,collectionValue:d}=i;!o&&!c||d||(u=!0);const{valid:p,errors:l}=oa({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:i,checkCollectionIds:r,checkCategory:e,checkGender:n,event:a});return!!p||(Array.isArray(l)&&s.push(...l),!1)})),p="number"==typeof i.winCriteria?.valueGoal&&i.winCriteria?.valueGoal>0&&!u||i.winCriteria?.aggregateValue;if(!p&&!i.winCriteria?.aggregateValue)return u?s.push("aggregateValue is required"):s.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),ti({context:{tieFormat:i,errors:s,aggregateValueImperative:u},result:{error:ae},stack:o});const l=i.collectionDefinitions.map((({collectionId:t})=>t)),m=!r||l.length===w(l).length,f=d&&p&&m;return f?{valid:f,errors:s}:ti({result:{error:ae},context:{tieFormat:i,errors:s},stack:o})}const ca="resourceSubType",ua="resourceType",da="identifier",pa={RESOURCE_SUB_TYPE:ca,RESOURCE_TYPE:ua,IDENTIFIER:da};function la(t,e,n,r,i=0){if(Yr().makeDeepCopy)return Yr().makeDeepCopy(t,e,n,r);const a=Nr(),{stringify:o,toJSON:s,ignore:c,modulate:u}=a||{};if(!a?.enabled&&!n||"object"!=typeof t||V(t)||null===t||"number"==typeof a?.threshold&&i>=a.threshold)return t;const d=Array.isArray(t)?[]:{},p=Object.keys(t).filter((t=>!n||!c||Array.isArray(c)&&!c.includes(t)||V(c)&&!c(t))),l=(t,e)=>{d[t]=V(e?.toString)?e.toString():JSON.stringify(e)};for(const a of p){const c=t[a],p=V(u)?u(c):void 0;if(void 0!==p)d[a]=p;else if(e&&"extensions"===a&&Array.isArray(c)){const t=ma(c);Object.assign(d,...t)}else r&&"extensions"===a?d[a]=[]:Array.isArray(o)&&o.includes(a)?l(a,c):Array.isArray(s)&&s.includes(a)&&V(c?.toJSON)?d[a]=c.toJSON():null===c?d[a]=void 0:Ai(c)?d[a]=new Date(c).toISOString():d[a]=la(c,e,n,r,i+1)}return d}function ma(t){return t?.map((t=>{const{name:e,value:n}=t;return e&&n&&{[`_${e}`]:n}})).filter(Boolean)}function fa(t=1,e){return E(0,t).map((()=>ha(e)))}function ha(t){const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);const n=4294967295*Math.random()|0,r=4294967295*Math.random()|0,i=4294967295*Math.random()|0,a=4294967295*Math.random()|0,o=e[255&n]+e[n>>8&255]+e[n>>16&255]+e[n>>24&255]+"-"+e[255&r]+e[r>>8&255]+"-"+e[r>>16&15|64]+e[r>>24&255]+"-"+e[63&i|128]+e[i>>8&255]+"-"+e[i>>16&255]+e[i>>24&255]+e[255&a]+e[a>>8&255]+e[a>>16&255]+e[a>>24&255];return"string"==typeof t?`${t}_${o.replace(/-/g,"")}`:o}var ga={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}},Ia={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}},Ua={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}},ya={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}},Sa={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}},va={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}},wa={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}},Pa={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}},Da={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}},Ta={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}]};const ba="SET3-S:6/TB7",Ra="SET3-S:6/TB7-F:TB10",Ma={FORMAT_STANDARD:ba,FORMAT_STANDARD_NOAD:"SET3-S:6NOAD",FORMAT_ATP_DOUBLES:Ra,FORMAT_SHORT_SETS:"SET3-S:4/TB7",FORMAT_FAST4:"SET3-S:4/TB5@3",FORMAT_PRO_SET:"SET1-S:8/TB7",FORMAT_COLLEGE_PRO_SET:"SET1-S:8/TB7@7",TIMED20:"SET1-S:T20"};var Na={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}},Aa={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}},Ea={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}},Ca={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}},Oa={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}},Fa={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}},ka={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}};const xa="COLLEGE_DEFAULT",_a="COLLEGE_JUCO",La="COLLEGE_D3",Ba="DOMINANT_DUO",Va="DOMINANT_DUO_MIXED",ja="LAVER_CUP",Ga="TEAM_DOUBLES_3_AGGREGATION",qa="TIME_TENNIS_DUAL",$a="TIME_TENNIS_PRO_CIRCUIT",Wa="USTA_BREWER_CUP",Ha="USTA_OZAKI_CUP",za="USTA_COLLEGE",Ya="USTA_GOLD_TEAM_CHALLENGE",Ka="USTA_LEVEL_1",Qa="USTA_INTERSECTIONAL",Ja="USTA_SECTION_BATTLE",Za="USTA_SOUTHERN_LEVEL_5",Xa="USTA_TOC",to="USTA_WTT_ITT",eo="USTA_ZONAL",no={COLLEGE_D3:La,COLLEGE_DEFAULT:xa,COLLEGE_JUCO:_a,DOMINANT_DUO:Ba,DOMINANT_DUO_MIXED:Va,LAVER_CUP:ja,TEAM_DOUBLES_3_AGGREGATION:Ga,TIME_TENNIS_DUAL:qa,TIME_TENNIS_PRO_CIRCUIT:$a,USTA_BREWER_CUP:Wa,USTA_OZAKI_CUP:Ha,USTA_COLLEGE:za,USTA_GOLD_TEAM_CHALLENGE:Ya,USTA_INTERSECTIONAL:Qa,USTA_LEVEL_1:Ka,USTA_SECTION_BATTLE:Ja,USTA_SOUTHERN_LEVEL_5:Za,USTA_TOC:Xa,USTA_WTT_ITT:to,USTA_ZONAL:eo},ro="STANDARD",io={[ro]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[La]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:ba,matchUpCount:6,matchUpValue:1},tieFormatName:La,valueGoal:5},[xa]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:ba,matchUpCount:6,matchUpValue:1},tieFormatName:xa,valueGoal:4},[_a]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:ba,matchUpCount:6,matchUpValue:1},tieFormatName:_a,valueGoal:5},[ja]:Fa,[Ba]:Na,[Va]:wa,[Ga]:Ia,[qa]:Pa,[$a]:va,[Wa]:Da,[Ha]:Ta,[za]:Aa,[Ya]:ga,[Qa]:Sa,[Ka]:Ea,[Ja]:ya,[Za]:Ua,[to]:Ca,[Xa]:ka,[eo]:Oa},ao=t=>{const e=t?.namedFormat&&Object.keys(io).includes(t.namedFormat)?t.namedFormat:ro,r=Array.isArray(t?.uuids)?t?.uuids:[];let a;const{category:o,gender:s}=t?.event??{},c=la(io[e],!1,!0),u=e=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??ha();const n=t?.event?.eventId;return r.pop()??`${n}-COL-${e+1}`};return c.hydrate?(a={winCriteria:{valueGoal:c.valueGoal},collectionDefinitions:[{collectionId:u(0),matchUpFormat:Ra,collectionName:"Doubles",matchUpType:i,...c.doubles},{collectionId:u(1),matchUpFormat:ba,collectionName:"Singles",matchUpType:n,...c.singles}]},c.tieFormatName&&(a.tieFormatName=c.tieFormatName)):(c.collectionDefinitions.forEach(((t,e)=>t.collectionId=u(e))),a=c),t?.hydrateCollections&&a.collectionDefinitions.forEach((t=>{o&&!t.category&&(t.category=o),s&&!t.gender&&(t.gender=s)})),a},oo="SINGLES",so="SINGLES",co="DOUBLES",uo="DOUBLES",po="TEAM",lo="TEAM",mo={AGE:"AGE",BOTH:"BOTH",DOUBLES:co,DOUBLES_EVENT:uo,RATING:"RATING",SINGLES:oo,SINGLES_EVENT:so,TEAM_EVENT:lo,TEAM:po},fo="MAIN",ho="QUALIFYING",go="CONSOLATION",Io="VOLUNTARY_CONSOLATION",Uo="PLAY_OFF",yo=[fo,ho,go,Uo,Io],So={[ho]:1,[fo]:2,[Uo]:3,[go]:3,[Io]:4},vo="finishingPositions",wo="aggregateEventStructures",Po={[fo]:1,[Uo]:2,[go]:3,[ho]:4,[Io]:5},Do={[Uo]:1,[fo]:2,[go]:3,[ho]:4,[Io]:5},To="CLUSTER",bo="WATERFALL",Ro="ITEM",Mo="CONTAINER",No="DRAW",Ao="RANDOM",Eo="TOP_DOWN",Co="BOTTOM_UP",Oo="POSITION",Fo="WINNER",ko="LOSER",xo="FIRST_MATCHUP",_o="AD_HOC",Lo="FEED_IN",Bo="COMPASS",Vo="OLYMPIC",jo="SINGLE_ELIMINATION",Go="DOUBLE_ELIMINATION",qo="FIRST_MATCH_LOSER_CONSOLATION",$o="FIRST_ROUND_LOSER_CONSOLATION",Wo="LUCKY_DRAW",Ho="CURTIS_CONSOLATION",zo="CURTIS_CONSOLATION",Yo="FEED_IN_CHAMPIONSHIP_TO_SF",Ko="FEED_IN_CHAMPIONSHIP_TO_SF",Qo="FEED_IN_CHAMPIONSHIP_TO_QF",Jo="FEED_IN_CHAMPIONSHIP_TO_QF",Zo="FEED_IN_CHAMPIONSHIP_TO_R16",Xo="FEED_IN_CHAMPIONSHIP_TO_R16",ts="MODIFIED_FEED_IN_CHAMPIONSHIP",es="MODIFIED_FEED_IN_CHAMPIONSHIP",ns="FEED_IN_CHAMPIONSHIP",rs="ROUND_ROBIN",is="ROUND_ROBIN_WITH_PLAYOFF",as="DECIDER",os="BACKDRAW",ss={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"}},cs={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},us="WIN_RATIO",ds="ROUND_OUTCOME",ps=[Bo,Ho,Jo,Xo,Ko,ns,Qo,Zo,Yo,qo,$o,Wo,es,Vo,Uo,is],ls={MAIN:fo,QUALIFYING:ho,CONSOLATION:go,ITEM:Ro,CONTAINER:Mo,FIRST_MATCHUP:xo,WINNER:Fo,LOSER:ko,AD_HOC:_o,FEED_IN:Lo,FLEX_ROUNDS:"AD_HOC",COMPASS:Bo,PLAY_OFF:Uo,OLYMPIC:Vo,KNOCKOUT:"SINGLE_ELIMINATION",SINGLE_ELIMINATION:jo,DOUBLE_ELIMINATION:Go,CURTIS:Ho,FICSF:Yo,FICQF:Qo,FICR16:Zo,MFIC:ts,VOLUNTARY_CONSOLATION:Io,FIRST_MATCH_LOSER_CONSOLATION:qo,FIRST_ROUND_LOSER_CONSOLATION:$o,MODIFIED_FEED_IN_CHAMPIONSHIP:es,FEED_IN_CHAMPIONSHIP_TO_R16:Xo,FEED_IN_CHAMPIONSHIP_TO_QF:Jo,FEED_IN_CHAMPIONSHIP_TO_SF:Ko,FEED_IN_CHAMPIONSHIP:ns,LUCKY_DRAW:Wo,ROUND_ROBIN_WITH_PLAYOFF:is,ROUND_ROBIN:rs,DECIDER:as,BACKDRAW:os,COMPASS_ATTRIBUTES:ss,OLYMPIC_ATTRIBUTES:cs,DRAW:No,RANDOM:Ao,TOP_DOWN:Eo,BOTTOM_UP:Co,WATERFALL:bo,WIN_RATIO:us,ROUND_OUTCOME:ds,MULTI_STRUCTURE_DRAWS:ps,generatedDrawTypes:[_o,Bo,Ho,Go,Jo,Xo,Ko,ns,Lo,qo,$o,Wo,es,Vo,Uo,rs,is,jo],stageOrder:So,finishOrder:Po,AGGREGATE_EVENT_STRUCTURES:wo,FINISHING_POSITIONS:vo},ms="tournamentRecords",fs="policyDefinitions",hs="tournamentRecord",gs="onlineResource",Is="drawDefinition",Us="tieFormatName",ys="matchUpFormat",Ss="participantId",vs="scheduleDates",ws="tournamentId",Ps="scheduleDate",Ds="roundNumber",Ts="structureId",bs="participant",Rs="matchUpIds",Ms="entryStage",Ns="policyType",As="structures",Es="eventType",Cs="matchUpId",Os="tieFormat",Fs="inContext",ks="structure",xs="courtIds",_s="personId",Ls="venueIds",Bs="matchUps",Vs="courtId",js="eventId",Gs="matchUp",qs="drawId",$s="error",Ws="event",Hs="param",zs="uuids",Ys="averageMatchUpMinutes",Ks="recoveryMinutes",Qs="periodLength",Js="object",Zs="array",Xs="_validate",tc="_message",ec="_invalid",nc="_ofType",rc="_anyOf",ic="_oneOf",ac={[gs]:t=>3===O(Object.keys(t),[ca,ua,da]).length,[Us]:t=>t&&ao({namedFormat:t}),[zs]:t=>!t||Array.isArray(t)&&t.every(j),[Os]:t=>!sa({tieFormat:t}).error,[Es]:t=>[oo,co,po].includes(t),[Ms]:t=>yo.includes(t)},oc={[ms]:et,[hs]:nt,[fs]:Ie,[Is]:ot,[Ss]:Xe,[ys]:se,[ws]:it,[Ts]:_t,[Rs]:pe,[bs]:Je,[gs]:Yn,[Es]:qt,[As]:Bt,[Cs]:de,[Os]:ae,[ks]:Vt,[Vs]:Te,[Bs]:me,[js]:Wt,[Gs]:fe,[xs]:be,[Ls]:be,[qs]:Tt,[Ws]:$t},sc={[ms]:Js,[fs]:Js,[hs]:Js,[Is]:Js,[gs]:Js,[vs]:Zs,[bs]:Js,[Rs]:Zs,[As]:Zs,[Os]:Js,[ks]:Js,[xs]:Zs,[Ls]:Zs,[Bs]:Zs,[Gs]:Js,[Ws]:Js,[zs]:Zs};function cc(t,e,n){if(!t&&!G(t))return{error:Jn};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:Jn};const{paramError:r,errorParam:i}=function(t,e){let n,r;const i=e.find((({_ofType:e,_oneOf:i,_anyOf:a,_validate:o,_info:s,...c})=>{const u=i&&function(t,e){if(!e)return;const n=uc(t,e);return 1!==n.length?{error:Jn}:n.reduce(((t,e)=>({...t,[e]:!0})),{})}(t,i);if(u?.error)return u.error;u&&Object.assign(c,u);const d=a&&function(t,e){if(!e)return;const n=uc(t,e).filter((e=>t[e]));return n.length<1?{error:Jn}:n.reduce(((t,e)=>({...t,[e]:!0})),{})}(t,a);if(d?.error)return d.error;d&&Object.assign(c,d);const p=Object.keys(c).filter((t=>"boolean"==typeof c[t])),l=p.find((i=>{const a=o&&!V(o),u=void 0!==t[i]&&!o&&function(t,e,n){if(n=n||sc[e]||"string","array"===n)return!Array.isArray(t[e]);return typeof t[e]!==n}(t,i,e),d=c[i]&&[void 0,null].includes(t[i]),p=a||u||d||o&&void 0!==t[i]&&(l=t[i],!(!V(m=o)||m(l)))||ac[i]&&!ac[i](t[i]);var l,m;return p&&(n=i,r=s),p}));return!p.length||l}));return{paramError:i,errorParam:n,paramInfo:r}}(t,e);if(!r)return{valid:!0};const a=r[Xs]&&(r[$s]||r[ec])||void 0===t?.[i]&&(r[$s]||r[ec]||oc[i]||Jn)||Jn;return ti({info:{param:i??(r[ic]&&Object.keys(r[ic]).join(", ")),message:r[tc]},result:{error:a},stack:n})}function uc(t,e){return O(Object.keys(t),Object.keys(e))}const dc="DYNAMIC",pc="RANKING",lc="RATING",mc="SCALE",fc="SEEDING",hc={RANKING:pc,RATING:lc,SCALE:mc,SEEDING:fc};function gc(t){const e=cc(t,[{[bs]:!0}]);if(e.error)return e;const n=t.participant.timeItems?.filter((({itemType:t})=>t?.startsWith(mc)&&[pc,lc,fc].includes(t.split(".")[1]))),r={ratings:{},rankings:{},seedings:{}};if(n?.length){const t=t=>n.filter((e=>e?.itemType===t)).sort(((t,e)=>new Date(t.createdAt||void 0).getTime()-new Date(e.createdAt||void 0).getTime())).pop(),e=w(n.map((({itemType:t})=>t)));for(const n of e){const e=t(n);if(e){const[,t,n,i,a]=e.itemType.split("."),o=a?`${i}.${a}`:i,s=(t===fc?"seedings":t===pc&&"rankings")||"ratings";r[s][n]||(r[s][n]=[]),r[s][n].push({scaleValue:e.itemValue,scaleDate:e.itemDate,scaleName:o})}}}return{...z,...r}}function Ic(t){if(null===t)return{};const{source:e,template:n}=t||{};if(!n)return e;const r={};return function t(e,n,r){if(!e||!n)return;const i=Object.keys(e),a=Object.keys(n),o=Object.assign({},...a.filter((t=>t.indexOf("||"))).map((t=>t.split("||").map((e=>({[e]:t}))))).flat()),s=a.concat(...Object.keys(o)),c=s.includes("*");for(const a of i)if(s.indexOf(a)>=0||c){const i=n[o[a]||a]||c,s=e[a];if("object"!=typeof i||"function"==typeof s||Array.isArray(i)){const t=e[a];if(Array.isArray(i)&&!i.includes(t))return!1;(n[a]||c&&!1!==n[a])&&(r[a]=t)}else if(Array.isArray(s)){const e=s.map((e=>{const n={};return!1!==t(e,i,n)?n:void 0})).filter(Boolean);r[a]=e}else s&&(r[a]={},t(s,i,r[a]))}return}(e,n,r),r}const Uc="voluntaryConsolation",yc="competitiveBands",Sc="roundRobinTally",vc="positionActions",wc="matchUpActions",Pc="rankingPoints",Dc="roundNaming",Tc="participant",bc="progression",Rc="scheduling",Mc="avoidance",Nc="scoring",Ac="seeding",Ec="feedIn",Cc="draws",Oc={POLICY_TYPE_VOLUNTARY_CONSOLATION:Uc,POLICY_TYPE_COMPETITIVE_BANDS:yc,POLICY_TYPE_ROUND_ROBIN_TALLY:Sc,POLICY_TYPE_POSITION_ACTIONS:vc,POLICY_TYPE_MATCHUP_ACTIONS:wc,POLICY_TYPE_RANKING_POINTS:Pc,POLICY_TYPE_ROUND_NAMING:Dc,POLICY_TYPE_PARTICIPANT:Tc,POLICY_TYPE_PROGRESSION:bc,POLICY_TYPE_SCHEDULING:Rc,POLICY_TYPE_AVOIDANCE:Mc,POLICY_TYPE_DISPLAY:"display",POLICY_TYPE_PRIVACY:"participant",POLICY_TYPE_FEED_IN:Ec,POLICY_TYPE_SCORING:Nc,POLICY_TYPE_SEEDING:Ac,POLICY_TYPE_AUDIT:"audit",POLICY_TYPE_DRAWS:Cc};function Fc({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:n,participantId:r,internalUse:i,personId:a}){const o=la(t.find((t=>r&&t.participantId===r||a&&t.person&&t.person.personId===a)),!1,i);if(o){const t=e?.[Tc];if(n?.withScaleValues){const{ratings:t,rankings:e}=gc({participant:o});o.rankings=e,o.ratings=t}if(t?.participant)return Ic({template:t.participant,source:o})}return o}function kc(t){if(!t||"object"!=typeof t)return{error:be};if(t.element&&"object"!=typeof t?.element)return{error:Jn};if(!t?.name)return{error:be,info:"missing name"};if(!t?.element){if(t.discover&&t.tournamentRecords){for(const e of Object.keys(t.tournamentRecords)){const n=kc({element:t.tournamentRecords[e],name:t.name});if(n.error)return ti({result:n,stack:"removeExtension"})}return{...z}}return{error:be,info:"element required"}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter((e=>e?.name!==t.name)),{...z}):{...z,info:rr}}function xc({requiredAttributes:t=["name","value"],extension:e}){if(!e||"object"!=typeof e)return!1;if("string"!=typeof e.name)return!1;const n=Object.keys(e);return t.filter((t=>n.includes(t))).length===t.length}function _c(t){if("object"!=typeof t)return{error:be};const e="addExtension";if(t?.element&&"object"!=typeof t.element)return ti({result:{error:Jn},stack:e});if(!xc({extension:t.extension}))return ti({result:{error:Jn,info:"invalid extension"},stack:e});if(!t.element){if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(const n of Object.values(t.tournamentRecords)){const r=_c({extension:t.extension,element:n});if(r.error)return ti({result:r,stack:e})}return{...z}}return ti({result:{error:be},stack:e})}t.element.extensions||(t.element.extensions=[]);if(t?.creationTime??!0){const e=(new Date).toISOString();Object.assign(t.extension,{createdAt:e})}const n=t.element.extensions.find((({name:e})=>e===t.extension.name));return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...z}}function Lc(t){return t&&"object"==typeof t?t.tournamentRecord?_c({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:nt}:{error:be}}function Bc(t){return t&&"object"==typeof t?t.drawDefinition?_c({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:ct}:{error:be}}function Vc(t){return t&&"object"==typeof t?t.event?_c({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Wt}:{error:be}}function jc(t){if(!t||"object"!=typeof t)return{error:be};if(!t.participantId)return{error:Xe};const e=t.tournamentRecord?.participants||[],n=Fc({participantId:t.participantId,tournamentParticipants:e});return n?_c({creationTime:t.creationTime,extension:t.extension,element:n}):{error:en}}function Gc(t){return t&&"object"==typeof t?t.tournamentRecord?kc({element:t.tournamentRecord,name:t.name}):{error:nt}:{error:be}}function qc(t){return t&&"object"==typeof t?t.drawDefinition?kc({element:t.drawDefinition,name:t.name}):{error:ct}:{error:be}}function $c(t){return t&&"object"==typeof t?t?.event?kc({element:t.event,name:t.name}):{error:Wt}:{error:be}}function Wc(t){if(!t||"object"!=typeof t)return{error:be};if(!t.participantId)return{error:Xe};const e=t.tournamentRecord?.participants||[],n=Fc({participantId:t.participantId,tournamentParticipants:e});return n?kc({element:n,name:t.name}):{error:en}}function Hc({tournamentRecords:t}){return{tournamentIds:G(t)?Object.keys(t):[],...z}}function zc({discover:t,element:e,name:n,...r}){if(!e||!n){if(t&&r){const e=Object.keys(r).filter((e=>"boolean"==typeof t||Array.isArray(t)&&t.includes(e))).find((t=>!!Array.isArray(r[t]?.extensions)&&r[t].extensions.find((t=>t?.name===n))));let i=e&&r[e];!i&&r.tournamentRecords&&(i=Object.values(r.tournamentRecords).find((t=>t.extensions?.length)));const a=i?.extensions?.find((t=>t?.name===n));return{extension:a,info:a?void 0:rr}}return ti({result:{error:be},stack:"extensionQueries"})}if(!Array.isArray(e.extensions))return{info:"no extensions"};const i=e.extensions.find((t=>t?.name===n));return{extension:i,info:i?void 0:rr}}const Yc="appliedPolicies",Kc="context",Qc="delegatedOutcome",Jc="disabled",Zc="disableAutoCalc",Xc="disableLinks",tu="display",eu="drawDeletions",nu="entryProfile",ru="flightProfile",iu="groupingAttribute",au="lineUps",ou="linkedTournamentsIds",su="matchUpHistory",cu="participantRepresentatives",uu="personRequests",du="positionActions",pu="roundTarget",lu="scheduleLimits",mu="scheduleTiming",fu="schedulingProfile",hu="subOrder",gu="tally",Iu="tieFormatModification",Uu={ACTIVE_SUSPENSION:"activeSuspension",APPLIED_POLICIES:Yc,CONTEXT:Kc,DELEGATED_OUTCOME:Qc,DISABLED:Jc,DISABLE_LINKS:Xc,DISABLE_AUTO_CALC:Zc,DISPLAY:tu,DRAW_DELETIONS:eu,DRAW_PROFILE:"drawProfile",ENTRY_PROFILE:nu,EVENT_PROFILE:"eventProfile",EVENT_WITHDRAWAL_REQUESTS:"eventWithdrawalRequests",FLIGHT_PROFILE:ru,GROUPING_ATTRIBUTE:iu,LINEUPS:au,LINKED_TOURNAMENTS:ou,MATCHUP_HISTORY:su,PARTICIPANT_REPRESENTATIVES:cu,PERSON_REQUESTS:uu,POSITION_ACTIONS:du,RANKING_POINTS:"rankingPoints",REGISTRATION:"registration",ROUND_TARGET:pu,SCHEDULE_LIMITS:lu,SCHEDULE_TIMING:mu,SCHEDULING_PROFILE:fu,STATUS_DETAIL:"statusDetail",SUB_ORDER:hu,TALLY:gu,TIE_FORMAT_MODIFICATIONS:Iu,FACTORY:"factory"},yu=[Qc,Jc,Zc,Xc,ru,au,ou,su,cu,uu,pu,lu,mu,fu,hu,gu,Iu];function Su({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:et};const e=Hc({tournamentRecords:t}),{tournamentIds:n}=e;if(n?.length>1){return _c({tournamentRecords:t,discover:!0,extension:{name:ou,value:{tournamentIds:n}}})}return{...z}}function vu({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:et};return ti({result:kc({name:ou,tournamentRecords:t,discover:!0}),stack:"unlinkTournaments"})}function wu({tournamentRecords:t,tournamentId:e}){if("object"!=typeof t)return{error:Jn};if(!e)return{error:it};const n=Hc({tournamentRecords:t}),{tournamentIds:r}=n;if(!r.includes(e))return{error:it};let i;return r.every((n=>{const r=t[n],{extension:a}=zc({element:r,name:ou});if(!a)return!0;const o=a?.value?.tournamentIds||[];if(!o?.length||1===o.length&&o.includes(e)||n===e){const t=Gc({name:ou,tournamentRecord:r});return t.error&&(i=t.error),t.success}const s=o.filter((t=>t!==e));a.value={tournamentIds:s};const c=Lc({tournamentRecord:r,extension:a});return c.error&&(i=c.error),c.success})),i?{error:i}:{...z}}function Pu({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:et};return{linkedTournamentIds:Object.assign({},...Object.keys(t).map((e=>{const n=t[e],r=n?.tournamentId,{extension:i}=zc({element:n,name:ou}),a=(i?.value?.tournamentIds||[]).filter((t=>t!==r));return{[e]:a}})))}}var Du={__proto__:null,getLinkedTournamentIds:Pu,getTournamentIds:Hc,linkTournaments:Su,mutate:{__proto__:null,linkTournaments:Su,unlinkTournament:wu,unlinkTournaments:vu},query:{__proto__:null,getLinkedTournamentIds:Pu,getTournamentIds:Hc},unlinkTournament:wu,unlinkTournaments:vu};const Tu=t=>e=>t[e],bu=(t=[])=>t.map(Nu).filter(Boolean),Ru=(t=[])=>t.map(Mu).filter(Boolean),Mu=(t={})=>Tu(t)("participantId"),Nu=(t={})=>Tu(t)("matchUpId"),Au=(t={})=>Tu(t)("drawId");function Eu({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:ct};if(!Array.isArray(t))return{error:Jn};const n=Ru(e?.entries||[]);if(t.length&&O(t,n).length<t.length)return{error:Jn};return Bc({drawDefinition:e,extension:{name:cu,value:t}})}const Cu="ABANDONED",Ou="AWAITING_RESULT",Fu="BYE",ku="CANCELLED",xu="COMPLETED",_u="DEAD_RUBBER",Lu="DEFAULTED",Bu="DOUBLE_DEFAULT",Vu="DOUBLE_WALKOVER",ju="IN_PROGRESS",Gu="INCOMPLETE",qu="NOT_PLAYED",$u="RETIRED",Wu="SUSPENDED",Hu="TO_BE_PLAYED",zu="WALKOVER",Yu=[Ou,xu,Lu,ju,Gu,$u,Wu],Ku=[Ou,xu,Lu,Vu,Bu,ju,Gu,$u,Wu,zu],Qu=[Cu,Ou,Fu,ku,xu,_u,Lu,Vu,Bu,ju,Gu,qu,$u,Wu,Hu,zu],Ju=[Fu,Vu,Bu,xu,Lu,$u,zu],Zu=[Cu,Ou,ku,_u,ju,Gu,qu,Wu,Hu,void 0],Xu=[ku,Cu,xu,_u,Lu,Vu,Bu,$u,zu],td=[Cu,xu,Lu,Vu,Bu,ju,$u,zu],ed=[ju,Gu,Wu,Hu],nd={ABANDONED:Cu,AWAITING_RESULT:Ou,BYE:Fu,CANCELLED:ku,COMPLETED:xu,DEAD_RUBBER:_u,DEFAULTED:Lu,DOUBLE_WALKOVER:Vu,DOUBLE_DEFAULT:Bu,IN_PROGRESS:ju,INCOMPLETE:Gu,NOT_PLAYED:qu,RETIRED:$u,SUSPENDED:Wu,TO_BE_PLAYED:Hu,WALKOVER:zu};function rd(t,e,n){const r=t=>zc({element:t,name:pu})?.extension?.value,i=n?.deprioritizeCompleted,a=n?.mode===wo&&Do,o=n?.mode===vo&&Po,s=o||a||So,c=t=>(t=>t?.stage===fo&&1===t?.stageSequence)(t)?-1:s[t?.stage],u=t=>t?.matchUps.every((({matchUpStatus:t})=>Xu.includes(t)?1:-1));return i&&u(t)-u(e)||a&&c(t)-c(e)||(t?.stage&&s[t.stage]||0)-(e?.stage&&s[e.stage]||0)||(r(t)||0)-(r(e)||0)||!o&&!a&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(id(t)||0)-(id(e)||0)}function id(t){return(t?.matchUps||[]).reduce(((t,e)=>{const n=(e.finishingPositionRange?.winner||[]).reduce(((t,e)=>t+e),0);return!t||n<t?n:t}),void 0)}function ad(t){const e=cc(t,[{[Is]:!0,[Ts]:!0}]);if(e.error)return e;const{drawDefinition:n,structureId:r}=t,{structures:i}=od({drawDefinition:n}),a=i?.map((t=>t.structures?[...t.structures].concat(t):t)).flat(),o=a?.find((t=>t.structureId===r));if(!o)return{error:Lt};return{structure:o,containingStructure:o.structureType===Ro?a?.find((t=>t.structures?.some((t=>t.structureId===r)))):void 0}}function od({withStageGrouping:t,drawDefinition:e,stageSequences:n,stageSequence:r,roundTarget:i,sortConfig:a,stages:o,stage:s}){const c=!e&&ot||!e?.structures&&Bt||void 0;if(c)return{error:c,structures:[],stageStructures:{}};const u=e?.structures?.filter((function(t){return!s&&!Array.isArray(o)||s&&t.stage===s||Array.isArray(o)&&o.includes(t.stage)})).filter((function(t){return!r&&!Array.isArray(n)||r&&t.stageSequence===r||Array.isArray(n)&&n.includes(t.stageSequence)})).filter((t=>{const e=zc({element:t,name:pu})?.extension?.value;return!i||i===e})).sort(((t,e)=>rd(t,e,a)))??[],d=t?Object.assign({},...yo.map((t=>{const e=u?.filter((e=>e.stage===t));return e?.length&&{[t]:e}})).filter(Boolean)):{};return{structures:u,stageStructures:d}}function sd({drawDefinition:t}){if(!t)return{error:ot};const e={};return{allPositionedParticipantIds:(t.structures||[]).map((t=>{const n=t.stage;e[n]||(e[n]=[]);const{positionAssignments:r}=cd({structure:t}),i=r?.map(Mu).filter(Boolean)??[];return e[n].push(...i),i})).flat(),stagePositionedParticipantIds:e}}function cd({drawDefinition:t,structureId:e,structure:n}){let r,i=[];if(!n){if(!t)return{positionAssignments:i,error:ot};if(({structure:n,error:r}=ad({drawDefinition:t,structureId:e})),r)return{positionAssignments:i,error:r}}return n.structures?i=[].concat(...n.structures.map((t=>cd({structure:t}).positionAssignments))):n.positionAssignments?i=n.positionAssignments:r=Xt,{positionAssignments:i,error:r}}function ud({drawDefinition:t,structureId:e,structure:n}){const r=cd({drawDefinition:t,structureId:e,structure:n})?.positionAssignments||[],i=r?.filter((t=>t.participantId??t.bye??t.qualifier)),a=r&&r?.length===i?.length,o=r?.filter((t=>!t.participantId&&!t.bye&&!t.qualifier)),s=r?.filter((t=>!t.participantId&&t.bye)),c=r?.filter((t=>!t.participantId&&t.qualifier));return{allPositionsAssigned:a,positionAssignments:r,unassignedPositions:o,assignedPositions:i,qualifierPositions:c,byePositions:s}}const dd="addDrawDefinition",pd="addMatchUps",ld="addParticipants",md="addScaleItems",fd="addEvent",hd="addVenue",gd="audit",Id="dataIssue",Ud="deleteParticipants",yd="deleteVenue",Sd="deletedDrawIds",vd="deletedMatchUpIds",wd="modifyDrawDefinition",Pd="modifyDrawEntries",Dd="modifyEventEntries",Td="modifyMatchUp",bd="modifyParticipants",Rd="modifyPositionAssignments",Md="modifySeedAssignments",Nd="modifyTournamentDetail",Ad="modifyVenue",Ed="mutations",Cd="publishEvent",Od="publishEventSeeding",Fd="publishOrderOfPlay",kd="publishParticipants",xd="unPublishEvent",_d="unPublishEventSeeding",Ld="unPublishOrderOfPlay",Bd="updateInContextMatchUp",Vd={ADD_DRAW_DEFINITION:dd,ADD_MATCHUPS:pd,ADD_PARTICIPANTS:ld,ADD_SCALE_ITEMS:md,ADD_EVENT:fd,ADD_VENUE:hd,AUDIT:gd,DATA_ISSUE:Id,DELETE_PARTICIPANTS:Ud,DELETE_VENUE:yd,DELETED_DRAW_IDS:Sd,DELETED_MATCHUP_IDS:vd,MODIFY_DRAW_DEFINITION:wd,MODIFY_DRAW_ENTRIES:Pd,MODIFY_EVENT_ENTRIES:Dd,MODIFY_MATCHUP:Td,MODIFY_PARTICIPANTS:bd,MODIFY_POSITION_ASSIGNMENTS:Rd,MODIFY_SEED_ASSIGNMENTS:Md,MODIFY_TOURNAMENT_DETAIL:Nd,MODIFY_VENUE:Ad,MUTATIONS:Ed,PUBLISH_EVENT_SEEDING:Od,PUBLISH_EVENT:Cd,PUBLISH_ORDER_OF_PLAY:Fd,PUBLISH_PARTICIPANTS:kd,UNPUBLISH_EVENT_SEEDING:_d,UNPUBLISH_EVENT:xd,UNPUBLISH_ORDER_OF_PLAY:Ld,UPDATE_INCONTEXT_MATCHUP:Bd};function jd(t,e){if(!t)return{error:ot};let n=Date.now();t.updatedAt&&n===new Date(t.updatedAt).getTime()&&(n+=1);const r=new Date(n).toISOString(),i=e?.filter(Boolean);return t.updatedAt=r,t.structures?.filter(Boolean).forEach((t=>{i?.length&&!i?.includes(t.structureId)||(t.updatedAt=r)})),{...z}}function Gd({drawDefinition:t,tournamentId:e,matchUps:n,eventId:r}){return t&&jd(t),Or({payload:{matchUps:n,tournamentId:e,eventId:r},topic:pd}),{...z}}function qd({drawDefinition:t,tournamentId:e,matchUpIds:n,eventId:r,action:i}){t&&jd(t),Or({topic:vd,payload:{tournamentId:e,matchUpIds:n,eventId:r,action:i}});for(const t of n)xr({key:t});return{...z}}function $d({drawDefinition:t,tournamentId:e,structureId:n,context:r,eventId:i,matchUp:a}){if(!a)return console.log(fe),{error:fe};if(t){Hd({drawDefinition:t,structureIds:n?[n]:void 0,tournamentId:e,eventId:i})}return Or({topic:Td,payload:{matchUp:a,tournamentId:e,context:r},key:a.matchUpId}),{...z}}function Wd({tournamentId:t,eventId:e,drawDefinition:n}){return n?(jd(n),Or({payload:{drawDefinition:n,tournamentId:t,eventId:e},topic:dd,key:n.drawId}),{...z}):(console.log(ot),{error:ot})}function Hd({drawDefinition:t,tournamentId:e,structureIds:n,eventId:r}){return t?(jd(t,n),Or({payload:{tournamentId:e,eventId:r,drawDefinition:t},topic:wd,key:t.drawId}),{...z}):{error:ot}}function zd({drawDefinition:t,tournamentId:e,structure:n,eventId:r}){if(!t)return{error:ot};if(!n)return{error:Vt};const i=n.seedAssignments,a=n.structureId;return Or({payload:{tournamentId:e,eventId:r,drawId:t.drawId,structureId:a,seedAssignments:i},topic:Md,key:t.drawId}),Hd({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:r}),{...z}}function Yd({drawDefinition:t,tournamentId:e,structure:n,event:r}){if(!t)return{error:ot};if(!n)return{error:Vt};const i=cd({structure:n}),a=n.structureId,o=t.drawId,s=r?.eventId;return Or({topic:Rd,payload:{positionAssignments:i,tournamentId:e,structureId:a,eventId:s,drawId:o},key:a}),Hd({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:s}),{...z}}function Kd({tournamentRecord:t,drawDefinition:e,resetEntries:n,event:r}){if(!e)return{error:ot};const i=e.structures?.find((t=>t.stage===Io));if(!i)return{error:Lt};const a=i.matchUps?.map((({matchUpId:t})=>t))||[];return i.positionAssignments=[],i.seedAssignments=[],i.matchUps=[],qd({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:a,drawDefinition:e}),n&&(e.entries=e.entries.filter((t=>t.entryStage!==Io))),Hd({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[i.structureId]}),{...z}}function Qd({drawPositions:t,structure:e}){if([ho,fo].includes(e.stage)&&1===e.stageSequence)return;const{positionAssignments:n}=cd({structure:e}),r=n?.filter((({drawPosition:e})=>t?.includes(e)));r?.forEach((t=>{_c({element:t,extension:{name:Xc,value:!0}})}))}function Jd(t){const{appliedPolicies:e,positionAction:n,drawDefinition:r}=t;if(!1===e?.audit?.[du])return;const{extension:i}=zc({name:du,element:r}),a=Array.isArray(i?.value)?i?.value??[]:[];if(!a?.length){const t=r.structures.find((t=>t.stage===fo));if(t){const e=cd({structure:t}).positionAssignments?.map((({drawPosition:t,participantId:e,bye:n,qualifier:r})=>({drawPosition:t,participantId:e,qualifier:r,bye:n})));a.push({name:"initialMainAssignments",initialAssignments:e})}}_c({element:r,extension:{value:a.concat(n),name:du}})}function Zd({tournamentRecord:t,drawDefinition:e,event:n}){const r=t?.events||n&&[n],i=r?.map((t=>t?.drawDefinitions)).flat().filter(Boolean)||e&&[e]||[],a={},o={},s=i.map((t=>t?.structures?.filter((t=>t?.structures)))).flat().filter(Boolean);for(const t of s){const{structures:e,structureId:n}=t??{};e&&n&&(a[n]=e?.map((t=>t.structureId)))&&e.forEach((e=>o[e.structureId]=t?.structureId))}return{containedStructures:a,containerStructures:o}}function Xd(t){const{sides:e,matchUpType:n}=t||{},r=t.potentialParticipants?.length?t.potentialParticipants.flat().map((t=>n===i?t?.individualParticipantIds||[]:t.participantId)).flat():[],a=(e||[]).map((t=>n===i&&(t?.participant?.individualParticipantIds||[])||t?.participantId&&[t.participantId]||[])).flat();return{individualParticipantIds:a.concat(r).flat(),enteredIndividualParticipantIds:a,potentialIndividualParticipantIds:r}}function tp(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}const ep="SIGN_IN_STATUS",np="SIGNED_OUT",rp="SIGNED_IN",ip="TEAM",ap="INDIVIDUAL",op="GROUP",sp="PAIR",cp="TEAM",up={TEAM_PARTICIPANT:ip,INDIVIDUAL:ap,GROUP:op,TEAM:cp,PAIR:sp},dp={INDIVIDUAL:ap,GROUP:op,PAIR:sp,TEAM:cp,SIGN_IN_STATUS:ep,SIGNED_OUT:np,SIGNED_IN:rp};function pp({participantsProfile:t,participants:e=[],deepCopy:n}){const r=new Map,i=!1!==n?la(e,t?.convertExtensions,!0):e,a=i.filter((t=>t.participantType===cp)),o=i.filter((t=>t.participantType===op)),s=i.filter((t=>t.participantType===sp));return i.forEach((t=>{if(t.participantType===ap){const{participantId:e}=t;t.groupParticipantIds=[],t.teamParticipantIds=[],t.pairParticipantIds=[],t.groups=[],t.teams=[],a.forEach((n=>{(n?.individualParticipantIds||[]).forEach((i=>{i!==e||t.teamParticipantIds?.includes(n.participantId)||(t.teamParticipantIds.push(n.participantId),r.get(n.participantId)||r.set(n.participantId,{participantName:n.participantName,participantId:n.participantId}),t.teams.push({participantRoleResponsibilities:n.participantRoleResponsibilities,participantOtherName:n.participantOtherName,participantName:n.participantName,participantId:n.participantId,teamId:n.teamId}))}))})),s.forEach((n=>{(n?.individualParticipantIds||[]).forEach((r=>{r!==e||t.pairParticipantIds.includes(n.participantId)||t.pairParticipantIds.push(n.participantId)}))})),o.forEach((n=>{(n?.individualParticipantIds||[]).forEach((r=>{r!==e||t.groupParticipantIds.includes(n.participantId)||(t.groupParticipantIds.push(n.participantId),t.groups.push({participantRoleResponsibilities:n.participantRoleResponsibilities,participantOtherName:n.participantOtherName,participantName:n.participantName,participantId:n.participantId}))}))}))}})),{participantsWithGroupings:i,groupInfo:Object.fromEntries(r)}}function lp(t){return t&&void 0!==String.fromCodePoint?t.toUpperCase().replace(/./g,(t=>String.fromCodePoint(t.charCodeAt(0)+127397))):t}const mp=[{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 fp({participant:t,withISO2:e,withIOC:n}){const{person:r,individualParticipants:i}=t;[r,i?.map((({person:t})=>t))].flat().filter(Boolean).forEach((function(t){const{nationalityCode:r}=t||{};if(r){const i=mp.find((({iso:t})=>t===r));n&&i?.ioc&&!t.iocNationalityCode&&(t.iocNationalityCode=i.ioc),e&&i?.iso2&&!t.iso2NationalityCode&&(t.iso2NationalityCode=i.iso2),i?.label&&!t.countryName&&(t.countryName=i.label)}}))}function hp(t){const{tournamentRecord:e,participantId:n}=t,r=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(const t of Object.values(r)){const e=t.participants?.find((t=>t.participantId===n));if(e)return{participant:e,tournamentId:t.tournamentId}}return{error:en}}function gp(t){const{tournamentRecord:e,participantId:n}=t;if(n){const t=hp({tournamentRecord:e,participantId:n});return t.participant??t}const r=t.element||t.drawDefinition||t.event||t.tournamentRecord;return r||{error:be}}function Ip(t){const{returnPreviousValues:e,itemSubTypes:n,itemType:r}=t,i=gp(t);if(i.error)return i;if(n&&!Array.isArray(n))return{error:Jn,context:{itemSubTypes:n}};if(!Array.isArray(i.timeItems))return{error:Ln};const a=i.timeItems.filter((t=>t?.itemType===r)).filter((t=>!n?.length||n.some((e=>t?.itemSubTypes?.includes(e))))).sort(((t,e)=>new Date(t.createdAt||void 0).getTime()-new Date(e.createdAt||void 0).getTime())),o=la(a.pop(),!1,!0);if(o){const t={timeItem:o,...z};return e&&Object.assign(t,{previousItems:a}),t}return{info:rr}}function Up({returnPreviousValues:t,drawDefinition:e,itemSubTypes:n,itemType:r}){if(!e)return{error:Tt};if(!e.timeItems)return{info:rr};const{timeItem:i,previousItems:a,info:o}=Ip({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}}function yp({returnPreviousValues:t,itemSubTypes:e,itemType:n,event:r}){if(!r)return{error:$t};if(!r.timeItems)return{info:rr};const{timeItem:i,previousItems:a,info:o}=Ip({returnPreviousValues:t,element:r,itemSubTypes:e,itemType:n});return i&&{timeItem:i,previousItems:a}||{info:o}}function Sp({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:n,itemType:r}){if(!e)return{error:nt};if(!e.timeItems)return{info:rr};const{timeItem:i,previousItems:a,info:o}=Ip({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}}function vp({returnPreviousValues:t,tournamentRecord:e,participantId:n,itemSubTypes:r,itemType:i}){if(!e)return{error:nt};if(!n)return{error:Xe};const a=hp({tournamentRecord:e,participantId:n});if(a.error)return a;const{participant:o}=a;if(!o?.timeItems)return{info:rr};const{timeItem:s,previousItems:c,info:u}=Ip({element:a.participant,returnPreviousValues:t,itemSubTypes:r,itemType:i});return s&&{timeItem:s,previousItems:c}||{info:u}}const wp={[op]:"groupParticipantIds",[sp]:"pairParticipantIds",[cp]:"teamParticipantIds"},Pp={[op]:"groups",[cp]:"teams"};function Dp({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:n,withSignInStatus:r,withScaleValues:i,withGroupings:a,internalUse:o,withISO2:s,withIOC:c}){const u=[],d={};for(const t of n.participants??[]){const e=t?.participantId;e&&Rp({participantMap:d,participantId:e})}for(const t of n.participants??[]){const n=la(t,e,o),{participantId:a,individualParticipantIds:p,participantType:l}=n;if(d[a]){if(Object.assign(d[a].participant,n),p){const t=bp({individualParticipantIds:p,participantCopy:n,participantMap:d,participantType:l,participantId:a});t.missingParticipantIds.length&&u.push(...t.missingParticipantIds)}if(r&&(d[a].participant.signedIn=Tp(n)),i){const{ratings:t,rankings:e,seedings:r}=gc({participant:n});d[a].participant.seedings=r,d[a].participant.rankings=e,d[a].participant.ratings=t}(c||s)&&fp({participant:d[a].participant,withISO2:s,withIOC:c})}else u.push(a)}if(t){!function({participantMap:t,template:e}){const n=Object.values(t);for(const r of n){const n=r.participant;if(n.individualParticipantIds?.length){n.individualParticipants=[];for(const r of n.individualParticipantIds){const i=t[r].participant;n.individualParticipants.push(e?Ic({template:e,source:i}):i)}}}}({participantMap:d,template:G(t)?t:void 0})}let p;return a&&(p=pp({participants:Object.values(d).map((({participant:t})=>t)),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:d,groupInfo:p}}function Tp(t){const{timeItem:e}=Ip({itemType:ep,element:t});return e?.itemValue===rp}function bp({individualParticipantIds:t,participantCopy:e,participantMap:n,participantType:r,participantId:i}){const a=[];for(const o of t){const s=n[o]?.participant;if(s){if(s[wp[r]].push(i),[cp,op].includes(r)){const{participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:a,teamId:o}=e;s[Pp[r]].push({participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:a,teamId:o})}if(r===sp){const e=t.find((t=>t!==o));n[o].pairIdMap[i]=e,n[o].pairIdMap[e]=i}}else a.push(o)}return{missingParticipantIds:a}}function Rp({participantMap:t,participantId:e}){if(t[e])return;const 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:{[n]:{...r},[i]:{...r},[cp]:{...r},...r}}}function Mp({participantsProfile:t,useParticipantMap:e,tournamentRecord:n,contextProfile:r,inContext:i}){if(e)return Dp({...t,...r,tournamentRecord:n});let a,o=la(n.participants,!1,!0)||[];if((t?.withIOC||t?.withISO2)&&o.forEach((e=>fp({participant:e,...t}))),(i||t?.withGroupings)&&o?.length&&({participantsWithGroupings:o,groupInfo:a}=pp({participantsProfile:t,deepCopy:!1,participants:o})),t?.withScaleValues&&o?.length)for(const t of o){const{ratings:e,rankings:n}=gc({participant:t});t.rankings=n,t.ratings=e}return{participants:o,groupInfo:a}}function Np({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:n,drawDefinition:r,structure:i,event:a}){if(!Array.isArray(e))return{error:ge};const o={};return n&&s(n),a&&s(a),r&&s(r),i&&s(i),{appliedPolicies:o,...z};function s(n){const r=n?.extensions,i=r?.find((t=>t.name===Yc))?.value;if(i)for(const n of Object.keys(i))(t?e.includes(n):!e.length||e.includes(n))&&(o[n]=la(i[n],!1,!0))}}function Ap({policyTypes:t=[],tournamentRecord:e,drawDefinition:n,structure:r,event:i}){if(!Array.isArray(t))return{error:ge};const{appliedPolicies:a}=Np({tournamentRecord:e,drawDefinition:n,structure:r,event:i}),o={};for(const e of t){const t=a?.[e];t&&(o[e]=t)}return Object.keys(o).length?{policyDefinitions:o}:{info:we.message}}const Ep="WALKOVER",Cp="RETIRED",Op="COMPETITIVE",Fp="ROUTINE",kp="DECISIVE",xp="winRatio",_p={[yc]:{policyName:"Competitive Bands Default",profileBands:{[kp]:20,[Fp]:50}}};function Lp({policyDefinitions:t,tournamentRecord:e,contextProfile:n,drawDefinition:r,event:i}){const a={policies:{}};if(!n)return a;const o=Ap({tournamentRecord:e,drawDefinition:r,event:i}).policyDefinitions;if(n.withCompetitiveness){const e=t?.[yc]??o?.[yc]??_p[yc];a.policies[yc]=e}return a}function Bp({tournamentRecord:t,drawDefinition:e,policyType:n,structure:r,event:i}){if(!t)return{error:nt};const{appliedPolicies:a}=Np({tournamentRecord:t,drawDefinition:e,structure:r,event:i});return a?.[n]?{policy:a[n]}:{info:we?.message}}function Vp({tournamentRecord:t,categoryName:e,categoryType:n,event:r}){e=e??r?.category?.categoryName??r?.category?.ageCategoryCode,n=n??r?.category?.categoryType??r?.category?.subType;const{policy:i}=Bp({policyType:Rc,tournamentRecord:t,event:r}),a=t?zc({element:t,name:mu}).extension:void 0,o=a?.value,s=r&&zc({name:mu,element:r}).extension,c=s?.value;return{scheduleTiming:{tournamentScheduling:o,eventScheduling:c,categoryName:e,categoryType:n,policy:i}}}function jp({drawDefinition:t,attributes:e}){let{extension:n}=zc({element:t,name:nu});const r=n?.value||{};return e.forEach((t=>{Object.keys(t).forEach((e=>{r[e]?Object.assign(r[e],t[e]):r[e]=t[e]}))})),n={name:nu,value:r},Bc({drawDefinition:t,extension:n}),{entryProfile:r}}function Gp({drawDefinition:t}){const{extension:e}=zc({element:t,name:nu});return{entryProfile:e?.value||{}}}const qp="ALTERNATE",$p="CONFIRMED",Wp="DIRECT_ACCEPTANCE",Hp="FEED_IN",zp="JUNIOR_EXEMPT",Yp="LUCKY_LOSER",Kp="ORGANISER_ACCEPTANCE",Qp="QUALIFIER",Jp="SPECIAL_EXEMPT",Zp="UNGROUPED",Xp="UNPAIRED",tl="WILDCARD",el="WITHDRAWN",nl=[$p,Wp,zp,Kp,Jp],rl=[Hp,Yp,Qp],il=[$p,Wp,Hp,zp,Kp,Jp,tl],al=[$p,Wp,zp,Yp,Qp,Kp,Jp,tl],ol=[qp,$p,Wp,Hp,zp,Yp,Kp,Qp,"REGISTERED",Jp,Zp,Xp,tl,el],sl={ALTERNATE:qp,CONFIRMED:$p,DIRECT_ACCEPTANCE:Wp,DIRECT_ENTRY_STATUSES:il,DRAW_SPECIFIC_STATUSES:rl,EQUIVALENT_ACCEPTANCE_STATUSES:nl,FEED_IN:Hp,JUNIOR_EXEMPT:zp,LUCKY_LOSER:Yp,ORGANISER_ACCEPTANCE:Kp,QUALIFIER:Qp,SPECIAL_EXEMPT:Jp,STRUCTURE_SELECTED_STATUSES:al,UNGROUPED:Zp,UNPAIRED:Xp,VALID_ENTRY_STATUSES:ol,WILDCARD:tl,WITHDRAWN:el};function cl({stage:t,drawDefinition:e}){const{entryProfile:n}=Gp({drawDefinition:e}),r=Object.keys(n).includes(t);if(!r&&yo.includes(t)){return jp({drawDefinition:e,attributes:[{[t]:{drawSize:void 0,alternates:!0}}]}),!0}return r}function ul({stage:t,drawDefinition:e,entryStatus:n}){return e.entries.reduce(((e,r)=>r.entryStage===t&&r.entryStatus===n?e+1:e),0)}function dl({provisionalPositioning:t,placementGroup:e,drawDefinition:n,stageSequence:r,entryStatuses:i,structureId:a,roundTarget:o,stages:s,stage:c}){const d=n.entries?.reduce(((t,e)=>{const n=zc({name:pu,element:e})?.extension?.value,a=c&&e.entryStage===c||s?.length&&e.entryStage&&s.includes(e.entryStage),u=!i||e.entryStatus&&i.includes(e.entryStatus),d=e.entryStageSequence??1;return a&&(!r||d===r)&&u&&(!o||!n||o===n)?t.concat(e):t}),[])??[];if(a&&c===Uo){const{playoffEntries:r,error:i}=function({provisionalPositioning:t,drawDefinition:e,structureId:n}){const r=[],i=(e.links??[]).find((t=>t.linkType===Oo&&t.target.structureId===n));if(i){const{finishingPositions:n,structureId:a}=i.source,{structure:o}=ad({drawDefinition:e,structureId:a});if(o?.structureType===Mo){(o.structures??[]).forEach((e=>{const i=e.positionAssignments??[],{structureId:a}=e,o=a,s=Object.assign({},...i.map((t=>{const{participantId:e}=t,n=zc({element:t,name:gu}).extension?.value;return n&&e?{[e]:n}:void 0})).filter(Boolean)),c=Object.keys(s).reduce(((e,n)=>{const r=s[n],i=r.groupOrder||t&&r.provisionalOrder;return e.includes(i)||e.push(i),e}),[]),d=c.length===Object.keys(s).length,p=Object.keys(s).filter((e=>{const r=s[e],i=r.groupOrder||t&&r.provisionalOrder;return n?.includes(i)}));t&&!d||p.forEach((e=>{const i=s[e],{groupOrder:a,provisionalOrder:c,GEMscore:d}=i,p=a||t&&c,l=[...n??[]].sort(u).indexOf(p)+1;r.push({entryStage:Uo,entryStatus:Hp,placementGroup:l,groupingValue:o,participantId:e,GEMscore:d})}))}))}}return{playoffEntries:r}}({provisionalPositioning:t,drawDefinition:n,structureId:a});return i&&console.log("playoff entries error"),(r?.length?r:d).filter((t=>!e||t.placementGroup===e))}return d}function pl({provisionalPositioning:t,returnAllProxies:e,drawDefinition:n,structureId:r,structure:i}){let a,o=[];i||({structure:i,error:a}=ad({drawDefinition:n,structureId:r}));const s=cd({structure:i}).positionAssignments;if(a||!i)return{seedAssignments:[],error:Lt};r||(r=i.structureId);const{stage:c,stageSequence:u}=i,d=c===Uo&&n&&dl({provisionalPositioning:t,drawDefinition:n,stageSequence:u,structureId:r,stage:c}),p=d?d.filter((t=>1===t.placementGroup)).sort(((t,e)=>(t.GEMscore<e.GEMscore?1:t.GEMscore>e.GEMscore&&-1)||0)).map(((t,e)=>{const n=e+1;return{participantId:t.participantId,seedValue:n,seedProxy:!0,seedNumber:n}})):[],l=p?.slice(0,e?p.length:s.length/2);l.length?o=l:i.seedAssignments?o=i.seedAssignments:a=Ct;return{seedAssignments:o,stageSequence:u,seedLimit:i.seedLimit??i?.positionAssignments?.length,stage:c,error:a}}function ll(t){if(!t)return;const{tieFormatId:e,tieFormats:n}=t;return t.tieFormat?t.tieFormat:e&&Array.isArray(n)?n.find((t=>t.tieFormatId===e)):void 0}function ml({item:t,drawDefinition:e,structure:n,event:r}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;const n=e.tieFormats?.find((e=>t.tieFormatId===e.tieFormatId));return n||(r.tieFormat?r.tieFormat:r.tieFormats?.find((e=>t.tieFormatId===e.tieFormatId)))}if(n.tieFormat)return n.tieFormat;if(n.tieFormatId){const t=e.tieFormats?.find((t=>n.tieFormatId===t.tieFormatId));if(t)return t}}}function fl({drawDefinition:t,structure:e,matchUp:n,event:r}){return{tieFormat:ml({item:n,drawDefinition:t,structure:e,event:r})||ml({item:e,drawDefinition:t,structure:e,event:r})||ll(t)||ll(r)}}function hl({drawDefinition:t,structure:e}){const n={},r=[];return(t?.structures??[e]).filter((t=>t&&"object"==typeof t)).forEach((t=>{if(!t)return;const{structureId:e,matchUps:i,structures:a}=t,o=Array.isArray(a);if(o)o&&a.forEach((t=>{const{structureName:i}=t,a=t.matchUps;n[t.structureId]={matchUps:a,itemStructureIds:[],structureName:i},a&&(r.push(...a),a.forEach((t=>{t.tieMatchUps&&r.push(...t.tieMatchUps)}))),n[e]||(n[e]={itemStructureIds:[],matchUps:[]}),n[e].itemStructureIds||(n[e].itemStructureIds=[]),n[e].itemStructureIds.push(t.structureId)}));else{const t=i;n[e]={matchUps:t,itemStructureIds:[]},t?.forEach((t=>{r.push(t),t.tieMatchUps&&r.push(...t.tieMatchUps)}))}})),{mappedMatchUps:n,drawMatchUps:r}}function gl({mappedMatchUps:t,matchUpsMap:e,structureId:n,inContext:r}){const i=(t=e?.mappedMatchUps??t)[n],a=(i?.itemStructureIds||[]).map((e=>{const{matchUps:i,structureName:a}=t[e];return r?i.map((t=>Object.assign(la(t,!0,!0),{containerStructureId:n,structureId:e,structureName:a}))):i})).flat();return(i?.matchUps||[]).concat(...a)}function Il({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;const n=x(t,t.length/e).map((t=>t.reduce(((t,e)=>t+e)))),r=n.slice().sort(u);return n.map((t=>r.indexOf(t)+1))}function Ul(t){if(!G(t))return!1;const{matchUpId:e,drawPositions:n}=t,r="string"==typeof e,i=!n||Array.isArray(n)&&n.length<=2&&n.every((t=>y(t)||null==t));return r&&i}function yl(t){return!!Array.isArray(t)&&t.every(Ul)}function Sl({matchUps:t=[],interpolate:e}){if(!yl(t))return{roundMatchUps:[],error:Jn};const n=t.reduce(((t,e)=>{const n="string"==typeof e.roundNumber?d(e.roundNumber):e.roundNumber;return!e.roundNumber||t.includes(n)?t:t.concat(n)}),[]).sort(u).map((e=>{const n=t.filter((t=>t.roundNumber===e)),r=n.find((({matchUpType:t})=>t===o))?n.filter((({matchUpType:t})=>t===o)):n;return{[e]:(i=r,i.sort(((t,e)=>u(t.roundPosition,e.roundPosition))))};var i})),r=t.reduce(((t,e)=>{const n="string"==typeof e.roundNumber?d(e.roundNumber):e.roundNumber;return t[n]||(t[n]=Xr({abbreviatedRoundName:e.abbreviatedRoundName,finishingRound:e.finishingRound,roundName:e.roundName})),t}),{}),i=Object.assign({},...n);if(e){const t=Math.max(...Object.keys(i).map((t=>d(t))).filter((t=>!isNaN(t)))),e=i[t]?.length;if(e>1&&p(e)){const n=t+1;E(n,n+e/2).forEach(((t,n)=>{i[t]=E(0,e/(2+2*n)).map((()=>({})))}))}}let a=0;const s=Object.assign({},...Object.keys(i).map((t=>{const e=i[t]?.length,n=i[t]?.filter((t=>!Xu.includes(t.matchUpStatus)&&!t.score?.scoreStringSide1))?.length,r=e&&e===n;return a=Math.max(a,e),{[t]:{matchUpsCount:e,inactiveCount:n,inactiveRound:r}}})));let c=0,l=0;const m=Object.keys(i).map((t=>d(t))).filter((t=>!isNaN(t)));m.forEach((t=>{const e=i[t].sort(((t,e)=>t.roundPosition-e.roundPosition)),n=e.map((t=>t?.drawPositions||[])).flat();if(s[t].roundNumber=t,s[t].roundFactor=s[t].matchUpsCount?a/s[t].matchUpsCount:1,s[t].finishingRound=r[t]?.finishingRound,s[t].roundName=r[t]?.roundName,s[t].abbreviatedRoundName=r[t]?.abbreviatedRoundName,s[t].finishingPositionRange=i[t]?.[0]?.finishingPositionRange,1!==t&&s[t-1]){const n=s[t-1],r=n.drawPositions,i=n.matchUpsCount/s[t].matchUpsCount,a=x(r,i),o=e.map((e=>{const{roundPosition:n}=e,i=[...e.drawPositions||[],void 0,void 0].slice(0,2);if(!n)return i;const o=i?.filter(Boolean)||[];if(!o?.length)return[void 0,void 0];if(t<3&&2===o?.length)return i?.slice().sort(u);const s=O(r,o).length!==o?.length;if(o?.length&&s)return 1===o?.length?[o[0],void 0]:i?.slice().sort(u);const c=2*(n-1);return a.slice(c,c+2).map((t=>o?.find((e=>t.includes(e)))))}));s[t].drawPositions=o?.flat(),s[t].pairedDrawPositions=o}else{const e=n.sort(u),r=x(e,2);s[t].drawPositions=e,s[t].pairedDrawPositions=r}s[t+1]&&s[t+1].matchUpsCount===s[t].matchUpsCount&&(s[t+1].feedRound=!0,s[t+1].feedRoundIndex=l,s[t].preFeedRound=!0,l+=1),s[t]&&!s[t].feedRound&&(s[t].roundIndex=c,c+=1)}));const f=!!Object.values(s).find((({matchUpsCount:t})=>!p(t)));return{hasNoRoundPositions:t.some((t=>!t.roundPosition)),roundsNotPowerOf2:f,maxMatchUpsCount:a,roundMatchUps:i,roundNumbers:m,roundProfile:s,...z}}function vl(t){if(!Array.isArray(t))return"";const e=t.filter(h);if(!e.length)return"";return w([Math.min(...e),Math.max(...e)]).join("-")}function wl({drawDefinition:t}){if("object"!=typeof t)return{error:at};const e={},{structures:n=[],links:r=[]}=t||{},i=n.reduce(((t,e)=>{const{stage:n}=e;return t[n]?t[n].push(e):t[n]=[e],t}),{});for(const t of Object.keys(i)){const n=i[t].find((({stageSequence:t})=>1===t));if(!n)continue;const{structureId:r}=n;a({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:r,stage:t})}return{exitProfiles:e};function a({exitProfiles:t,exitProfile:e,structureId:i,targetRound:o,aggregator:s,stage:c}){t[i]||(t[i]=[]),"0"===e&&[go,Uo].includes(c)||t[i].push(e);const u=r.filter((t=>t.source.structureId===i&&t.source.roundNumber>=o));for(const r of u){const i=r.source.roundNumber,o=r.target.roundNumber,c=r.target.structureId,u=n.find((t=>t.structureId===c)).stage,d=[u,c,o,i].join("|");if(s[d])return;s[d]=!0,a({exitProfile:`${e}-${i}`,structureId:c,exitProfiles:t,targetRound:o,aggregator:s,stage:u})}}}function Pl({roundsNotPowerOf2:t,drawDefinition:e,structure:n,matchUps:r}){if(!n)return!1;r=r??n.matchUps??[],t=t??Sl({matchUps:r}).roundsNotPowerOf2;const i=!!n.positionAssignments?.find((({drawPosition:t})=>t))||!!r?.find((({drawPositions:t})=>t?.length));return(!e?.drawType||e.drawType!==Wo)&&!n?.structures&&t&&i}function Dl({structure:t}){if(!t)return!1;const e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),n=!!e?.find((t=>t?.roundPosition)),r=!!e?.find((t=>t?.drawPositions?.length));return!(t?.structures||t?.stage===Io||e.length&&(n||r))}const Tl={[Dc]:{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:{[fo]:"",[Uo]:"P",[ho]:"Q",[go]:"C"}}};const bl=(t,e)=>(t||0)+(e||0);function Rl(t,e){const n=Array.isArray(t)?t[0]:t;return isNaN(n)&&Ep||n<=e[kp]&&kp||n<=e[Fp]&&Fp||Op}function Ml({score:t}){const e=t?.sets||[],n=e.reduce(((t,e)=>(t[0]+=e.side1Score||0,t[1]+=e.side2Score||0,t)),[0,0]),r=e.reduce(((t,e)=>(t[0]+=e.side1TiebreakScore||0,t[1]+=e.side2TiebreakScore||0,t)),[0,0]);return r.reduce(bl)&&(n[r[0]>r[1]?0:1]+=1),{sets:e,games:n,score:t}}function Nl(t){const e=Math.min(...t.games),n=Math.max(...t.games);return Math.round(e/n*100)}function Al(t){return t.map(Nl).sort().map((t=>parseFloat(t.toFixed(2))))}function El({tournamentRecord:t,profileBands:e,matchUp:n}){if(!n)return{error:fe};const{score:r,winningSide:i}=n;if(!i)return{error:Jn};const a=!e&&t&&Bp({policyType:yc,tournamentRecord:t}).policy,o=e||a?.profileBands||_p[yc].profileBands,s=Al([Ml({score:r})]),c=Rl(s,o),u=Array.isArray(s)?s[0]:s;return{...z,competitiveness:c,pctSpread:u}}function Cl({matchUp:t}){if(!t)return{error:fe};if(t&&!t.sides)return{error:he};if(t&&!t.hasContext)return{error:Bn};const e=(t.sides??[])?.map((t=>t?.participantId)).filter(Boolean),n=t.sides?.filter((t=>t.participant?.participantType===ap)).map((t=>t.participantId)).filter(Boolean)??[],r=((t.sides??[])?.map((t=>t.participant?.individualParticipants)).filter(Boolean)??[]).map((t=>(t??[]).map((t=>t?.participantId)).filter(Boolean))),i=[...n,...r.flat()].filter(Boolean)??[];return{nestedIndividualParticipantIds:r,allRelevantParticipantIds:w(i.concat(e)).filter(Boolean)??[],individualParticipantIds:i,sideParticipantIds:e,...z}}const Ol="CHECK_IN",Fl="CHECK_OUT",kl="SCHEDULE.ASSIGNMENT.VENUE",xl="SCHEDULE.ALLOCATION.COURTS",_l="SCHEDULE.ASSIGNMENT.COURT",Ll="SCHEDULE.COURT.ORDER",Bl="SCHEDULE.DATE",Vl="HOME_PARTICIPANT_ID",jl="SCHEDULE.ASSIGN.OFFICIAL",Gl="SCHEDULE.TIME.SCHEDULED",ql="SCHEDULE.TIME.START",$l="SCHEDULE.TIME.STOP",Wl="SCHEDULE.TIME.RESUME",Hl="SCHEDULE.TIME.END",zl="SCHEDULE.TIME.MODIFIERS",Yl="TO_BE_ANNOUNCED",Kl="NEXT_AVAILABLE",Ql="FOLLOWED_BY",Jl="AFTER_REST",Zl="RAIN_DELAY",Xl=[Yl,Kl,Ql,Jl,Zl],tm="SCALE",em="RATING",nm="RANKING",rm="SEEDING",im="PUBLISH",am="PUBLIC",om="STATUS",sm={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:Xl,AFTER_REST:Jl,ALLOCATE_COURTS:xl,ASSIGN_COURT:_l,ASSIGN_OFFICIAL:jl,ASSIGN_VENUE:kl,CHECK_IN:Ol,CHECK_OUT:Fl,COMPLETED_DATE:"COMPLETED.DATE",COURT_ORDER:Ll,ELIGIBILITY:"ELIGIBILITY",END_TIME:Hl,FOLLOWED_BY:Ql,MEDICAL:"MEDICAL",MODIFICATION:"MODIFICATION",NEXT_AVAILABLE:Kl,NOT_BEFORE:"NOT_BEFORE",OTHER:"other",PENALTY:"PENALTY",PUBLIC:am,PUBLISH:im,RANKING:nm,RATING:em,RAIN_DELAY:Zl,REGISTRATION:"REGISTRATION",RESUME_TIME:Wl,RETRIEVAL:"RETRIEVAL",SCALE:tm,SCHEDULE:"SCHEDULE",SCHEDULED_DATE:Bl,SCHEDULED_TIME:Gl,SEEDING:rm,START_TIME:ql,STATUS:om,STOP_TIME:$l,SUSPENSION:"SUSPENSION",TIME_MODIFIERS:zl,TO_BE_ANNOUNCED:Yl};function cm({matchUp:t}){if(!t)return{error:fe};if(!t.hasContext)return{error:Bn};if(!t.sides||2!==t.sides.filter(Boolean).length)return{error:he};const{nestedIndividualParticipantIds:e,allRelevantParticipantIds:n,sideParticipantIds:r}=Cl({matchUp:t}),i=(t.timeItems??[]).filter((t=>t?.itemType&&[Ol,Fl].includes(t.itemType))).sort(((t,e)=>(t.createdAt?new Date(t.createdAt).getTime():0)-(e.createdAt?new Date(e.createdAt).getTime():0))),a=i.map((t=>t.itemValue)).filter((t=>i.filter((e=>e?.itemValue===t)).reverse()[0].itemType===Ol));e?.forEach(((t,e)=>{const n=r?.[e],i=t?.length&&t.every((t=>a.includes(t)));n&&i&&!a.includes(n)&&a.push(n)})),r?.forEach(((t,n)=>{a.includes(t)&&(e?.[n]??[]).forEach((t=>{t&&!a.includes(t)&&a.push(t)}))}));const o=r?.reduce(((t,e)=>a.includes(e)&&t),!0);return{allRelevantParticipantIds:n,allParticipantsCheckedIn:o,checkedInParticipantIds:a,...z}}const um=t=>e=>{const n=G(e)&&e?.matchUpType||j(e)&&e;return n&&c[t].includes(n)};function dm(t){const{matchUpAverageTimes:e,matchUpFormat:n}=t||{},r=e?.map((({matchUpFormatCodes:t})=>t?.filter((t=>t===n)))).flat().filter(Boolean).sort(((t,e)=>(t?.length||0)-(e?.length||0)))||[],i=r.includes(n)?n:r[0],a=e?.find((({matchUpFormatCodes:t,averageTimes:e})=>t?.find((t=>i===t))&&e));return a?.averageTimes}function pm(t){const{matchUpRecoveryTimes:e,averageMinutes:n,matchUpFormat:r}=t||{};return e?.find((({matchUpFormatCodes:t,averageTimes:e,recoveryTimes:i})=>{if(e&&n){const{greaterThan:t=0,lessThan:r=360}=e;if(n>t&&n<r)return!0}return t?.find((t=>t===r))&&i}))?.recoveryTimes}function lm({timesBlockArray:t,categoryName:e,categoryType:n}){return t.filter((t=>Array.isArray(t))).map((t=>t.sort(((t,e)=>(e.categoryNames?.length||0)-(t.categoryNames?.length||0))).find((({categoryTypes:t,categoryNames:r})=>!r?.length&&!t?.length||r?.includes(e)||t?.includes(n))))).find(Boolean)}const mm="DOUBLES_SINGLES",fm="SINGLES_DOUBLES",hm="total",gm="participantConflict",Im="matchUpConflict",Um="ISSUE_IDS",ym="CONFLICT",Sm="WARNING",vm="ERROR",wm="ISSUE",Pm="STATE",Dm={SINGLES_DOUBLES:fm,DOUBLES_SINGLES:mm,TOTAL:hm,CONFLICT_MATCHUP_ORDER:Im,CONFLICT_PARTICIPANTS:gm,SCHEDULE_ISSUE_IDS:Um,SCHEDULE_CONFLICT:ym,SCHEDULE_WARNING:Sm,SCHEDULE_ERROR:vm,SCHEDULE_ISSUE:wm,SCHEDULE_STATE:Pm};function Tm({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:n,matchUpFormat:r,categoryName:i,categoryType:a,eventType:o,event:s}){if(!n)return{error:nt};o=o??s?.eventType??so;const c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Vp({tournamentRecord:n,categoryName:i,categoryType:a,event:s});return bm({eventType:o,timingDetails:{...u,matchUpFormat:r,categoryType:a,defaultTiming:c}})}function bm({timingDetails:t,eventType:e}){const n=function({matchUpFormat:t,categoryName:e,categoryType:n,defaultTiming:r,tournamentScheduling:i,eventScheduling:a,policy:o}){return lm({categoryName:e,categoryType:n,timesBlockArray:[a?.matchUpAverageTimes&&dm({...a,matchUpFormat:t}),i?.matchUpAverageTimes&&dm({...i,matchUpFormat:t}),o?.matchUpAverageTimes&&dm({...o,matchUpFormat:t}),o?.defaultTimes?.averageTimes,r?.averageTimes]})}(t),r=Object.keys(n?.minutes||{}),i=n?.minutes&&(r?.includes(e)&&n.minutes[e]||n.minutes.default),a=function({tournamentScheduling:t,eventScheduling:e,averageMinutes:n,defaultTiming:r,matchUpFormat:i,categoryName:a,categoryType:o,policy:s}){return lm({categoryName:a,categoryType:o,timesBlockArray:[e?.matchUpRecoveryTimes&&pm({...e,averageMinutes:n,matchUpFormat:i}),t?.matchUpRecoveryTimes&&pm({...t,averageMinutes:n,matchUpFormat:i}),s?.matchUpRecoveryTimes&&pm({...s,averageMinutes:n,matchUpFormat:i}),s?.defaultTimes?.recoveryTimes,r?.recoveryTimes]})}({...t,averageMinutes:i}),o=Object.keys(a?.minutes||{}),s=a?.minutes&&(o?.includes(e)&&a.minutes[e]||a.minutes.default),c=um(so)(e)?fm:mm;return{averageMinutes:i,recoveryMinutes:s,typeChangeRecoveryMinutes:a?.minutes&&(o?.includes(c)&&a.minutes[c]||s)}}function Rm(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Mm({timeItems:t,itemType:e}){const n=t.filter((t=>t&&t.itemType===e)).sort(((t,e)=>Rm(t)-Rm(e))).pop(),r=n&&Rm(n);return{itemValue:n?.itemValue,timeStamp:r}}function Nm({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=Mm({timeItems:n?.timeItems||[],itemType:Gl});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{scheduledTime:r}:e}function Am({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=Mm({timeItems:n?.timeItems||[],itemType:Bl});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{scheduledDate:r}:e}function Em(t){if(bi.test(t)){const e=Oi();return new Date(`${e}T${t}`)}return new Date(t)}function Cm(t){const e=(t,e=2)=>("00"+t).slice(-e);return e(t/36e5|0)+":"+e(t%36e5/6e4|0)+":"+e(t%6e4/1e3|0)}function Om(t){const{disableNotice:e,venue:n,context:r}=t;if("object"!=typeof n)return{error:Jn};const i=tp(t);let a;n.venueId||(n.venueId=ha());for(const t of Object.values(i)){const e=Fm({disableNotice:!0,tournamentRecord:t,context:r,venue:n});if(e?.error)return e;a=e.venue}return e||Or({topic:hd,payload:{venue:n}}),Xr({...z,venue:a})}function Fm({tournamentRecord:t,disableNotice:e,context:n,venue:r}){if(!t)return{error:nt};if(!r)return{error:be,info:"missing venue"};t.venues||(t.venues=[]),r.venueId||(r.venueId=ha());if(t.venues.reduce(((t,e)=>t||e.venueId===r.venueId),void 0))return{error:Rn};if(n){_c({element:r,extension:{value:n,name:Kc}})}return t.venues.push(r),{...z,venue:la(r)}}function km({tournamentRecords:t,tournamentRecord:e,venueId:n}){if(!e)return{error:nt};if(!n)return{error:Nn};const r=(e.venues??[]).reduce(((t,e)=>e.venueId===n?e:t),void 0);if(!r&&t){const i=(Pu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const a of i){const i=km({tournamentRecord:t[a],venueId:n});if(i.success&&i.venue)return Om({tournamentRecord:e,venue:i.venue}),{...z,venue:r}}}return r?{...z,venue:r}:{error:Mn}}function xm({convertExtensions:t,...e}){const{tournamentRecords:n,tournamentRecord:r,venueId:i}=e;return la(km({tournamentRecords:n,tournamentRecord:r,venueId:i}),t,!0)}function _m({tournamentRecords:t,tournamentRecord:e,courtId:n}){if(!e)return{error:nt};if(!n)return{error:Te};let r,i;if((e.venues??[]).forEach((t=>{(t.courts??[]).forEach((e=>{e.courtId===n&&(r=e,i=t)}))})),r)return{...z,court:r,venue:i};if(t){const a=(Pu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const o of a){const a=_m({tournamentRecord:t[o],courtId:n});if(a.success)return a.venue&&Om({tournamentRecord:e,venue:a.venue}),{...z,court:r,venue:i}}}return ti({result:{error:Tn},stack:"findCourt"})}function Lm(t){return la(_m(t),!1,!0)}function Bm({tournamentRecord:t,internalUse:e,courtId:n}){if(!t)return{error:nt};if(!n)return{error:Te};const r=_m({tournamentRecord:t,courtId:n});if(r.error)return r;const i=r.court&&(({altitude:t,courtId:e,courtName:n,courtDimensions:r,latitude:i,longitude:a,surfaceCategory:o,surfaceType:s,surfacedDate:c,pace:u,notes:d})=>({altitude:t,courtId:e,courtName:n,courtDimensions:r,latitude:i,longitude:a,surfaceCategory:o,surfaceType:s,surfacedDate:c,pace:u,notes:d}))(r.court);return{...z,courtInfo:la(i,!1,e)}}function Vm(t){const e=cc(t,[{[hs]:!0},{venueId:!0,[$s]:Nn}]);if(e.error)return e;const{tournamentRecord:n,venueId:r}=t,i=km({tournamentRecord:n,venueId:r});if(i.error)return i;const a=(i.venue?.courts??[]).map((t=>(({courtInfo:t})=>({...t}))(Bm({courtId:t.courtId,internalUse:!0,tournamentRecord:n})))),o=i.venue&&(({venueId:t,venueName:e,venueAbbreviation:n})=>({venueAbbreviation:n,venueName:e,venueId:t}))(i.venue),s=o&&{...o,courtsInfo:a};return{...z,venueData:la(s,!1,!0)}}function jm({event:t,eventId:e}){if(!t)return{error:$t};const n=zc({name:ru,element:t}),r=n?.extension,i=e?la(r?.value,!1,!0):r?.value;return e&&t.drawDefinitions?.forEach((t=>{i?.flights?.forEach((e=>{e.drawId===t.drawId&&Object.assign(e,{drawDefinition:t})}))})),{flightProfile:i}}function Gm(t){const{tournamentRecord:e,eventId:n,drawId:r}=t,i="findEvent",a={},o=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},s=Object.values(o).map((({events:t,tournamentId:e})=>(t&&t.forEach((t=>{a[t.eventId]={tournamentId:e}})),t??[]))).flat();let c;if(r){let t;const e=s.find((e=>{const n=(e?.drawDefinitions??[]).find((t=>t.drawId===r));if(n)t=n,c=a[e.eventId].tournamentId;else{const t=e&&jm({event:e})?.flightProfile,n=t?.flights?.find((t=>t.drawId===r));if(n)return c=a[e.eventId].tournamentId,{entries:n.drawEntries,drawName:n.drawName,tournamentId:c,drawId:r}}return n}));if(e)return{event:e,drawDefinition:t,tournamentId:c}}if(n){const t=s.find((t=>t?.eventId===n));return t?(c=a[t.eventId].tournamentId,{event:t,drawDefinition:void 0,tournamentId:c}):{event:void 0,drawDefinition:void 0,...ti({result:{error:Wt},stack:i})}}return{event:void 0,drawDefinition:void 0,...ti({result:{error:ct},context:{drawId:r,eventId:n},stack:i})}}function qm(t){let e=t.event,n=t.matchUpType;const{scheduleVisibilityFilters:r,afterRecoveryTimes:i,tournamentRecord:a,usePublishState:o,scheduleTiming:s,matchUpFormat:c,publishStatus:u,matchUp:d}=t;if(!d)return{error:fe};if(i&&!d.matchUpType&&!t.matchUpType&&(e||a)&&d.drawId){let r=t.drawDefinition||e?.drawDefinitions?.find((t=>t.drawId===d.drawId));!r&&a&&({drawDefinition:r,event:e}=Gm({drawId:d.drawId,tournamentRecord:a}));const i=d.structureId&&r?.structures?.find((({structureId:t})=>t===d.structureId));n=t.matchUpType||i?.matchUpType||r?.matchUpType||e?.eventType!==po&&e?.eventType}const{milliseconds:p,time:l}=function({matchUp:t}){if(!t)return{error:fe};if(!t.timeItems)return{error:Ln};const e=t.timeItems.filter((t=>[ql,$l,Wl,Hl].includes(t?.itemType))).sort(((t,e)=>Em(t.itemValue).getTime()-Em(e.itemValue).getTime())),n=e.reduce(((t,e)=>{let n;const r=e?.itemType?.split("."),i=`SCHEDULE.TIME.${e?.itemType?.startsWith("SCHEDULE.TIME")&&r[2]}`;switch(i){case ql:n=0;break;case Hl:if(t.lastValue&&[ql,Wl].includes(t.lastType)){const r=Em(e.itemValue).getTime()-Em(t.lastValue).getTime();n=t.milliseconds+r}else n=t.milliseconds;break;case $l:if([ql,"SCHECULE.TIME.RESUME"].includes(t.lastType)){const r=Em(e.itemValue).getTime()-Em(t.lastValue).getTime();n=t.milliseconds+r}else n=t.milliseconds;break;default:n=t.milliseconds}return{milliseconds:n,lastType:i,lastValue:e.itemValue}}),{milliseconds:0,lastType:void 0,lastValue:void 0});if([ql,Wl].includes(n.lastType)){const t=(new Date).getTime()-Em(n.lastValue).getTime();n.milliseconds+=t}return{milliseconds:n.milliseconds,time:Cm(n.milliseconds),relevantTimeItems:e}}({matchUp:d}),{startTime:m}=function({matchUp:t}){const e=t=>t.createdAt?new Date(t.createdAt).getTime():0,n=(t?.timeItems||[]).reduce(((t,n)=>{const r=n.itemType===ql&&n;return r&&(!t||e(r)<e(t))?r:t}),void 0),r=n?.itemValue;return{startTime:r}}({matchUp:d}),{endTime:f}=function({matchUp:t}){const e=t=>t.createdAt?new Date(t.createdAt).getTime():0,n=(t?.timeItems||[]).reduce(((t,n)=>{const r=n.itemType===Hl&&n;return r&&(!t||e(r)>e(t))?r:t}),void 0),r=n?.itemValue;return{endTime:r}}({matchUp:d});let h;const{eventIds:g,drawIds:I}=r??{};if(g&&!g.includes(d.eventId)||I&&!I.includes(d.drawId))h=Xr({milliseconds:p,startTime:m,endTime:f,time:l});else{const t=t=>t.createdAt?new Date(t.createdAt).getTime():0,e=new Map,r=d.timeItems?.toSorted(((e,n)=>t(e)-t(n)))??[];for(const t of r)e.set(t.itemType,t.itemValue);const o=e.get(Vl),u=e.get(xl),g=e.get(Gl),I=e.get(zl);let U=e.get(Bl);const y=e.get(jl),S=e.get(Ll),v=e.get(kl),w=e.get(_l);let P,D,T,b,R;const M=d.matchUpType??n;if(s&&g&&i&&M){const t={matchUpFormat:d.matchUpFormat??c,...s};({averageMinutes:D=0,recoveryMinutes:T=0,typeChangeRecoveryMinutes:b=0}=bm({timingDetails:t,eventType:M})),(D||T)&&(P=f?Zi(qi(f),T):Zi(g,D+T)),b&&(R=f?Zi(qi(f),b):Zi(g,D+b))}!U&&g&&(U=$i(g));const N=Ni({scheduledDate:U,scheduledTime:g}),A={},E=(a&&v&&Vm({tournamentRecord:a,venueId:v}))?.venueData||{};v&&(A[v]=E);const{venueName:C,venueAbbreviation:O,courtsInfo:F}=E,k=w&&F?.find((t=>t.courtId===w)),x=k?.courtName;for(const t of u||[]){if(!a)break;t.venueId&&!A[t.venueid]&&(A[t.venueId]=Vm({venueId:t.venueId,tournamentRecord:a})?.venueData);const e=A[t.venueId];t.venueName=e?.venueName;const n=e?.courtsInfo?.find((e=>e.courtId===t.courtId));t.courtName=n?.courtName}h=Xr({typeChangeTimeAfterRecovery:R,timeAfterRecovery:P,scheduledDate:U,scheduledTime:g,isoDateString:N,homeParticipantId:o,venueAbbreviation:O,allocatedCourts:u,timeModifiers:I,venueName:C,venueId:v,courtOrder:S,courtName:x,courtId:w,official:y,typeChangeRecoveryMinutes:b,recoveryMinutes:T,averageMinutes:D,milliseconds:p,startTime:m,endTime:f,time:l})}const{scheduledDate:U}=Am({matchUp:d}),{scheduledTime:y}=Nm({matchUp:d});if(o&&u?.displaySettings?.draws){const t=u.displaySettings.draws,e=(t?.[d.drawId]??t?.default)?.scheduleDetails;if(e){const t=(e.find((t=>U&&t.dates?.includes(U)))??e.find((t=>!t.dates?.length)))?.attributes;if(t){h=Ic({source:h,template:Object.assign({},...Object.keys(h).map((t=>({[t]:!0}))),t)})}}}return{schedule:h,endDate:d.matchUpStatus&&Xu.includes(d.matchUpStatus)&&($i(f)||$i(U)||$i(y))||void 0}}function $m({collectionPosition:t,collectionId:e,lineUp:n}){let r=[];const i=[];if(n){const a=t=>void 0===t?-1:t,o=n.map((n=>{const{collectionAssignments:r,participantId:i}=n,a=r?.find((n=>n.collectionPosition===t&&n.collectionId===e));return a&&{participantId:i,...a}})).filter(Boolean).sort(((t,e)=>a(t.substitutionOrder)-a(e.substitutionOrder)));for(const t of o){const{participantId:e,previousParticipantId:n,substitutionOrder:a}=t;r.includes(e)||(n&&i.push({previousParticipantId:n,substitutionOrder:a,participantId:e}),r=r.filter((t=>t!==n)),r.push(e))}}return{assignedParticipantIds:r,substitutions:i}}function Wm({tournamentParticipants:t,tournamentRecord:e,participantIds:n}){const r="getPairedParticipant";if(!t&&!e)return{error:nt};if(!Array.isArray(n)||n.length>2)return{error:ze};if(!n.length)return ti({result:{error:an},stack:r});const i=(t=t??e?.participants??[]).filter((t=>t.participantType===sp&&O(n,t.individualParticipantIds).length===n.length&&t.individualParticipantIds.length===n.length)),a=i[0];if(!a)return ti({result:{error:en},stack:r});const o=la(i.slice(1),!1,!0);return{participant:la(a),duplicatedPairParticipants:o,...z}}function Hm({drawDefinition:t,participantId:e}){if("object"!=typeof t)return{error:ot};if("string"!=typeof e)return{error:Xe};const{extension:n}=zc({element:t,name:au});return{lineUp:(n?.value||{})[e]}}function zm(t){const e=cc(t,[{[Gs]:!0}]);if(e.error)return e;const r=t?.matchUp;let a=r?.matchUpType;if(!a&&r?.sides?.length){const t=r.sides.find((({participant:t})=>t)),e=t?.participant,o=e?.participantType;a=o===ap&&n||o===sp&&i||o===cp&&cp||void 0}return{matchUpType:a}}function Ym({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:n,displaySideNumber:r,seedAssignments:i,drawPosition:a,isFeedRound:o,sideNumber:s}){const c=n.find((t=>t.drawPosition&&t.drawPosition===a)),u=a&&t,d=s&&e,p=u?u[a]?.participantId:c?.participantId,l=c?function({displaySideNumber:t,seedAssignments:e,participantId:n,assignment:r,sideNumber:i}){const a={drawPosition:r.drawPosition,displaySideNumber:t,sideNumber:i};if(n){const t=function({seedAssignments:t,participantId:e}){return t?.find((t=>!t.seedProxy&&t.participantId===e))}({seedAssignments:e,participantId:n});Object.assign(a,t,{participantId:n}),t?.seedNumber&&""===t?.seedValue&&(a.seedValue="~")}else r.bye&&Object.assign(a,{bye:!0});r.qualifier&&Object.assign(a,{qualifier:!0});return a}({displaySideNumber:r,seedAssignments:i,participantId:p,assignment:c,sideNumber:s}):{...d?.[s]};if(o&&(1===s?Object.assign(l,{participantFed:!0}):Object.assign(l,{participantAdvanced:!0})),a&&u){const t=u[a]?.teamParticipant,e=u[a]?.participant,n=u[a]?.substitutions;e&&(l.participant=e),n&&(l.substitutions=n),t&&(l.teamParticipant=t)}return l}function Km({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:a,drawPositionsRanges:o,hydrateParticipants:s,afterRecoveryTimes:c,initialRoundOfPlay:p,additionalContext:l,roundNamingProfile:m,tournamentRecord:f,tieDrawPositions:h,appliedPolicies:g,isCollectionBye:I,seedAssignments:U,usePublishState:S,participantMap:v,contextContent:P,scheduleTiming:D,contextProfile:T,drawDefinition:b,publishStatus:R,scoringActive:M,matchUpTieId:N,isRoundRobin:A,roundProfile:E,sideLineUps:C,structure:O,context:F,matchUp:x,event:B}){l=l??{};const V=fl({drawDefinition:b,structure:O,matchUp:x,event:B})?.tieFormat,{roundOffset:j,structureId:G,structureName:q,stage:$,stageSequence:W}=O,{drawId:H,drawName:z,drawType:Y}=b??{},K=V?.collectionDefinitions,Q=x.collectionId&&K?.find((t=>t.collectionId===x.collectionId)),J=x.collectionId?Q?.matchUpFormat:x.matchUpFormat??O?.matchUpFormat??b?.matchUpFormat??B?.matchUpFormat,Z=x.matchUpType||Q?.matchUpType||O?.matchUpType||b?.matchUpType||!um(po)(B?.eventType)&&B?.eventType,X=I?Fu:x.matchUpStatus,{schedule:tt,endDate:et}=qm({scheduleVisibilityFilters:t,afterRecoveryTimes:c,tournamentRecord:f,usePublishState:S,scheduleTiming:D,drawDefinition:b,matchUpFormat:J,publishStatus:R,matchUpType:Z,matchUp:x,event:B}),nt=h??x.drawPositions??[],{collectionPosition:rt,collectionId:it,roundPosition:at}=x,ot=x.roundNumber??l.roundNumber,st=it?function({tournamentParticipants:t,positionAssignments:e,collectionPosition:n,drawPositions:r=[],participantMap:a,drawDefinition:o,collectionId:s,sideLineUps:c,matchUpType:u}){if(!s||!n)return{};const d=({attribute:e,lineUp:r,teamParticipant:o})=>{const{assignedParticipantIds:c,substitutions:d}=$m({collectionPosition:n,collectionId:s,lineUp:r});if(u!==i){const t=c?.[0];return t&&{[e]:{participantId:t,teamParticipant:o,substitutions:d}}}if(c?.length<=2){const n=a?.[c[0]]?.pairIdMap?.[c[1]],r=n&&a[n]?.participant||Wm({participantIds:c,tournamentParticipants:t}).participant,i=r?.participantId;return{[e]:{participantId:i,teamParticipant:o,substitutions:d}}}if(c?.length>2)return{[e]:{teamParticipant:o,substitutions:d}}};if(!r?.length){const t=c?.map((t=>{const{teamParticipant:e,sideNumber:n}=t,r=t.lineUp||Hm({participantId:e.teamParticipantId,drawDefinition:o})?.lineUp;return d({attribute:n,lineUp:r,teamParticipant:e})})).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...t)}}const p=r?.map((n=>{const r=e.find((t=>t.drawPosition===n))?.participantId,i=c?.find((t=>t?.drawPosition===n)),s=i?.teamParticipant||r&&a?.[r]?.participant||t?.find((({participantId:t})=>t===r)),u=i?.lineUp||Hm({participantId:r,drawDefinition:o})?.lineUp;return d({attribute:n,lineUp:u,teamParticipant:s})})).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}({tournamentParticipants:r,positionAssignments:a,collectionPosition:rt,participantMap:v,drawDefinition:b,drawPositions:nt,collectionId:it,sideLineUps:C,matchUpType:Z}):void 0,ct=m?.[ot]?.roundName||l.roundName,ut=m?.[ot]?.abbreviatedRoundName||l.abbreviatedRoundName,dt=E?.[ot]?.feedRound,pt=E?.[ot]?.preFeedRound,lt=E?.[ot]?.roundFactor,mt=o?.[ot],ft=at?mt?.[at]:void 0,ht=e?.[ot],gt=Q?.category?{...F?.category||{},...Q.category}:F?.category??B?.category,It=x.processCodes?.length&&x.processCodes||Q?.processCodes?.length&&Q?.processCodes||O?.processCodes?.length&&O?.processCodes||b?.processCodes?.length&&b?.processCodes||B?.processCodes?.length&&B?.processCodes||f?.processCodes,Ut=T?.withCompetitiveness&&El({...P,matchUp:x}),yt=x.finishingPositionRange??l.finishingPositionRange,St=$!==ho&&y(p)&&p+(ot||0),vt=t=>Xr(t,void 0,!0),wt={...vt(F),...vt({matchUpFormat:Z===po?void 0:J,tieFormat:Z!==po?void 0:V,gender:Q?.gender??B?.gender,endDate:x.endDate??et,discipline:B?.discipline,category:gt,finishingPositionRange:yt,abbreviatedRoundName:ut,drawPositionsRange:ft,competitiveProfile:Ut,structureName:q,stageSequence:W,drawPositions:nt,matchUpStatus:X,processCodes:It,isRoundRobin:A,matchUpTieId:N,preFeedRound:pt,matchUpType:Z,roundFactor:lt,roundOffset:j,structureId:G,roundNumber:ot,roundOfPlay:St,feedRound:dt,roundName:ct,drawName:z,drawType:Y,schedule:tt,drawId:H,stage:$}),...la(vt(x),!0,!0)};if(J&&x.score?.scoreStringSide1){const t=Ii(J),{bestOf:e,finalSetFormat:n,setFormat:r}=t??{};(n?.tiebreakSet||r?.tiebreakSet||r?.timed)&&(wt.score.sets=wt.score.sets.sort(((t,e)=>t.setNumber-e.setNumber)).map(((t,i)=>(i+1===e?(n?.tiebreakSet||n?.timed)&&(t.tiebreakSet=!0):(r?.tiebreakSet||r?.timed)&&(t.tiebreakSet=!0),t))))}if(Array.isArray(nt)){const{orderedDrawPositions:t,displayOrder:e}=function({drawPositions:t,roundProfile:e,roundNumber:n}){const r=[void 0,void 0];if(L(t))return{orderedDrawPositions:r,displayOrder:r};const i=e?.[n],a=i?.pairedDrawPositions,o=a?.find((e=>k(e||[],t.filter(Boolean))))??r,s=i?.feedRound;if(_(t)){const e=[...t].sort(u);return{orderedDrawPositions:2===e.length?e:o,displayOrder:s?e:o}}if(s){const e=[t.find((t=>!isNaN(d(t)))),void 0];return{orderedDrawPositions:e,displayOrder:e}}return{orderedDrawPositions:o,displayOrder:o}}({drawPositions:nt,roundProfile:E,roundNumber:ot}),n=E?.[ot]?.feedRound,r=e[0]!==t[0],i=t.concat(void 0,void 0).slice(0,2).map(((t,e)=>{const i=e+1,o=Ym({...st,positionAssignments:a,displaySideNumber:r?3-i:i,seedAssignments:U,drawPosition:t,isFeedRound:n,sideNumber:i}),s=x.sides?.find((t=>t.sideNumber===i)),c=at?2*(at-1)+e+1:void 0;return vt({sourceDrawPositionRange:c?ht?.[c]:void 0,...s,...o})}));Object.assign(wt,la({sides:i},!0,!0))}if(r&&wt.sides){const t=g?.[Tc],e=e=>{const n=v?.[e]?.participant;return n&&Ic({template:t?.participant,source:n})};if(wt.sides.filter(Boolean).forEach((t=>{if(t.participantId){const n=la(e(t.participantId)||(r?Fc({policyDefinitions:g,participantId:t.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(n){let e,r;if(b?.entries){const i=b.entries.find((e=>e.participantId===t.participantId)),a=B?.entries?.find((e=>e.participantId===t.participantId));e=i?.entryStatus||a?.entryStatus,n.entryStatus=e,i?.entryStage&&(r=i.entryStage,n.entryStage=r)}!1!==s?Object.assign(t,{participant:n}):Object.assign(t,{participant:{entryStage:r,entryStatus:e}})}}if(t?.participant?.individualParticipantIds?.length&&!t.participant.individualParticipants?.length){const n=t.participant.individualParticipantIds.map((t=>e(t)||(r?Fc({policyDefinitions:g,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:t}):void 0)));!1!==s&&Object.assign(t.participant,{individualParticipants:n})}})),!wt.matchUpType){const{matchUpType:t}=zm({matchUp:wt});t&&Object.assign(wt,{matchUpType:t})}if(T?.inferGender&&(!wt.gender||wt.gender===ri)&&2===wt.sides?.length&&wt.matchUpType!==po){const t=wt.sides.map((t=>{if(um(n)(wt.matchUpType))return t.participant?.person?.sex;if(2===t.participant?.individualParticipants?.length){const e=w(t.participant.individualParticipants.map((t=>t.person?.sex))).filter(Boolean);if(1===e.length)return e[0]}}));if(2===t.filter(Boolean).length&&1===w(t).length){const e=t[0];wt.inferredGender=e}}}if(wt.tieMatchUps){const n=wt.matchUpStatus===Fu,i=wt.sides?.map((({participant:t,drawPosition:e,sideNumber:n,lineUp:r})=>{const i=t?.participantType===po&&t;return{teamParticipant:i&&Xr({participantRoleResponsibilities:i.participantRoleResponsibilities,participantOtherName:i.participanOthertName,participantName:i.participantName,participantId:i.participantId,teamId:i.teamId}),drawPosition:e,sideNumber:n,lineUp:r}}));wt.tieMatchUps=wt.tieMatchUps.map((s=>{const c=wt.matchUpId,u=wt.finishingPositionRange;return Km({tieDrawPositions:nt,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:i,drawPositionsRanges:o,initialRoundOfPlay:p,roundNamingProfile:m,additionalContext:{finishingPositionRange:u,abbreviatedRoundName:ut,roundNumber:ot,roundName:ct},appliedPolicies:g,isCollectionBye:n,usePublishState:S,publishStatus:R,matchUpTieId:c,isRoundRobin:A,roundProfile:E,matchUp:s,event:B,tournamentParticipants:r,positionAssignments:a,tournamentRecord:f,seedAssignments:U,participantMap:v,contextContent:P,scheduleTiming:D,contextProfile:T,drawDefinition:b,scoringActive:M,structure:O,context:F})}))}const Pt=wt.sides&&2===wt.sides.filter((t=>t?.participantId)).length,Dt=!wt.winningSide,Tt=M&&Pt&&Dt;if(Object.assign(wt,{readyToScore:Tt,hasContext:!0}),Pt){const{allParticipantsCheckedIn:t,checkedInParticipantIds:e}=cm({matchUp:wt});Object.assign(wt,{allParticipantsCheckedIn:t,checkedInParticipantIds:e})}return Array.isArray(T?.exclude)&&T?.exclude.forEach((t=>delete wt[t])),wt}function Qm(t){if(!Array.isArray(t.matchUps))return[];const{matchUps:e,excludeMatchUpStatuses:n,hasParticipantsCount:r,isCollectionMatchUp:i,matchUpStatuses:o,hasWinningSide:s,matchUpFormats:c,roundPositions:u,matchUpFormat:d,collectionIds:p,isMatchUpTie:l,roundNumbers:m,matchUpIds:f,roundNames:h,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:U,scheduledDates:y,scheduledDate:S,participantIds:v,processContext:w,tournamentIds:P,matchUpTypes:D,structureIds:T,readyToScore:b,courtIds:R,eventIds:M,venueIds:N,drawIds:A,stages:E}=t,C=Array.isArray(v)?v.filter(Boolean):[],O=Array.isArray(o)?o.filter(Boolean):[],F=Array.isArray(n)?n.filter(Boolean):[],k=Array.isArray(E)?E.filter(Boolean):[],x=Array.isArray(U)?U.filter(Boolean):[],_=Array.isArray(p)?p.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],B=Array.isArray(m)?m.filter(Boolean):[],V=Array.isArray(u)?u.filter(Boolean):[],j=Array.isArray(f)&&I?f.filter(Boolean):[],G=Array.isArray(D)&&g?D.filter(Boolean):[],q=Array.isArray(R)?R.filter(Boolean):[],$=Array.isArray(N)?N.filter(Boolean):[],W=Array.isArray(c)&&c.filter(Boolean)||"string"==typeof d&&[d]||[],z=Array.isArray(y)&&y.filter(Boolean)||"string"==typeof S&&S.length&&[S]||[],Y=Array.isArray(P)?P.filter(Boolean):[],K=Array.isArray(M)?M.filter(Boolean):[],Q=Array.isArray(A)?A.filter(Boolean):[],J=Array.isArray(T)?T.filter(Boolean):[];return e.filter((t=>{if(b&&!um(a)(t)&&!t.readyToScore)return!1;if(t.winningSide&&s&&![1,2].includes(t.winningSide))return!1;if(void 0!==l){if(l&&!t.tieMatchUps)return!1;if(!l&&t.tieMatchUps)return!1}if(void 0!==i){if(i&&!t.collectionId)return!1;if(!i&&t.collectionId)return!1}if(k.length&&!k.includes(t.stage))return!1;if(x.length&&!x.includes(t.stageSequence))return!1;if(_.length&&(!t.collectionId||!_.includes(t.collectionId)))return!1;if(L.length&&(!t.roundName||!L.includes(t.roundName)))return!1;if(B.length&&(!t.roundNumber||!B.includes(t.roundNumber)))return!1;if(V.length&&(!t.roundPosition||!V.includes(t.roundPosition)))return!1;if(O.length&&(!t.matchUpStatus||!O.includes(t.matchUpStatus)))return!1;if(F.length&&t.matchUpStatus&&F.includes(t.matchUpStatus))return!1;if(j.length&&!j.includes(t.matchUpId))return!1;if(G.length&&(!t.matchUpType||!H(G,t.matchUpType)))return!1;if(W.length&&(!t.matchUpFormat||!W.includes(t.matchUpFormat)))return!1;if(z?.length){const{scheduledTime:e}=Nm({matchUp:t}),{scheduledDate:n}=Am({matchUp:t}),r=$i(e)||n;if(!z.find((t=>ea(t,r))))return!1}if(q.length){const{courtId:e}=function({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=Mm({timeItems:n?.timeItems||[],itemType:_l});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{courtId:r}:e}({matchUp:t}),{allocatedCourts:n}=function({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=Mm({timeItems:n?.timeItems||[],itemType:xl});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{allocatedCourts:la(r,!1,!0)}:e}({matchUp:t}),r=n?.map((({courtId:t})=>t));if(!q.filter(Boolean).includes(e)||r?.includes(e))return!1}if($.length){const{venueId:e}=function({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=Mm({timeItems:n?.timeItems||[],itemType:kl});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{venueId:r}:e}({matchUp:t});if(!$.filter(Boolean).includes(e))return!1}if(w){if(Y.length&&!Y.includes(t.tournamentId))return!1;if(K.length&&!K.includes(t.eventId))return!1;if(Q.length&&!Q.includes(t.drawId))return!1;if(J.length&&!J.includes(t.structureId))return!1;const e=t.sides?.map((({participantId:t})=>t)).filter(Boolean)??[];if(r&&e.length<r)return!1;if(C.length){if(!C.some((t=>e.includes(t))))return!1}}return!0}))}function Jm(t){const{provisionalPositioning:e,tournamentRecord:n,contextFilters:r,matchUpFilters:i,contextProfile:a,drawDefinition:o,context:s={},structure:c,inContext:d,event:p}=t;let{seedAssignments:l,contextContent:m,exitProfiles:f,matchUpsMap:h}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:Vt,roundMatchUps:I,matchUps:[]};const U=Array.isArray(i?.eventIds)?i?.eventIds.filter(Boolean):[],y=Array.isArray(i?.structureIds)?i?.structureIds.filter(Boolean):[],S=Array.isArray(i?.drawIds)?i?.drawIds.filter(Boolean):[],v=!s?.eventId||!U?.length&&!r?.eventIds?.filter(Boolean).length||U?.includes(s.eventId)||r?.eventIds?.includes(s.eventId),P=!y?.length||y.includes(c.structureId),D=!o||!S?.length||S.includes(o.drawId);if(!v||!P||!D)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};a&&!m&&(m=Lp({tournamentRecord:n,contextProfile:a,drawDefinition:o}));const{appliedPolicies:T}=Np({drawDefinition:o}),b={...t.tournamentAppliedPolicies,...T,...t.policyDefinitions},R=b?.scoring?.structures,M=c.stage&&R?.stage?.[c.stage],N=c.stageSequence&&M?.stageSequence?.[c.stageSequence],A=b?.scoring?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned||N?.requireAllPositionsAssigned;h||(h=hl({drawDefinition:o,structure:c}));const{positionAssignments:C,allPositionsAssigned:O}=ud({structure:c}),F=!A||O,{seedAssignments:k}=pl({provisionalPositioning:e,drawDefinition:o,structure:c});l=l??k;const{structureId:_}=c;f=f||o&&wl({drawDefinition:o}).exitProfiles;const L=f?.[_],B=L?.length&&(L[0].split("-").map((t=>parseInt(t))).reduce(((t,e)=>t+e))||0),V=!!c.structures;let j=gl({matchUpsMap:h,structureId:_,inContext:d});const G=b?.[Dc],q=function({roundNamingPolicy:t,drawDefinition:e,structure:n,matchUps:r}){const{roundProfile:i,roundMatchUps:a}=Sl({matchUps:r}),{structureAbbreviation:o,stage:s}=n,c=Dl({structure:n}),u=Pl({structure:n}),d=n.structures,p={},l=Tl[Dc],m=n.stage===ho,f=m?Math.max(...(e?.structures??[]).filter((t=>t.stage===ho)).map((({stageSequence:t})=>t??1)),0):0,h=(n.stageSequence??1)<f?n.stageSequence??1:"",g=h&&(t?.affixes?.preQualifying||l.affixes.preQualifying)||"",I=t?.roundNamingMap||l.roundNamingMap||{},U=t?.abbreviatedRoundNamingMap||l.abbreviatedRoundNamingMap||{},y=t?.affixes?.preFeedRound||l.affixes.preFeedRound,S=t?.affixes?.roundNumber||l.affixes.roundNumber,v=(t?.namingConventions||l.namingConventions).round,w=s&&s!==fo?s[0]:"",P=t?.stageConstants||l.stageConstants,D=`${g}${s&&P?.[s]||w}${h}`,T=i?Object.keys(i):[],b=m&&P?.[ho]?`${P?.[ho]}-`:"";if(d||c||u)Object.assign(p,...T.map((t=>{const e=`${b}${v} ${t}`,n=`${S}${t}`;return{[t]:{roundName:e,abbreviatedRoundName:n}}})));else{const e=m&&(t?.qualifyingFinishMap||l?.qualifyingFinishMap||{});Object.assign(p,...T.map((t=>{if(!i?.[t])return;const{matchUpsCount:n,preFeedRound:r}=i[t],a=2*n,s=e?.[i?.[t].finishingRound]||e&&`${S}${a}`||I[n]||`${S}${a}`,c=r?`-${y}`:"",u=[D,o,`${s}${c}`].filter(Boolean).join("-"),d=U[n]||`${S}${a}`,p=[D,o,`${d}${c}`].filter(Boolean).join("-");return{[t]:{abbreviatedRoundName:p,roundName:u}}})))}return{roundNamingProfile:p,roundProfile:i,roundMatchUps:a}}({roundNamingPolicy:G,drawDefinition:o,structure:c,matchUps:j}),{roundNamingProfile:$,roundProfile:W}=q;if(I=q?.roundMatchUps??[],i&&(j=Qm({matchUps:j,...i,filterMatchUpTypes:!1,filterMatchUpIds:!1})),d){const{sourceDrawPositionRanges:e}=function({drawDefinition:t,structureId:e,matchUpsMap:n}){if(!t)return{error:ot};if(!e)return{error:_t};const{structure:r}=ad({drawDefinition:t,structureId:e});if(r?.stage!==go)return{error:Jt,info:"Structure is not CONSOLATION stage"};const{links:i}=t,a=i?.filter((t=>t.target.structureId===e))||[],o=a?.reduce(((t,e)=>{const{structureId:n}=e.source;return t.includes(n)?t:t.concat(n)}),[])||[],s=Object.assign({},...o.map((t=>{const e=Sl({matchUps:gl({structureId:t,matchUpsMap:n})}).roundProfile;return{[t]:e}}))),c=gl({matchUpsMap:n,structureId:e}),{roundProfile:u}=Sl({matchUps:c}),d={};return a?.forEach((t=>{const{structureId:e,roundNumber:n}=t.source,{feedProfile:r,groupedOrder:i,positionInterleave:a,roundNumber:o}=t.target,c=s[e],p=c[1]?.drawPositions,l=c[n],m=l?.matchUpsCount;if(!m)return;const f=m?p.length/m:0,h=p.length/f;let g=p.slice();const I=Il({roundPositionsCount:h,groupedOrder:i}),U=I?.length||1;if(U<=h){const t=x(g,p.length/U);r===Co&&t.forEach((t=>t.reverse())),g=I?.length&&I?.map((e=>t[e-1])).flat()||t.flat()}let y=x(g,f);if(a){const t=E(0,a.interleave).map((()=>{})),e=E(0,a.offset).map((()=>{}));y=y.map((e=>[e,...t])),y.unshift(e),y=y.flat(1);const n=y.length-a.offset;y=y.slice(0,n)}d[o]||(d[o]={});const S=u?.[o],v=S?.feedRound?2:1;y.forEach(((t,e)=>{const n=1+e*v;d[o][n]||(d[o][n]=vl(t))}))})),{sourceDrawPositionRanges:d}}({drawDefinition:o,matchUpsMap:h,structureId:_}),i=o?function({drawDefinition:t,roundProfile:e,structureId:n,matchUpsMap:r}){if(!t)return{error:ot};if(!n)return{error:_t};if(!e){const t=gl({matchUpsMap:r,structureId:n});if(({roundProfile:e}=Sl({matchUps:t})),!e)return{error:be}}const i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,a=Object.keys(e),o=Object.assign({},...(a||[]).map((t=>{const n=e?.[t]?.matchUpsCount,r=e?.[1]?.drawPositions??[],o=x(r,r.length/n),s=o.map(vl),c=o.map((t=>t.map((t=>t-i)))).map(vl),d=a.map((r=>{if(r>t)return;const i=e?.[r]?.drawPositions??[];return x(i,i.length/n)})).filter(Boolean),p=E(0,n).map((t=>d.map((e=>e[t])).flat().filter(Boolean).sort(u))).map((t=>w(t))),l=p.map((t=>{return(e=t,e.reduce(((t,e)=>{const n=t[t.length-1];return n&&n[n.length-1]===e-1||t.push([]),t[t.length-1].push(e),t}),[])).map(vl).join(", ");var e})),m=Object.assign({},...E(0,n).map((t=>{const e=t+1;return{[e]:{firstRoundDrawPositionsRange:s[t],firstRoundOffsetDrawPositionsRange:c[t],possibleDrawPositions:p[t],drawPositionsRange:l[t]}}})));return{[t]:m}})));return{drawPositionsRanges:o}}({drawDefinition:o,roundProfile:W,matchUpsMap:h,structureId:_}).drawPositionsRanges:void 0;let f=t.tournamentParticipants,g=t.participantMap;f?.length||g||!n||({participants:f=[],participantMap:g}=Mp({participantsProfile:t.participantsProfile,useParticipantMap:t.useParticipantMap,policyDefinitions:t.policyDefinitions,tournamentRecord:n,contextProfile:a,inContext:d})),j=j.map((r=>Km({scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:e,tournamentParticipants:f,positionAssignments:C,drawPositionsRanges:i,initialRoundOfPlay:B,roundNamingProfile:$,tournamentRecord:n,appliedPolicies:b,seedAssignments:l,contextContent:m,participantMap:g,contextProfile:a,drawDefinition:o,scoringActive:F,isRoundRobin:V,roundProfile:W,structure:c,context:s,matchUp:r,event:p})));const I=j?.filter((t=>Array.isArray(t.tieMatchUps)));I.forEach((t=>{const e=t.tieMatchUps;j=j.concat(...e)})),r&&(j=Qm({processContext:!0,...r,matchUps:j}))}else{const t=j?.filter((t=>Array.isArray(t.tieMatchUps)));t.forEach((t=>{const e=t.tieMatchUps;j=j.concat(...e)}))}return i&&(j=Qm({matchUps:j,...i,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(i?.matchUpTypes||i?.matchUpIds)&&(j=Qm({matchUpTypes:i.matchUpTypes,matchUpIds:i.matchUpIds,matchUps:j})),(i?.matchUpTypes||i?.matchUpIds||d)&&(I=Sl({matchUps:j}).roundMatchUps??[]),fl({drawDefinition:o,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=function({matchUps:t}){const e=t.reduce(((t,e)=>!e.collectionPosition||t.includes(e.collectionPosition)?t:t.concat(e.collectionPosition)),[]).map((e=>({[e]:t.filter((t=>t.collectionPosition===e))})));return{collectionPositionMatchUps:Object.assign({},...e)}}({matchUps:j})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:V,roundProfile:W,matchUpsMap:h,matchUps:j}}function Zm({matchUp:t}){return!!t&&(Xu.includes(t?.matchUpStatus)||t?.winningSide)}function Xm({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:n,tournamentParticipants:r,hydrateParticipants:i,afterRecoveryTimes:a,policyDefinitions:s,tournamentRecord:c,usePublishState:u,matchUpFilters:d,contextFilters:p,contextContent:l,participantMap:m,scheduleTiming:f,publishStatus:h,contextProfile:g,drawDefinition:I,exitProfiles:U,matchUpsMap:y,structureId:S,inContext:v,structure:w,context:P,event:D}){!w&&S&&({structure:w}=ad({drawDefinition:I,structureId:S}));const T=Jm({tournamentAppliedPolicies:n,scheduleVisibilityFilters:e,tournamentParticipants:r,hydrateParticipants:i,afterRecoveryTimes:a,policyDefinitions:s,tournamentRecord:c,usePublishState:u,matchUpFilters:d,contextFilters:p,contextContent:l,participantMap:m,scheduleTiming:f,publishStatus:h,contextProfile:g,drawDefinition:I,exitProfiles:U,matchUpsMap:y,structure:w,inContext:v,context:P,event:D}),b=[],R=[],M=[],N=[],A=[];if(T.error)return T;const{matchUps:E}=T,{assignedPositions:C}=ud({structure:w}),O=C?.filter((t=>t.participantId)).map((t=>t.drawPosition));let F;return E.filter((t=>{const e=1===d?.matchUpTypes?.length&&d.matchUpTypes[0]===o;return!(t.matchUpType!==o&&e)})).forEach((e=>{if(e.matchUpStatus===Cu)return void b.push(e);e.matchUpType===o&&(F=!0);const n=Boolean(e.collectionId),r=n&&e.sides?.every((t=>t.participantId)),i=!n&&2===e.drawPositions?.filter(Boolean).length,a=!n&&e.drawPositions?.every((t=>O?.includes(t))),s=C?.filter((t=>t.bye)).map((t=>t.drawPosition)),c=!n&&e.drawPositions?.find((t=>s?.includes(t))),u=ed.includes(e.matchUpStatus)&&(r||i&&(!t||a));return c?A.push(e):Zm({matchUp:e})?R.push(e):u?M.push(e):N.push(e)})),{includesTeamMatchUps:F,abandonedMatchUps:b,completedMatchUps:R,upcomingMatchUps:M,pendingMatchUps:N,byeMatchUps:A,structure:w}}function tf({finishingPositions:t,linkCondition:e,linkType:n,source:r}){const i=r.find((r=>{const i=!r.source?.finishingPositions||!t||k(t,r.source?.finishingPositions);return e===r.linkCondition&&i&&r.linkType===n}));return[Fo,ko].includes(i?.linkType)&&!i?.source?.roundNumber?ti({result:{error:Jn},stack:"getTargetLink",context:i}):i}function ef({drawDefinition:t,structureId:e,roundNumber:n}){if(!t)return{error:ot};if(!e)return{error:_t};return{links:(t.links||[]).filter(Boolean).reduce(((t,r)=>(r.source?.structureId!==e||n&&r.source.roundNumber!==n||(t.source=t.source.concat(r)),r.target?.structureId!==e||n&&r.target.roundNumber!==n||(t.target=t.target.concat(r)),t)),{source:[],target:[]})}}function nf({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:n,drawDefinition:r,targetLink:i}){if(!i)return{error:kt};const{target:{structureId:a,feedProfile:o,groupedOrder:s,roundNumber:c,positionInterleave:u}}=i,{structure:d}=ad({drawDefinition:r,structureId:a}),{positionAssignments:p}=cd({structure:d}),l=e?.filter((t=>t.structureId===d?.structureId)),m=l.filter((t=>t.roundNumber===c&&!t.matchUpTieId)),f=m.length,h=E(1,f+1),g=f/t;let I=Math.ceil(g*n),U=1-n%2;if(u?.interleave&&.5!==g){const t=n+(u.offset+(n-1)*u.interleave);I=Math.ceil(t/2),U=1-t%2}let y=h,S=h[I-1];const v=Il({roundPositionsCount:h.length,groupedOrder:s}),w=v?.length||1;if(w<=h.length){const t=x(h,f/w);o===Co&&t.forEach((t=>t.reverse())),y=v?.length&&v?.map((e=>t[e-1])).flat()||y}o===Eo?S=y[I-1]:o===Co?((!v?.length||w>h.length)&&(I=m.length+1-I),S=y[I-1]):o===Ao&&Pr()&&console.log(ir,{feedProfile:o});const P=S&&m.reduce(((t,e)=>e.roundPosition===S?e:t),void 0);let D;P?.feedRound?(U=0,D=Math.min(...(P.drawPositions||[]).filter(Boolean))):D=2===P?.drawPositions?.length&&P?.drawPositions[U];const T=p?.find((({drawPosition:t})=>t===D));if(T){const{extension:t}=zc({element:T,name:Xc});if(t?.value)return{disabledDrawPosition:D}}return{matchUp:P,targetDrawPosition:D,matchUpDrawPositionIndex:U}}function rf({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:n,drawDefinition:r,matchUpId:i}){let a=n;t.length&&!a&&(a=t.find((t=>t.matchUpId===i)));const{structure:o}=ad({structureId:a?.structureId,drawDefinition:r}),s=o?.finishingPosition;return s===ds?function({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:r,matchUp:i}){const{winnerMatchUpId:a,loserMatchUpId:o}=i,{links:s}=function({drawDefinition:t,roundNumber:e,structureId:n}){if(!t)return{error:ot};if(!n)return{error:_t};const{links:r}=ef({drawDefinition:t,structureId:n});return{links:{source:r.source.reduce(((t,n)=>n.source.roundNumber&&n.source.roundNumber!==e?t:t.concat(n)),[]),target:r.target.reduce(((t,n)=>n.target.roundNumber&&n.target.roundNumber!==e?t:t.concat(n)),[])}}}({roundNumber:i.roundNumber,structureId:r.structureId,drawDefinition:n}),c=s?.source,u=tf({source:c,linkType:Fo}),d=tf({linkCondition:xo,linkType:ko,source:c});let p=tf({source:c,linkType:ko});const l=d&&p;p||(p=d);const m=u?.target?.feedProfile,f=p?.target?.feedProfile,h=d?.target?.feedProfile;let g,I,U,y,S,v,w,P,D,T;if(e&&(a||o)&&(w=a&&m!==No&&t.find((({matchUpId:t})=>t===a)),y=o&&f!==No&&t.find((({matchUpId:t})=>t===o)),w||y))return{matchUp:i,targetLinks:{loserTargetLink:p,winnerTargetLink:u},targetMatchUps:{loserMatchUp:y,winnerMatchUp:w}};const{roundPosition:b}=i;T=T||t.filter((t=>t.structureId===r.structureId));const R=T.reduce(((t,e)=>e.roundNumber!==i.roundNumber||e.matchUpTieId?t:t+1),0);p&&!y&&f!==No&&({matchUpDrawPositionIndex:v,targetDrawPosition:S,matchUp:y}=nf({targetLink:p,sourceRoundMatchUpCount:R,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));l&&h!==No&&({matchUpDrawPositionIndex:U,targetDrawPosition:I,matchUp:g}=nf({targetLink:d,sourceRoundMatchUpCount:R,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));u&&!w&&m!==No&&({matchUpDrawPositionIndex:D,targetDrawPosition:P,matchUp:w}=nf({targetLink:u,sourceRoundMatchUpCount:R,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));w||(T=T||t.filter((t=>t.structureId===r.structureId)),({matchUp:w}=function({structureMatchUps:t,matchUp:e}){const{roundNumber:n,roundPosition:r}=e,i=t.filter((t=>t.roundNumber===n&&!t.matchUpTieId)),a=t.filter((t=>t.roundNumber===n+1&&!t.matchUpTieId));if(a.length){let t;return a.length===i.length?t=a.find((t=>t.roundPosition===r)):a.length===i.length/2&&(t=a.find((t=>t.roundPosition===Math.ceil(r/2)))),{matchUp:t}}return{message:"no progression found"}}({structureMatchUps:T,matchUp:i})));return Xr({matchUp:i,targetLinks:{loserTargetLink:p,winnerTargetLink:u,byeTargetLink:d},targetMatchUps:{winnerMatchUpDrawPositionIndex:D,loserMatchUpDrawPositionIndex:v,byeMatchUpDrawPositionIndex:U,winnerTargetDrawPosition:P,loserTargetDrawPosition:S,byeTargetDrawPosition:I,winnerMatchUp:w,loserMatchUp:y,byeMatchUp:g},targetMatchUpIds:!(!a&&!o)})}({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:o,matchUp:a}):function({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}({matchUp:a})}function af({drawDefinition:t,inContextDrawMatchUps:e}){const n={};return e.forEach((r=>{const{matchUpId:i,structureId:a,drawPositions:o=[]}=r,{structure:s}=ad({drawDefinition:t,structureId:a});if(s?.finishingPosition===us){const{roundNumber:t}=r,e=t&&d(t)+1,n=s.matchUps??[],{roundMatchUps:i}=Sl({matchUps:n});if(e&&i?.[e]){const t=[...o].sort(u).map(((t,n)=>{const r=i[e].find((e=>e.drawPositions?.includes(t)));return{matchUpId:r?.matchUpId,roundNumber:e,schedule:r?.schedule,sideNumber:n+1,structureName:s.structureName}}));Object.assign(r,{sidesTo:t})}}else{const a=rf({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:t,matchUpId:i});let{winnerMatchUp:o}=a.targetMatchUps;const{loserMatchUp:s}=a.targetMatchUps;!r.winnerMatchUpId&&o&&(r.winnerMatchUpId=o.matchUpId),!r.loserMatchUpId&&s&&(r.loserMatchUpId=s.matchUpId);const u=sf({upcomingMatchUp:o});let d=sf({upcomingMatchUp:s});if(r.matchUpStatus!==Fu&&s?.matchUpStatus===Fu){const{matchUp:n}=of({matchUp:s,drawDefinition:t,inContextDrawMatchUps:e})||{};d=n&&sf({upcomingMatchUp:n})||d}const p=r.schedule?.timeAfterRecovery;if(p){if(u?.schedule?.scheduledTime){ji(u.schedule.scheduledTime)<ji(p)&&(n[u.matchUpId]=r.matchUpId,u.schedule.scheduleConflict=r.matchUpId)}if(d?.schedule?.scheduledTime){ji(d.schedule.scheduledTime)<ji(p)&&(n[d.matchUpId]=r.matchUpId,d.schedule.scheduleConflict=r.matchUpId)}}if(Object.assign(r,{winnerTo:u,loserTo:d}),r.drawPositions?.filter(Boolean).length){const t=a.targetLinks?.loserTargetLink,n=t?.linkCondition===xo,i=(c=r,c?.sides?.map((({participant:t,participantId:e,qualifier:n})=>t||e&&{participantId:e}||n&&{qualifier:n})).filter(Boolean)||[]);if(i.length){const t=Ru(o?.sides),r=Ru(s?.sides),c=i.find((({participantId:e})=>t.includes(e)))?[]:i,u=i.find((({participantId:t})=>r.includes(t)))?[]:i;s&&n&&u.length<2&&u.push({bye:!0,tbd:!0}),c?.length&&o&&(!a.targetMatchUpIds&&o&&(o=e.find((({matchUpId:t})=>t===o.matchUpId))),o.potentialParticipants||(o.potentialParticipants=[]),o.potentialParticipants.push(c)),u?.length&&s&&(a.targetMatchUpIds||(o=e.find((({matchUpId:t})=>t===s.matchUpId))),s.potentialParticipants||(s.potentialParticipants=[]),s.potentialParticipants.push(u))}}}var c})),Object.keys(n).length&&e.forEach((t=>{Object.keys(n).includes(t.matchUpId)&&(t.schedule.scheduleConflict=n[t.matchUpId])})),{scheduleConflictMatchUpIds:n}}function of({matchUp:t,drawDefinition:e,inContextDrawMatchUps:n}){const{matchUpId:r,matchUpStatus:i,structureId:a}=t||{};if(!t||!a||t?.matchUpStatus===Hu)return{matchUp:t};if(i===Fu){let i;if(t.winnerMatchUpId)i=n.find((({matchUpId:e})=>e===t.winnerMatchUpId));else{const t=rf({inContextDrawMatchUps:n,drawDefinition:e,matchUpId:r});({winnerMatchUp:i}=t?.targetMatchUps||{})}return of({matchUp:i,drawDefinition:e,inContextDrawMatchUps:n})}return{matchUp:void 0}}function sf(t){if(t?.upcomingMatchUp)return(({matchUpId:t,structureId:e,schedule:n,roundNumber:r,roundPosition:i,structureName:a})=>({matchUpId:t,structureId:e,schedule:n,roundNumber:r,roundPosition:i,structureName:a}))(t.upcomingMatchUp)}function cf(t){Object.assign(t,{requireParticipants:!1});const e=uf(t);if(e.error)return ti({result:e,stack:"getAllDrawMatchUps"});const{abandonedMatchUps:n,completedMatchUps:r,upcomingMatchUps:i,pendingMatchUps:a,byeMatchUps:o,matchUpsMap:s}=e;return{matchUps:(n??[]).concat(...r??[],...i??[],...a??[],...o??[]),matchUpsMap:s}}function uf(t){if(!t?.drawDefinition)return{error:ot};let{tournamentParticipants:e,contextContent:n,matchUpsMap:r}=t;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:a,requireParticipants:o,participantsProfile:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:d,usePublishState:p,contextFilters:l,matchUpFilters:m,scheduleTiming:f,participantMap:h,publishStatus:g,contextProfile:I,drawDefinition:U,nextMatchUps:y,inContext:S,context:v,event:w}=t;let P,D=[],T=[],b=[],R=[],M=[];I&&!n&&(n=Lp({policyDefinitions:u,tournamentRecord:d,contextProfile:I,event:w})),!e?.length&&d&&(e=d?.participants,(S||s?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:P}=pp({participants:e,participantsProfile:s})));const{structures:N}=od({drawDefinition:U});if(!N)return{error:Lt};r||(r=hl({drawDefinition:U}));const A=U&&wl({drawDefinition:U}).exitProfiles;N.forEach((s=>{const{byeMatchUps:P=[],pendingMatchUps:N=[],upcomingMatchUps:E=[],completedMatchUps:C=[],abandonedMatchUps:O=[]}=Xm({matchUpFilters:y?void 0:m,contextFilters:y?void 0:l,inContext:S||y||l,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:a,scheduleVisibilityFilters:i,tournamentParticipants:e,requireParticipants:o,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:d,usePublishState:p,contextContent:n,participantMap:h,scheduleTiming:f,publishStatus:g,contextProfile:I,drawDefinition:U,exitProfiles:A,matchUpsMap:r,structure:s,context:v,event:w});D=D.concat(...O),T=T.concat(...C),b=b.concat(...E),R=R.concat(...N),M=M.concat(...P)}));const E=t=>m||y||l?(m&&(t=Qm({matchUps:t,...m})),l&&(t=Qm({matchUps:t,...l,processContext:!0})),t):t,C={abandonedMatchUps:E(D),completedMatchUps:E(T),upcomingMatchUps:E(b),pendingMatchUps:E(R),byeMatchUps:E(M),matchUpsMap:r,...z,groupInfo:P};if(y){const t="object"==typeof y||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:e,completed:n,upcoming:r,pending:i,bye:a}=t;af({inContextDrawMatchUps:[].concat(...e&&D||[],...n&&T||[],...r&&b||[],...i&&R||[],...a&&M||[]),drawDefinition:U})}return C}function df(t){let{participants:e=[],contextContent:n,participantMap:r}=t;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:a,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,usePublishState:p,contextFilters:l,matchUpFilters:m,contextProfile:f,nextMatchUps:h,inContext:g,context:I,event:U}=t;if(!U)return{error:$t};const{eventId:y,eventName:S,endDate:v,eventType:w,category:P,gender:D,matchUpFormat:T}=U??{},b={...I,...Xr({indoorOutDoor:U.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:U.surfaceCategory??d?.surfaceCategory,endDate:U.endDate??d?.endDate,tournamentId:d?.tournamentId,matchUpFormat:T,eventName:S,eventType:w,category:P,eventId:y,gender:D})};let R;if(v&&(b.endDate=v),f&&!n&&(n=Lp({policyDefinitions:c,tournamentRecord:d,contextProfile:f,event:U})),!e?.length&&!r&&d){const t=Mp({participantsProfile:o,useParticipantMap:u,tournamentRecord:d,contextProfile:f,inContext:g});r=t.participantMap,e=t.participants??[],R=t.groupInfo}const M=U.drawDefinitions??[],N=Vp({tournamentRecord:d,event:U}).scheduleTiming;return{matchUps:M.flatMap((t=>{const{matchUps:u}=cf({tournamentParticipants:e,tournamentAppliedPolicies:a,scheduleVisibilityFilters:i,context:b,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,usePublishState:p,contextFilters:l,contextProfile:f,drawDefinition:t,contextContent:n,matchUpFilters:m,participantMap:r,scheduleTiming:N,nextMatchUps:h,inContext:g,event:U});return u??[]})),groupInfo:R}}function pf(t){const e=cc(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:nt};let{participantMap:n,participants:r}=t;const{scheduleVisibilityFilters:i,participantsProfile:a,afterRecoveryTimes:o,useParticipantMap:s,policyDefinitions:c,tournamentRecord:u,inContext:d=!0,usePublishState:p,contextProfile:l,matchUpFilters:m,contextFilters:f,nextMatchUps:h,context:g}=t,I=t.tournamentId??u.tournamentId,U=u?.events??[];r||({participants:r,participantMap:n}=Mp({participantsProfile:a,useParticipantMap:s,tournamentRecord:u,contextProfile:l,inContext:d}));const{appliedPolicies:y}=Np({tournamentRecord:u}),S={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},v=Lp({policyDefinitions:c,tournamentRecord:u,contextProfile:l});return{matchUps:U.flatMap((t=>(S.eventDrawsCount=t.drawDefinitions?.length??0,df({context:S,scheduleVisibilityFilters:i,tournamentAppliedPolicies:y,participantsProfile:a,afterRecoveryTimes:o,policyDefinitions:c,tournamentRecord:u,usePublishState:p,contextContent:v,contextFilters:f,contextProfile:l,matchUpFilters:m,participantMap:n,nextMatchUps:h,participants:r,inContext:d,event:t}).matchUps??[]))).concat(...u.matchUps??[])}}function lf({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,tournamentRecords:r,policyDefinitions:i,usePublishState:a,matchUpFilters:o,contextFilters:s,nextMatchUps:c,inContext:u}){if("object"!=typeof r||!Object.keys(r).length)return{error:et};const d=Object.keys(r).map((d=>{const p=r[d];return pf({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,policyDefinitions:i,tournamentRecord:p,usePublishState:a,matchUpFilters:o,contextFilters:s,nextMatchUps:c,inContext:u}).matchUps??[]})).flat();return{...z,matchUps:d}}function mf(t,e){return function(t,e){return(So[t?.stage]||0)-(So[e?.stage]||0)}(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function ff(t){let{participants:e,participantMap:n,contextContent:r}=t;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:a,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,matchUpFilters:p,contextFilters:l,contextProfile:m,drawDefinition:f,nextMatchUps:h,inContext:g,context:I,event:U}=t,{eventId:y,eventName:S,endDate:v,eventType:w,category:P,gender:D,matchUpFormat:T}=U??{},b={...I,surfaceCategory:U?.surfaceCategory??d?.surfaceCategory,indoorOutDoor:U?.indoorOutdoor??d?.indoorOutdoor,matchUpFormat:T,eventType:w,eventName:S,category:P,eventId:y,endDate:v,gender:D};let R;e?.length||n||!d||({participants:e=[],participantMap:n,groupInfo:R}=Mp({participantsProfile:o,useParticipantMap:u,tournamentRecord:d,contextProfile:m,inContext:g})),m&&!r&&(r=Lp({policyDefinitions:c,tournamentRecord:d,contextProfile:m,drawDefinition:f,event:U}));return{...cf({context:b,tournamentAppliedPolicies:a,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,drawDefinition:f,contextContent:r,contextFilters:l,contextProfile:m,matchUpFilters:p,participantMap:n,nextMatchUps:h,inContext:g,event:U}),groupInfo:R}}function hf({element:t,accessor:e}){if("string"!=typeof e)return{values:[]};const n=la(t),r=e.split("."),i=[];let a;!function t({targetElement:e,attributes:n=[],significantCharacters:r}){for(const[r,s]of n.entries())if(e?.[s]){const c=n.slice(r+1);if(c.length)if(Array.isArray(e[s])){e[s].forEach((e=>t({targetElement:e,attributes:c})))}else o({targetElement:e=e[s],index:r});else a||(a=e[s]),i.includes(e[s])||i.push(e[s])}function o({targetElement:t,index:e}){if(t&&e===n.length-1&&["string","number"].includes(typeof t)){const e=r?t.slice(0,r):t;a?i.includes(e)||i.push(e):(a=e,i.push(e))}}}({targetElement:n,attributes:r});const o={value:a};return i.length&&(o.values=i),o}const gf=t=>e=>t&&"object"==typeof e?Array.isArray(t)&&t.map((t=>({[t]:hf({element:e,accessor:t})?.value})))||"object"==typeof t&&Object.keys(t).map((t=>({[t]:hf({element:e,accessor:t})?.value})))||("string"==typeof t&&hf({element:e,accessor:t}))?.value:void 0,If=gf;function Uf({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:n,roundsCount:r,roundLimit:i,matchUps:a,lucky:o,fmlc:s}){if(!yl(a))return[];const{roundProfile:c,roundNumbers:u=[]}=Sl({interpolate:!0,matchUps:a});r=r??Math.max(...u,0);const d=i?r-i:0,p=d&&c?.[r-d]?.matchUpsCount,l=c&&Object.values(c).map(If("matchUpsCount")),m=(t,n)=>{let r=Math.min(...t);p&&n&&1===r&&(r=p);let i=Math.max(...t);return e&&i>e&&(i=e),[r,i]},f=c&&Object.assign({},...u.map((e=>{const i=(r??0)+1-e-d,a=c[e].matchUpsCount,u={finishingPositionRange:{},finishingRound:i},p=l?.slice(e-1).reduce(((t,e)=>t+(e||0)),0),f=1+t+(s&&1!==e?n??0:0),h=E(f,o?f+2*a:p+f+1),g=p+1-a,I=m(h.slice(g)),U=m(h.slice(0,g),!0);return u.finishingPositionRange={loser:I,winner:U},{[e]:u}}))),h=Pr({finishingRound:!0});return a.filter(Boolean).forEach((t=>{const e=t.roundNumber&&f[t.roundNumber];h&&!e&&console.log({roundFinishingData:f,matchUp:t}),t.finishingRound=e?.finishingRound,t.finishingPositionRange=e?.finishingPositionRange})),a}function yf({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:n}){if(!e)return{error:ot};const r={loserMatchUpIds:{},winnerMatchUpIds:{}};t||({matchUps:t,matchUpsMap:n}=cf({inContext:!0,drawDefinition:e,matchUpsMap:n}));const i=n?.drawMatchUps.some((t=>t.finishingPositionRange));if(!i&&1===e?.structures?.length&&!e?.structures[0].structures){Uf({matchUps:n?.drawMatchUps??[]})}return(t??[]).filter((({collectionId:t})=>!t)).forEach((i=>{const{matchUpId:a,structureId:o}=i,s=rf({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:a}),{winnerMatchUp:c,loserMatchUp:u}=s.targetMatchUps,d=c?.matchUpId,p=u?.matchUpId,l=gl({matchUpsMap:n,structureId:o}).find((t=>t.matchUpId===a));if(l&&(d&&(r.winnerMatchUpIds[l.matchUpId]=d,Object.assign(l,{winnerMatchUpId:d}),Object.assign(i,{winnerMatchUpId:d})),p&&(r.loserMatchUpIds[l.matchUpId]=p,i.loserMatchUpId=p,l.loserMatchUpId=p,i.finishingPositionRange))){const t=u.finishingPositionRange&&[...i.finishingPositionRange.loser,...u.finishingPositionRange.loser],e=t&&[Math.min(...t),Math.max(...t)];i.finishingPositionRange.loser=e,l.finishingPositionRange.loser=e}})),{inContextDrawMatchUps:t,goesToMap:r}}function Sf(t){let e=tp(t);const n=t.matchUps??[];let r=t.drawIds??[];const{includeParticipantDependencies:i,tournamentRecord:a,drawDefinition:o}=t;if(!Array.isArray(n))return{error:me};if(!Array.isArray(r))return{error:Tt};const s=t.matchUpIds?.length?t.matchUpIds:n.map((t=>t.matchUpId));if(!Array.isArray(s))return{error:pe};const c={},u={},d={},p={};a&&!Object.keys(e).length&&(e={[a.tournamentId]:a});const l=Object.values(e),m=l.reduce(((t,e)=>t.concat(e.events??[]).map((t=>(t.drawDefinitions||[]).map((t=>t.links||[])))).flat(1/0)),[]),f=m.filter((({linkType:t})=>t===Oo));let h=n;if(f.length){h=lf({nextMatchUps:!0,tournamentRecords:e}).matchUps;const t=f.reduce(((t,e)=>{const n=e.source?.structureId,r=e.target?.structureId;return n&&r&&(d[r]=n),n&&!t.includes(n)&&t.push(n),t}),[]);for(const e of t)c[e]=[];for(const e of h??[]){const n=e.containerStructureId||e.structureId;t.includes(n)&&c[n].push(e.matchUpId)}}const g=t=>{u[t]||(u[t]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},p[t]=[])},I=(t,e)=>{u[t].matchUpIds.forEach((t=>{u[e].matchUpIds.push(t)})),u[e].matchUpIds.push(t),u[t].dependentMatchUpIds.push(e),i&&u[t].participantIds.forEach((t=>u[e].participantIds.push(t)))},U=t=>{const e=Object.keys(c).length;for(const n of t||[]){const{matchUpId:t,winnerMatchUpId:r,loserMatchUpId:a}=n;if(!s.length||s.includes(t)){if(g(t),i){const{individualParticipantIds:e}=Xd(n);u[t].participantIds=e}r&&(g(r),I(t,r),p[r].push(t)),a&&(g(a),I(t,a),p[a].push(t)),u[t].sources.push(p[t]);const o=p[t].map((t=>u[t].sources[0])).flat(),s=p[t].map((t=>u[t].sources[1])).flat();if(u[t].sources.push(o,s),e){const e=n.containerStructureId||n.structureId,r=d[e];if(c[r])for(const e of c[r])g(e),I(e,t),p[e].push(t)}}}};if(o)yf({drawDefinition:o}),h?.length||(h=ff({drawDefinition:o}).matchUps),U(h);else{if(h?.length||(h=lf({nextMatchUps:!0,tournamentRecords:e}).matchUps),!r.length){const t=l?.length?l.map((({events:t=[]})=>t.map((({drawDefinitions:t=[]})=>t.map((({drawId:t})=>t)))))).flat(1/0):[];t&&(r=t)}for(const t of r){const n=h?.filter((e=>e.drawId===t)).sort(mf),r=n?.find((({roundPosition:t})=>!t));if(!r){const r=n?.find((({tournamentId:t})=>t)),{drawDefinition:i}=Gm({tournamentRecord:e[r?.tournamentId],drawId:t});i&&yf({drawDefinition:i})}U(n)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:p,matchUps:h,...z}}function vf(t){const e=t?.matchUp,n=t?.score||e?.score,r=n?.sets?.[0],{side1Score:i,side2Score:a,side1TiebreakScore:o,side2TiebreakScore:s,side1PointScore:c,side2PointScore:u}=r||{},d=i||a||o||s||c||u;return!!(n?.sets?.length>1||d)}function wf({matchUpStatus:t}){return Ju.includes(t)}function Pf({matchUpStatus:t}){return Zu.includes(t)}function Df({matchUpStatus:t,winningSide:e,tieMatchUps:n,sides:r,score:i}){const a=r?.find((({participantId:t})=>t)),o=n?.filter(Df)?.length;return vf({score:i})||o||e&&a||t&&function({matchUpStatus:t}){return td.includes(t)}({matchUpStatus:t})&&![Lu,zu,ju].includes(t)}function Tf(t){const{drawDefinition:e,findContainer:n,structureId:r,event:i}=t;let a=t.structure;const{containedStructures:o}=Zd({drawDefinition:e}),s=r&&o[r]||[];if(!a){const t=ad({drawDefinition:e,structureId:r});if(t.error)return t;a=n?t.containingStructure??t.structure:t.structure}if(Dl({structure:a}))return{structure:a,isAdHoc:!0,error:yt};const{matchUps:c}=cf({inContext:!0,matchUpFilters:{isCollectionMatchUp:!1},drawDefinition:e,event:i}),d=c?.filter((t=>t.structureId===r||s.includes(t.structureId))),{matchUpDependencies:p}=Sf({drawIds:[e.drawId],matchUps:c,drawDefinition:e}),l=[],m=[],f={},h=[];for(const t of c??[]){if(t.structureId===r||s.includes(t.structureId)){m.push(...t.drawPositions??[]);const e=t.roundNumber;for(const n of(t.drawPositions??[]).filter(Boolean))(!f[n]||e&&f[n]>e)&&(f[n]=e)}Df(t)&&(h.push(t),l.push(t.matchUpId,...p?.[t?.matchUpId]?.matchUpIds||[]))}const g=w(m.filter(Boolean)).sort(u),I=w(l),U=w(d?.map((({matchUpId:t,drawPositions:e})=>I.includes(t)?e:[])).flat().filter(Boolean)).sort(u),{positionAssignments:y}=cd({drawDefinition:e,structure:a}),S=y?.filter((t=>t.bye)).map((t=>t.drawPosition)),v=y?.filter((t=>t.qualifier)).map((t=>t.drawPosition)),P=g?.filter((t=>!U.includes(t)))||[];return{allDrawPositions:g,inContextStructureMatchUps:d,drawPositionInitialRounds:f,activeDependentMatchUpIds:I,qualifyingDrawPositions:v,inactiveDrawPositions:P,positionAssignments:y,activeDrawPositions:U,byeDrawPositions:S,activeMatchUps:h,structure:a}}function bf({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter((({drawPositions:e})=>t&&e?.includes(t))).map((({roundNumber:t})=>t)).sort(u)[0]}}const Rf={reset:"[0m",bright:"[1m",dim:"[2m",red:"[31m",brightred:"[91m",green:"[32m",brightgreen:"[92m",yellow:"[33m",brightyellow:"[93m",blue:"[34m",brightblue:"[94m",lightblue:"[105m",magenta:"[35m",brightmagenta:"[95m",cyan:"[36m",brightcyan:"[96m",white:"[37m",brightwhite:"[97m"},Mf=[];function Nf(t,e){j(t)&&(t={method:t}),(e||Pr())&&Mf.push(t)}function Af(t){const e=Mf.slice().map((t=>{const{color:e,keyColors:n,method:r,newline:i}=t,a=Object.keys(Rf).includes(e)?Rf[e]:Rf.cyan,o=Object.keys(t).filter((t=>!["color","keyColors","method","newline"].includes(t))).map((e=>{const r=n&&Object.keys(n).includes(e)&&Rf[n[e]]?Rf[n[e]]:Rf.brightwhite;return`${Rf.white}${e}: ${r}${t[e]}`})).join(", ");return[i?"\n":"",a,r,r?.length<15?"\t\t":"\t",Rf.white,o,Rf.reset,"\n"].join("")}));e?.length&&console.log(...e)}function Ef({provisionalPositioning:t,isPositionAction:e,tournamentRecord:n,drawDefinition:r,drawPosition:i,matchUpsMap:a,structureId:o,structure:s,event:c}){if(!r)return{error:ot};if(s||({structure:s}=ad({drawDefinition:r,structureId:o})),!s)return{error:Lt};o||({structureId:o}=s);const u="assignDrawPositionBye";Nf({method:u,color:"cyan",drawPosition:i}),a||(a=hl({drawDefinition:r}));const{positionAssignments:d}=cd({structure:s}),{activeDrawPositions:p}=Tf({drawDefinition:r,structureId:o}),l=d?.find((t=>t.drawPosition===i));if(l?.bye)return{...z};const m=p?.includes(i);if(m)return{error:It};const f=d?.find((t=>t.drawPosition===i));if(!f)return{error:yt};const{filled:h,containsBye:g,assignedParticipantId:I}=function(t){const e=t.bye,n=t.qualifier,r=t.participantId,i=e||n||r;return{containsBye:e,containsQualifier:n,assignedParticipantId:r,filled:i}}(f);if(g)return{...z};if(h&&!g)return ti({result:{error:lt},stack:u});const U=Np({tournamentRecord:n,drawDefinition:r,event:c}).appliedPolicies??{},y=cf({inContext:!0,drawDefinition:r,matchUpsMap:a}).matchUps??[],{matchUps:S}=Jm({provisionalPositioning:t,drawDefinition:r,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:a,structure:s});if(d?.forEach((t=>{t.drawPosition===i&&(t.bye=!0)})),s.structureType===Mo)return function({tournamentRecord:t,drawDefinition:e,drawPosition:n,matchUps:r,event:i}){r.forEach((r=>{r.drawPositions?.includes(n)&&Of({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:r})}))}({tournamentRecord:n,drawDefinition:r,drawPosition:i,matchUps:S}),Yd({tournamentId:n?.tournamentId,drawDefinition:r,structure:s,event:c}),Cf({assignedParticipantId:I,isPositionAction:e,appliedPolicies:U,drawDefinition:r,drawPosition:i,structureId:o,stack:u});const{roundProfile:v,roundMatchUps:w}=Sl({matchUps:S}),P=v&&Object.keys(v).map((t=>parseInt(t))).reverse(),D=P?.find((t=>v?.[t].drawPositions?.includes(i))),T=D?w?.[D].find((({drawPositions:t})=>t?.includes(i))):void 0;T&&Of({tournamentRecord:n,drawDefinition:r,matchUp:T,event:c});const b=T?.drawPositions?.find((t=>t!==i));if(T&&b){const t=Ff({sourceDrawPositions:T.drawPositions,matchUpId:T.matchUpId,inContextDrawMatchUps:y,drawPositionToAdvance:b,tournamentRecord:n,drawDefinition:r,matchUpsMap:a});if(t.error)return t}return Yd({tournamentId:n?.tournamentId,drawDefinition:r,structure:s,event:c}),Cf({assignedParticipantId:I,isPositionAction:e,appliedPolicies:U,drawDefinition:r,drawPosition:i,structureId:o,stack:u})}function Cf({assignedParticipantId:t,isPositionAction:e,appliedPolicies:n,drawDefinition:r,drawPosition:i,structureId:a,stack:o}){if(e){Jd({appliedPolicies:n,drawDefinition:r,positionAction:{removedParticipantId:t,drawPosition:i,structureId:a,name:o}})}return ti({result:{...z},stack:o})}function Of({tournamentRecord:t,drawDefinition:e,eventId:n,matchUp:r,event:i}){Object.assign(r,{matchUpStatus:Fu,score:void 0,winningSide:void 0}),$d({tournamentId:t?.tournamentId,eventId:n??i?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:r})}function Ff({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:n,tournamentRecord:r,drawDefinition:i,matchUpsMap:a,matchUpId:o,event:s}){Nf({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});const c=a.drawMatchUps.find((t=>t.matchUpId===o)),d=e.find((t=>t.matchUpId===o)),p=d?.structureId,{structure:l}=ad({drawDefinition:i,structureId:p}),{positionAssignments:m}=cd({structure:l}),f=m?.filter((t=>t.bye)).map((t=>t.drawPosition)),h=c?.drawPositions?.find((e=>e!==t)),g=h&&f?.includes(h),{targetLinks:{loserTargetLink:I},targetMatchUps:{loserMatchUp:U,winnerMatchUp:y,loserTargetDrawPosition:S}}=rf({inContextDrawMatchUps:e,drawDefinition:i,matchUpId:o});if(y&&y.structureId===l?.structureId&&function({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:n,tournamentRecord:r,drawDefinition:i,winnerMatchUp:a,matchUpsMap:o,event:s}){const c="advanceWinner",d=o.drawMatchUps.find((t=>t.matchUpId===a.matchUpId)),p=e.find((t=>t.matchUpId===a.matchUpId)),l=p?.structureId,{structure:m}=ad({drawDefinition:i,structureId:l}),{positionAssignments:f}=cd({structure:m}),h=f?.find((({drawPosition:e})=>e===t)),g=h?.bye,I=d.drawPositions?.filter(Boolean),U=f?.filter((t=>I?.includes(t.drawPosition))),y=f?.find((({drawPosition:e})=>e===t)),S=n?.find((e=>e!==t)),v=S&&U?.find((({drawPosition:t})=>t===S)),w=v?.bye,P=g&&w;P&&console.log({isByeAdvancedBye:P});if(I?.length>1&&g&&!w)return ti({result:{error:lt},stack:c});const D=I?.find((e=>e!==t));let T=P;const b=[...(d.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),R=b.map((e=>!e&&!T||e===t?(T=!0,t):e)).sort(u);if(!T)return console.log("@@@@@@@",{advancingAssignmentIsBye:y,drawPositionToAdvance:t,existingAssignments:U}),ti({result:{error:lt},stack:c});const M=f?.find((({drawPosition:t})=>t===D))?.bye,N=f?.find((({drawPosition:e})=>e===t))?.bye,A=N||M?Fu:Hu;Object.assign(d,{matchUpStatus:A,score:void 0,winningSide:void 0,drawPositions:R});const E=d.drawPositions.find((t=>!b.includes(t)));Nf({method:c,color:"brightyellow",changedDrawPosition:E,pairedDrawPositionIsBye:M,drawPositionIsBye:N}),$d({tournamentId:r?.tournamentId,matchUp:d,eventId:s?.eventId,context:c,drawDefinition:i});const{targetLinks:{loserTargetLink:C},targetMatchUps:{loserMatchUp:O,loserTargetDrawPosition:F}}=rf({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:i});if(M||N){const n=M?t:D;if(n)Ff({drawPositionToAdvance:n,matchUpId:a.matchUpId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,matchUpsMap:o});else if(N&&C&&O)if(O.feedRound)kf({loserTargetDrawPosition:F,tournamentRecord:r,loserTargetLink:C,drawDefinition:i,loserMatchUp:O,matchUpsMap:o});else{const t=1-a.roundPosition%2,e=O.drawPositions[t],n=Ef({structureId:C.target.structureId,drawPosition:e,tournamentRecord:r,drawDefinition:i,event:s});if(n.error);}}}({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:n,tournamentRecord:r,drawDefinition:i,winnerMatchUp:y,matchUpsMap:a,event:s}),U&&g&&U.structureId!==l?.structureId){const{roundNumber:t}=U;if(1===t){const t=Ef({structureId:I.target.structureId,drawPosition:S,tournamentRecord:r,drawDefinition:i,event:s});if(t.error)return t}else kf({loserTargetDrawPosition:S,tournamentRecord:r,loserTargetLink:I,drawDefinition:i,loserMatchUp:U,matchUpsMap:a,event:s})}return{...z}}function kf({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:n,drawDefinition:r,loserMatchUp:i,matchUpsMap:a,event:o}){const{roundNumber:s}=i;Nf({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});const c=(a?.mappedMatchUps||{})[i.structureId].matchUps,{initialRoundNumber:u}=bf({drawPosition:t,matchUps:c});if(u===s){const i=Ef({structureId:n.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:r,event:o});if(i.error)return i}}function xf({positionAssignments:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:r,structure:i,event:a}){const{matchUps:o}=Jm({drawDefinition:n,matchUpsMap:r,structure:i,event:a});o.forEach((r=>{const i=t.filter((({drawPosition:t})=>r.drawPositions?.includes(t))).filter((t=>t.bye)).length;if(!r.winningSide){const t=i?Fu:Hu;Object.assign(r,{matchUpStatus:t}),$d({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:a?.eventId,drawDefinition:n,matchUp:r})}}))}function _f(t){let{inContextDrawMatchUps:e,participantId:n,drawPosition:r}=t;const{tournamentRecord:i,drawDefinition:a,structureId:o,matchUpsMap:s,event:c}=t,{structure:u}=ad({drawDefinition:a,structureId:o}),d=(ud({drawDefinition:a,structure:u}).positionAssignments||[]).find((t=>n&&t.participantId===n||r&&t.drawPosition===r));if(d&&n&&!r&&(r=d?.drawPosition),!r)return{error:St};n||(n=d?.participantId);const{activeDrawPositions:p}=Tf({drawDefinition:a,structureId:o});if(p.includes(r))return{error:It};e||({matchUps:e}=cf({inContext:!0,drawDefinition:a,matchUpsMap:s}));return Lf({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,structureId:o,drawPosition:r,matchUpsMap:s,event:c}).drawPositionCleared?(Yd({tournamentId:i?.tournamentId,drawDefinition:a,structure:u,event:c}),{...z,participantId:n}):{error:ft}}function Lf({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:i,structureId:a,event:o}){const{structure:s}=ad({drawDefinition:n,structureId:a});if(!s)return{error:Lt};const c=ud({drawDefinition:n,structure:s}).positionAssignments||[],u=c.some((t=>{if(t.drawPosition===r)return delete t.participantId,delete t.qualifier,delete t.bye,!0}));if(s.structureType===Mo)return xf({positionAssignments:c,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,structure:s}),{drawPositionCleared:u,...z};const{matchUps:p}=Jm({drawDefinition:n,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:i,structure:s,event:o}),{roundProfile:l,roundMatchUps:m}=Sl({matchUps:p}),f=l&&Object.keys(l),h=f?.map((t=>d(t)));let g=r;const I=h?.map((t=>{const e=l?.[t],n=e?.pairedDrawPositions?.find((t=>t.includes(g))),r=n?.find((t=>t!==g)),i=c.find((t=>t.drawPosition===r)),a=l?.[t+1],o=i?.bye,s=a?.pairedDrawPositions?.find((t=>t.includes(r))),u=o&&s&&a&&a.drawPositions?.includes(r),d=n&&{pairedDrawPositionByeAdvancedPair:!u&&s,pairedDrawPosition:r,targetDrawPosition:g,relevantPair:n,roundNumber:t};return u&&(g=r),d})).filter((t=>t?.targetDrawPosition)),U=I?.reduce(((t,e)=>{const{roundNumber:n,relevantPair:r,targetDrawPosition:i,pairedDrawPosition:a,pairedDrawPositionByeAdvancedPair:o}=e,s=[{roundNumber:n,targetDrawPosition:i,relevantPair:r},o&&{roundNumber:n+1,targetDrawPosition:a,relevantPair:o,subsequentRoundRemoval:!0}].filter(Boolean);return t.concat(...s)}),[]);return U?.forEach((({roundNumber:u,targetDrawPosition:d,relevantPair:p})=>{const l=m?.[u].find((t=>k(t.drawPositions?.filter(Boolean),p.filter(Boolean))));l&&(!function({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,roundNumber:a,structureId:o}){const{structure:s}=ad({drawDefinition:r,structureId:o});if(!s)return{error:Lt};if(s.structureType===Mo)return;i=i||hl({drawDefinition:r});const c=i?.mappedMatchUps||{},u=c[o].matchUps,{initialRoundNumber:d}=bf({drawPosition:e,matchUps:u}),p=u?.filter((t=>t.roundNumber>=a&&t.roundNumber!==d&&t.drawPositions?.includes(e))),l=cd({drawDefinition:r,structureId:o}).positionAssignments??[];p?.forEach((a=>Bf({drawPosition:e,targetMatchUp:a,inContextDrawMatchUps:t,positionAssignments:l,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,structure:s})))}({inContextDrawMatchUps:t,targetDrawPosition:d,tournamentRecord:e,drawDefinition:n,structureId:a,roundNumber:u,matchUpsMap:i}),Bf({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:n,targetMatchUp:l,drawPosition:r,matchUpsMap:i,structure:s,event:o}))})),{tasks:U,drawPositionCleared:u,positionAssignments:c}}function Bf({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:n,drawDefinition:r,targetMatchUp:i,drawPosition:a,matchUpsMap:s,structure:c,event:u}){const d="removeDrawPosition",p=i.drawPositions?.slice(),l=i.matchUpStatus,m=i.winningSide,f=(s=s??hl({drawDefinition:r})).mappedMatchUps[c.structureId].matchUps,{initialRoundNumber:h}=bf({drawPosition:a,matchUps:f});if(i.roundNumber&&h&&i.roundNumber>h){const t=(i.drawPositions??[]).map((t=>t===a?void 0:t));i.drawPositions=t}if(i.matchUpType===o){const e=t?.find((t=>t.matchUpId===i.matchUpId)),o=(e?.sides??[]).reduce(((t,e,n)=>e.drawPosition===a?n:t),void 0);void 0!==o&&i.sides?.[o]?.lineUp&&(delete i.sides?.[o].lineUp,$d({tournamentId:n?.tournamentId,context:`${d}-TEAM`,eventId:u?.eventId,matchUp:i,drawDefinition:r}))}const g=rf({matchUpId:i.matchUpId,inContextDrawMatchUps:t,drawDefinition:r}),{targetLinks:{winnerTargetLink:I},targetMatchUps:{loserMatchUp:U,winnerMatchUp:y,loserMatchUpDrawPositionIndex:S}}=g,v=e.filter((({drawPosition:t})=>i.drawPositions?.includes(t))),w=v.filter((t=>t.bye)).length,P=w&&Fu||i.matchUpStatus&&[Lu,zu].includes(i.matchUpStatus)&&i.matcHUpStatus||Hu;i.matchUpStatus=P,i.matchUpStatus&&[zu,Lu].includes(i.matchUpStatus)&&(i.winningSide=void 0);const D=p?.find((t=>!i.drawPositions?.includes(t)));if(p?.includes(a)&&l===i.matchUpStatus&&m===i.winningSide||(D&&Nf({method:d,color:"brightyellow",removedDrawPosition:D}),$d({tournamentId:n?.tournamentId,context:`${d}-${a}`,eventId:u?.eventId,matchUp:i,drawDefinition:r})),U&&U.structureId!==g.matchUp.structureId&&!w){const{drawPositions:e,roundNumber:i}=U;if(1===i){const i=e[S];Lf({structureId:U.structureId,drawPosition:i,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,matchUpsMap:s})}else{const i=Math.min(...e.filter(Boolean)),a=function({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,loserMatchUp:i,matchUpsMap:a,event:o}){const{structure:s}=ad({structureId:i.structureId,drawDefinition:r}),{positionAssignments:c}=cd({structure:s}),u=c?.find((e=>e.drawPosition===t));if(u?.bye){const s=_f({drawPosition:t,structureId:i.structureId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:a,event:o});if(s.error)return s}return{...z}}({loserMatchUpDrawPosition:i,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,loserMatchUp:U,matchUpsMap:s,event:u});if(a.error)return ti({result:a,stack:d});const o=(s?.mappedMatchUps||{})[U.structureId].matchUps,{initialRoundNumber:c}=bf({drawPosition:i,matchUps:o});1===c&&(Nf({method:d,color:"brightyellow",loserMatchUpDrawPosition:i}),Lf({structureId:U.structureId,drawPosition:i,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,matchUpsMap:s}))}}return y&&y.structureId!==g.matchUp.structureId&&I.target.feedProfile,{...z}}function Vf({drawDefinition:t,stages:e}){if(!t)return{error:ot};const n=w((t?.structures??[]).filter((t=>!e?.length||t.stage&&e.includes(t.stage))).map((t=>{const{positionAssignments:e}=cd({structure:t});return e?e.map(Mu):[]})).flat().filter(Boolean));return{...z,assignedParticipantIds:n}}function jf(t){const e=(t?.entries??[]).filter(Boolean).reduce(((t,e)=>{const{entryStage:n,entryStatus:r}=e,i=`_${n||fo}${r||""}`;return t[i]||(t[i]=[]),t[i].push(e),t}),{}),n=t=>isNaN(t)?1/0:t;return Object.keys(e).map((t=>e[t].sort(((t,e)=>n(t.entryPosition)-n(e.entryPosition))).map(((t,e)=>({...t,entryPosition:e+1}))))).flat()}function Gf(t){return[Xp,Zp].includes(t)}function qf({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:n,drawDefinition:r,participantIds:i,entryStatus:a,entryStage:o,extension:s,eventSync:c,drawId:u,stage:d,event:p}){if(!i||!Array.isArray(i))return{error:He,method:"modifyEntriesStatus",participantIds:i};if(!r&&!p)return{error:$t};if(a&&!ol.includes(a))return{error:ln};if(o&&!yo.includes(o))return{error:Jt};const l="modifyEntriesStatus",m=[];if(!a&&!s)return ti({result:{error:be},info:"Missing entryStatus",stack:l});if(s&&!xc({extension:s,requiredAttributes:["name"]}))return ti({result:{error:Jn},info:"Invalid extension",context:{extension:s},stack:l});const f=[];p?.drawDefinitions?.forEach((t=>{const e=Vf({stages:d&&[d],drawDefinition:t}).assignedParticipantIds??[];f.push(...e)}));const h=n?.participants??[];if(!i.every((t=>{const e=Fc({tournamentParticipants:h,participantId:t})?.participantType;return!(e&&[sp,ip].includes(e)&&Gf(a)||a&&p?.eventType&&e===ap&&[co,lo].includes(p.eventType)&&[qp,...nl].includes(a))})))return{error:ln};const g=p&&jm({event:p}).flightProfile,I=g?.flights?.find((t=>t.drawId===u)),U=t=>{const n=(t||[]).filter((t=>!d||!t.entryStage||d===t.entryStage)).filter((({participantId:t})=>i.includes(t)));return n.every((t=>!((t=>a&&f.includes(t.participantId)&&!(nl.includes(t.entryStatus)&&nl.includes(a)))(t)&&!e)&&(a&&(t.entryStatus=a,delete t.entryPosition),o&&(t.entryStage=o,delete t.entryPosition),s&&(s.value?_c({element:t,extension:s}):kc({element:t,name:s.name})),!0)))?{...z}:{error:un}},y=({flight:t,drawDefinition:e})=>{p&&(p.entries=jf({entries:p.entries??[]})),t&&(t.drawEntries=jf({entries:t.drawEntries})),e&&(e.entries=jf({entries:e.entries}))},S=t=>{const{flight:e,drawDefinition:n}=t,r="updateDrawEntries";if(e){const t=U(e.drawEntries);if(t.error)return ti({result:t,stack:r})}if(n){const t=U(n.entries);if(t.error)return ti({result:t,stack:r});m.includes(n.drawId)||m.push(n.drawId)}return{...z}},v=p?.entries?.find((({entryPosition:t})=>t))??(I?.drawEntries?.find((({entryPosition:t})=>t))||r?.entries?.find((({entryPosition:t})=>t)));if(t&&!v&&y({flight:I,drawDefinition:r}),I||r){const t=S({flight:I,drawDefinition:r});if(t.error)return ti({result:t,stack:l})}const w=p?.drawDefinitions?.map((({drawId:t})=>t))??[],P=g?.flights?.filter((t=>!w.includes(t.drawId)))||[];for(const t of P){const e=t&&S({flight:t});if(e?.error)return ti({result:e,stack:l})}const D=1===g?.flights?.length&&(p?.drawDefinitions?.length??0)<=g?.flights?.length;if(!I&&!r&&a&&rl.includes(a))return{error:In};if(!I&&!r||a===el||c&&D){const t=U(p?.entries);if(t?.error)return ti({result:t,stack:l});let e;if(a===el&&(g?.flights?.every((t=>{const n=U(t.drawEntries);return n.error?(e=n.error,!1):(t.drawEntries=t.drawEntries.filter((({participantId:t})=>!i.includes(t))),!0)})),p?.drawDefinitions?.every((t=>{const n=U(t.entries);return n.error?(e=n.error,!1):(t.entries=t.entries?.filter((({participantId:t})=>!i.includes(t))),!0)}))),e)return ti({result:{error:e},stack:l})}t&&y({flight:I,drawDefinition:r});for(const t of p?.drawDefinitions??[])m.length&&!m.includes(t.drawId)||Hd({tournamentId:n.tournamentId,eventId:p?.eventId,drawDefinition:t});return{...z}}function $f({requireTimeStamp:t,scaleAttributes:e,participant:n}){if(!n)return{error:Je};if(!G(e))return{error:Jn};if(n.timeItems||(n.timeItems=[]),Array.isArray(n.timeItems)){const{accessor:r,scaleType:i,eventType:a,scaleName:o}=e,s=[mc,i,a,o].join("."),c=n.timeItems.filter((t=>t?.itemType===s)).filter((e=>!t||e?.itemDate)).sort(((t,e)=>(t.createdAt?new Date(t.createdAt).getTime():0)-(e.createdAt?new Date(e.createdAt).getTime():0))),u=c.pop();if(u){const[t,e,n,i]=u.itemType?.split(".")??[];if(t!==mc)return{error:jn};const a=r&&hf({element:u.itemValue,accessor:r}),o=a?.value||u.itemValue,s={eventType:n,scaleDate:u.itemDate,scaleValue:o,scaleName:i,scaleType:e};return{...z,scaleItem:s}}}return{...z,scaleItem:void 0}}function Wf({publishedSeeding:t,usePublishState:e,withSeeding:n,participant:r,event:i}){const a={},o=t=>[mc,fc,i.eventType,t].join("."),s=Object.assign({},...(r.timeItems||[]).filter((({itemType:t})=>t.split(".")[1]===fc)).map((({itemType:t,itemValue:e})=>({[t]:e})))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(o),u=O(Object.keys(s),c);if(!(e&&(Object.keys(s).length||t?.drawIds?.length)&&!u.length)&&u.length){if(t?.stageSeedingScaleNames){const e=Object.keys(t.stageSeedingScaleNames).map((e=>{const n=o(t.stageSeedingScaleNames[e]);return[e,s[n]]})).filter((t=>t[1])).map((t=>({[t[0]]:{seedValue:t[1]}}))),n=Object.assign({},...e);a.seedAssignments=n}else if(u){const t=u.map((t=>s[t]));a.seedValue=t.pop()}}else if(e||"object"!=typeof n){const{categoryName:n,ageCategoryCode:o}=i.category||{},s=[o,i.eventId,n].filter(Boolean);let c;for(const t of s){const e=$f({scaleAttributes:{eventType:i.eventType,scaleType:fc,scaleName:t},participant:r});if(e.scaleItem){c=e.scaleItem;break}}if(c){if(!e||t?.published&&!t?.published?.drawIds?.length){const t=c.scaleValue;a.seedValue=t}}}else{const t=Object.keys(n).map((t=>{const e=o(n[t]);return[t,s[e]]})).filter((t=>t[1])).map((t=>({[t[0]]:{seedValue:t[1]}}))),e=Object.assign({},...t);a.seedAssignments=e}return a}function Hf({convertExtensions:t,seedAssignments:e,participant:n,withSeeding:r,seedValue:i,eventId:a,ranking:o,entry:s}){const{entryStatus:c,entryStage:u,entryPosition:d,extensions:p}=s,l=p?.length&&t?Object.assign({},...ma(p??[])):{},m=Object.assign(l,{entryPosition:d,entryStatus:c,entryStage:u,ranking:o,eventId:a});n.events[a]=Xr(m,!1,!1,!0),r&&(e&&(n.events[a].seedAssignments=e),i&&(n.events[a].seedValue=i))}function zf(t){const e=cc(t,[{[hs]:!0}]);if(e.error)return e;const{tournamentRecord:n,status:r=am}=t,i=`${im}.${om}`;return la(Sp({tournamentRecord:n,itemType:i})?.timeItem?.itemValue?.[r],!1,!0)}function Yf({event:t,status:e=am}){const n=`${im}.${om}`;return yp({itemType:n,event:t})?.timeItem?.itemValue?.[e]}function Kf({drawDetails:t,drawId:e}){const n=t?.[e]?.publishingDetail;return n?.published}function Qf(t){const{tournamentRecord:e,drawDefinition:n,eventIds:r,eventId:i,drawIds:a,drawId:o,event:s}=t??{};if(e&&!function(t){const{tournamentId:e}=t??{};return!!e}(e))return{error:Jn};if(i&&!s)return{error:Wt};if(Array.isArray(r)&&r?.length){const t={};for(const n of r){if(!j(n))return{error:Jn};const r=Gm({tournamentRecord:e,eventId:n})?.event;if(!r)return{error:Wt};const i=Jf({event:r});t[n]=i}return{...z,publishState:t}}if(s){const t=Jf({event:s});let e={};if(o)return n?{publishState:{status:{published:!!t.status.publishedDrawIds?.includes(o),drawDetail:t.status.drawDetails?.[o]},...z}}:{error:ct};if(Array.isArray(a)&&a?.length){const n=s.drawDefinitions?.map(Au)??[];for(const r of a){if(!j(r))return{error:Jn};if(!n.includes(r))return{error:ct};e[r]={status:{published:!!t.status.publishedDrawIds.includes(r),drawDetail:t.status.drawDetails?.[r]}}}}else e=t;return{...z,publishState:e}}const c=[];let u=!1;const d={};for(const t of e?.events??[]){const e=Jf({event:t});d[t.eventId]=e,e.status.published&&(c.push(t.eventId),u=!0);for(const{drawId:n}of t.drawDefinitions??[]){const t=e.status?.publishedDrawIds?.includes(n);t&&(d[n]={status:{published:t}})}}if(e){const t=zf({tournamentRecord:e});d.tournament=t??{},(t?.orderOfPlay?.published||t?.participants?.published)&&(u=!0),d.tournament.status={published:u,publishedEventIds:c}}return{...z,publishState:d}}function Jf({event:t}){const e=Yf({event:t});if(!e)return{status:{published:!1}};const n={published:void 0,seedingScaleNames:[],drawIds:[]};e.seeding&&Object.assign(n,e.seeding);const r=e.drawDetails??{};for(const e of t.drawDefinitions?.map(Au)||[])r[e]||(r[e]={publishingDetail:{published:!1}});const i=r&&Object.keys(r).length&&Object.keys(r).filter((t=>Kf({drawDetails:r,drawId:t}))),a=i?.length?i:e.drawIds??[];if(a?.length&&!i?.length)for(const t of a)r[t]={publishingDetail:{published:!0}};return{status:{publishedDrawIds:a,publishedSeeding:n,drawDetails:r,published:a?.length>0}}}function Zf(t){const{participantMap:e,participantId:n,matchUpStatus:r,roundPosition:i,structureId:a,matchUpType:o,roundNumber:s,matchUpId:c,potential:u,schedule:d,drawId:p,score:l}=t;if(!d||!Object.keys(d).length)return;r===Fu||e[n].scheduleItems.push({...d,scheduledDate:$i(d?.scheduledDate),scheduledTime:qi(d?.scheduledTime),checkScoreHasValue:vf({score:l}),matchUpStatus:r,roundPosition:i,structureId:a,matchUpType:o,roundNumber:s,matchUpId:c,potential:u,drawId:p})}function Xf({finishingPositionRange:t={},participantMap:e,finishingRound:n,participantWon:r,matchUpStatus:i,participantId:a,stageSequence:o,roundNumber:s,structureId:c,matchUpId:u,drawId:d,stage:p}){const l=e[a],m=t=>Math.abs(t[0]-t[1]);l.structureParticipation[c]||(l.structureParticipation[c]={rankingStage:p,walkoverWinCount:0,defaultWinCount:0,stageSequence:o,winCount:0,structureId:c,drawId:d});const f=l.structureParticipation[c],{winner:h,loser:g}=t,I=r?h:g;r&&(f.winCount+=1,i===zu&&(f.walkoverWinCount+=1),i===Lu&&(f.defaultWinCount+=1)),I&&(!f.finishingPositionRange||m(I)<m(f.finishingPositionRange))&&(f.finishingPositionRange=I),n&&((!f.finishingRound||n<f.finishingRound)&&(f.finishingMatchUpId=u,f.finishingRound=n,f.roundNumber=s),1===n&&(f.participantWon=r))}function th(t){const{withScheduleItems:e,scheduleAnalysis:n,withTeamMatchUps:r,participantMap:i,withOpponents:a,withMatchUps:s,withEvents:c,withDraws:u,finishingPositionRange:d,finishingRound:p,matchUpStatus:l,stageSequence:m,roundNumber:f,structureId:h,score:g,stage:I,withRankingProfile:U,tieWinningSide:y,roundPosition:S,matchUpTieId:v,matchUpSides:w,collectionId:P,matchUpType:D,winningSide:T,matchUpId:b,schedule:R,eventId:M,drawId:N,sides:A}=t,E=a&&2===A?.length&&Object.assign({},...A.map((({sideNumber:t},e)=>{const n=A[1-e].participantId;return t&&{[t]:n}})).filter(Boolean));for(const t of A){const{participantId:A,sideNumber:C,bye:O}=t;if(O)continue;const F=T===C,k=t=>{const e=i[t]?.participant,n=e?.participantType,r=[{participantId:t,participantType:n}];if(n!==ip)for(const t of e?.individualParticipantIds||[]){const e=i[t]?.participant;r.push({participantType:e?.participantType,participantId:t})}return r},x=(t,r)=>{if(s){if(i[t].matchUps[b]={participantWon:F,matchUpType:D,structureId:h,sideNumber:C,matchUpId:b,eventId:M,drawId:N,stage:I},a){const e=k(r);i[t].matchUps[b].opponentParticipantInfo=e}P&&(i[t].matchUps[b].collectionId=P)}a&&r&&(i[t].opponents[r]={participantId:r,matchUpId:b,eventId:M,drawId:N}),U&&Xf({finishingPositionRange:d,participantMap:i,participantWon:F,finishingRound:p,matchUpStatus:l,participantId:t,stageSequence:m,roundNumber:f,structureId:h,matchUpId:b,drawId:N,stage:I}),(n||e)&&Zf({participantMap:i,participantId:t,matchUpStatus:l,roundPosition:S,matchUpType:D,roundNumber:f,structureId:h,matchUpId:b,schedule:R,drawId:N,score:g})},_=({participant:t,partnerParticipantId:e})=>{const n=(t,e)=>{t&&(t.partnerParticipantIds||(t.partnerParticipantIds=[]),t.partnerParticipantIds.includes(e)||t.partnerParticipantIds.push(e))};u&&n(t?.draws?.[N],e),c&&n(t?.events?.[M],e),s&&n(t?.matchUps?.[b],e)};if(A&&i[A]){const t=E?.[C];x(A,t);const e=i[A]?.participant.participantType===sp,n=i[A]?.participant.individualParticipantIds||[];if(v){if(r){const t=t=>i[t].matchUps[v]={participantWon:y===C,matchUpId:v,matchUpType:o,sideNumber:C};t(A),n.forEach(t)}if(u&&!i[A].draws[N]){const t=w.find((t=>t.sideNumber===C))?.participant?.participantId,e=i[t]?.draws?.[N]?.entryStatus,r=t=>i[t].draws[N]={entryStatus:e,eventId:M,drawId:N};r(A),n.forEach(r)}}if(e&&(n.forEach((e=>i[e]&&x(e,t))),n.forEach(((t,e)=>{const r=n[1-e],a=i[t];a&&_({participant:a,partnerParticipantId:r})})),c&&w)){const t=w.find((t=>t.sideNumber===C))?.participant?.participantId;if(t){const e=i[t]?.events[M];e?(i[A].events[M]={...e},n.forEach((t=>i[t].events[M]={...e}))):console.log("Missing teamEntry",{eventId:M,teamParticipantId:t})}}if(T){const t=t=>{F?(i[t].counters[D].wins+=1,i[t].counters.wins+=1,l===zu&&(i[t].counters[D].walkoverWins+=1,i[t].counters.walkoverWins+=1),l===Lu&&(i[t].counters[D].defaultWins+=1,i[t].counters.defaultWins+=1)):(i[t].counters[D].losses+=1,i[t].counters.losses+=1,l===zu&&(i[t].counters[D].walkovers+=1,i[t].counters.walkovers+=1),l===Lu&&(i[t].counters[D].defaults+=1,i[t].counters.defaults+=1))};t(A),n.forEach(t)}}}}function eh(t,e){return(t||"").localeCompare(e||"")}function nh({participantFilters:t={},tournamentRecord:e,participants:n=[]}){if(!Object.keys(t).length)return n;const{accessorValues:r,drawEntryStatuses:i,positionedParticipants:a,eventEntryStatuses:o,participantRoles:s,participantRoleResponsibilities:c,participantTypes:u,participantIds:d,signInStatus:p,enableOrFiltering:l,eventIds:m,genders:f}=t,h=rh(m)&&e?.events?.filter((t=>m?.includes(t.eventId)))||e?.events||[],g=i&&function({drawEntryStatuses:t,tournamentEvents:e}){const n=({entryStatus:e})=>!Array.isArray(t)||t.includes(e);return w(e.reduce(((t,e)=>{const{flightProfile:r}=jm({event:e}),i=r?.flights?.map((({drawEntries:t})=>Array.isArray(t)?t.filter(n).map(Mu):[])).flat()||[],a=e.drawDefinitions?.map((({entries:t})=>t?t.filter(n).map(Mu):[]))||[];return t.concat(...i,...a)}),[]))}({drawEntryStatuses:i,tournamentEvents:h}),I=o&&function({eventEntryStatuses:t,tournamentEvents:e}){return w(e.reduce(((e,n)=>{const r=(n.entries||[]).filter((({entryStatus:e})=>!Array.isArray(t)||t.includes(e))).map(Mu);return e.concat(...r)}),[]))}({eventEntryStatuses:o,tournamentEvents:h}),U=void 0!==a&&[!0,!1].includes(a)&&h.reduce(((t,e)=>t.concat(...(e.drawDefinitions||[]).map((t=>sd({drawDefinition:t}).allPositionedParticipantIds)).filter(Boolean))),[]),y=t=>r?.reduce(((e,n)=>{const{accessor:r,value:i}=n,{values:a}=hf({element:t,accessor:r});return e&&a?.includes(i)}),!0);if(n=n?.filter((t=>{const e=Ip({element:t,itemType:ep})?.timeItem?.itemValue,{participantRoleResponsibilities:n,participantType:i,participantRole:o,participantId:m,person:h}=t,S=Array.isArray(f)&&f?.length&&h?.sex&&f.includes(h.sex);return l?f&&S||a&&U.includes(m)||!1===a&&!U.includes(m)||g?.includes(m)||I?.includes(m)||d?.includes(m)||p&&e===p||u&&i&&rh(u)&&u.includes(i)||s&&o&&rh(s)&&s.includes(o)||c&&rh(n)&&rh(c)&&c.find((t=>n?.includes(t)))||r?.length&&rh(r)&&y(t):(!f||S)&&(void 0===a||a&&U.includes(m)||!1===a&&!U.includes(m))&&(!g||g.includes(m))&&(!I||I.includes(m))&&(!d||d.includes(m))&&(!p||e===p)&&(!u||i&&rh(u)&&u.includes(i))&&(!s||o&&rh(s)&&s.includes(o))&&(!c||rh(n)&&rh(c)&&c.find((t=>n?.includes(t))))&&(!r?.length||rh(r)&&y(t))})),h.length&&m){const t=h.filter((t=>m.includes(t.eventId))).map((t=>{const n=(t.entries||[]).map((t=>t.participantId));if(um(oo)(t.eventType))return n;const r=(e?.participants??[]).filter((t=>n.includes(t.participantId))).map((t=>t.individualParticipantIds)).flat(1);return n.concat(...r)})).flat(1);n=n?.filter((e=>t.includes(e.participantId)))}return n}function rh(t){return t&&Array.isArray(t)&&t.length}function ih(t){const{withIndividualParticipants:e,participantFilters:r={},withPotentialMatchUps:a,withRankingProfile:o,convertExtensions:s,policyDefinitions:c,withScheduleItems:u,tournamentRecord:d,scheduleAnalysis:p,withSignInStatus:l,withTeamMatchUps:m,withScaleValues:f,usePublishState:h,withStatistics:g,contextFilters:I,matchUpFilters:U,contextProfile:y,withOpponents:S,withMatchUps:v,internalUse:P,withSeeding:D,withEvents:T,withDraws:b,withISO2:R,withIOC:M}=t;if(!d)return{error:nt};(v||o)&&Sf({tournamentRecord:d});const N=Dp({convertExtensions:s,tournamentRecord:d,withSignInStatus:l,withScaleValues:f,internalUse:P,withISO2:R,withIOC:M});let{participantMap:A}=N;const E=function(t){const{participantFilters:e,convertExtensions:r,policyDefinitions:a,tournamentRecord:o,usePublishState:s,contextFilters:c,matchUpFilters:u,participantMap:d,contextProfile:p,withPotentialMatchUps:l,withRankingProfile:m,withScheduleItems:f,scheduleAnalysis:h,withTeamMatchUps:g,withStatistics:I,withOpponents:U,withMatchUps:y,withSeeding:S,withEvents:v,withDraws:P}=t,D=e?.participantIds,T=t=>{const e=[t];return d[t]?.participant.individualParticipantIds?.forEach((t=>e.push(t))),e.some((t=>!D?.length||D.includes(t)))?e:[]},b={withMatchUps:y||m,withEvents:v||m,withDraws:P||m,withPotentialMatchUps:l,withRankingProfile:m,withScheduleItems:f,scheduleAnalysis:h,withTeamMatchUps:g,withStatistics:I,participantMap:d,withOpponents:U,withSeeding:S},R=[],M={},N=[],A={},E={},C={},O=({eventType:t,scaleNames:e,participantId:n})=>d[n]?.participant?.rankings?.[t]?.find((t=>e.includes(t.scaleName)))?.scaleValue;for(const t of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(t.eventId))continue;const{drawDefinitions:n=[],extensions:i=[],eventType:D,eventName:R,category:F,entries:k,eventId:x,gender:_}=t,{flightProfile:L}=jm({event:t}),B=L?.flights??[],V=Qf({event:t}).publishState;V&&(A[x]=V);const j=V?.status?.publishedSeeding;if(v||S||m){const e=r?Object.assign({},...ma(i??[])):{};E[x]={...e,eventName:R,eventType:D,category:F,eventId:x,gender:_};const n=[F?.categoryName,F?.ageCategoryCode].filter(Boolean);for(const e of k){const{participantId:i}=e;if(!i||!d[i])continue;const a=O({eventType:D,scaleNames:n,participantId:i});let o,c;if(S){const e=d[i].participant;({seedAssignments:o,seedValue:c}=Wf({publishedSeeding:j,usePublishState:s,withSeeding:S,participant:e,event:t}))}const u=t=>{if(d[t]?.events?.[x])return;const n=d[t];Hf({convertExtensions:r,seedAssignments:o,participant:n,withSeeding:S,seedValue:c,eventId:x,ranking:a,entry:e})};u(i),(d[i].participant.individualParticipantIds||[]).forEach(u)}}const G=A?.[x]?.publishedSeeding;if(P||m||S){const t=t=>t?Object.assign({},...t.map((({participantId:t,seedValue:e,seedNumber:n})=>({[t]:{seedValue:e,seedNumber:n}})))):void 0,e=w([...n.map(Au),...B.map(Au)]);for(const r of e){const e=n.find((t=>t.drawId===r)),i=[F?.categoryName,F?.ageCategoryCode].filter(Boolean),{structures:a=[],drawOrder:o,drawName:c,drawType:u}=e??{},p=B?.find((t=>t.drawId===r)),l=e?.entries||p?.drawEntries,f=p?.flightNumber,h=(e?.structures||[]).sort(((t,e)=>rd(t,e))).map((({structureId:t,structures:e})=>[t,...(e||[]).map((({structureId:t})=>t))])).flat(1/0);let g,I,U,y,v=0;const w=a.filter((({stage:t,stageSequence:e})=>t===fo&&1===e||t===ho)).flatMap((t=>{const{positionAssignments:e}=cd({structure:t}),{seedAssignments:n,stageSequence:r,stage:i}=t;return i===fo?(v=e?.length??0,U=e,y=n):1===r&&(g=e,I=n),e})).map((({participantId:t})=>t)).filter(Boolean),T=t(y),b=t(I),R=e?l.filter((({participantId:t})=>w.includes(t))):l,M=!s||G?.published&&(0===G?.drawIds?.length||G?.drawIds?.includes(r));for(const t of R){if(!d[t.participantId])continue;const{entryStatus:e,entryStage:n,entryPosition:a,participantId:o}=t,s=O({participantId:o,scaleNames:i,eventType:D}),c=t=>{if(!d[t]||d[t].draws?.[r])return;const i=S&&M,c=i?{}:void 0,u=i?T?.[o]?.seedValue||T?.[o]?.seedNumber:void 0,p=u?T?.[o]:void 0,l=i?b?.[o]?.seedValue||b?.[o]?.seedNumber:void 0,f=l?b?.[o]:void 0;c&&u&&(c[fo]=p),c&&l&&(c[ho]=f);const h=u||l;h&&(d[t].participant.seedings[D]||(d[t].participant.seedings[D]=[]),p&&d[t].participant.seedings[D].push({...p,scaleName:r}),f&&d[t].participant.seedings[D].push({...f,scaleName:r}),c&&(d[t].events[x].seedAssignments||(d[t].events[x].seedAssignments={}),Object.keys(c).forEach((e=>d[t].events[x].seedAssignments[e]=c[e])))),(P||m)&&(d[t].draws[r]=Xr({seedAssignments:c,entryPosition:a,entryStatus:e,entryStage:n,seedValue:h,eventId:x,ranking:s,drawId:r},!1,!1,!0))};if(![Zp,Xp].includes(e)){c(o);const t=d[o].participant.individualParticipantIds||[];t?.forEach(c)}}const N=(e?.structures??[]).reduce(((t,e)=>(t.includes(e.stage)||t.push(e.stage),t)),[]),A=(e?.links??[]).length;C[r]={qualifyingPositionAssignments:g,qualifyingSeedAssignments:I,mainPositionAssignments:U,qualifyingSeedingMap:b,mainSeedAssignments:y,orderedStructureIds:h,mainSeedingMap:T,flightNumber:f,linksCount:A,drawOrder:o,drawName:c,drawType:u,drawSize:v,drawId:r,stages:N}}}if(m||h||g||I||U||y||P){const e=!!h||l,n=df({afterRecoveryTimes:!!h,policyDefinitions:a,tournamentRecord:o,inContext:!0,participantMap:d,contextFilters:c,matchUpFilters:u,contextProfile:p,nextMatchUps:e,event:t})?.matchUps??[];for(const t of n){const{finishingPositionRange:n,potentialParticipants:r,tieMatchUps:i=[],sides:a=[],winningSide:s,matchUpType:c,matchUpId:u,eventId:p,drawId:l,collectionId:m,stageSequence:g,finishingRound:I,matchUpStatus:U,roundPosition:y,roundNumber:S,structureId:v,schedule:w,score:P,stage:D}=t;M[u]=t;const R={finishingPositionRange:n,finishingRound:I,stageSequence:g,roundPosition:y,collectionId:m,roundNumber:S,structureId:v,schedule:w,eventId:p,drawId:l,score:P,stage:D};th({...R,...b,matchUpStatus:U,winningSide:s,matchUpType:c,matchUpId:u,sides:a});for(const t of i){const{winningSide:e,sides:n=[],matchUpId:r,matchUpStatus:i,matchUpType:o}=t;th({...R,...b,winningSide:e,tieWinningSide:s,matchUpTieId:u,matchUpId:r,sides:n,matchUpSides:a,matchUpStatus:i,matchUpType:o})}if(Array.isArray(r)&&(e||h||f)){const t=r.flat().map(Mu).filter(Boolean);t?.forEach((t=>{const e=T(t);e?.forEach((t=>{d[t]&&(d[t].potentialMatchUps[u]=Xr({tournamentId:o?.tournamentId,matchUpId:u,eventId:p,drawId:l}))})),(h||f)&&Zf({potential:!0,participantMap:d,participantId:t,matchUpStatus:U,roundPosition:y,structureId:v,matchUpType:c,roundNumber:S,matchUpId:u,schedule:w,drawId:l,score:P})}))}}N.push(...n)}}if(I||m||h){const t=Object.values(d);for(const e of t){const{wins:t,losses:r,[n]:{wins:a,losses:o},[i]:{wins:s,losses:c}}=e.counters,u=(t,n,r)=>{const i=n+r,a=n,o=i&&a/i;e.statistics[t]={denominator:i,numerator:a,statValue:o,statCode:t}};if(I&&(u(xp,t,r),u(`${xp}.${n}`,a,o),u(`${xp}.${i}`,s,c)),m){const t=(t=[])=>Math.abs(t[0]-t[1]);for(const n of Object.keys(e.draws)){const{orderedStructureIds:r=[],flightNumber:i}=C[n]||{};if(e.structureParticipation&&r.length){let a,o=0;const s=r.map((n=>{const r=e.structureParticipation[n];if(!r)return;a||(a=r?.finishingPositionRange),t(a)>t(r?.finishingPositionRange)&&(a=r?.finishingPositionRange);const s=r.stage!==ho;s&&(o+=1);const c=s?o:void 0;return Xr({...r,participationOrder:c,flightNumber:i})})).filter(Boolean);e.draws[n]&&(e.draws[n].finishingPositionRange=a,e.draws[n].structureParticipation=s)}}}if(h){const t=G(h)?h.scheduledMinutesDifference:0,n=e.scheduleItems||[],r=e.potentialMatchUps||{},i=n.reduce(((t,e)=>{const{scheduledDate:n,scheduledTime:r}=e;return t[n]||(t[n]=[]),r&&t[n].push(e),t}),{});Object.values(i).forEach((t=>t.sort(Yi)));for(const a of n){const{typeChangeTimeAfterRecovery:n,timeAfterRecovery:o,scheduledDate:s,scheduledTime:c}=a,u=i[s],d=ji(c);for(const i of u){if(i.matchUpId===a.matchUpId||[zu,Lu].includes(i.matchUpStatus)&&!i.checkScoreHasValue)continue;const s=a.matchUpType!==i.matchUpType&&n||o,c=a.drawId===i.drawId,u=r[a.matchUpId]&&r[i.matchUpId],p=ji(i.scheduledTime),l=Math.abs(p-d),m=p>=d;if((t&&!isNaN(t)?l<=t:m&&ji(i.scheduledTime)<ji(s))&&(!u||!c)&&m){const t=[a.matchUpId,i.matchUpId].sort(eh).join("|");e.scheduleConflicts[t]={priorScheduledMatchUpId:a.matchUpId,matchUpIdWithConflict:i.matchUpId}}}}const a=e.participant.participantId;Object.keys(e.scheduleConflicts).length&&R.push(a),d[a].scheduleConflicts=e.scheduleConflicts}}}return{participantIdsWithConflicts:R,eventsPublishStatuses:A,derivedEventInfo:E,derivedDrawInfo:C,mappedMatchUps:M,participantMap:d,matchUps:N}}({withMatchUps:v??o,withEvents:T??o,withDraws:b??o,withPotentialMatchUps:a,participantFilters:r,withRankingProfile:o,convertExtensions:s,withScheduleItems:u,policyDefinitions:c,tournamentRecord:d,scheduleAnalysis:p,withTeamMatchUps:m,usePublishState:h,withStatistics:g,contextFilters:I,matchUpFilters:U,participantMap:A,withOpponents:S,contextProfile:y,withSeeding:D}),{participantIdsWithConflicts:C,eventsPublishStatuses:O,derivedEventInfo:F,derivedDrawInfo:k,mappedMatchUps:x}=E,_=E.matchUps;A=E.participantMap;const L=p??a,B=({potentialMatchUps:t,scheduleConflicts:e,scheduleItems:n,participant:r,statistics:i,opponents:a,matchUps:s,events:c,draws:d})=>{const l=Object.values(d),m=Object.values(a);return S&&l?.forEach((t=>{t.opponents=m.filter((e=>e.drawId===t.drawId))})),Xr({...r,scheduleConflicts:p?Object.values(e):void 0,draws:b||o?l:void 0,events:T||o?Object.values(c):void 0,matchUps:v||o?Object.values(s):void 0,opponents:S?m:void 0,potentialMatchUps:L?Object.values(t):void 0,statistics:g?Object.values(i):void 0,scheduleItems:u?n:void 0},!1,!1,!0)},V=new Map;for(const t of Object.keys(A))V.set(t,B(A[t]));const j=[...V.values()],q=c?.[Tc],$=q?.participant,W=nh({participants:j,participantFilters:r,tournamentRecord:d});if(e){const t=G(e)?e:void 0;for(const e of W)for(const n of e.individualParticipantIds??[]){e.individualParticipants||(e.individualParticipants=[]);const r=V.get(n),i=t?Ic({template:t,source:r}):r;e.individualParticipants.push(i)}}const H=$?W.map((t=>Ic({source:t,template:$}))):W;return{participantMap:!1!==t.returnParticipantMap?A:void 0,mappedMatchUps:!1!==t.returnMatchUps?x:void 0,matchUps:!1!==t.returnMatchUps?_:void 0,missingParticipantIds:N.missingParticipantIds,participantIdsWithConflicts:C,eventsPublishStatuses:O,derivedEventInfo:F,derivedDrawInfo:k,participants:H,...z}}function ah({participantId:t,drawDefinition:e,entryStatus:n,entryStage:r}){if(!e)return{error:ot};const i=e.entries?.find((e=>!(e.participantId!==t||n&&n!==e.entryStatus||r&&r!==e.entryStage)));return t&&i}function oh(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,structureId:i,stage:a}=t;if(!n)return{error:ot};const{entryProfile:o}=Gp({drawDefinition:n}),s=a&&r&&o?.[a]?.stageSequence?.[r]?.qualifiersCount||a&&o?.[a]?.qualifiersCount||0,c={};if(!i)return{qualifiersCount:s,roundQualifiersCounts:c};const{structure:u}=ad({drawDefinition:n,structureId:i}),d=n.links?.filter((t=>t?.target?.structureId===u?.structureId));let p=0;if(d?.length)for(const t of d){const r=ad({structureId:t.source.structureId,drawDefinition:n})?.structure;if(r?.stage===ho){const n=t.source.roundNumber,i=t.target.roundNumber;let a=0;if(r.structureType===Mo){a=(r.structures?.length??0)*(t.source.finishingPositions?.length??0)}else{const t=Jm({matchUpFilters:{roundNumbers:[n]},structure:r,afterRecoveryTimes:!1,provisionalPositioning:e,inContext:!1}).matchUps;a=t?.length||0}c[i]||(c[i]=0),c[i]+=a,p+=a}}const l=Object.keys(c);if(l.length<=1){const t=l[0]||1;c[t]=Math.max(c[t]||0,s)}return p=Math.max(p,s),{qualifiersCount:p,roundQualifiersCounts:c}}function sh({stage:t,drawDefinition:e}){const{entryProfile:n}=Gp({drawDefinition:e});return n?.[t]?.drawSize||0}function ch({stage:t,drawDefinition:e}){return Boolean(t===Io||cl({stage:t,drawDefinition:e})&&sh({stage:t,drawDefinition:e}))}function uh({entryStatus:t=Wp,drawDefinition:e,stageSequence:n,stage:r}){if(t===qp)return function({stage:t,drawDefinition:e}){const{entryProfile:n}=Gp({drawDefinition:e});return n[t]?.alternates||0}({stage:r,drawDefinition:e})?{positionsAvailable:1/0,...z}:{error:gn};const i=function(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,stage:i}=t,a=sh({stage:i,drawDefinition:n}),{qualifiersCount:o}=oh({provisionalPositioning:e,drawDefinition:n,stageSequence:r,stage:i});return a&&a-o}({drawDefinition:e,stageSequence:n,stage:r}),a=function({stage:t,drawDefinition:e}){const{entryProfile:n}=Gp({drawDefinition:e});return n[t]?.wildcardsCount||0}({drawDefinition:e,stage:r}),o=ul({entryStatus:tl,drawDefinition:e,stage:r}),s=o+ul({entryStatus:Wp,drawDefinition:e,stage:r}),c=i-s;return r!==Io&&s>=i?{error:Un}:t===tl?o<a?{...z}:{error:Un}:{positionsAvailable:c,...z}}function dh(t){const e=cc(t,[{[Is]:!0,[Ms]:!0}]);if(e.error)return e;const{suppressDuplicateEntries:n=!0,entryStatus:r=Wp,entryStageSequence:i,entryStage:a=fo,ignoreStageSpace:o,drawDefinition:s,entryPosition:c,participant:u,roundTarget:d,extensions:p,extension:l,drawType:m,event:f}=t,h="addDrawEntry";if(m!==_o&&!ch({stage:a,drawDefinition:s}))return ti({result:{error:Jt},stack:h});const g=uh({stageSequence:i,stage:a,drawDefinition:s,entryStatus:r});if(!(o||g.success||m&&m===_o))return{error:g.error};if(l&&!xc({extension:l}))return ti({result:{error:Jn},info:"Invalid extension",context:{extension:l},stack:h});const I=t.participantId||u?.participantId;if(!I)return ti({result:{error:Xe},stack:h});const U=r===Yp&&ah({participantId:I,drawDefinition:s,entryStatus:r}),y=a===Io&&ah({participantId:I,drawDefinition:s,entryStage:a}),S=ah({participantId:I,drawDefinition:s}),v=r!==Yp&&a!==Io&&S;if(v)return n?(Or({payload:{drawId:s.drawId,eventId:f?.eventId,error:Z,participantId:I},topic:Id}),{...z}):ti({result:{error:Z},context:{participantId:I},stack:h});if(U||y)return ti({context:{invalidEntry:v,invalidLuckyLoser:U,invalidVoluntaryConsolation:y},result:{error:dn},stack:h});const w=Xr({entryStageSequence:i,participantId:I,entryPosition:c,entryStatus:r,entryStage:a,extensions:p});return l&&_c({element:w,extension:l}),d&&_c({extension:{name:"roundEntry",value:d},element:w}),s.entries||(s.entries=[]),s.entries.push(w),Hd({drawDefinition:s}),{...z}}function ph({suppressDuplicateEntries:t=!0,autoEntryPositions:e=!0,entryStageSequence:n,ignoreStageSpace:r,participantIds:i,drawDefinition:a,entryStatus:o,roundTarget:s,entryStage:c,extension:u,drawId:d,event:p}){if(!i?.length)return{error:an};if(!p)return{error:Wt};if(!d)return{error:Tt};const l=(p.entries||[]).map(Mu);if(i.filter((t=>!l.includes(t))).length)return{error:zt};if(a){const d=function(t){const e="addDrawEntries",{suppressDuplicateEntries:n=!0,entryStatus:r=Wp,autoEntryPositions:i=!0,ignoreStageSpace:a,participantIds:o,drawDefinition:s,stageSequence:c,stage:u=fo,roundTarget:d,extension:p,event:l}=t;if(!u)return{error:Qt};if(!s)return{error:ot};if(!Array.isArray(o))return{error:ze};if(!ch({stage:u,drawDefinition:s}))return{error:Jt};if(p&&!xc({extension:p}))return ti({result:{error:Jn},info:"Invalid extension",context:{extension:p},stack:e});const m=uh({drawDefinition:s,stageSequence:c,entryStatus:r,stage:u});if(!a&&!m.success)return{error:m.error};const f=m.positionsAvailable??0;if(!a&&u!==Io&&f<o.length)return{error:pn};const h=[],g=s.drawId,I=l?.eventId,U=o.reduce(((t,e)=>{const i=r===Yp&&ah({participantId:e,drawDefinition:s,entryStatus:r}),a=u===Io&&ah({entryStage:u,drawDefinition:s,participantId:e}),o=ah({participantId:e,drawDefinition:s});return r!==Yp&&u!==Io&&o&&(h.push(e),n&&Or({payload:{error:Z,participantId:e,eventId:I,drawId:g},topic:Id})),i||a?t.concat(e):t}),[]);return h.length&&!n?ti({context:{eventId:I,drawId:g,duplicateEntries:h},result:{error:Z},stack:e}):(o.filter((t=>t&&!U.includes(t))).forEach((t=>{const e={entryStageSequence:c,entryStage:u,participantId:t,entryStatus:r};p&&_c({element:e,extension:p}),d&&_c({extension:{name:pu,value:d},element:e}),s.entries||(s.entries=[]),s.entries.push(e)})),i&&(s.entries=jf({entries:s.entries})),Hd({drawDefinition:s}),U?.length||h?.length?{info:"some participantIds could not be added",participantIdsNotAdded:U,duplicateEntries:h,...z}:{...z})}({stageSequence:n,suppressDuplicateEntries:t,autoEntryPositions:e,stage:c,ignoreStageSpace:r,participantIds:i,drawDefinition:a,entryStatus:o,roundTarget:s,extension:u});if(d.error)return d}const{flightProfile:m}=jm({event:p}),f=m?.flights.find((t=>t.drawId===d));return f?.drawEntries&&(i.forEach((t=>{const e=o===Yp&&lh({participantId:t,entryStatus:o,flight:f}),n=c===Io&&lh({participantId:t,entryStage:c,flight:f});o!==Yp&&c!==Io&&lh({flight:f,participantId:t})||e||n||f.drawEntries.push({participantId:t,entryStatus:o,entryStage:c})})),e&&(f.drawEntries=jf({entries:f.drawEntries}))),{...z}}function lh({participantId:t,entryStatus:e,entryStage:n,flight:r}){const i=r.drawEntries?.find((r=>!(r.participantId!==t||e&&e!==r.entryStatus||n&&n!==r.entryStage)));return t&&i}function mh({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:n,stage:r,event:i}){const a="removeEventEntries";if(!i?.eventId)return{error:$t};if(!Array.isArray(e)||e.some((t=>!j(t))))return ti({result:{error:He},stack:a});const o=(i.drawDefinitions??[]).flatMap((t=>Vf({drawDefinition:t}).assignedParticipantIds??[])),s=(n?.length&&i.entries?.filter((t=>t.entryStatus&&n.includes(t.entryStatus)))||[]).map(Mu).filter((t=>!o.includes(t))),c=(r&&i.entries?.filter((t=>t.entryStage&&t.entryStage===r))||[]).map(Mu).filter((t=>!o.includes(t)));if(e.length?e=e.filter((t=>(!n?.length||s.includes(t))&&(!r||c.includes(t)))):s.length&&c.length?e=O(s,c):s.length?e=s:c.length&&(e=c),e?.length&&o.some((t=>e.includes(t))))return ti({result:{error:un},stack:a});if(!e?.length)return{...z,participantIdsRemoved:[]};const u=[];i.entries=(i.entries??[]).filter((t=>{const n=!e.includes(t?.participantId);return n||u.push(t.participantId),n})),t&&(i.entries=jf({entries:i.entries}));const{flightProfile:d}=jm({event:i});return d?.flights?.forEach((t=>{t.drawEntries=(t.drawEntries||[]).filter((t=>!e.includes(t.participantId)))})),i.drawDefinitions?.forEach((t=>{t.entries=(t.entries??[]).filter((t=>!e.includes(t.participantId)))})),{...z,participantIdsRemoved:u}}const fh={[wc]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}};function hh(t){const{suppressDuplicateEntries:e=!0,entryStatus:r=Wp,autoEntryPositions:a=!0,enforceGender:o=!0,entryStageSequence:s,policyDefinitions:c,entryStage:u=fo,tournamentRecord:d,ignoreStageSpace:p,drawDefinition:l,roundTarget:m,extensions:f,extension:h,drawId:g,event:I}=t,U="addEventEntries";if(!Array.isArray(t.participantIds))return ti({result:{error:ze},stack:U});const y=w(t.participantIds??[]);if(!I)return{error:$t};if(!y?.length)return ti({result:{error:an},stack:U});if(!I?.eventId)return{error:Wt};const S=Np({tournamentRecord:d,event:I}).appliedPolicies??{},v=c?.[wc]??S?.[wc]??fh[wc],P=!1!==(o??v?.participants?.enforceGender),D=[],T=[];if(f&&(!Array.isArray(f)||!f.every((t=>xc({extension:t}))))||h&&!xc({extension:h}))return ti({context:Xr({extension:h,extensions:f}),result:{error:Jn},info:"Invalid extension(s)",stack:U});const b=!!d,R=[];let M;const N=d?.participants?.filter((t=>{if(!y.includes(t.participantId))return!1;const e=um(n)(I.eventType)&&t.participantType===ap&&!Gf(r),a=I.eventType===i&&t.participantType===sp;return!(!e||I.gender&&P&&![ri,ei].includes(I.gender)&&I.gender!==t.person?.sex)||(!(!a||Gf(r))||(!(I.eventType!==i||t.participantType!==ap||!Gf(r))||(e&&I.gender&&P&&![ri,ei].includes(I.gender)&&I.gender!==t.person?.sex?(R.push({participantId:t.participantId,sex:t.person?.sex}),!1):I.eventType===cp&&(t.participantType===cp||Gf(r)&&t.participantType===ap))))})).map((t=>t.participantId))??[],A=y.filter((t=>!b||N.includes(t)));I.entries||(I.entries=[]);const E=I.entries.map((t=>t.participantId||t.participant?.participantId));if(A.forEach((t=>{if(!E.includes(t)){const e=Xr({participantId:t,entryStatus:r,entryStage:u,extensions:f});h&&_c({element:e,extension:h}),m&&_c({extension:{name:pu,value:m},element:e}),s&&(e.entryStageSequence=s),D.push(e.participantId),I.entries?.push(e)}})),g&&!Gf(u)){const t=ph({participantIds:A,suppressDuplicateEntries:e,autoEntryPositions:a,entryStageSequence:s,ignoreStageSpace:p,drawDefinition:l,entryStatus:r,roundTarget:m,entryStage:u,extension:h,drawId:g,event:I});t.error&&(M=t.error)}if(I.eventType&&[uo,lo].includes(I.eventType)){const t=(I.entries||[]).map((t=>t.participantId)),e=(I.entries||[]).filter((t=>Gf(t.entryStatus))).map((t=>t.participantId)),n=(d?.participants??[]).filter((e=>t.includes(e.participantId)&&e.participantType&&[sp,cp].includes(e.participantType))).map((t=>t.individualParticipantIds)).flat(1/0),r=e.filter((t=>n.includes(t)));r.length&&(T.push(...r),mh({participantIds:r,autoEntryPositions:!1,event:I}))}if(A.length!==y.length)return ti({context:{mismatchedGender:R,gender:I.gender},result:{error:ze},stack:U});a&&(I.entries=jf({entries:I.entries||[]}));const C=D.length,O=T.length;return ti({result:{...z,addedEntriesCount:C,removedEntriesCount:O},stack:U,info:M})}const gh="ADMINISTRATION",Ih="COMPETITOR",Uh="MEDIA",yh="MEDICAL",Sh="OFFICIAL",vh="OTHER",wh="SECURITY",Ph={ADMINISTRATION:gh,CAPTAIN:"CAPTAIN",COACH:"COACH",COMPETITOR:Ih,MEDIA:Uh,MEDICAL:yh,OFFICIAL:Sh,OTHER:vh,SECURITY:wh};function Dh({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:n,tournamentRecord:r,suppressErrors:i}){const a="removeIndividualParticipantIds";if(!r)return ti({result:{error:nt},stack:a});if(!n||!e)return ti({result:{error:be},stack:a});const o=(r.participants??[]).find((t=>t.participantId===n));if(!o)return ti({result:{error:en},stack:a});if(![cp,op].includes(o.participantType))return ti({result:{participantType:o.participantType,error:Ke},stack:a});const s=Th({individualParticipantIds:e,groupingParticipant:o,tournamentRecord:r,suppressErrors:i}),{removed:c,error:u}=s;if(u)return ti({result:s,stack:a});if(t)for(const t of r.events??[]){const e=(t.entries??[]).map((({participantId:t})=>t)).filter(Boolean);if(e.includes(n)){const n=c?.filter((t=>!e.includes(t)));hh({participantIds:n,entryStatus:Zp,tournamentRecord:r,event:t})}}return c&&Or({topic:bd,payload:{tournamentId:r.tournamentId,participants:[o]}}),{...z,...s}}function Th({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:n,suppressErrors:r,mappedMatchUps:i,participants:a}){const o=[];if(!e)return{removed:o};const s=[],c=[];a||({participants:a,mappedMatchUps:i}=ih({withMatchUps:!0,tournamentRecord:n,withEvents:!0}));const u=a?.find((({participantId:t})=>t===e.participantId)),d=u?.events?.map((({eventId:t})=>t)),p=(e.individualParticipantIds??[]).filter((r=>{const u=t?.includes(r),p=u&&a?.find((t=>t.participantId===r))?.matchUps.filter((({eventId:t})=>d.includes(t))).map((({matchUpId:t})=>i?.[t])).filter((({winningSide:t,score:e})=>t||vf({score:e}))),l=u&&!p?.length;if(u&&!l&&c.push(r),l){o.push(r);for(const t of n.events??[])for(const i of t.drawDefinitions??[]){const{extension:t}=zc({element:i,name:au}),a=t?.value[e.participantId];t&&a&&(t.value[e.participantId]=a.filter((t=>t.participantId!==r)),_c({element:i,extension:t}),Wd({drawDefinition:i}));const o=ff({drawDefinition:i,inContext:!1}).matchUps??[];for(const t of o){const e=t.sides??[];for(const a of e){const e=a.lineUp??[];e.find((t=>t.participantId===r))&&(a.lineUp=e.filter((t=>t.participantId!==r)),$d({tournamentId:n?.tournamentId,drawDefinition:i,matchUp:t}))}}}}else s.push(r);return!l}));e.individualParticipantIds=p;const l={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:s,removed:o};return c.length&&!r&&{...l,cannotRemove:c,error:Ge}||l}function bh({participantRole:t=Ih,individualParticipantIds:e=[],groupingTypes:n=[ip,op],tournamentRecord:r}){if(!r)return{error:nt};const i=r.participants??[],{participants:a,mappedMatchUps:o}=ih({withMatchUps:!0,tournamentRecord:r,withEvents:!0});let s=0;return i.filter((e=>(e.participantRole===t||!e.participantRole)&&e.participantType&&n.includes(e.participantType))).forEach((t=>{const{removed:n}=Th({groupingParticipant:t,individualParticipantIds:e,tournamentRecord:r,mappedMatchUps:o,participants:a});n&&s++})),s?z:{error:rn}}function Rh(t){const e=cc(t,[{[hs]:!0},{participantIds:!0,[nc]:Zs,[$s]:an}]);if(e.error)return e;const{addIndividualParticipantsToEvents:n,tournamentRecord:r,participantIds:a}=t,o=r.participants?.length||0;if(!o)return{...z};const s=(r.events||[])?.filter((({eventType:t})=>t===po)).map((t=>t?.drawDefinitions?.map((({drawId:t})=>t)))).flat(1/0),c=ih({participantFilters:{participantIds:a},tournamentRecord:r,withDraws:!0}).participants??[],u=s?.length?(t=>O((pf({matchUpFilters:{drawIds:t,matchUpTypes:[i]},tournamentRecord:r}).matchUps??[]).flatMap((({sides:t})=>t?.map((({participantId:t})=>t||[])))).filter(Boolean),a))(s):[],d=c.filter((t=>t.draws?.filter((t=>(!s?.length||!s?.includes(t.drawId))&&t.positionAssignments)).length));if(u?.length||d.length)return{error:un};const p={},l={};for(const t of r.events||[]){const e=mh({participantIds:a,event:t});if(e.error)return e;p[t.eventId]=e.participantIdsRemoved}r.participants=(r.participants??[]).filter((t=>{const e=a.includes(t.participantId)||t.participantType===sp&&t.individualParticipantIds?.some((t=>a.includes(t)));if(!e&&t.participantType===po&&t.individualParticipantIds?.some((t=>a.includes(t)))&&(t.individualParticipantIds=t.individualParticipantIds.filter((t=>!a.includes(t)))),e&&n&&t.participantType&&[sp,cp].includes(t.participantType))for(const e of t.individualParticipantIds||[])a.includes(e)||(l[t.participantId]||(l[t.participantId]=[]),l[t.participantId].push(e));return!e}));const m=o-r.participants.length;if(bh({individualParticipantIds:a,tournamentRecord:r}),n)for(const t of r.events||[]){hh({participantIds:p[t.eventId].map((t=>l[t]||[])).flat(),entryStatus:Zp,tournamentRecord:r,event:t})}return m&&Or({payload:{participantIds:a,tournamentId:r.tournamentId},topic:Ud}),m?{...z,participantsRemovedCount:m}:{error:Ge}}function Mh({selected:t=!0,drawDefinition:e,entryStatuses:n,drawId:r,event:i,stage:a}){let o=i.entries??[];if(r){const{flightProfile:t}=jm({event:i}),n=t?.flights?.find((t=>t.drawId===r));n?o=n.drawEntries:e.entries&&(o=e?.entries)}const s=o.filter((e=>(!n?.length||!e.entryStatus||n.includes(e.entryStatus))&&(!a||!e.entryStage||e.entryStage===a)&&(!t||e.entryStatus&&al.includes(e.entryStatus))));return{entries:o,stageEntries:s}}function Nh({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,stage:a,event:o}){const s="destroyGroupEntry";if(!e)return{error:nt};if(!r)return ti({result:{error:Xe},stack:s});if(!o)return{error:$t};if(!o.eventType||![uo,lo].includes(o.eventType))return ti({result:{error:qt},stack:s});const c=e.participants??[],u=c.find((t=>t.participantId===r));if(!u)return ti({result:{error:en},stack:s});if(!u.participantType||![sp,ip].includes(u.participantType)||u.participantType===ip&&o.eventType!==lo||u.participantType===sp&&o.eventType!==uo)return{error:Ke};const d=(o.entries??[]).find((t=>t.participantId===r));if(!d)return{error:mn};const{stageEntries:p}=Mh({selected:!1,drawDefinition:n,drawId:i,event:o,stage:a}),l=p.map(Mu),m=c.filter((({participantId:t})=>l.includes(t))).map((({individualParticipantIds:t})=>t)).flat().filter(Boolean),f=u.individualParticipantIds?.filter((t=>1===C(t,m).length));let h,g=mh({participantIds:[r],event:o});if(g.error)return g;if(f?.length&&(g=hh({participantIds:f,entryStatus:Zp,entryStage:d.entryStage,tournamentRecord:e,drawDefinition:n,drawId:i,event:o}),g.error))return g;if(t){Rh({participantIds:[r],tournamentRecord:e}).success&&(h=!0)}return{...z,participantRemoved:h}}function Ah({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:a}){return Nh({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:a})}function Eh(t){if(!t.tournamentRecord)return{error:nt};const{participantIds:e,...n}=t;let r=0;const i=[];for(const t of e){const e=Nh({participantId:t,...n});e.success&&(r+=1),e.error&&i.push(e.error)}return r?{destroyedCount:r,...z}:{error:i}}function Ch(t){const{tournamentRecord:e,replaceWithBye:n,drawDefinition:r,destroyPair:i,entryStatus:a,matchUpsMap:o,drawId:s}=t,c="removeDrawPositionAssignment",u=_f(t);if(u.error)return ti({result:u,stack:c});const{participantId:d}=u,{drawPosition:p,event:l,structureId:m}=t,f=Np({tournamentRecord:e,drawDefinition:r,event:l}).appliedPolicies??{};if([qp,el].includes(a)&&d){const{tournamentRecord:e}=t,{participant:n}=hp({tournamentRecord:e,participantId:d}),{participantType:o,individualParticipantIds:u}=n??{};if(i&&o===sp){const t=Ah({tournamentRecord:e,drawDefinition:r,participantId:d,event:l});if(t.error)return ti({result:t,stack:c});u&&qf({participantIds:u,tournamentRecord:e,drawDefinition:r,entryStatus:a,drawId:s,event:l})}else qf({participantIds:[d],tournamentRecord:e,drawDefinition:r,entryStatus:a,drawId:s,event:l})}if(n){const t=Ef({tournamentRecord:e,drawDefinition:r,drawPosition:p,structureId:m,matchUpsMap:o,event:l});if(t.error)return ti({result:t,stack:c})}const{structure:h}=ad({drawDefinition:r,structureId:m});Qd({structure:h,drawPositions:[p]});return Jd({appliedPolicies:f,drawDefinition:r,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:n,drawPosition:p,entryStatus:a,structureId:m}}),u}function Oh(t){return Object.assign(t,{entryStatus:el}),Ch(t)}const Fh=({finishingPosition:t=ds,hasExistingDrawDefinition:e,qualifyingRoundNumber:n,structureAbbreviation:r,seedAssignments:i=[],stageSequence:a=1,qualifyingOnly:o,structureOrder:s,seedingProfile:c,matchUpFormat:u,structureType:d,structureName:p,matchUps:l=[],matchUpType:m,structureId:f,roundOffset:h,roundLimit:g,stageOrder:I,structures:U,tieFormat:y,stage:S})=>{const v={structureId:f??ha(),structureAbbreviation:r,finishingPosition:t,seedAssignments:i,matchUpFormat:u,stageSequence:a,structureName:p};(o||e&&y)&&(v.tieFormat=y),s&&(v.structureOrder=s),d&&(v.structureType=d),c&&("string"==typeof c?v.seedingProfile=c:"object"==typeof c&&"string"==typeof c.positioning&&(v.seedingProfile=c.positioning)),m&&(v.matchUpType=m),h&&(v.roundOffset=h),I&&(v.stageOrder=I),g&&(v.roundLimit=g),S&&(v.stage=S),n&&(v.qualifyingRoundNumber=n);const P=l.flatMap((({drawPositions:t})=>t)).filter(Boolean);return U?v.structures=U:(v.matchUps=l,v.positionAssignments=w(P).sort(((t,e)=>t-e)).map((t=>({drawPosition:t})))),v};function kh(t){return j(t)?t.split(" ").map((t=>t.split("").map(((t,e)=>e?t.toLowerCase():t.toUpperCase())).join(""))).join(" "):t}function xh(t){return j(t)?kh(t.replace(/_/g," ")):""}function _h({structureName:t=xh(Io),structureAbbreviation:e,drawDefinition:n,matchUpType:r,structureId:i}){if(!n)return{error:ot};const a=Fh({stage:Io,structureAbbreviation:e,structureName:t,matchUps:[],structureId:i,matchUpType:r});return n.structures||(n.structures=[]),n.structures.push(a),Hd({drawDefinition:n,structureIds:[a.structureId]}),{...z}}function Lh({drawPositions:t}){if(!t?.length)return{error:gt};const e=[].concat(...(t??[]).map((e=>t.filter((t=>t!==e)).map((t=>[e,t]))))),n=w(e.map(Bh)).map((t=>t.split("|").map((t=>+t))));return{groupMatchUps:e,uniqueMatchUpGroupings:n}}function Bh(t=[]){return Array.isArray(t)&&t.length?[...t].sort(u).join("|"):""}function Vh({groupSize:t,drawPositionOffset:e}){if(!t)return[];const n=t=>[...Array(t)].map(((t,e)=>e)),r=n(2*Math.round(t/2)+1).slice(1),i=n(r.length-1).map((()=>[]));let a=r.slice(0,r.length/2),o=r.slice(r.length/2);r.slice(1).forEach(((t,e)=>{a.forEach(((t,n)=>{i[e].push([a[n],o[n]])}));const n=a.shift(),r=a.pop(),s=o.shift();a=[n,s,...a].filter(Boolean),o=[...o,r].filter(Boolean)}));const s=a.shift(),c=a.pop(),u=o.shift();a=[s,u,...a].filter(Boolean),o=[...o,c].filter(Boolean);const d=t=>t[0].reduce(((t,e)=>t+e));return[...i].reverse().sort(((t,e)=>d(t)-d(e))).map((n=>n.filter((e=>e.every((e=>e<=t)))).map((t=>Bh(t.map((t=>t+e)))))))}const jh={getRoundRobinGroupMatchUps:Lh,determineRoundNumber:function({rounds:t,hash:e}){return t?.length?t?.reduce(((t,n,r)=>n.includes(e)?r+1:t),void 0):{error:be}},drawPositionsHash:Bh,groupRounds:Vh};function Gh(t){const{hasExistingDrawDefinition:e,groupNameBase:n="Group",playoffAttributes:r,stageSequence:i=1,structureOptions:a,appliedPolicies:o,qualifyingOnly:s,seedingProfile:c,stage:u=fo,matchUpType:d,roundTarget:p,structureId:l,groupNames:m,tieFormat:f,drawSize:h,idPrefix:g,isMock:I,uuids:U}=t,y=t.structureName??r?.[0]?.name??xh(fo),{groupCount:S,groupSize:v}=function({appliedPolicies:t,structureOptions:e,drawSize:n}){let r=e?.groupSize;const i=e?.groupSizeLimit||8,{validGroupSizes:a}=qh({groupSizeLimit:i,drawSize:n}),o=a&&Math.max(...a),s=r&&a?.includes(r);s||(r=r&&r>4||!a?.includes(4)?o:4);const c=Math.ceil(n/r);return{groupSize:r,groupCount:c}}({structureOptions:a,appliedPolicies:o,drawSize:h}),w=us;let P;const D=E(1,S+1).map((t=>{const r=function({structureOrder:t,matchUpType:e,groupSize:n,drawSize:r,idPrefix:i,isMock:a,uuids:o}){const s=(t-1)*n,c=E(1+s,n+1+s),u=Lh({drawPositions:c}).uniqueMatchUpGroupings??[],d=Vh({groupSize:n,drawPositionOffset:s}),p=u.map(m).sort(((t,e)=>(t.roundNumber??1/0)-(e.roundNumber??1/0)));return p;function l(t){return d.reduce(((e,n,r)=>n.includes(t)?r+1:e),void 0)}function m(n){const s=l(Bh(n)),c=[1,r],u=function({structureOrder:t,drawPositions:e,roundNumber:n,idPrefix:r,uuids:i}){return r?`${r}-${t}-${n}-DP-${e.join("-")}`:i?.pop()||ha()}({structureOrder:t,drawPositions:n,roundNumber:s,idPrefix:i,uuids:o}),d={matchUpStatus:s?Hu:Fu,matchUpType:e,finishingPositionRange:{winner:c,loser:c},drawPositions:n,roundNumber:s,matchUpId:u};return a&&(d.isMock=!0),d}}({groupSize:v,structureOrder:t,matchUpType:d,drawSize:h,idPrefix:g,isMock:I});P=Array.isArray(r)?Math.max(...r.map((({roundNumber:t})=>t??0))):0;const i=m?.[t-1]??`${n} ${t}`;return Fh({structureId:U?.pop(),hasExistingDrawDefinition:e,structureType:Ro,finishingPosition:w,qualifyingOnly:s,structureOrder:t,structureName:i,tieFormat:f,matchUps:r})})),T=Fh({structureId:l??U?.pop(),hasExistingDrawDefinition:e,structureType:Mo,finishingPosition:w,seedingProfile:c,structureName:y,stageSequence:i,structures:D,tieFormat:f,stage:u});return p&&_c({extension:{name:pu,value:p},element:T}),{structures:[T],maxRoundNumber:P,groupCount:S,links:[],groupSize:v,...z}}function qh(t){const{groupSizeLimit:e=10,drawSize:n=0}=t??{},r=E(3,e+1).filter((t=>{const e=Math.ceil(n/t),r=e*t-n,i=Math.ceil(n/e),a=Math.ceil(r/e);return(!r||r<t)&&i===t&&i>=3&&a<2}));return{...z,validGroupSizes:r}}function $h(t){const{roundRobinGroupsCount:e,participantsCount:n,cluster:r}=t;if(!y(n))return{seedBlocks:void 0,...ti({result:{error:Jn},context:{participantsCount:n},stack:"getSeedBlocks"})};const i=I(n);if(e){const t=Math.min(e,i),n=[];let r=1;for(E(0,t).forEach((()=>{n.push([r]),r++}));r<i;){const e=E(r,r+t);r+=t,n.push(e)}return{...z,seedBlocks:n}}const a=E(1,i+1),o=[];let s=i/2;for(;s>1;){const t=x(a,s),e=t.length;t.forEach(((t,n)=>{let i;const a=n<e/2,s=n%2==0,c=t[0],u=t[t.length-1];i=r&&e>4?8===e?a?u:c:s?c:u:a?c:u,k(t,o)||o.push(i)})),s/=2}const c=a.filter((t=>!o.includes(t)));for(;c.length;)c.length%2==0?o.push(c.pop()):o.push(c.shift());const u=E(0,20).map((t=>Math.pow(2,t)));u.unshift(1);const d=u.indexOf(i);let p=0;const l=[];return E(0,d).forEach((t=>{l.push(o.slice(p,p+u[t])),p+=u[t]})),{...z,seedBlocks:l}}function Wh({roundRobinGroupsCount:t,drawSize:e}){const n="getSeedGroups";if(!y(e))return{seedGroups:void 0,...ti({result:{error:Jn},context:{drawSize:e},stack:n})};if(t){if(!y(t))return{seedGroups:void 0,...ti({context:{roundRobinGroupsCount:t},result:{error:Jn},stack:n})};let r=1;return{seedGroups:E(0,Math.floor(e/t)).map((()=>{const e=E(r,r+t);return r+=t,e}))}}{const{seedBlocks:n}=$h({participantsCount:e,roundRobinGroupsCount:t});let r=0;return{seedGroups:(n||[]).map((t=>(t||[]).map((()=>(r+=1,r)))))}}}function Hh({roundRobinGroupsCount:t,participantsCount:e}){if(t){const{validGroupSizes:n}=qh({drawSize:e}),r=n?.map((t=>Math.ceil(e/t)));if(!r?.includes(t))return ti({context:{roundRobinGroupsCount:t},result:{error:Jn}})}const{seedGroups:n}=Wh({drawSize:e,roundRobinGroupsCount:t}),r=n?.map((t=>Math.min(...t)))||[];return{...z,seedingThresholds:r}}function zh(t){if(!t)return 1/0;if(y(t))return d(t);const e=t.split("-")[0];return y(e)?d(e):1/0}function Yh({positioning:t,size:e}){const n=function({size:t}){const e=[t];let n=t;for(;n/2===Math.floor(n/2);)n/=2,e.push(n);return e.includes(1)||e.push(1),e.sort(u),e.reverse(),e}({size:e}),r=[],i=[],a=t=>t[0],o=(e,n)=>(t&&[To,bo].includes(t)&&n%2?(t=>t[t.length-1])(e):a(e))||a(e),s=(t,e)=>{if(t.every((t=>!i.includes(t)))){const n=o(t,e);return i.push(n),n}},c=t=>{const e=t.filter((t=>!i.includes(t)));if(e.length)return i.push(...e),e},d=(t,e)=>{const n=o(t,e);if(!i.includes(n))return i.push(n),n},p=E(1,e+1);for(const t of n)if(1===t){const t=x(p,2),e=t.map(s).filter(Boolean);e.length&&r.push(e);const n=t.flatMap(c).filter(Boolean);n.length&&r.push(n)}else{const e=x(p,t).map(d).filter(Boolean);e.length&&r.push(e)}return{divisions:n,divisionGroupings:r}}function Kh({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:n,seedingProfile:r,drawDefinition:i,allPositions:a,structure:o}){let s=[];if(!o)return{error:Vt};const{matchUps:c,roundMatchUps:u}=Jm({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:o}),{seedAssignments:d}=pl({provisionalPositioning:t,returnAllProxies:e,drawDefinition:i,structure:o}),{positionAssignments:p}=ud({structure:o}),l=p?.length,m=d?.length??0;let f=[];const h=Object.keys(u).map((t=>parseInt(t))).sort(((t,e)=>t-e)).map((t=>{const e=u[t].map((t=>t.drawPositions)).flat(1/0).filter(Boolean),n=e.filter((t=>!f.includes(t)));return f=f.concat(...e),n})).filter((t=>t.length)).reverse(),g=h.pop()??[],I=g&&Math.min(...g)-1||0;r=r??n?.seeding?.seedingProfile;const U=g?.length||0,y=h.filter((t=>t.filter((t=>t<=m)).length)),{stage:S,structureType:v,roundLimit:w}=o,P=v===Mo,D=!P&&h?.length,T=!P&&S===ho&&w,b=y.flat(1/0),R=D?b?.length:0,M=a?l:m,N=Pl({drawDefinition:i,structure:o,matchUps:c}),A=N?0:!D&&M||M&&b.length<M&&M-b.length||0;if(T){const t=o?.matchUps?o.matchUps.filter((({roundNumber:t})=>t===o.roundLimit)).length:0,e=g.length/t;if(D);else{const t=Xh(r),n=x(g,e);let i=1;const a=E(0,n[0].length).map((()=>{const t=E(i,i+n.length);return i+=n.length,t}));({validSeedBlocks:s}=Qh({drawPositionBlocks:n,nonRandom:r?.nonRandom,positioning:t,seedGroups:a}))}}else if(P){const t=function({seedingProfile:t,structure:e,nonRandom:n}){const r=e.structures||[],i=r.length,a=cd({structure:e})?.positionAssignments,o=Xh(t),s=a?.length??0,{seedGroups:c}=Wh({roundRobinGroupsCount:i,drawSize:s});return Qh({drawPositionBlocks:r.map((t=>cd({structure:t}).positionAssignments?.map((t=>t.drawPosition)))),positioning:o,seedGroups:c,nonRandom:n})}({nonRandom:r?.nonRandom,seedingProfile:r,structure:o});({validSeedBlocks:s}=t)}else if(D)s=y.map((t=>({seedNumbers:t,drawPositions:t})));else if(N){x(g,2).map(((t,e)=>({drawPositions:[t[0]],seedNumbers:[e+1]}))).forEach((t=>s.push(t)))}if(!P&&!N&&!T){const{blocks:t}=function(t){const{drawPositionOffset:e=0,roundRobinGroupsCount:n,seedNumberOffset:r=0,seedingProfile:i,seedCountGoal:a,baseDrawSize:o}=t;let s=1;const c=[],{seedBlocks:u}=$h({cluster:Xh(i)===To,participantsCount:o,roundRobinGroupsCount:n});s=0;for(const t of u){if(s+1>a)break;const n=t.map((t=>t+e)),i=d(s+1,t.length).map((t=>+t+r));s+=t.length,c.push({drawPositions:n,seedNumbers:i})}return{blocks:c};function d(t,e){return Array.from(new Array(e),((e,n)=>n+t))}}({drawPositionOffset:I,seedNumberOffset:R,seedCountGoal:A,seedingProfile:r,baseDrawSize:U});t.forEach((t=>s.push(t)))}const C=s.flatMap((t=>t.drawPositions)).reduce(((t,e)=>g?.includes(e)&&t),!0);return N||D||P||C?{isLuckyStructure:N,validSeedBlocks:s,isContainer:P,isFeedIn:D}:{error:Ft,validSeedBlocks:[],isContainer:P,isFeedIn:D}}function Qh({drawPositionBlocks:t,positioning:e,seedGroups:n,nonRandom:r}){const i=[],{divisionGroupings:a}=Yh({size:n.length,positioning:e}),o=[];return n.forEach(((n,s)=>{const c=function({blockPattern:t,index:e}){let n=0;for(const r of t){if(n===e)return r;let t=0;for(;t<r.length;){if(n===e)return r;n+=1,t++}}}({blockPattern:a,index:s});n.forEach(((n,a)=>{const u=s%2?t.length-a-1:a;let d=t[u].slice().filter(((t,e)=>c.includes(e+1)&&t));e!==bo?d=r?d:P(d):s%2&&d.reverse();const p=d.find((t=>!o.includes(t)));p&&(o.push(p),i.push({drawPositions:[p],seedNumbers:[n]}))}))})),{validSeedBlocks:i}}function Jh({appliedPolicies:t,drawDefinition:e,seedBlockInfo:n,drawPosition:r,structureId:i,seedNumber:a}){const{structure:o}=ad({drawDefinition:e,structureId:i});t||(t=Np({drawDefinition:e}).appliedPolicies);let s=n?.validSeedBlocks;if(!s&&o&&(s=Kh({appliedPolicies:t,drawDefinition:e,structure:o})?.validSeedBlocks),t?.seeding?.validSeedPositions?.ignore)return!0;if(t?.seeding?.validSeedPositions?.strict){const t=s.find((t=>t.seedNumbers.includes(a)));return(t?.drawPositions||[]).includes(r)}return[].concat(...s.map((t=>t.drawPositions))).includes(r)}function Zh(t){const{provisionalPositioning:e,drawDefinition:n,seedingProfile:r,seedBlockInfo:i,structureId:a,randomize:o}=t,{structure:s}=ad({drawDefinition:n,structureId:a}),{seedAssignments:c}=pl({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:n,structure:s}),{positionAssignments:u}=ud({structure:s}),d=u?.filter((t=>t.participantId??t.bye??t.qualifier)),p=d?.map((t=>t.drawPosition)).filter(Boolean),{appliedPolicies:l}=Np({drawDefinition:n}),m=(i?.validSeedBlocks||s&&Kh({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:l,drawDefinition:n,seedingProfile:r,structure:s})?.validSeedBlocks||[]).filter((t=>t.drawPositions.filter((t=>!p?.includes(t))).length))[0],f=c?.map((t=>t.participantId)).filter(Boolean),h=u?.map((t=>t.participantId)).filter(Boolean),g=f?.filter((t=>h?.includes(t))),I=f?.filter((t=>!h?.includes(t))),U=c?.filter((t=>I?.includes(t.participantId))),y=c?.filter((t=>!t.participantId)),S=(U?.length&&U.length>0?U.length:y?.length??0)&&m?.drawPositions.filter((t=>!p?.includes(t)))||[],v=o?P(S):S,w=[],D=v.map((()=>{const t=function(t,e){const n=t.filter((t=>!e.includes(t.participantId))),r=Math.min(...n.map((t=>zh(t.seedValue)))),i=n.filter((t=>zh(t.seedValue)===r));return P(i).pop()}(U,w),e=t?.participantId;return e&&w.push(e),e})).filter(Boolean),T=c?.filter((t=>g?.includes(t.participantId))).map((t=>t.seedNumber)),b=(m?.seedNumbers||[]).filter((t=>!T?.includes(t))),R=c?.filter((t=>b.includes(t.seedNumber))).map((t=>t.participantId)),M=l?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:m,unplacedSeedParticipantIds:void 0===M||M?D:R,unplacedSeedNumbers:b,unfilledPositions:v,unplacedSeedAssignments:U}}function Xh(t){return"string"==typeof t?t:"object"==typeof t?t.positioning:void 0}function tg({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,seedingProfile:r,participantId:i,seedBlockInfo:a,structureId:o,seedNumber:s,seedValue:c,eventId:u,event:d}){const p="assignSeed",{structure:l}=ad({drawDefinition:n,structureId:o}),{positionAssignments:m}=ud({structure:l}),f=pl({provisionalPositioning:t,drawDefinition:n,structure:l}).seedAssignments,h=f.map((t=>t.seedNumber)),g=ah({drawDefinition:n,participantId:i});if(i&&!g)return ti({result:{error:He},context:{participantId:i},stack:p});const I=d?jm({event:d}).flightProfile?.flights?.length:0,U=I&&I>1,y=m?.find((t=>t.participantId===i)),S=y?.drawPosition;if(S){if(!Jh({drawPosition:S,drawDefinition:n,seedBlockInfo:a,structureId:o,seedNumber:s}))return ti({result:{error:pt},context:{assignedDrawPosition:S},info:"invalid seed position",stack:p})}let v;return h.includes(s)||f.push({seedNumber:s,seedValue:c}),f.forEach((t=>{t.participantId===i&&t.seedNumber!==s&&(t.participantId=void 0),t.seedNumber===s&&(t.participantId=i,r?.groupSeedingThreshold||U||(t.seedValue=c??s),v=!0)})),v?(zd({tournamentId:e?.tournamentId,drawDefinition:n,structure:l,eventId:u}),{...z}):ti({result:{error:Ot},stack:p})}function eg({inContextTargetMatchUp:t,drawPositionSideIndex:e,teamParticipantId:n,tournamentRecord:r,drawDefinition:i,matchUp:a,event:o}){const s=t?.sides?.[e]?.sideNumber,c=s&&a.sides?.find((t=>t.sideNumber===s)),{extension:u}=zc({element:i,name:au}),d=la((u?.value||{})[n],!1,!0);if(c)a?.sides?.forEach((t=>{t.sideNumber===s&&(t.lineUp=d)}));else{a.sides=[1,2].map((t=>({...a.sides?.find((e=>e.sideNumber===t))??{},sideNumber:t})));const t=a.sides.find((t=>t.sideNumber===s));t&&(t.lineUp=d)}$d({tournamentId:r?.tournamentId,context:"updateSidLineUp",eventId:o?.eventId,drawDefinition:i,matchUp:a})}function ng(t){let{sourceMatchUp:e}=t;const{targetMatchUp:n,structure:r,matchUpsMap:i,drawPosition:a}=t,o=n.roundNumber>1&&n.roundNumber-1,s=gl({structureId:r.structureId,matchUpsMap:i});!e&&a&&(e=s.find((({drawPositions:t,roundNumber:e})=>e===o&&t?.includes(a))));const c=e?.roundPosition,u=c+(c%2?1:-1),d=o&&s.find((({roundNumber:t,roundPosition:e})=>t===o&&e===u)),p=d?.matchUpStatus;return{pairedPreviousMatchUp:d,pairedPreviousMatchUpIsDoubleExit:[Vu,Bu].includes(p)}}function rg({structureId:t,matchUpsMap:e,matchUp:n}){const r=n?.roundPosition,i=r+(r%2?1:-1);return{pairedPreviousMatchUp:gl({matchUpsMap:e,structureId:t}).find((({roundNumber:t,roundPosition:e})=>t===n?.roundNumber&&e===i))}}function ig({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:r,matchUp:i}){const a=t.find((t=>t.matchUpId===n)),{pairedPreviousMatchUp:o}=rg({structureId:a?.structureId,matchUp:a,matchUpsMap:r});if(a&&o){const n=o?.matchUpId,r=t.find((t=>t.matchUpId===n)),s=a?.structureId===r?.structureId?a?.roundPosition<r?.roundPosition?1:2:a.structureId===r?.structureId?2:1;i.matchUpStatusCodes=(i.matchUpStatusCodes??[]).map((t=>{const n=j(t)||!isNaN(t)?{code:t}:t;return n.sideNumber===s?{...n,previousMatchUpStatus:e}:n}))}}function ag({inContextDrawMatchUps:t,drawPosition:e,matchUpId:n}){const r=t.filter((({winnerMatchUpId:t,loserMatchUpId:e})=>e===n||t===n)).sort(((t,e)=>t.roundPosition-e.roundPosition));return t.find((t=>t.matchUpId===n)).feedRound?1:r.reduce(((t,n,r)=>n.drawPositions?.includes(e)?r+1:t),void 0)}function og({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:n,sourceMatchUpId:r,drawDefinition:i,matchUpStatus:a,drawPosition:s,matchUpsMap:c,matchUpId:d,event:p}){const l="assignMatchUpDrawPosition";c||(c=hl({drawDefinition:i})),t||(t=cf({inContext:!0,drawDefinition:i,matchUpsMap:c}).matchUps??[]);const m=t.find((t=>t.matchUpId===d)),f=m?.structureId,h=i?.structures?.find((t=>t.structureId===f));if(!h)return{error:Lt};const g=c?.drawMatchUps?.find((t=>t.matchUpId===d)),I=g?.drawPositions??[],{positionAdded:U,positionAssigned:y,updatedDrawPositions:S}=function({drawPosition:t,drawPositions:e}){let n=!1,r=!!e?.includes(t);return{updatedDrawPositions:r?e||[]:[...e,void 0,void 0].slice(0,2).map((e=>e||r?e:(r=!0,n=!0,t))).sort(u).filter(Boolean),positionAdded:n,positionAssigned:r}}({drawPositions:I,drawPosition:s}),{positionAssignments:v}=cd({drawDefinition:i,structure:h}),w=v?.filter((t=>S.includes(t.drawPosition))),P=w?.find((({bye:t})=>t)),D=g?.matchUpStatus&&[zu,Lu].includes(g.matchUpStatus)&&S.filter(Boolean).length<2;if(a=P&&Fu||a||D&&g.matchUpStatus||g?.matchUpStatus&&[Vu,Bu].includes(g.matchUpStatus)&&g.matchUpStatus||Hu,g&&U){t=cf({inContext:!0,drawDefinition:i,matchUpsMap:c}).matchUps??[];const o=D&&ag({inContextDrawMatchUps:t,drawPosition:s,matchUpId:d})||void 0;g?.matchUpStatusCodes&&ig({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:c,matchUp:g}),Object.assign(g,{drawPositions:S,winningSide:o,matchUpStatus:a}),$d({tournamentId:n?.tournamentId,eventId:m?.eventId,context:l,drawDefinition:i,matchUp:g})}const T=rf({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:i,matchUpId:d}),{targetMatchUps:{winnerMatchUp:b,loserMatchUp:R,loserTargetDrawPosition:M},targetLinks:{loserTargetLink:N}}=T,A=gl({structureId:h.structureId,matchUpsMap:c});if(y&&P){if(b)if([Fu,Vu,Bu].includes(a)){const e=og({matchUpId:b.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:s,matchUpsMap:c});if(e.error)return e}else{const{structureId:t}=b;t!==h.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(b&&m&&!m.feedRound){const{pairedPreviousMatchUpIsDoubleExit:e}=ng({targetMatchUp:g,drawPosition:s,matchUpsMap:c,structure:h});if(e){const e=og({matchUpId:b.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:s,matchUpsMap:c});if(e.error)return e}}if(g?.matchUpType===o){const e=t?.find((({matchUpId:t})=>t===g.matchUpId)),r=(e?.sides??[]).reduce(((t,e,n)=>e.drawPosition===s?n:t),void 0),a=v?.find((t=>t.drawPosition===s))?.participantId;a&&void 0!==r&&eg({inContextTargetMatchUp:e,drawPositionSideIndex:r,teamParticipantId:a,tournamentRecord:n,drawDefinition:i,matchUp:g})}if(N?.linkCondition===xo&&2===S.filter(Boolean).length&&!P){const t=A.filter((({drawPositions:t,roundNumber:e})=>1===e&&k(t,S))),e=t.every((({matchUpStatus:t})=>[xu,$u].includes(t)));if(e&&R){const{structureId:t}=R,e=Ef({drawPosition:M,tournamentRecord:n,drawDefinition:i,structureId:t,matchUpsMap:c,event:p});if(e.error)return e}}return y?{...z}:ti({result:{error:lt},context:{drawPosition:s},stack:l})}function sg({inContextDrawMatchUps:t,drawDefinition:e,assignments:n,matchUpsMap:r,structure:i}){const a=Zd({drawDefinition:e})?.containedStructures,o=a?.[i.structureId]?.map((({structureId:t})=>t))||[];o.push(i?.structureId);const s=n?.map((({drawPosition:t})=>t))||[],c=t?.filter((t=>o.includes(t.structureId)&&O(t.drawPositions??[],s).length))??[],u=c.map((({matchUpId:t})=>t)),d=r?.drawMatchUps?.filter((t=>u.includes(t.matchUpId)))??[];return{drawPositions:s,matchUps:d,targetMatchUps:c}}function cg({lineUp:t}){if(!Array.isArray(t))return;const e={};return w(t.flatMap((({collectionAssignments:t})=>t?.map((({collectionId:t,collectionPosition:e})=>[t,e].join("|"))))).filter(Boolean)).forEach((n=>{const[r,i]=n.split("|"),a=parseInt(i),{assignedParticipantIds:o}=$m({collectionPosition:a,collectionId:r,lineUp:t});o.forEach((t=>{e[t]||(e[t]=[]),e[t].push({collectionId:r,collectionPosition:a})}))})),Object.keys(e).map((t=>({participantId:t,collectionAssignments:e[t]})))}function ug(t){return`${t} must be an array`}function dg({lineUp:t,tieFormat:e}){const n=[];if(!Array.isArray(t))return n.push(ug("lineUp")),{valid:!1,errors:n,error:Jn};const r=t.every((t=>{if("object"!=typeof t)return n.push("lineUp entries must be objects"),!1;const{participantId:e,collectionAssignments:r}=t;return e?"string"!=typeof e?(n.push("participantIds must be strings"),!1):Array.isArray(r)?r.every((t=>{if("object"!=typeof t)return n.push("collectionAssignments must be objects"),!1;const{collectionPosition:e}=t;return"number"==typeof e||(n.push("collectionPosition must be a number"),!1)})):(n.push(ug("collectionAssignments")),!1):(n.push("Missing participantId"),!1)})),i=w(t.map(Mu)).length===t.length;i||n.push("Duplicated participantId(s)");return{valid:r&&i,errors:n,error:n.length?Jn:void 0}}function pg({drawDefinition:t,participantId:e,tieFormat:n,lineUp:r}){if("object"!=typeof t)return{error:ot};if("string"!=typeof e)return{error:Xe};const i=dg({lineUp:r,tieFormat:n});if(!i.valid)return i;const{extension:a}=zc({element:t,name:au}),o=a?.value||{};o[e]=cg({lineUp:r});return _c({element:t,extension:{name:au,value:o}}),Wd({drawDefinition:t}),{...z}}function lg({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,assignments:o,structure:s,event:c}){if(!r)return{error:ot};const{drawPositions:u,matchUps:d,targetMatchUps:p}=sg({inContextDrawMatchUps:t,matchUpsMap:i,assignments:o,structure:s});for(const t of p)t.matchUpType===a&&(t.sides??[]).forEach(((i,a)=>{if(i?.drawPosition&&u?.includes(i.drawPosition)){const o=d.find((({matchUpId:e})=>e===t.matchUpId));if(o?.sides?.[a]){if(delete o.sides[a].lineUp,!1===e){const e=t.tieFormat,n=i.participantId;e&&n&&pg({drawDefinition:r,participantId:n,lineUp:[],tieFormat:e})}$d({tournamentId:n?.tournamentId,context:"resetLineUps",eventId:c?.eventId,drawDefinition:r,matchUp:o})}}}));return{...z}}function mg({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:n,sourceMatchUpStatus:r,tournamentRecord:i,drawDefinition:a,seedingProfile:s,participantId:c,seedBlockInfo:u,drawPosition:d,matchUpsMap:p,structureId:l,event:m}){const f="assignDrawPosition";if(!c&&!n)return ti({result:{error:Xe},stack:f});p=p??hl({drawDefinition:a}),e||({matchUps:e}=cf({inContext:!0,drawDefinition:a,matchUpsMap:p}));const h=ad({drawDefinition:a,structureId:l});if(h.error)return ti({result:h,stack:f});const{structure:g}=h;if(!g)return{error:Lt};if(Dl({structure:g}))return ti({result:{error:he},stack:f});const{seedAssignments:I}=pl({provisionalPositioning:t,drawDefinition:a,structure:g}),U=I?.find((t=>t.participantId===c)),y=U?.seedNumber,{appliedPolicies:S}=Np({tournamentRecord:i,drawDefinition:a,structure:g,event:m});if(y){if(!Jh({seedNumber:y,appliedPolicies:S,drawDefinition:a,seedBlockInfo:u,drawPosition:d,structureId:l}))return ti({result:{error:pt},context:{drawPosition:d},stack:f})}const v=ud({structure:g}).positionAssignments||[],w=v?.find((t=>t.drawPosition===d));if(!w)return ti({result:{error:yt},context:{drawPosition:d},stack:f});const P=v?.map(Mu).includes(c);if(P)return ti({result:{error:un},context:{drawPosition:d},stack:f});const{containsParticipant:D,containsBye:T}=function(t){const e=t.bye,n=t.qualifier,r=t.participantId,i=e||n||r;return{containsBye:e,containsQualifier:n,containsParticipant:r,filled:i}}(w);if(T){const t=_f({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,drawPosition:d,structureId:l,matchUpsMap:p,event:m});if(t.error)return ti({result:t,stack:f})}if(D&&w.participantId!==c){const{activeDrawPositions:t}=Tf({drawDefinition:a,structureId:l});if(t.includes(d))return ti({result:{error:It},stack:f});lg({assignments:[w],inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,matchUpsMap:p,structure:g})}w.participantId=c,n&&(w.qualifier=!0);if(g.stage===fo&&(!g.stageSequence||g.stageSequence>1)||g.stage&&[go,Uo].includes(g.stage)){const e=g.stage===ho?ho:fo,n=a.structures?.find((t=>t?.stage===e&&1===t?.stageSequence)),r=(n?.seedAssignments??[]).find((t=>t.participantId===c));if(r?.participantId){const{participantId:e,seedNumber:n,seedValue:o}=r;tg({eventId:m?.eventId,provisionalPositioning:t,tournamentRecord:i,drawDefinition:a,seedingProfile:s,participantId:e,seedNumber:n,seedValue:o,structureId:l,event:m})}}if(g.structureType!==Mo)!function({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:r,drawDefinition:i,drawPosition:a,matchUpsMap:o,structure:s,event:c}){const u={isCollectionMatchUp:!1},{matchUps:d}=Jm({provisionalPositioning:t,matchUpFilters:u,drawDefinition:i,matchUpsMap:o,structure:s,event:c}),{roundMatchUps:p}=Sl({matchUps:d}),{initialRoundNumber:l}=bf({drawPosition:a,matchUps:d}),m=l&&p?.[l].find((t=>t.drawPositions?.includes(a)));if(m){const t=og({matchUpId:m.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:r,drawDefinition:i,drawPosition:a,matchUpsMap:o});if(t.error)return ti({stack:"assignDrawPositionToMatchUps",context:{drawPosition:a},result:t})}}({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:i,drawDefinition:a,drawPosition:d,matchUpsMap:p,structure:g,event:m});else{xf({positionAssignments:v,tournamentRecord:i,drawDefinition:a,matchUpsMap:p,structure:g});const{drawPositions:t,matchUps:n,targetMatchUps:r}=sg({assignments:[w],inContextDrawMatchUps:e,drawDefinition:a,matchUpsMap:p,structure:g});if(t&&1===n?.length&&n[0].matchUpType===o){const e=(r?.[0].sides??[]).reduce(((e,n,r)=>t?.includes(n.drawPosition)?r:e),void 0);eg({inContextTargetMatchUp:r[0],teamParticipantId:c,matchUp:n[0],drawPositionSideIndex:e,tournamentRecord:i,drawDefinition:a})}}const b=a.entries?.find((t=>t.participantId===c)),R=m?.entries?.find((t=>t.participantId===c));return!b&&R&&dh({entryStatus:R.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:a,participantId:c,event:m}),Yd({tournamentId:i?.tournamentId,drawDefinition:a,structure:g,event:m}),{positionAssignments:v,...z}}function fg(t){const{participantIdAttributeName:e="participantId",isQualifierPosition:n,positionActionName:r,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,event:u}=t,d="positionParticipantAction";if(!a)return{error:ot};const p=Np({tournamentRecord:i,drawDefinition:a,event:u}).appliedPolicies??{};let{inContextDrawMatchUps:l,matchUpsMap:m}=t;m||(m=hl({drawDefinition:a}),Object.assign(t,{matchUpsMap:m})),l||(({matchUps:l}=cf({inContext:!0,drawDefinition:a,matchUpsMap:m})),Object.assign(t,{inContextDrawMatchUps:l}));const{positionAssignments:f}=cd({drawDefinition:a,structureId:c}),h=f?.find((t=>t.drawPosition===s));if(h?.participantId){const t=h.participantId,e=mg({inContextDrawMatchUps:l,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:m,event:u});return e.success?y({appliedPolicies:p,removedParticipantId:t}):ti({result:e,stack:d})}const g=_f({inContextDrawMatchUps:l,tournamentRecord:i,drawDefinition:a,drawPosition:s,structureId:c,matchUpsMap:m,event:u});if(g.error)return ti({result:g,stack:d});const I=g.participantId,U=mg({inContextDrawMatchUps:l,isQualifierPosition:n,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:m,event:u});return U.success?y({appliedPolicies:p,removedParticipantId:I}):ti({result:U,stack:d});function y({appliedPolicies:t,removedParticipantId:n}){const{structure:i}=ad({drawDefinition:a,structureId:c});Qd({drawPositions:[s],structure:i});return Jd({appliedPolicies:t,drawDefinition:a,positionAction:{[e]:o,name:r,drawPosition:s,structureId:c}}),ti({context:{removedParticipantId:n},result:{...z},stack:d})}}function hg(t){return function({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return fg({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)}function gg({params:t,modMap:e,structure:n}){const{tournamentRecord:r,drawDefinition:i,event:a}=t;for(const t of n.matchUps)e[t.matchUpId]&&(t.roundNumber=e[t.matchUpId],$d({tournamentId:r?.tournamentId,eventId:a?.eventId,drawDefinition:i,matchUp:t}))}function Ig(t,e){const n=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&n.push(...e);const r=cc(t,n);if(r.error)return r;const i=ad(t);if(i.error)return i;const a=i.structure;if(!Dl({structure:a}))return ti({result:{error:ut,message:"structure must be adHoc"}});const{roundMatchUps:o=[],roundNumbers:s}=Sl({matchUps:a?.matchUps});return s?.length?{valid:!0,structure:a,roundMatchUps:o,roundNumbers:s}:{error:me}}function Ug(t){const e=Ig(t,[{targetRoundNumber:!0,roundNumber:!0,[nc]:"number"}]);if(e.error)return e;const{structure:n,roundMatchUps:r,roundNumbers:i}=e,{targetRoundNumber:a,roundNumber:o}=t;if(!i?.includes(o)||!i?.includes(a))return ti({result:{error:Jn},info:"roundNumbers must be valid rounds"});const s=a>o,c=s?E(o+1,a+1):E(a,o),u={};return c.forEach((t=>(r?.[t]??[]).forEach((({matchUpId:e})=>{u[e]=t-(s?1:-1)})))),r?.[o]?.forEach((({matchUpId:t})=>u[t]=a)),gg({params:t,modMap:u,structure:n}),{...z}}function yg({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:n,drawDefinition:r,event:i}){if(!r)return{error:ot};if(!Array.isArray(t))return{error:Jn};for(const a of t){const{structureId:t,positionAssignments:o}=a;if(!o)continue;const s=ad({drawDefinition:r,structureId:t});if(s.error)return s;const c=s.structure;if(!c)return{error:Lt};const u=cd({structure:c}).positionAssignments?.map((({drawPosition:t})=>t)),d=o?.map((({drawPosition:t})=>t));if(O(u,d).length!==u?.length)return ti({result:{error:Jn},info:"drawPositions do not match",stack:"setPositionAssignments"});const p=hl({drawDefinition:r}),{matchUps:l}=cf({inContext:!0,drawDefinition:r,matchUpsMap:p});for(const a of o||[]){const{drawPosition:s,participantId:u,bye:d,qualifier:m}=a;if(d){const e=Ef({tournamentRecord:n,drawDefinition:r,drawPosition:s,matchUpsMap:p,structureId:t,structure:c,event:i});if(e?.error)return e}else if(m)o.forEach((t=>{t.drawPosition===s&&(t.qualifier=!0,delete t.participantId,delete t.bye)}));else if(u){const a=mg({provisionalPositioning:e,inContextDrawMatchUps:l,tournamentRecord:n,drawDefinition:r,participantId:u,drawPosition:s,matchUpsMap:p,structureId:t,event:i});if(a?.error)return a}}Yd({tournamentId:n?.tournamentId,drawDefinition:r,structure:c,event:i})}const a=t.map((({structureId:t})=>t));return Hd({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:r,structureIds:a}),{...z}}function Sg(t){const e=Ig(t,[{roundNumbers:!0,[nc]:Zs,[Xs]:t=>2===t.length&&t.every(h)}]);if(e.error)return e;const{structure:n,roundMatchUps:r,roundNumbers:i}=e;if(!t.roundNumbers.every((t=>i?.includes(t))))return ti({result:{error:Jn,message:"roundNumbers must be valid rounds"}});const a={};return t.roundNumbers.forEach(((e,n)=>(r?.[e]??[]).forEach((({matchUpId:e})=>{a[e]=t.roundNumbers[1-n]})))),gg({params:t,modMap:a,structure:n}),{...z}}function vg({alternateParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i,event:a}){return fg({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i,event:a})}function wg({drawDefinition:t,structureId:e}){if(!t)return{error:ot};const{structure:n}=ad({drawDefinition:t,structureId:e}),r=(t?.links||[]).filter((t=>t.source?.structureId===e)).map((t=>t.target?.structureId)),i=(t?.structures||[]).filter((t=>r.includes(t.structureId)));return{playoffStructures:i,structure:n}}function Pg({withStageGrouping:t,stageSequences:e,stageSequence:n,roundTarget:r,stages:i,event:a,stage:o}){if(!a)return{error:$t};const s={},c=[];for(const u of a.drawDefinitions||[]){const{structures:a,stageStructures:d}=od({withStageGrouping:t,stageSequences:e,drawDefinition:u,stageSequence:n,roundTarget:r,stages:i,stage:o});if(c.push(...a),d)for(const t of Object.keys(d))s[t]||(s[t]=[]),s[t].push(...d[t])}return{structures:c,stageStructures:s}}function Dg({withStageGrouping:t,tournamentRecord:e,stageSequences:n,stageSequence:r,roundTarget:i,stages:a,stage:o}){if(!e)return{error:nt};const s={},c=[];for(const u of e.events||[]){const{structures:e,stageStructures:d}=Pg({withStageGrouping:t,stageSequences:n,stageSequence:r,roundTarget:i,stages:a,event:u,stage:o});if(e&&c.push(...e),d)for(const t of Object.keys(d))s[t]||(s[t]=[]),s[t].push(...d[t])}return{structures:c,stageStructures:s}}function Tg(t){if(!t?.drawDefinition)return!1;const e=Xm(t),n=e?.includesTeamMatchUps;let{completedMatchUps:r,pendingMatchUps:i,upcomingMatchUps:a}=e||{};n&&(r=r?.filter((({matchUpType:t})=>t===o)),i=i?.filter((({matchUpType:t})=>t===o)),a=a?.filter((({matchUpType:t})=>t===o)));return!!(r?.length&&!i?.length&&!a?.length)}function bg(t){const{drawDefinition:e,structureId:n}=t;if(!e)return{error:ot};const{playoffStructures:r}=wg({drawDefinition:e,structureId:n});if(!r?.length)return!1;const i=e?.entries?.filter((t=>t?.entryStatus&&al.includes(t.entryStatus)))?.length??0;let a=0;return(r||[]).reduce(((t,e)=>{const n=cd({structure:e}).positionAssignments??[],r=n?.filter((t=>(t.participantId&&a++,t?.bye??t?.participantId))).length;return!(!r||!t)}),!!r.length)||a===i}function Rg({significantCharacters:t,accessors:e=[],value:n}){const r=[],i=e[0];if(n?.[i]){const a=e.slice(1);if(Array.isArray(n[i])){n[i].forEach((e=>{const n=Rg({accessors:a,significantCharacters:t,value:e});r.push(...n)}))}else if(n=n[i],a.length){const e=Rg({accessors:a,significantCharacters:t,value:n});r.push(...e)}else!function({value:e}){if(e&&["string","number"].includes(typeof e)){const n=t?e.slice(0,t):e;r.push(n)}}({value:n})}return r}function Mg({policyAttributes:t,idCollections:e,participants:n,participant:r}){if(!Array.isArray(t))return{error:ye};if(!r)return{error:Je};const i=[];t.forEach((t=>{const{directive:a,groupings:o,key:s,significantCharacters:c}=t||{};if(s){const t=s.split(".");i.push(...Rg({significantCharacters:c,value:r,accessors:t}))}else if(a){const o=t?.includeIds,s=(e?.[a]||[]).filter((t=>!o||o.includes(t)));s?.length&&n?.length&&s.forEach((t=>{const e=n.find((e=>e.participantId===t));if(e?.individualParticipantIds?.includes(r.participantId)){const t=e?.participantId;i.push(t)}}))}else o&&Object.keys(o).forEach((t=>{o[t].includes(r.participantId)&&i.push(t)}))}));return{values:w(i)}}function Ng({candidatePositionAssignments:t,participantsWithGroupings:e,policyAttributes:n,idCollections:r}){const i=Object.assign({},...e.map((t=>({[t.participantId]:t}))));return t.map((t=>{const a=i[t.participantId],{values:o}=Mg({participants:e,policyAttributes:n,idCollections:r,participant:a});return{...t,values:o}}))}function Ag({participantIdGroups:t,positionAssignments:e,groupsToAvoid:n}){return Object.assign({},...e.filter((t=>t?.participantId)).map((e=>{const{drawPosition:r,participantId:i}=e,a=t&&t[i]||[],o=!!n.some((t=>a.includes(t)));return{[r]:{participantGroups:a,includesGroupsToAvoid:o}}})))}function Eg(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=Ag(t);return n.map((t=>{const n=e.filter((e=>t.includes(e))),i=function(t){return t.filter((t=>!e(t)));function e(e){const n=Cg(e);return!t.includes(n)}}(n),a=n.filter((t=>!i.includes(t))).filter((t=>{const e=Cg(t);return!r[e]?.includesGroupsToAvoid}));return{unassigned:n,unpaired:i,pairedNoConflict:a}}))}function Cg(t){return Number(t%2?t+1:t-1)}function Og({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:n,drawPositionChunks:r,unfilledPositions:i,isRoundRobin:a}){const o=r.map((r=>a?function(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=Ag(t);return n.map((t=>{const n=e.filter((e=>t.includes(e))),i=n.length===t.length?n:[],a=t.filter((t=>r[t]?.includesGroupsToAvoid)).length;return{unassigned:n,unpaired:i,pairedNoConflict:a?[]:n,conflictsCount:a}}))}({groupsToAvoid:t,chunkedDrawPositions:r,participantIdGroups:e,positionAssignments:n,unfilledPositions:i}):Eg({groupsToAvoid:t,chunkedDrawPositions:r,participantIdGroups:e,positionAssignments:n,unfilledPositions:i})));if(a){return{unassigned:o.map((t=>t.map((t=>t.unassigned)).filter((t=>t?.length)))).filter((t=>t?.length)).sort(((t,e)=>(e.length||0)-(t.length||0))),unpaired:o.map((t=>t.map((t=>t.unpaired)).filter((t=>t?.length)))).filter((t=>t?.length)),pairedNoConflict:o.map((t=>t.map((t=>t.pairedNoConflict)).filter((t=>t?.length)))).filter((t=>t?.length)).sort(((t,e)=>(e.length||0)-(t.length||0)))}}return{unassigned:o.map((t=>t.map((t=>t.unassigned)).filter((t=>t?.length)))).filter((t=>t?.length)),unpaired:o.map((t=>t.map((t=>t.unpaired)).filter((t=>t?.length)))).filter((t=>t?.length)),pairedNoConflict:o.map((t=>t.map((t=>t.pairedNoConflict)).filter((t=>t?.length)))).filter((t=>t?.length))}}function Fg({positionAssignments:t,participantIds:e}){const n=t.map((t=>t.participantId));return e.filter((t=>!n.includes(t)))}function kg({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:n,drawPositionChunks:r,drawPositionGroups:i,pairedPriority:a,allGroups:o,groupKey:s}){const c=i.reduce(((t,e)=>e.length>t?e.length:t),0)<=2,u=Fg({positionAssignments:t,participantIds:e}),d=function({drawPositionGroups:t,positionAssignments:e}){const n=Object.assign({},...e.map((t=>({[t.drawPosition]:t}))));return t.map((t=>t.filter(Boolean).map((t=>n[t])).filter(Boolean).filter((t=>!t.participantId&&!t.bye)).map((t=>t.drawPosition)))).flat().filter(Boolean)}({positionAssignments:t,drawPositionGroups:i}),{participantId:p,groupKey:l}=function({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:n=!0,allGroups:r,groupKey:i}){const a=Object.assign({},...Object.keys(r).map((t=>[t,r[t].filter((t=>e.includes(t)))])).filter((t=>t[1].length)).map((([t,e])=>({[t]:e})))),o=Object.keys(a).reduce(((t,e)=>a[e].length>t?a[e].length:t),0),s=Object.keys(a).filter((t=>a[t].length===o)),c=A(n?s:Object.keys(a));return{participantId:(i=t&&a[i]?.length?i:c)&&a[i]?A(a[i]):A(e),groupKey:i}}({targetParticipantIds:u,useSpecifiedGroupKey:c,allGroups:o,groupKey:s}),m=function({allGroups:t,participantId:e}){return Object.keys(t).filter((n=>t[n].includes(e)))}({participantId:p,allGroups:o}),f=Og({positionAssignments:t,isRoundRobin:c,selectedParticipantGroups:m,participantIdGroups:n,drawPositionChunks:r,unfilledPositions:d}),{unassigned:h,unpaired:g,pairedNoConflict:I}=f,U=I?.length&&I[0],y=g?.length&&g[0],S=a&&U?U:y,v=a?y:U,w=S?.length&&S||v?.length&&v;let P;if(w?.length){const t=N(w);P=N(t)}else{const t=N(h[0]);P=N(t)}return{newGroupKey:l,selectedParticipantId:p,targetDrawPosition:P}}function xg({isRoundRobin:t,groupedParticipants:e}){const n=[];return t?e.forEach((t=>{const e=Lh({drawPositions:t.map((t=>t.drawPosition))}).uniqueMatchUpGroupings??[],r=Object.assign({},...t.map((t=>({[t.drawPosition]:t}))));e.forEach((e=>{k(r[e[0]].values||[],r[e[1]].values||[])&&(n.push(e),t.conflict=!0)}))})):e.forEach((t=>{k(t[0]?.values||[],t[1]?.values||[])&&(n.push(t),t.conflict=!0)})),n}function _g({positionedParticipants:t,potentialDrawPositions:e,drawPositionGroups:n,avoidanceConflicts:r,isRoundRobin:i}){return r.map((r=>{const a=r.map((t=>t.drawPosition));return r.filter((t=>e.includes(t.drawPosition))).map((r=>{const o=e.filter((t=>!a?.includes(t))).filter((e=>{const a=n.find((t=>t.includes(e))).find((t=>t!==e)),o=t.find((t=>t.drawPosition===a)),s=xg({isRoundRobin:i,groupedParticipants:[[r,o]]}),c=t.find((t=>t.drawPosition===e)),u=xg({isRoundRobin:i,groupedParticipants:[[c,o]]});return!s.length&&!u.length}));if(o.length)return{drawPosition:r.drawPosition,possibleDrawPositions:o}})).filter(Boolean)})).flat(1)}function Lg(t){const{initialPositionAssignments:e,participantsWithGroupings:n,opponentsToPlaceCount:r,unseededByePositions:i,drawPositionGroups:a,policyAttributes:o,idCollections:s,allGroups:c}=t,u=[];let d;const p=Math.min(...(a||[]).map((t=>t?.length)).filter(Boolean)),l=p>2,m=la(e,!1,!0).filter((t=>!t.qualifier)),f=e.filter((t=>!t.participantId&&(!t.bye||i?.includes(t.drawPosition)))).map((t=>t.drawPosition));E(0,r).forEach((()=>{const{newGroupKey:e,selectedParticipantId:n,targetDrawPosition:r}=kg({...t,candidatePositionAssignments:m,allGroups:c,groupKey:d});d=e,m.forEach((t=>{t.drawPosition===r&&(t.participantId=n)}))}));let h=Ng({candidatePositionAssignments:m,participantsWithGroupings:n,policyAttributes:o,idCollections:s}),g=x(h,p),I=xg({groupedParticipants:g,isRoundRobin:l}),U=0;for(;U<20&&I.length;){const t=_g({positionedParticipants:h,potentialDrawPositions:f,avoidanceConflicts:I,drawPositionGroups:a,isRoundRobin:l});if(t.length){const e=Bg({candidatePositionAssignments:m,swapOptions:t});e.error&&console.log({result:e}),h=Ng({candidatePositionAssignments:m,participantsWithGroupings:n,policyAttributes:o,idCollections:s}),g=x(h,p),I=xg({groupedParticipants:g,isRoundRobin:l}),U++}else U=20}return m.forEach((t=>{if(t.bye&&t.participantId){const t=Et;u.push(t)}if(t.qualifier&&t.participantId){const t=Et;u.push(t)}})),{positionAssignments:m,conflicts:I.length,groupedParticipants:g,errors:u}}function Bg({candidatePositionAssignments:t,swapOptions:e}){const n=N(e);if(!n)return{error:{message:"No swap options"}};const r=n.drawPosition,i=N(n.possibleDrawPositions),a=t.find((t=>t.drawPosition===r)),o=t.find((t=>t.drawPosition===i))??{},s={participantId:o?.participantId,qualifier:o?.qualifier,bye:o?.bye},c={participantId:a.participantId,qualifier:a.qualifier,bye:a.bye};return Object.assign(a,s),Object.assign(o,c),{...z}}function Vg({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:n,unseededByePositions:r,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,participants:s,matchUpsMap:c,structureId:d,avoidance:l,drawSize:m,event:h}){if(!l)return{error:Ue};const{candidatesCount:g=1,policyAttributes:I,targetDivisions:U}=l;let{roundsToSeparate:y}=l;const S="randomUnseededSeparation",{structure:v}=ad({drawDefinition:a,structureId:d}),{matchUps:w}=Jm({provisionalPositioning:t,matchUpsMap:c,structure:v,event:h});if(U&&p(U)&&!y){const t=function(t){if(!p(t))return!1;let e=t,n=1;for(;2!==e;)n+=1,e/=2;return n}(U)||0,e=w.reduce(((t,e)=>e.roundNumber>t?e.roundNumber:t),0);y=e<t?1:e-t+1}const{positionAssignments:P}=ud({structure:v}),D=pp({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:s}).participantsWithGroupings,T=P?.filter((t=>!t.participantId)),b=P?.map((t=>t.drawPosition)),R=v?.structureType===Mo,M=R?{structure:v,matchUps:w,allDrawPositions:b,roundsToSeparate:y}:{matchUps:w,allDrawPositions:b,roundsToSeparate:y},{drawPositionGroups:N,drawPositionChunks:A}=R?function(t){const{structure:{structures:e}}=t,n=e.map((t=>t.positionAssignments.map((t=>t.drawPosition))));return{drawPositionGroups:n,drawPositionChunks:[n]}}(M):function({allDrawPositions:t,roundsToSeparate:e,matchUps:n}){const r=n.filter((t=>1===t.roundNumber)).map((t=>t.drawPositions)),i=r.flat().sort(u),a=Math.max(...i),o=t.filter((t=>t>a)),s=i.length,c=E(2===s?1:2,s).filter((t=>t===f(t))),d=c.slice(0,e||c.length).reverse(),p=d.map((t=>x(i,t)));o.length&&console.log({fedDrawPositions:o});return{drawPositionGroups:r,drawPositionChunks:p}}(M),C={groupParticipants:s.filter((t=>t.participantType===op)).map((t=>t.participantId)),teamParticipants:s.filter((t=>t.participantType===cp)).map((t=>t.participantId)),pairParticipants:s.filter((t=>t.participantType===sp)).map((t=>t.participantId))},O=function({targetParticipantIds:t,policyAttributes:e,idCollections:n,participants:r}){if(!Array.isArray(e))return{error:ye};if(!Array.isArray(r))return{error:Ze};const i={};return t.forEach((t=>{const a=r.find((e=>e.participantId===t)),{values:o}=Mg({policyAttributes:e,idCollections:n,participants:r,participant:a});o&&o.forEach((e=>{i[e]||(i[e]=[]),i[e].includes(t)||i[e].push(t)}))})),i}({targetParticipantIds:e,policyAttributes:I,idCollections:C,participants:s});if(O.error)return ti({result:O,stack:S});const F=Object.assign({},...e.map((t=>{const e=Object.keys(O).filter((e=>(O[e]??[]).includes(t)));return{[t]:e}}))),k=Fg({participantIds:e,positionAssignments:P});if(k.length>(T?.length||0))return{error:Sn};let _;const L=k.length,B=E(0,g).map((()=>Lg({initialPositionAssignments:P,participantsWithGroupings:D,unseededParticipantIds:e,opponentsToPlaceCount:L,pairedPriority:!1,unseededByePositions:r,participantIdGroups:F,drawPositionChunks:A,drawPositionGroups:N,policyAttributes:I,idCollections:C,allGroups:O,drawSize:m})));if(_=B.reduce(((t,e)=>!t||(e.conflicts||0)<(t.conflicts||0)?e:t),void 0),!_||_.conflicts){const t=E(0,g).map((()=>Lg({initialPositionAssignments:P,participantsWithGroupings:D,unseededParticipantIds:e,opponentsToPlaceCount:L,pairedPriority:!0,unseededByePositions:r,participantIdGroups:F,drawPositionChunks:A,drawPositionGroups:N,policyAttributes:I,idCollections:C,allGroups:O,drawSize:m}))),n=B.concat(...t).filter((t=>!t.errors?.length));_=n.reduce(((t,e)=>!t||(e.conflicts||0)<(t.conflicts||0)?e:t),void 0)}if(!_)return{error:Wn};const V=(cd({structure:v})?.positionAssignments??[]).filter((t=>t.participantId)).map((t=>t.participantId)),j=_.positionAssignments.filter((t=>!V.includes(t.participantId)));for(const t of j)if(t.bye){const e=Ef({tournamentRecord:i,drawDefinition:a,structureId:d,matchUpsMap:c,event:h,...t});if(e.error)return ti({result:e,stack:S})}else if(t.participantId){const e=mg({inContextDrawMatchUps:n,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,structureId:d,matchUpsMap:c,event:h,...t});if(e.error)return ti({result:e,stack:S,context:{assignment:t}})}return{...z}}function jg({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:n,multipleStructures:r,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,participants:s,matchUpsMap:c,structureId:u,structure:d,drawSize:p,event:l}){d||({structure:d}=ad({drawDefinition:a,structureId:u})),u||({structureId:u}=d);const{positionAssignments:m}=ud({structure:d}),{seedAssignments:f}=pl({provisionalPositioning:t,drawDefinition:a,structure:d}),h=f?.map((t=>t.participantId)).filter(Boolean),{stage:g,stageSequence:I}=d,U=g===ho?zc({element:d,name:pu})?.extension?.value:void 0,y=dl({provisionalPositioning:t,drawDefinition:a,stageSequence:I,entryStatuses:il,structureId:u,roundTarget:U,stage:g}),S=y.filter((t=>!h?.includes(t.participantId))).map((t=>t.participantId)),v=m?.filter((t=>!t.participantId&&!t.bye&&!t.qualifier)).map((t=>t.drawPosition));if(!r&&S.length>(v?.length||0))return ti({result:{error:Sn},context:{unseededParticipantsCount:S.length,unfilledDrawPositionsCount:v?.length},stack:"positionUnseededParticipants"});const{appliedPolicies:w}=Np({tournamentRecord:i,drawDefinition:a,event:l});let D=w?.[Mc];if(d.stage===Uo){const t=y.reduce(((t,e)=>(t[e.groupingValue]||(t[e.groupingValue]=[]),t[e.groupingValue].push(e.participantId),t)),{});Object.keys(t).length&&(D||(D={policyName:"Playoff Avoidance"}),D.policyAttributes||(D.policyAttributes=[]),D.policyAttributes.push({groupings:t}))}return D&&s?Vg({provisionalPositioning:t,unseededParticipantIds:S,inContextDrawMatchUps:e,unseededByePositions:n,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,participants:s,matchUpsMap:c,structureId:u,avoidance:D,drawSize:p}):function({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:n,unfilledDrawPositions:r,multipleStructures:i,tournamentRecord:a,drawDefinition:o,seedBlockInfo:s,matchUpsMap:c,structureId:u,drawSize:d,event:p}){const l=d>2?P(r):r.reverse();for(const r of e){const e=l.pop();if(!i||e){const i=mg({provisionalPositioning:t,inContextDrawMatchUps:n,tournamentRecord:a,drawDefinition:o,seedBlockInfo:s,participantId:r,drawPosition:e,matchUpsMap:c,structureId:u,event:p});if(i?.error&&console.log("!!!!!",{result:i}),i?.error)return ti({result:i,stack:"randomUnseededDistribution"})}}return{...z}}({provisionalPositioning:t,unseededParticipantIds:S,inContextDrawMatchUps:e,unfilledDrawPositions:v,multipleStructures:r,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,structureId:u,matchUpsMap:c,drawSize:p,event:l})}function Gg(t){const e=t.structure??ad(t).structure,n="positionQualifiers",r=[];if(e.stage===go)return ti({result:{error:Jt},stack:n});const{unplacedRoundQualifierCounts:i,positionAssignments:a,roundDrawPositions:o}=function({drawDefinition:t,structure:e,structureId:n}){e||({structure:e}=ad({drawDefinition:t,structureId:n}));n||({structureId:n}=e);const{positionAssignments:r}=ud({structure:e}),{stage:i,stageSequence:a}=e,{qualifiersCount:o,roundQualifiersCounts:s}=oh({drawDefinition:t,stageSequence:a,structureId:n,stage:i}),c=(s?Object.keys(s):[]).map((t=>d(t))),{matchUps:u}=Jm({structure:e}),{roundProfile:p}=Sl({matchUps:u}),l=Object.assign({},...c.filter((t=>p?.[t])).map((t=>({[t]:p?.[t]?.drawPositions?.filter(Boolean)??[]})))),m=r?.filter((t=>t.qualifier)).map((t=>t.drawPosition)),f=o-(m?.length??0),h=m?.length,g=Object.assign({},...c.map((t=>{const e=r?.filter((e=>e.qualifier&&l[t]?.drawPositions?.includes(e.drawPosition))).map((t=>t.drawPosition));return{[t]:(s?.[t]??0)-(e?.length??0)}})));return{unplacedRoundQualifierCounts:g,unplacedQualifiersCount:f,placedQualifiersCount:h,roundQualifiersCounts:s,positionAssignments:r,roundDrawPositions:l,qualifiersCount:o}}(t);for(const t of Object.keys(i)){const e=a?.filter((e=>o[t].includes(e.drawPosition)&&!e.participantId&&!e.qualifier&&!e.bye)).map((t=>t.drawPosition));if(i[t]>(e||0))return ti({result:{error:yn},context:{unfilledDrawPositions:e},stack:n});E(0,i[t]).forEach((()=>{const t=N(e);r.push(t),a?.forEach((e=>{e.drawPosition===t&&(e.qualifier=!0,delete e.participantId,delete e.bye)}))}))}return{...z,qualifierDrawPositions:r}}function qg({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,appliedPolicies:r,validSeedBlocks:i,drawDefinition:a,seedingProfile:o,seedBlockInfo:s,participants:c,groupsCount:u,structureId:d,matchUpsMap:p,structure:l,event:m}){const f=[],h=[];let g=0;if(l||({structure:l}=ad({drawDefinition:a,structureId:d})),d||(d=l?.structureId),r||(r=Np({drawDefinition:a}).appliedPolicies),!i){const e=l&&Kh({provisionalPositioning:t,appliedPolicies:r,drawDefinition:a,seedingProfile:o,structure:l});e?.error&&h.push(e.error),i=e?.validSeedBlocks}return E(0,u=u??i?.length??0).forEach((()=>{if(g<(u||0)){const r=function({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,participants:o,structureId:s,matchUpsMap:c,event:u}){const{unplacedSeedParticipantIds:d,unfilledPositions:p}=Zh({provisionalPositioning:t,randomize:!0,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,structureId:s}),{appliedPolicies:l}=Np({drawDefinition:r}),{avoidance:m}=l??{};const f=[];for(const o of d){const d=p.pop();if(!d)return{error:St};f.push(d);const l=mg({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,seedingProfile:i,participantId:o,seedBlockInfo:a,drawPosition:d,matchUpsMap:c,structureId:s,event:u});if(!l.success)return l}return{...z,seedPositions:f}}({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:a,seedingProfile:o,seedBlockInfo:s,participants:c,structureId:d,matchUpsMap:p,event:m});r?.success&&(g++,f.push(...r.seedPositions??[])),r.error&&h.push({seedPositionError:r.error})}})),h.length?{error:h}:{...z,seedPositions:f}}function $g({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:n}){const r=[];e.forEach((e=>function(t,e,n,r){const i=e-n.length;if(i>t.drawPositions.length)n.push(...t.drawPositions);else{!function(t,e,n){let r,i=n[e.length];for(;r=Wg(t,i);)e.push(r),i=n[e.length]}(Hg(x(t.drawPositions,2)),n,r)}}(e,n,r,t)));const i=r.map((t=>Array.isArray(t)?P(t):t)).flat(1/0);if(g(n)){if(e.map((t=>t.seedNumbers[0])).includes(n))return t}return i}function Wg(t,e){return Array.isArray(t)&&2!==t.length?t.pop():Array.isArray(t[0])?function(t,e){const n=t[0].flat(1/0).length,r=t[1].flat(1/0).length;if(n===r){const n=t[0].flat(1/0).includes(e)?t[0]:t[1];return Wg(e?n:t[Math.round(Math.random())],e)}return Wg(n<r?t[1]:t[0],e)}(t,e):function(t,e){return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(Math.random())?t.pop():t.shift()}(t,e)}function Hg(t){const e=Math.floor(t.length/2);return t.length>2?[Hg(t.slice(0,e)),Hg(t.slice(e))]:t}function zg({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:n,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,byesToPlace:o,structure:s}){a||(a=Kh({provisionalPositioning:t,appliedPolicies:n,drawDefinition:r,seedingProfile:i,structure:s}));const{isFeedIn:c,isLuckyStructure:u,isContainer:d}=a;let{validSeedBlocks:p}=a;n?.seeding?.containerByesIgnoreSeeding&&(p=[]);const l=function({provisionalPositioning:t,drawDefinition:e,structure:n}){const{positionAssignments:r}=ud({structure:n}),{seedAssignments:i}=pl({provisionalPositioning:t,drawDefinition:e,structure:n}),a=Object.assign({},...(i||[]).filter((t=>t.participantId)).map((t=>({[t.participantId]:t}))));return r?.map((t=>a[t.participantId]?{...t,seedNumber:a[t.participantId].seedNumber,seedValue:a[t.participantId].seedValue}:"")).filter(Boolean)}({provisionalPositioning:t,drawDefinition:r,structure:s})??[],m=w([].concat(...e.map((t=>t.drawPositions)))),f=l.filter((t=>m.includes(t.drawPosition))),h=(t,e)=>zh(t.seedValue)-zh(e.seedValue),g=p.reduce(((t,e)=>{const n=f.filter((t=>e.drawPositions?.includes(t.drawPosition))).sort(h);return t.concat(...n)}),[]).map((t=>t.drawPosition)),I=$g({orderedSortedFirstRoundSeededDrawPositions:g,validSeedBlocks:p,byesToPlace:o});return{strictSeedOrderByePositions:Yg({orderedSeedDrawPositions:g,relevantMatchUps:e}).slice(0,o),blockSeedOrderByePositions:Yg({orderedSeedDrawPositions:I,relevantMatchUps:e}).slice(0,o),isLuckyStructure:u,positionedSeeds:l,isContainer:d,isFeedIn:c}}function Yg({orderedSeedDrawPositions:t,relevantMatchUps:e}){const n=e.map((t=>t.drawPositions)).map((t=>t?.sort(((t,e)=>t-e)))).filter((t=>t?.[0]+1===t?.[1]));return t.map((t=>n.find((e=>e?.includes(t))))).filter(Boolean).map((e=>e?.reduce(((e,n)=>t.includes(n)?e:n),void 0))).filter(Boolean)}function Kg({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:n,drawDefinition:r,seedBlockInfo:i,seedingProfile:a,matchUpsMap:o,structureId:s,structure:c,seedLimit:d,seedsOnly:p,event:l}){c||({structure:c}=ad({drawDefinition:r,structureId:s})),s||(s=c?.structureId);const m=!(c?.structures??c?.stage===ho),{byesCount:f,placedByes:h,relevantMatchUps:g}=function({provisionalPositioning:t,drawDefinition:e,matchUpsMap:n,structure:r,event:i}){const{matchUps:a,roundMatchUps:o}=Jm({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:n,structure:r,event:i}),s=o?.[1]||[],c=r?.structureType===Mo,u=c?a:s,d=c?r?.structures?.length||0:a.length,{structureId:p,stage:l,stageSequence:m}=r,f=dl({entryStatuses:al,provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),{qualifiersCount:h}=oh({provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),g=f.length+h,{positionAssignments:I,unassignedPositions:U}=ud({structure:r}),y=U?.map((t=>t.drawPosition)),S=I?.filter((t=>t.bye)).length,v=I?.filter((t=>t.bye)).map((t=>t.drawPosition)),w=u.map((t=>t.drawPositions)).filter((t=>t?.reduce(((t,e)=>!v?.includes(e)&&t),!0))).flat(1/0).filter((t=>y?.includes(t))),P=I?.length;let D=P?P-g:0;return D>d&&1===r.stageSequence&&r.stage!==go&&(D=d),{placedByes:S,byesCount:D,relevantMatchUps:u,placedByePositions:v,roundMatchUps:o,positionsToAvoidDoubleBye:w}}({provisionalPositioning:t,drawDefinition:r,matchUpsMap:o,structure:c,event:l}),I=f-(h||0);if(I<=0)return{...z};const{strictSeedOrderByePositions:U,blockSeedOrderByePositions:y,isLuckyStructure:S,isFeedIn:v}=zg({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:n,drawDefinition:r,seedingProfile:a,seedBlockInfo:i,byesToPlace:I,structure:c}),D=c?.structureType&&[Mo,Ro].includes(c.structureType)&&n?.seeding?.containerByesIgnoreSeeding,T=m&&y?.length?y:U;let{unseededByePositions:b}=function({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:n,appliedPolicies:r,drawDefinition:i,seedLimit:a,structure:o,isFeedIn:s}){const c=r?.seeding?.seedingProfile,d=o.stage===ho,{positionAssignments:p}=ud({structure:o}),l=p?.filter((t=>t.participantId)).map((t=>t.drawPosition)),{matchUps:m,roundMatchUps:f}=Jm({provisionalPositioning:t,matchUpFilters:{isCollectionMatchUp:!1},structure:o}),h=f?.[1]||[],g=o.structureType===Mo?m:h,I=w([].concat(...g.map((t=>t.drawPositions)))),U=Math.min(...I)-1,y=l?.filter((t=>I.includes(t))),S=t=>{const e=Math.ceil(t.length/2),n=[t.slice(0,e),t.slice(e)],r=n.map((t=>[].concat(...t.flat(1/0)).length)),i=Math.min(...r.flat(1/0)),a=Math.max(...r.flat(1/0)),o=r.indexOf(a),s=i!==a,c=P(n),[u,d]=!i||s?[n[o],n[1-o]]:[c[0],c[1]];return{greaterHalf:u,lesserHalf:d}},v=t=>{const{greaterHalf:e,lesserHalf:n}=S(t),{greaterHalf:r,lesserHalf:i}=S(e),a=P(r.flat(1/0)).pop();return{newlyFilteredChunks:[...n,...i,r.flat().filter((t=>t!==a))],drawPosition:a}},D=t=>!y?.includes(t),T=t=>{let e=x(t.sort(u),Math.ceil(t.length/4)).map((t=>t.filter(D)));const n=[].concat(...e.flat(1/0)).length,r=[];for(let t=0;t<n;t++){const{newlyFilteredChunks:t,drawPosition:n}=v(e);r.push(n),e=t}return r},{validSeedBlocks:b}=Kh({provisionalPositioning:t,allPositions:!0,appliedPolicies:r,drawDefinition:i,structure:o}),R=b?.map((t=>t.drawPositions?.map((t=>t+U))));let M;if(s){const t=I.length,{seedBlocks:e}=$h({cluster:Xh(c)===To,participantsCount:t});M=e.map((t=>t.map((t=>t+U)))).map(T).filter((t=>t.length))}else M=d?R?.map((t=>t.filter(D))):R?.map(T).filter((t=>t.length));const N=g.map((t=>t.drawPositions)).map((t=>t?.sort(((t,e)=>t-e)))).filter((t=>t?.[0]+1===t?.[1])),A=t=>N.reduce(((e,n)=>n.includes(t)?n.reduce(((e,n)=>n!==t?n:e),void 0):e),void 0);let E=M.map((t=>t.map(A))).flat(1/0).filter(D).filter((t=>!e.includes(t))).filter(Boolean);if(d&&!o.structures){const t=a%4,e=E.slice(0,t),n=f[o.roundLimit]?.length,r=x(E.slice(t),n).map(P).flat();E=e.concat(r)}return{unseededByePositions:E}}({provisionalPositioning:t,seedOrderByePositions:T,isLuckyStructure:S,appliedPolicies:n,drawDefinition:r,seedLimit:d,structure:c,isFeedIn:v});let R=[].concat(...T);if(!p)for(;b.length;){const t=b.find((t=>{return e=t,(R||[]).every((t=>t%2?e!==t+1:e!==t-1));var e}));t?(R.push(t),b=b.filter((e=>e!==t))):(R.push(...b),b=[])}D&&(R=P(R),Pr({ignoreSeededByes:D})&&console.log({byePositions:R}));const M=R.slice(0,I);for(const n of M){const i=Ef({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:s,structure:c,event:l});if(i?.error)return i}return{...z,unseededByePositions:b,byeDrawPositions:M}}function Qg(t){let{drawDefinition:e}=t;const{applyPositioning:n=!0,provisionalPositioning:r,multipleStructures:i,placeByes:a=!0,tournamentRecord:o,placementGroup:s,seedingProfile:c,structureId:u,seedLimit:d,seedsOnly:p,drawType:l,drawSize:m,event:f}=t,h=[];n||(br(),e=la(e,!1,!0));const g=t=>(n||Rr(),ti({result:t,stack:"automatedPositioning"})),I=ad({drawDefinition:e,structureId:u});if(I.error)return g(I);const U=I.structure;if(!U)return{error:Lt};const y=t.appliedPolicies||Np({drawDefinition:e,structure:U,event:f})?.appliedPolicies,{qualifiersCount:S}=oh({stageSequence:U.stageSequence,provisionalPositioning:r,stage:U.stage,drawDefinition:e,structureId:u}),v=il,w=dl({stageSequence:U.stageSequence,provisionalPositioning:r,stage:U.stage,placementGroup:s,drawDefinition:e,entryStatuses:v,structureId:u});if(!w?.length&&!S)return(t=>(n||Rr(),t))({...z});const P=t.matchUpsMap??hl({drawDefinition:e}),D=t.inContextDrawMatchUps??cf({inContext:!0,drawDefinition:e,matchUpsMap:P})?.matchUps;let T=[];const b=Kh({provisionalPositioning:r,appliedPolicies:y,drawDefinition:e,seedingProfile:c,structure:U});if(b.error)return b;const{validSeedBlocks:R}=b;h.push({validSeedBlocks:R});const M=t.participants||(o?ih({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:o})?.participants:[]);if(Xh(U.seedingProfile||c)===bo){let t=a?Kg({provisionalPositioning:r,tournamentRecord:o,appliedPolicies:y,drawDefinition:e,seedBlockInfo:b,matchUpsMap:P,structure:U,seedLimit:d,seedsOnly:p,event:f}):void 0;if(t?.error)return g(t);T=t.unseededByePositions,h.push({action:"positionByes",unseededByePositions:T});if(t=qg({seedingProfile:U.seedingProfile?{positioning:U.seedingProfile}:c,provisionalPositioning:r,inContextDrawMatchUps:D,tournamentRecord:o,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:b,participants:M,matchUpsMap:P,structure:U,event:f}),t.error)return g(t);h.push({seedPositions:t.seedPositions,action:"positionSeedBlocks"})}else{if(l!==Wo){const t=qg({seedingProfile:U.seedingProfile?{positioning:U.seedingProfile}:c,provisionalPositioning:r,inContextDrawMatchUps:D,tournamentRecord:o,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:b,participants:M,matchUpsMap:P,structure:U,event:f});if(t.error)return g(t);h.push({action:"positionSeedBlocks",seedPositions:t.seedPositions})}const t=a?Kg({provisionalPositioning:r,tournamentRecord:o,appliedPolicies:y,drawDefinition:e,seedBlockInfo:b,matchUpsMap:P,structure:U,seedLimit:d,seedsOnly:p,event:f}):void 0;if(t?.error)return g(t);T=t?.unseededByePositions,h.push({action:"positionByes",byeDrawPositions:t?.byeDrawPositions,unseededByePositions:T})}const N={};if(!p){let t=Gg({inContextDrawMatchUps:D,tournamentRecord:o,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:b,participants:M,matchUpsMap:P,structure:U});if(t.error)return g(t);if(t.conflicts&&(N.qualifierConflicts=t.conflicts),h.push({action:"positionQualifiers",qualifierDrawPositions:t.qualifierDrawPositions}),t=jg({provisionalPositioning:r,inContextDrawMatchUps:D,unseededByePositions:T,multipleStructures:i,tournamentRecord:o,drawDefinition:e,seedBlockInfo:b,participants:M,matchUpsMap:P,structureId:u,structure:U,drawSize:m,event:f}),t.error)return g(t);t.conflicts&&(N.unseededConflicts=t.conflicts),h.push({action:"positionUnseededParticipants"})}const{positionAssignments:A}=cd({drawDefinition:e,structure:U});return Hd({drawDefinition:e,structureIds:[u]}),n||Rr(),{positionAssignments:A,conflicts:N,...z,positioningReport:h}}function Jg(t){const{applyPositioning:e=!0,provisionalPositioning:n,tournamentRecord:r,drawDefinition:i,seedingProfile:a,structureId:o,placeByes:s,seedsOnly:c}=t;if(!i)return{error:ct};if(!Tg({drawDefinition:i,structureId:o})&&!n)return{error:dt};const u=wg({drawDefinition:i,structureId:o}).playoffStructures?.sort(((t,e)=>id(t)-id(e))),d=[],p=[];if(u)for(const t of u){const{structureId:o}=t,u=Qg({structureId:o,provisionalPositioning:n,applyPositioning:e,tournamentRecord:r,drawDefinition:i,seedingProfile:a,placeByes:s,seedsOnly:c});if(u.error)return u;u.positionAssignments&&d.push({positionAssignments:u.positionAssignments,structureId:o}),u.positioningReport&&p.push(u.positioningReport)}return{...z,structurePositionAssignments:d,positioningReports:p}}function Zg({validation:t=!0,tournamentRecord:e,drawDefinition:n,participantId:r,structureId:i,seedValue:a,event:o}){if(!n)return{error:ot};if(!i)return{error:_t};const s=(e?.participants??[]).find((t=>t.participantId===r));if(e&&!s)return{error:He};const{structure:c}=ad({drawDefinition:n,structureId:i});if(!c)return{error:Lt};if(!(!t||h(a)||void 0===a||""===a||"string"==typeof a&&a.split("-").every((t=>h(t)&&d(t)>0))))return{error:Jn};const{seedAssignments:u}=pl({drawDefinition:n,structure:c}),p=u?.map((t=>t.seedNumber)),l=u?.find((t=>t.participantId===r));if(l){const t="string"==typeof a?a.includes("-")&&a.split("-").map((t=>parseInt(t))).join("-")||parseInt(a)>0&&parseInt(a)||"":a&&a>0&&a||"";l.seedValue=t}else{const t={seedNumber:Math.max(0,...p||[])+1,participantId:r};a&&(t.seedValue=a),c.seedAssignments||(c.seedAssignments=[]),c.seedAssignments.push(t)}return zd({tournamentId:e?.tournamentId,eventId:o?.eventId,drawDefinition:n,structure:c}),{...z}}function Xg({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return fg({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}function tI({targetRoundNumber:t,finishingPosition:e,drawDefinition:n,structureId:r,linkType:i}){const{links:a}=ef({drawDefinition:n,structureId:r})||{},o=(a?.target||[]).filter((({linkType:t})=>t===i)).filter((({target:e})=>!t||t===e.roundNumber)).map((t=>{const r=t.source.structureId,{structure:i}=ad({structureId:r,drawDefinition:n});if(!e||i?.finishingPosition===e)return t})).filter(Boolean);return{sourceStructureIds:o.map((({source:t})=>t.structureId)),relevantLinks:o}}function eI({targetRoundNumber:t=1,tournamentRecord:e,drawDefinition:n,event:r,randomList:i}){const a=cc({drawDefinition:n,event:r,tournamentRecord:e},[{[Is]:!0,[Ws]:!0,[hs]:!0}]);if(a.error)return a;const o=[],s=[],c=n.structures?.find((t=>t.stage===fo&&1===t.stageSequence));if(!c)return ti({result:{error:jt}});const u=(Np({tournamentRecord:e,drawDefinition:n,structure:c,event:r}).appliedPolicies??{})[vc],d=u?.requireCompletedStructures,{qualifierPositions:p,positionAssignments:l}=ud({structure:c});if(!p.length)return ti({result:{error:yn}});let m=E(0,p.length);i&&(m=((t,e)=>{const n=[...new Set(e.slice(0,t.length))],r=[...n].sort(((t,e)=>t-e)),i=new Set,a=[];n.forEach((e=>{const n=t.indexOf(e);if(-1===n||i.has(n)){const n=r.indexOf(e);let o=t.findIndex(((t,e)=>!i.has(e)));for(;i.has(o)&&-1===o&&i.size<t.length;)o=t.findIndex(((t,e)=>!i.has(e)&&e>o));a.push(n),i.add(n)}else a.push(n),i.add(n)}));const o=t.filter(((t,e)=>!i.has(e)));return[...a,...o]})(m,i));const f=l.map((t=>t.participantId)).filter(Boolean),{relevantLinks:h}=tI({structureId:c.structureId,targetRoundNumber:t,linkType:Fo,drawDefinition:n})||{},{relevantLinks:g}=tI({structureId:c.structureId,targetRoundNumber:t,linkType:Oo,drawDefinition:n})||{};for(const t of h){const e=n.structures?.find((e=>e.structureId===t.source.structureId));if(e?.stage!==ho)continue;const r=Tg({structureId:t.source.structureId,drawDefinition:n});if(!d||r){const t=e.qualifyingRoundNumber,{matchUps:n}=Jm({matchUpFilters:{...t&&{roundNumbers:[t]},isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,inContext:!0,structure:e});for(const t of n){const e=t.matchUpStatus===Fu&&t.sides?.find((({participantId:t})=>t)),n=t.sides.find((e=>e?.sideNumber===t.winningSide));if(n||e){const{participantId:t}=n||e||{};t&&!f.includes(t)&&s.push(t)}}}}for(const t of g){const e=n?.structures?.find((e=>e.structureId===t.source.structureId));if(e?.stage!==ho)continue;if(Tg({structureId:t.source.structureId,drawDefinition:n})){const{positionAssignments:t}=cd({structure:e}),n=t?.map((t=>{const e=t.participantId,n=zc({element:t,name:gu}).extension?.value;return n?{participantId:e,groupOrder:n?.groupOrder}:{}})).filter((({groupOrder:t,participantId:e})=>1===t&&!f.includes(e))).map((({participantId:t})=>t))??[];n&&s.push(...n)}}return s.length?(m.forEach(((t,r)=>{const i=s[r],a=p[t].drawPosition;if(i){const t=Xg({qualifyingParticipantId:i,structureId:c.structureId,drawPosition:a,tournamentRecord:e,drawDefinition:n});t?.success&&o.push({participantId:i,drawPosition:a})}})),ti({result:Xr({...z,assignedParticipants:o})})):ti({result:{error:tn}})}function nI({drawDefinition:t,orderMap:e}){return t?("object"==typeof e&&Object.values(e).every((t=>y(t)))||ti({result:{error:Jn},context:{orderMap:e}}),t.structures||(t.structures=[]),t.structures.forEach((t=>{const n=e[t.structureId];n&&(t.structureOrder=n)})),t.structures.sort(((t,e)=>D(t.structureOrder)-D(e.structureOrder))),{...z}):{error:ot}}function rI({drawDefinition:t}){const e=t.structures??[],n=t.links??[],r=new Map,i=t=>{const n=r.get(t)||r.set(t,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&r.get(t);if(n&&!n?.stage){const r=e.find((e=>e.structureId===t));n.stage=r?.stage}return n},a={},o={};let s=n.map((t=>{const e=t.source.structureId,n=t.target.structureId,r=i(e),s=i(n);return[Co,Eo,Ao,bo].includes(t.target.feedProfile)?(r?.targets.push(n),s?.sources.push(e)):t.target.feedProfile===No&&(s?.drawSources.push(e),r?.drawTargets.push(n)),o[n]=o[n]||t.target.feedProfile===No,a[n]=w([...a[n]||[],e]).filter(Boolean),[t.source.structureId,t.target.structureId]}));for(const t of r.keys()){const e=r.get(t);if(e){const t=e.targets??[];for(;t.length;){const n=t.pop(),i=n&&r[n];i?.targets?.length?t.push(...i.targets):i&&(e.rootStage=i.stage)}if(e.rootStage||(e.rootStage=e.stage),!e.targets?.length){const t=e.sources??[];for(;t.length;){const n=t.pop(),i=n&&r[n];if(i?.sources?.length){for(const t of i.sources)e.progeny?.includes(t)||e.progeny?.push(t);t.push(...i.sources)}}}}}let c=0;for(const t of r.keys()){const e=r.get(t);if(e&&e.rootStage===ho){const t=[e.drawTargets?.[0]];let n=0;for(;t.length;){n+=1;const e=t.pop(),i=e?r.get(e):void 0;i?.drawTargets?.length&&t.push(i.drawTargets[0])}e.distanceFromMain=n,n>c&&(c=n)}}const u=s.length;E(0,Math.ceil(u/2)).forEach((()=>{s=E(0,u).map((t=>{const e=s[t],n=s.reduce(((t,n)=>k(e,n)?t.concat(...n):t),[])||[];return w(e.concat(...n))}))}));const d=s[0],p=s.slice(1).reduce(((t,e)=>{return t&&O(n=e,d).length===n.length;var n}),!0),l=[d].filter(Boolean),m=[d].filter(Boolean);e.forEach((t=>{const{structureId:e,stage:n}=t;l.find((t=>t.includes(e)))||(l.push([e]),n!==Io&&m.push([e]))}));const f=p&&1===m.length;return n?.length||1!==e.length||i(e[0].structureId),{structureProfiles:Object.fromEntries(r),allStructuresLinked:f,maxQualifyingDepth:c,sourceStructureIds:a,hasDrawFeedProfile:o,structureGroups:l}}function iI({drawDefinition:t}){const{maxQualifyingDepth:e,structureProfiles:n}=rI({drawDefinition:t});for(const r of t.structures){const t=n[r.structureId];t.distanceFromMain&&(r.stageSequence=e+1-t.distanceFromMain)}return{...z}}function aI(t){const e=cc(t,[{[hs]:!0,[Is]:!0}]);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r,structure:i,link:a}=t;return function(t){const e=cc(t,[{[Is]:!0,[ks]:!0},{link:!0,[nc]:Js,[Y]:kt}]);if(e.error)return e;const{drawDefinition:n,tournamentId:r,structure:i,eventId:a,link:o}=t,s=o.target.structureId,c=ad({drawDefinition:n,structureId:s});if(c.error)return ti({stack:"attachQualifyingStructure",context:{targetStructureId:s},result:c});n.structures||(n.structures=[]);n.links||(n.links=[]);n.structures.push(i),n.links.push(o),iI({drawDefinition:n});const u=Jm({structure:i})?.matchUps||[];return Gd({drawDefinition:n,tournamentId:r,matchUps:u,eventId:a}),Hd({drawDefinition:n,structureIds:[i.structureId]}),{...z}}({tournamentId:n.tournamentId,drawDefinition:r,structure:i,link:a})}function oI({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:Jn};if(!t)return{error:ot};const n=Object.assign({},...e.map((t=>{if(!G(t))return;const{structureId:e,structureName:n}=t||{};return e&&n?{[e]:n}:void 0})).filter(Boolean));if(!Object.values(n).length)return{error:be};for(const e of t.structures||[]){const t=n[e.structureId];if(t&&(e.structureName=t),e.structures)for(const t of e.structures){const e=n[t.structureId];e&&(t.structureName=e)}}return{...z}}function sI({drawDefinition:t,timeItem:e}){if(!t)return{error:ct};if(!e)return{error:_n};const n=e&&Object.keys(e),r=["itemType","itemValue"];if(!(r.filter((t=>n.includes(t))).length===r.length))return{error:kn};t.timeItems||(t.timeItems=[]);const i=(new Date).toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Wd({drawDefinition:t}),{...z}}function cI(t){const{tournamentRecord:e,drawDefinition:n,structureId:r,event:i}=t,a=cc(t,[{drawDefinition:!0,structureId:!0}]);if(a.error)return a;const o=n.structures??[],s=o.find((t=>t.structureId===r));if(!s)return{error:Lt};const c=o.find((({stage:t,stageSequence:e})=>t===fo&&1===e)),u=r===c?.structureId,d=o.filter((({stage:t})=>t===ho)).map(If("structureId"));if(u&&!d.length)return{error:X};const p=d.includes(r),l=function({isQualifyingStructure:t,tournamentRecord:e,drawDefinition:n,structureId:r,structure:i,event:a,force:o}){const s=[r];if(t){const t=t=>n.links?.find((e=>e.target.structureId===t));let e=t(r)?.source.structureId;for(;e;)s.push(e),e=t(e)?.source.structureId}const c=cf({matchUpFilters:{structureIds:s},drawDefinition:n}).matchUps,u=c?.some((({score:t})=>vf({score:t})));if(u){const t=Np({tournamentRecord:e,drawDefinition:n,structure:i,event:a})?.appliedPolicies;if(!(o??t?.[Nc]?.allowDeletionWithScoresPresent?.structures))return{error:mr}}return{...z}}({isQualifyingStructure:p,structure:s,...t});if(l?.error)return l;const{structureIdsToRemove:m,relatedStructureIdsMap:f}=function({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:n,mainStageSequence1:r,drawDefinition:i,structureId:a}){const o=i.structures??[],s=o.map(If("structureId")),c=t=>i.links?.map((e=>e.source.structureId===t&&e.target.structureId!==r?.structureId&&e.target.structureId)).filter(Boolean)??[],u=e=>i.links?.map((n=>t.includes(n.source.structureId)&&n.target.structureId===e&&n.source.structureId)).filter(Boolean)??[],d=new Map;s.forEach((t=>d.set(t,e?u(t):c(t))));const p=n?d.get(a):[a];return{structureIdsToRemove:p,relatedStructureIdsMap:d}}({qualifyingStructureIds:d,isQualifyingStructure:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:n,structureId:r}),{removedMatchUpIds:h,removedStructureIds:g}=function({relatedStructureIdsMap:t,qualifyingStructureIds:e,isMainStageSequence1:n,mainStageSequence1:r,drawDefinition:i,structureIdsToRemove:a,structureId:o}){const s=[],c=[];for(;a?.length;){const u=a.pop();c.push(...pI({idBeingRemoved:u,drawDefinition:i}));const d=dI({qualifyingStructureIds:e,isMainStageSequence1:n,idBeingRemoved:u,drawDefinition:i,structureId:o});s.push(...d.removedStructureIds);const p=uI({relatedStructureIdsMap:t,mainStageSequence1:r,idBeingRemoved:u,structureId:o});p?.length&&a.push(...p)}return{removedMatchUpIds:c,removedStructureIds:s}}({relatedStructureIdsMap:f,qualifyingStructureIds:d,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:n,structureIdsToRemove:m,structureId:r});if(function({removedMatchUpIds:t,drawDefinition:e}){const{matchUps:n}=cf({drawDefinition:e});n?.forEach((e=>{e.winnerMatchUpId&&t.includes(e.winnerMatchUpId)&&delete e.winnerMatchUpId,e.loserMatchUpId&&t.includes(e.loserMatchUpId)&&delete e.loserMatchUpId}))}({removedMatchUpIds:h,drawDefinition:n}),u){const t=(c.matchUps??[])?.map(If("matchUpId"));h.push(...t),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return p&&iI({drawDefinition:n}),qd({tournamentId:e?.tournamentId,matchUpIds:h,action:"removeStructure",eventId:i?.eventId,drawDefinition:n}),Hd({drawDefinition:n,eventId:i?.eventId}),{...z,removedMatchUpIds:h,removedStructureIds:g}}function uI({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:n,structureId:r}){return t&&e.get(t)?.filter((t=>t!==n?.structureId||r===n.structureId))}function dI({qualifyingStructureIds:t,isMainStageSequence1:e,idBeingRemoved:n,drawDefinition:r,structureId:i}){const a=[];return r.links=r.links?.filter((t=>t.source.structureId!==n&&t.target.structureId!==n))??[],(!e||e&&t.length||n!==i)&&(r.structures=(r.structures??[]).filter((t=>(n&&n===t.structureId&&a.push(n),t.structureId!==n)))),{removedStructureIds:a}}function pI({idBeingRemoved:t,drawDefinition:e}){const{structure:n}=ad({structureId:t,drawDefinition:e}),r=Jm({structure:n}).matchUps;return bu(r)}function lI({stageSequence:t=1,drawDefinition:e,drawSize:n,stage:r}){if(!e)return{error:ot};if(!cl({drawDefinition:e,stage:r}))return{error:Jt};const i=function({stage:t,drawDefinition:e}){return il.reduce(((n,r)=>(ul({drawDefinition:e,entryStatus:r,stage:t})||0)+n),0)}({drawDefinition:e,stage:r}),{qualifiersCount:a}=oh({drawDefinition:e,stageSequence:t,stage:r});if(n<i+a)return{error:Pt};const{entryProfile:o}=jp({attributes:[{[r]:{drawSize:n}}],drawDefinition:e});return Hd({drawDefinition:e}),{...z,entryProfile:o}}function mI({qualifiersCount:t=0,drawDefinition:e,stage:n}){return e?cl({drawDefinition:e,stage:n})?(jp({attributes:[{[n]:{qualifiersCount:t}}],drawDefinition:e}),Hd({drawDefinition:e}),{...z}):{error:Jt}:{error:ot}}function fI(t){return function({drawDefinition:t,drawSize:e}){if(!t)return{error:ot};const n=lI({stage:Io,stageSequence:1,drawDefinition:t,drawSize:e});return n.error?n:(Hd({drawDefinition:t}),{...z})}(t)}function hI({tournamentRecord:t,drawDefinition:e,event:n,structureId:r}){if(!e)return{error:ot};const i=e.structures?.find((t=>t.stage===ho&&t.structureId===r));if(!i)return{error:Lt};const a=i.matchUps?.some((({matchUpStatus:t,score:e})=>vf({score:e})??Xu.includes(t)));if(a)return{error:mr};const o=i.matchUps?.map((({matchUpId:t})=>t))||[];return i.positionAssignments=[],i.seedAssignments=[],i.matchUps=[],qd({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:o,drawDefinition:e}),Hd({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[i.structureId]}),{...z}}const gI="removeDrawPositionAssignment",II="swapDrawPositionAssignments",UI="assignDrawPosition",yI="addPenalty",SI="MODIFY_PAIR",vI="QUALIFIER",wI="ALTERNATE",PI="WITHDRAW",DI="ASSIGN",TI="REMOVE",bI="LUCKY",RI="REMOVE_SEED",MI="SWAP",NI="NICKNAME",AI="SEED_VALUE",EI="PENALTY",CI="BYE",OI={MODIFY_PAIR_ASSIGNMENT:SI,QUALIFYING_PARTICIPANT:vI,ALTERNATE_PARTICIPANT:wI,WITHDRAW_PARTICIPANT:PI,ASSIGN_PARTICIPANT:DI,LUCKY_PARTICIPANT:bI,REMOVE_ASSIGNMENT:TI,SWAP_PARTICIPANTS:MI,ADD_NICKNAME:NI,REMOVE_SEED:RI,ADD_PENALTY:EI,ASSIGN_BYE:CI,SEED_VALUE:AI};function FI({tournamentRecord:t,drawDefinition:e,drawPositions:n,structureId:r,event:i}){if(!e)return{error:ot};if(!r)return{error:_t};if(2!==n?.length)return{error:Jn,drawPositions:n};const o=hl({drawDefinition:e}),{matchUps:s}=cf({inContext:!0,drawDefinition:e,matchUpsMap:o}),{structure:c}=ad({drawDefinition:e,structureId:r});if(!c)return{error:Lt};const u=Np({tournamentRecord:t,drawDefinition:e,event:i}).appliedPolicies??{};let d;if(d=c.structureType===Mo?function({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPositions:r,matchUpsMap:i,structure:a,event:o}){const s=a.structures?.reduce(((t,e)=>{const n=e?.positionAssignments.filter((t=>r?.includes(t.drawPosition)));return n&&t.push(...n),t}),[]);if(2===s.filter((({bye:t})=>t)).length)return{...z};if(2===s.filter((({qualifier:t})=>t)).length)return{...z};lg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,assignments:s,structure:a,event:o});const c=s.some((({qualifier:t})=>t));if(s.some((({bye:t})=>t))&&!c)kI({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:a,event:o});else{const t=la(s,!1,!0);s.forEach(((e,n)=>{const r=t[1-n].participantId;e.qualifier=t[1-n].qualifier,e.participantId=r}))}return{...z}}({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:o,structure:c,event:i}):function({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPositions:r,matchUpsMap:i,structure:a,event:o}){const s=a?.positionAssignments.filter((t=>r?.includes(t.drawPosition)));if(!s)return{error:Jn,structure:a,info:"Missing positionAssignments"};if(2===s.filter((({bye:t})=>t)).length)return{...z};if(2===s.filter((({qualifier:t})=>t)).length)return{...z};const c=s.some((({qualifier:t})=>t));return s.some((({bye:t})=>t))&&!c?kI({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:a,event:o}):function({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:r,matchUpsMap:i,structure:a,event:o}){const s=Object.assign({},...r.map(((t,e)=>{const{drawPosition:n}=t,i={...r[1-e],drawPosition:n};return{[n]:i}})));return a.positionAssignments=a.positionAssignments.map((t=>s[t.drawPosition]||t)),lg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,assignments:r,structure:a,event:o}),{...z}}({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:a,event:o})}({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:o,structure:c,event:i}),d.error)return d;Qd({structure:c,drawPositions:n});if(Jd({appliedPolicies:u,drawDefinition:e,positionAction:{name:II,drawPositions:n,structureId:r}}),Yd({tournamentId:t?.tournamentId,drawDefinition:e,structure:c,event:i}),i.eventType===lo){const r=Jm({matchUpFilters:{matchUpTypes:[a]},inContext:!0,structure:c}).matchUps.filter((t=>t.drawPositions?.some((t=>n.includes(t))))),o=Jm({matchUpFilters:{matchUpTypes:[a]},structure:c}).matchUps;r.forEach((r=>{(r.sides||[]).forEach((a=>{const s=a?.drawPosition;if(n.includes(s)){const n=a.participantId,c=o.find((({matchUpId:t})=>t===r.matchUpId)),u=r?.sides?.reduce(((t,e,n)=>e.drawPosition===s?n:t),void 0);eg({inContextTargetMatchUp:r,drawPositionSideIndex:u,teamParticipantId:n,tournamentRecord:t,drawDefinition:e,matchUp:c,event:i})}}))}))}return Hd({drawDefinition:e,structureIds:[r]}),{...z}}function kI({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:r,matchUpsMap:i,structure:a,event:o}){const s=r.find((({bye:t})=>t)),c=r.find((({participantId:t})=>t)),u=s.drawPosition,{participantId:d,drawPosition:p}=c,{structureId:l}=a;let m=Ch({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i});return m.error?m:(m=Ch({drawPosition:p,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i}),m.error?m:(Ef({drawPosition:p,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i,event:o}),m=mg({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,participantId:d,matchUpsMap:i,event:o}),m.error?m:{...z}))}function xI({tournamentRecord:t,drawDefinition:e,participantId:n,structureId:r}){const i="removeSeededParticipant";if(!t)return{error:nt};if(!e)return{error:ot};const a=(e.structures??[]).find((t=>t.structureId===r));if(!a)return ti({result:{error:Lt},stack:i});if(!a.stage||![fo,ho].includes(a.stage)||a.stage===fo&&1!==a.stageSequence)return ti({result:{error:ut},stack:i});const o=a.seedAssignments?.find((t=>t.participantId===n));return o?{...z}:ti({info:"participant not seeded",result:{error:rr},context:{participantId:n}})}function _I({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:n,sourceStructureId:r,targetStructureId:i,linkType:a=Fo}){if(!r||!i)return{error:_t};return{link:Xr({linkType:a,source:{roundNumber:n,structureId:r,finishingPositions:e},target:{feedProfile:No,roundNumber:t,structureId:i}})}}function LI({matchUp:t,tieFormat:e,isMock:n,uuids:r}){const{collectionDefinitions:i}=e??{};return{tieMatchUps:(i??[]).map((e=>BI({matchUp:t,collectionDefinition:e,uuids:r,isMock:n}))).filter(Boolean).flat()}}function BI({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:n,matchUp:r,isMock:i,uuids:a}){const{matchUpCount:o,matchUpType:s,collectionId:c,processCodes:u}=e||{},d=t=>{if(!i&&!r?.isMock)return a?.pop()??ha();const n=e?.collectionId;return a?.pop()??`${r?.matchUpId}-${n}-TMU-${t+1}`};return E(0,n??o??0).map((e=>{const n=t+e+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:d(e),matchUpStatus:Hu,collectionPosition:n,collectionId:c,processCodes:u,matchUpType:s,isMock:i}}))}function VI({roundPosition:t,roundNumber:e,idPrefix:n,uuids:r}){return n?`${n}-${e}-${t}`:r?.pop()||ha()}function jI({includeMatchUpType:t,matchUpType:e,roundNumber:n,matchUps:r,idPrefix:i,isMock:a,uuids:o,nodes:s}){let c=0;const u=[];let d=1;const p=n-1,l=s?.length;for(;c<(l||0);){const l=s?.[c],m=s?.[c+1];p&&(l.roundNumber=p),m&&p&&(m.roundNumber=p);const f={roundPosition:d,children:[l,m],matchUpId:VI({roundPosition:d,roundNumber:n,idPrefix:i,uuids:o})};u.push(f);const h={drawPositions:f.children.map((t=>t?.drawPosition)).filter(Boolean),matchUpStatus:Hu,matchUpId:f.matchUpId,roundPosition:d,roundNumber:n};t&&e&&(h.matchUpType=e),a&&(h.isMock=!0),r.push(h),d++,c+=2}return{roundNodes:u,matchUps:r}}function GI({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:n,qualifyingPositions:r,matchUpType:i,roundLimit:a,idPrefix:o,drawSize:s,isMock:c,uuids:u}){if(isNaN(s)||s<2||r&&s<=r)return{matchUps:[],roundsCount:0};if(r&&(!p(s)||s%r)){let t=r;for(;t<s;)t*=2;s=t}const d=r&&!(s%2)&&(!isNaN(r)||n&&!isNaN(n))&&(s/r===Math.round(s/r)||n&&s/n===Math.round(s/n));if(!p(s)&&!d)return{matchUps:[],roundsCount:0};const l=E(1,s+1).map((t=>({drawPosition:t})));let m,f=[],h=1;for(({roundNodes:m,matchUps:f}=jI({matchUpType:i,roundNumber:h,idPrefix:o,matchUps:f,isMock:c,nodes:l,uuids:u})),h++,a=a??n;m.length>1;)r&&m.length===r&&(a=h-1),({roundNodes:m,matchUps:f}=jI({nodes:m,matchUpType:i,roundNumber:h,idPrefix:o,matchUps:f,isMock:c,uuids:u})),h++;const g=h-1;return f=Uf({finishingPositionOffset:t,finishingPositionLimit:e,roundsCount:g,roundLimit:a,matchUps:f}),a?f=f.filter((t=>a&&(t.roundNumber??0)<=a)):a=h-1,{drawSize:s,matchUps:f,roundsCount:g,roundLimit:a}}function qI(t){const e="generateQualifyingStructure";if(!t.drawDefinition)return ti({result:{error:ot},stack:e});if(t.drawSize&&!y(t.drawSize)||t.participantsCount&&!y(t.participantsCount)||t.qualifyingPositions&&!y(t.qualifyingPositions))return ti({result:{error:Jn},stack:e});let n=t.drawSize??m(t.participantsCount);const{hasExistingDrawDefinition:r,qualifyingRoundNumber:i,qualifyingPositions:a,targetStructureId:o,structureOptions:s,appliedPolicies:c,qualifyingOnly:u,drawDefinition:d,matchUpFormat:p,structureName:l,structureId:f,roundTarget:h,tieFormat:g,drawType:I,idPrefix:U,isMock:S,uuids:v}=t;if(!t.drawSize)return ti({result:{error:Dt},context:{drawSize:n},stack:e});if(a&&a>=t.drawSize)return ti({result:{error:Jn},context:{drawSize:n,qualifyingPositions:a},stack:e});let w,P,D,T,b,R=0;const{structureProfiles:M}=rI({drawDefinition:d}),N=M[o];if(!N)return ti({result:{error:Lt},context:{targetStructureId:o},stack:e});const A=d.matchUpType,E=h?`${h}-`:"",C=N.stage===ho,O=c?.[Dc]?.namingConventions?.pre??Tl[Dc]?.namingConventions?.pre,F=C&&O?`${O}-`:"",k=l??(E?`${F}${xh(ho)} ${E}`:`${F}${xh(ho)}`);if(I===rs){const{maxRoundNumber:t,structures:e,groupCount:i}=Gh({structureName:l??k,structureId:f??v?.pop(),hasExistingDrawDefinition:r,stage:ho,structureOptions:s,appliedPolicies:c,qualifyingOnly:u,stageSequence:1,matchUpType:A,roundTarget:h,tieFormat:g,idPrefix:U,drawSize:n,isMock:S,uuids:v});R=i,w=t,D=e[0],b=[1]}else({drawSize:n,matchUps:T,roundLimit:w,roundsCount:P}=GI({qualifyingRoundNumber:i,qualifyingPositions:a,matchUpType:A,idPrefix:U,drawSize:n,isMock:S,uuids:v})),w||(w=P),D=Fh({structureName:l??k,structureId:f??v?.pop(),qualifyingRoundNumber:w,stage:ho,matchUpFormat:p,stageSequence:1,matchUpType:A,roundLimit:w,matchUps:T}),h&&_c({extension:{name:pu,value:h},element:D}),R=T?.filter((t=>t.roundNumber===w))?.length;const x=I===rs?Oo:Fo,_=D&&w&&_I({sourceStructureId:D.structureId,sourceRoundNumber:w,targetStructureId:o,finishingPositions:b,linkType:x})?.link;return g&&(T=Jm({structure:D})?.matchUps||[],T?.forEach((t=>{const{tieMatchUps:e}=LI({tieFormat:g,matchUp:t,isMock:S});Object.assign(t,{tieMatchUps:e,matchUpType:A})}))),{qualifyingDrawPositionsCount:n,qualifiersCount:R,...z,structure:D,link:_}}function $I(t){if(!t.tournamentRecord)return{error:nt};const e=function(t){if(!t.drawDefinition)return{error:ot};if(!t.targetStructureId)return{error:_t};const e=qI(t);if(e.error)return e;const{structure:n,link:r}=e;return n&&r?aI({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:n,link:r}):{error:Jn}}(t);return e.error,e}function WI(t){const e=cc(t,[{[Is]:!0,[Ts]:!0,[Cs]:!0},{[Ds]:!0,[Xs]:t=>Number.isInteger(t)&&t>0},{[Xs]:t=>Array.isArray(t)&&2===t.length&&t.every(j),[ec]:ze,participantIds:!0}]);if(e.error)return e;const{drawDefinition:n,structureId:r,tournamentRecord:i,event:a}=t,{structure:o}=ad({drawDefinition:n,structureId:r});if(!o)return{error:Lt};if(!Dl({structure:o}))return{error:ut};const s=(o?.matchUps??[]).filter((e=>e.roundNumber===t.roundNumber)).filter((t=>!vf(t))).filter((e=>e.sides?.map((t=>t.participantId)).some((e=>t.participantIds.includes(e)))));if(2!==s.length)return{error:ze};for(const e of s){const r=e?.sides?.find((e=>t.participantIds.includes(e?.participantId)));if(r){const o=t.participantIds.find((t=>t!==r?.participantId));r.participantId=o,$d({tournamentId:i?.tournamentId,eventId:a?.eventId,drawDefinition:n,matchUp:e})}}return Hd({drawDefinition:n,structureIds:[r]}),{...z}}function HI({includeMatchUpType:t,drawPosition:e,roundNumber:n,matchUpType:r,idPrefix:i,matchUps:a,isMock:o,uuids:s,nodes:c,fed:u}){const d=c.length,p=e?e-d:void 0,l=E(0,d).map((t=>p?p+t:void 0)),m=[];for(let e=0;e<d;e++){const d=l.shift(),p={drawPosition:d,fed:u+1,feed:!0},f=c[e];f.roundNumber=n-1;const h=VI({roundPosition:f.roundPosition,roundNumber:n,idPrefix:i,uuids:s}),g={roundPosition:f.roundPosition,drawPositions:[d],matchUpStatus:Hu,roundNumber:n,matchUpId:h};t&&(g.matchUpType=r),o&&(g.isMock=!0),a.push(g);const I={children:[f,p]};m.push(I)}return{roundNodes:m,matchUps:a,drawPosition:e?e-d:void 0}}function zI(t){const e=t.drawSize;let{feedRoundsProfile:n,feedRounds:r=0,skipRounds:i=0,baseDrawSize:a}=t;const{linkFedFinishingRoundNumbers:o,finishingPositionOffset:s,linkFedRoundNumbers:c,feedsFromFinal:u,isConsolation:d,matchUpType:p,idPrefix:l,isMock:m,uuids:h,fmlc:g}=t;a=a??function(t){const e=f(t);return e>t?e/2:e}(e);const I=function({drawSize:t}){const e=Math.ceil(Math.log(t)/Math.log(2));return E(0,e).reverse().map((t=>Math.pow(2,t)))}({drawSize:a}),U=I.length;let y=0;if(n?.length)y=n.reduce(((t,e)=>t+e),0);else if(e){let t=e-a;n=I.filter((e=>e<=t&&(t-=e,!0))),y=n.reduce(((t,e)=>t+e),0),r=n.length}else i>=U?r=0:u&&(r=U-u,i=0),n=I.filter(((t,e)=>u&&!r||r&&e>=i+r||e<i?0:t)),y=n.reduce(((t,e)=>t+e),0),r=n.length;const S=[...I,...n].sort(((t,e)=>e-t)),v=S.length,w=[...(c??[]).map((t=>t-1)),...(o??[]).map((t=>v-t))].map((t=>S[t])).reduce(((t,e)=>t+e),0);y-=w;let P,D=0,b=[],R=1;let M=E(0,a).map(((t,e)=>({drawPosition:e+1+y}))),N=y+1;for(const t of I){if(({roundNodes:P,matchUps:b}=jI({matchUpType:p,roundNumber:R,idPrefix:l,matchUps:b,isMock:m,nodes:M,uuids:h})),R++,n.includes(t)){const e=E(0,T(n)[t]),r=v+1-R,i=o?.includes(r)??c?.includes(R);e.forEach((()=>{const t=!i&&N||void 0;({roundNodes:P,matchUps:b,drawPosition:N}=HI({drawPosition:t,nodes:P,matchUpType:p,roundNumber:R,idPrefix:l,matchUps:b,isMock:m,uuids:h,fed:D})),R++,D+=1}))}M=P}v!==R-1&&console.log("ERROR");b=Uf({finishingPositionOffset:d?a-y:s,positionsFed:y,roundsCount:v,matchUps:b,fmlc:g});const A=P?.length?P[0]:P;return A&&(A.roundNumber=R-1,A.matchUps=b),{draw:A,matchUps:b,roundsCount:v}}function YI(t){const{finishingPositionOffset:e=0,addNameBaseToAttributeName:n,playoffStructureNameBase:r,finishingPositionNaming:i,finishingPositionLimit:a,playoffAttributes:o,stageSequence:s=1,exitProfile:c="0",exitProfileLimit:u,roundOffsetLimit:d,roundOffset:p=0,drawDefinition:l,staggeredEntry:m,sequenceLimit:f,stage:h=fo,drawSize:g,idPrefix:I,isMock:U,uuids:y}=t;if(!(!o||!u||o?.[c])||g<2||f&&s>f)return{};const S=[],v=[],w=[],P=t.matchUpType??l?.matchUpType,D=e+1,T=`${D}-${e+g}`,b=o?.[c],R=r&&`${r} `||"",M=o?.[T]??i?.[T],N=t.structureName||M?.name||b?.name&&(n?`${R}${b?.name}`:b.name)||`${R}${T}`,A=M?.abbreviation??b?.abbreviation,C=t.structureId??b?.structureId??y?.pop(),O={idPrefix:I&&`${I}-${N}-RP`,finishingPositionOffset:e,matchUpType:P,drawSize:g,isMock:U,uuids:y},{matchUps:F}=m?zI(O):GI(O),k=Fh({structureAbbreviation:A,stageSequence:s,structureName:N,matchUpType:P,roundOffset:p,structureId:C,matchUps:F,stage:h});S.push(...F),v.push(k);const x=Math.ceil(Math.log(g)/Math.log(2)),_=d?Math.min(d-p,x):(!a||D<a)&&x||0;return g>2&&E(1,_+1).forEach((t=>function(t){const m=g/Math.pow(2,t);if(m<2)return;const U=g/Math.pow(2,t)+e;if(a&&U+1>a)return;const{structures:D,structureId:T,matchUps:b,links:R}=YI({finishingPositionOffset:U,exitProfile:`${c}-${t}`,roundOffset:p+t,stageSequence:s+1,drawSize:m,addNameBaseToAttributeName:n,playoffStructureNameBase:r,finishingPositionNaming:i,finishingPositionLimit:a,playoffAttributes:o,exitProfileLimit:u,roundOffsetLimit:d,drawDefinition:l,sequenceLimit:f,matchUpType:P,idPrefix:I,uuids:y,stage:h});if(k.structureId&&T){const e={linkType:ko,source:{roundNumber:t,structureId:k.structureId},target:{roundNumber:1,feedProfile:Eo,structureId:T}};R&&k&&R.push(e),R?.length&&w.push(...R)}D?.length&&v.push(...D);b?.length&&S.push(...b);return{structureId:T,childLinks:R,structures:v}}(t))),{structureId:k.structureId,matchUps:S,structureName:N,structures:v,links:w,...z}}function KI({drawDefinition:t,matchUpsMap:e,structureId:n}){const r=ad({drawDefinition:t,structureId:n});if(r.error)return ti({result:r});const{matchUps:i}=Jm({structure:r.structure,matchUpsMap:e});return{...Sl({matchUps:i}),matchUps:i,matchUpsMap:e}}function QI({finishingPositions:t,drawDefinition:e,structureId:n}){const{roundProfile:r}=KI({drawDefinition:e,structureId:n}),i=r&&Object.keys(r);return i?.reduce(((e,n)=>(JI(r?.[n]).forEach((r=>{t.forEach((t=>{(function({position:t,rangeDefinition:e}){if(!Array.isArray(e))return!1;if(e.reduce(((t,e)=>t||isNaN(e)),!1))return!1;const[n,r]=e;return E(n,(r||n)+1).includes(t)})({position:t,rangeDefinition:r})&&(e[t]={roundNumber:n})}))})),e)),{})}function JI(t){return[w(t?.finishingPositionRange?.loser||[]),w(t?.finishingPositionRange?.winner||[])]}function ZI(t){return JI(t).map((t=>E(t[0],t[1]&&t[1]+1||t[0]+1)))}function XI({drawDefinition:t,structureIds:e,matchUpsMap:n}){if(e&&!Array.isArray(e))return{error:Jn,context:{structureIds:e}};if(!t)return{error:ot};const r=(e=e??(t.structures??[]).filter((t=>t.stage!==ho)).map((({structureId:t})=>t))).map((e=>{const{roundProfile:r}=KI({drawDefinition:t,matchUpsMap:n,structureId:e}),i=r&&Object.values(r);return i?.map(ZI).flat()})).flat(),i=r.filter((t=>1===t?.length)).sort(u).flat();return{positionsNotPlayedOff:w(r.flat()).filter((t=>!i.includes(t))),positionsPlayedOff:i}}function tU({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:n,structureId:r}){if(!n)return{error:ot};if(!r)return{error:_t};if(!e)return{error:be,info:"missing playoffPositions"};const i=XI({drawDefinition:n});if(i.error)return i;const a=i.positionsPlayedOff,o=QI({finishingPositions:e.filter((t=>!a.includes(t))),drawDefinition:n,structureId:r}),s=Object.values(o).reduce(((t,e)=>t.includes(e.roundNumber)?t:t.concat(e.roundNumber)),[]).map((t=>d(t))).filter((e=>!t.includes(e))),c=QI({finishingPositions:a,drawDefinition:n,structureId:r}),p=c?Object.values(c):[],l=c?p.reduce(((t,e)=>t.includes(e.roundNumber)?t:t.concat(e.roundNumber)),[]).map((t=>d(t))):[],m=s.filter((t=>!l.includes(t))).sort(u),{roundProfile:f}=KI({drawDefinition:n,structureId:r}),h=m.map((t=>{const e=f?.[t].finishingPositionRange.loser,[n,r]=e??[0,0];return E(n,(r||n)+1)})).flat().sort(u),{playoffRoundsRanges:g}=function({playoffSourceRounds:t,roundProfile:e}){const n=t.map((t=>{const n=e[t].finishingPositionRange.loser,[r,i]=n,a=E(r,(i||r)+1);return{finishingPositionRange:n.join("-"),finishingPositions:a,roundNumber:t}}));return{playoffRoundsRanges:n}}({playoffSourceRounds:m,roundProfile:f}),I=[...m,...l];return{playoffPositionsReturned:h,playedOffSourceRounds:l,playoffRoundsRanges:g,playoffSourceRounds:m,sourceRounds:I,roundProfile:f}}function eU({drawDefinition:t,structureId:e}){if(!t)return{error:ot};const{matchUps:n,matchUpsMap:r}=ff({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:i,positionsPlayedOff:a}=XI({drawDefinition:t,matchUpsMap:r}),{structures:o}=od({drawDefinition:t}),s=o.filter((t=>!e&&t.stage!==Io||t.structureId===e)),c={};for(const e of s){const r=e?.structureId,a=nU({playoffPositions:i,drawDefinition:t,structure:e,matchUps:n}),{error:o,...s}=a;if(o)return a;c[r]={structureId:r,...s}}return e?{positionsPlayedOff:a,...c[e]}:{availablePlayoffProfiles:Object.values(c),availablePlayoffRounds:Object.values(c),positionsPlayedOff:a}}function nU({playoffPositions:t,drawDefinition:e,structure:n,matchUps:r}){const i=n?.structureId,{links:a}=ef({drawDefinition:e,structureId:i});if(n.structureType===Mo||n.structures){const t=cd({structure:n})?.positionAssignments?.length,o=n.structures.length,s=(t??0)/o,c=a.source?.flatMap((({source:t})=>t?.finishingPositions||[]))||[],u=E(1,s+1).filter((t=>!c.includes(t))),d=r.find((t=>t.containerStructureId===i&&t.finishingPositionRange))?.finishingPositionRange?.winner||[0,1],p=a?.source.map((({target:t})=>t.structureId)),{positionsPlayedOff:l=[],positionsNotPlayedOff:m=[]}=XI({structureIds:p,drawDefinition:e}),f=[...l,...m],h=E(d[0],d[1]+1).filter((t=>!f.includes(t))),g=x(h,h.length/u.length);return{positionsNotPlayedOff:h,playoffFinishingPositionRanges:u.map(((t,e)=>{const n=g[e];return{finishingPosition:t,finishingPositions:n,finishingPositionRange:[Math.min(...n||[]),Math.max(...n||[])].join("-")}})),finishingPositionsAvailable:u,finishingPositionsPlayedOff:c,positionsPlayedOff:l,groupCount:o,groupSize:s}}const o=a?.source?.filter((t=>t.linkCondition!==xo)).map((t=>t.source?.roundNumber))||[],s=a?.source?.filter((t=>t.linkCondition===xo)).map((t=>t.source?.roundNumber))||[],c=tU({excludeRoundNumbers:o,playoffPositions:t,drawDefinition:e,structureId:i}),d=c?.playoffSourceRounds?[...c?.playoffSourceRounds||[]]:void 0,p=[...c?.playoffRoundsRanges||[]],{roundProfile:l,error:m}=c;for(const t of s){const e=a?.source.find((e=>e.source.roundNumber===t)),n=e?.target.roundNumber,i=e?.target.structureId,o=r.filter((({roundNumber:t,structureId:e})=>e===i&&t===n)),s=o.filter((({sides:t})=>t.find((t=>t.participantFed&&!t.participantId)))).length;if(d&&s===o.length){d.push(t);const e=l?.[t]?.finishingPositionRange?.loser;if(e){const n=Math.min(...e),r=n+s,i=E(n,r),a={finishingPositionRange:[n,r-1].join("-"),finishingPositions:i,roundNumber:t};p.push(a)}}}return d&&d.sort(u),p.sort(((t,e)=>t.roundNumber-e.roundNumber)),{playoffRounds:d,playoffRoundsRanges:p,error:m}}function rU(t){const{finishingPositionOffset:e=0,playoffAttributes:n,stageSequence:r=1,staggeredEntry:i,structureName:a,stage:o=fo,matchUpType:s,structureId:c,idPrefix:u,drawSize:d,isMock:p,uuids:l}=t,m={finishingPositionOffset:e,matchUpType:s,drawSize:d,idPrefix:u,isMock:p,uuids:l},{matchUps:f}=i?zI(m):GI(m),h=Fh({structureName:a||n?.[0]?.name||xh(fo),structureId:c||l?.pop(),stageSequence:r,matchUpType:s,matchUps:f,stage:o}),g=[h],I=[];if(d>2){const r=d/2,{matchUps:i}=GI({finishingPositionOffset:e+r,idPrefix:u&&`${u}-c`,drawSize:r,matchUpType:s,isMock:p}),o=xh(go),c=n?.["0-1"]?.name??t.consolationStructureName??(a?`${a} ${o}`:o),m=Fh({structureName:c,matchUps:i,structureId:l?.pop(),stage:go,stageSequence:1,matchUpType:s});g.push(m);const f={linkType:ko,source:{roundNumber:1,structureId:h.structureId},target:{roundNumber:1,feedProfile:Eo,structureId:m.structureId}};I.push(f)}return{...z,structures:g,links:I}}function iU({consolationStructure:t,roundOffset:e=0,mainStructure:n,roundsCount:r,feedPolicy:i,fmlc:a}){const o=t.matchUps.reduce(((t,e)=>(e.drawPositions||[]).filter(Boolean).length&&!t.includes(e.roundNumber)?t.concat(e.roundNumber):t),[]),s=i?.roundGroupedOrder||[],c=i?.roundFeedProfiles;return E(1+e,r+1+e).map((r=>{const i=c?.[r-1]?c[r-1]:r%2&&Eo||Co,u=r-e<=2?r-e:2*(r-e-2)+2,d={linkType:ko,source:{roundNumber:r,structureId:n.structureId},target:{feedProfile:i,roundNumber:u,structureId:t.structureId}},p=s[r-1];return p&&(d.target.groupedOrder=p),Pr()&&(d.source.structureName=n.structureName,d.target.structureName=t.structureName),2===r&&a&&(d.linkCondition=xo,d.target.feedProfile=Eo),o.includes(u)?d:void 0})).filter(Boolean)}function aU(t){const{playoffStructureNameBase:e,finishingPositionOffset:n,stageSequence:r=1,playoffAttributes:i,structureNameMap:a,staggeredEntry:o,stage:s=fo,matchUpType:c,structureId:u,drawSize:d,idPrefix:p,isMock:l,uuids:m}=t,f={finishingPositionOffset:n,matchUpType:c,drawSize:d,idPrefix:p,isMock:l,uuids:m},{matchUps:h,roundsCount:g}=o?zI(f):GI(f),I=t.structureName??i?.[0]?.name??xh(fo),U=Fh({structureId:u||m?.pop(),structureName:I,stageSequence:r,matchUpType:c,matchUps:h,stage:s}),y=[U],S=[];if(d>2){const t=[0,2].slice(0,d/16).map(((t,n)=>{const r=n+1,{consolationStructure:o}=function({playoffStructureNameBase:t,stageSequence:e=1,playoffAttributes:n,structureNameMap:r,roundOffset:i=0,matchUpType:a,structureId:o,idPrefix:s,drawSize:c,isMock:u,index:d,uuids:p}){const l=c/(2*Math.pow(2,i)),{matchUps:m,roundsCount:f}=zI({finishingPositionOffset:l,baseDrawSize:l,isConsolation:!0,feedRounds:1,matchUpType:a,idPrefix:s,isMock:u,uuids:p}),h=0===d&&n?.["0-1"]?.name||1===d&&n?.["0-3"]?.name,g=h||`${xh(go)} ${d+1}`,I=r?.[g]||g,U=t?`${t} ${I}`:I,y=Fh({matchUps:m,stage:go,structureName:U,stageSequence:e,matchUpType:a,structureId:o});return{consolationStructure:y,consolationRoundsCount:f}}({idPrefix:p&&`${p}-c${n}`,structureId:m?.pop(),playoffStructureNameBase:e,playoffAttributes:i,structureNameMap:a,stageSequence:r,roundOffset:t,matchUpType:c,drawSize:d,isMock:l,index:n,uuids:m});y.push(o);return{consolationStructure:o,links:iU({consolationStructure:o,roundsCount:2,mainStructure:U,roundOffset:t})}})),n=t.map((t=>t.links)).flat();if(S.push(...n),d>=4&&d<=16||d>32){const{matchUps:t}=GI({idPrefix:p&&`${p}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:l}),n=i?.["3-4"]?.name??xh(Uo),r=a?.[n]||n,o=e?`${e} ${r}`:r,s=Fh({structureId:m?.pop(),matchUps:t,stageSequence:2,stage:Uo,structureName:o,matchUpType:c}),u={linkType:ko,source:{roundNumber:g-1,structureId:U.structureId},target:{structureId:s.structureId,feedProfile:Eo,roundNumber:1}};y.push(s),S.push(u)}}return{structures:y,links:S,...z}}function oU(t){const{finishingPositionOffset:e,stageSequence:n=1,playoffAttributes:r,feedsFromFinal:i,staggeredEntry:a,structureName:o,stage:s=fo,structureId:c,matchUpType:u,skipRounds:d,feedRounds:p,idPrefix:l,drawSize:m,isMock:f,uuids:h,fmlc:g}=t,I=t.feedPolicy||t.policyDefinitions?.[Ec]||t.appliedPolicies?.[Ec],U={finishingPositionOffset:e,matchUpType:u,skipRounds:d,drawSize:m,idPrefix:l,isMock:f,uuids:h},{matchUps:y}=a?zI(U):GI(U),S=Fh({structureName:o||r?.[0]?.name||xh(fo),structureId:c||h?.pop(),stageSequence:n,matchUpType:u,matchUps:y,stage:s}),v=[S],w=[],P=m/2,{matchUps:D,roundsCount:T}=zI({finishingPositionOffset:P,idPrefix:l&&`${l}-c`,isConsolation:!0,feedsFromFinal:i,baseDrawSize:P,matchUpType:u,feedRounds:p,skipRounds:d,isMock:f,uuids:h,fmlc:g});if(m>2){const e=r?.["0-1"]?.name??xh(go),n=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${e}`:e,i=Fh({matchUps:D,structureId:h?.pop(),stage:go,stageSequence:1,structureName:n,matchUpType:u});v.push(i);const a=iU({consolationStructure:i,mainStructure:S,roundsCount:T,feedPolicy:I,fmlc:g});w.push(...a)}return{...z,structures:v,links:w}}function sU({requireSequential:t=!0,playoffMatchUpFormat:e,playoffAttributes:n,sourceStructureId:r,policyDefinitions:i,stageSequence:a,drawDefinition:o,playoffGroups:s,matchUpType:c,feedPolicy:d,groupCount:p,idPrefix:l,isMock:m,uuids:f}){d=d||i?.[Ec];const h="processPlayoffGroups";let g=0;const U=[],y=[],S=[],{error:v,positionRangeMap:w}=function({playoffGroups:t,drawDefinition:e,structureId:n}){if(!e)return{error:ot};if(!j(n)||!Array.isArray(t))return{error:Jn};const r=t.map((({finishingPositions:t})=>t)).flat(),i=eU({drawDefinition:e,structureId:n}),a=i.playoffFinishingPositionRanges?.filter((t=>r.includes(t.finishingPosition))),o=a?.reduce(((t,e)=>(t[e.finishingPosition]=e,t)),{});return{positionRangeMap:o}}({structureId:r,drawDefinition:o,playoffGroups:s});if(v)return ti({result:{error:v},stack:h});if(!(!w||s?.every((e=>{const{finishingPositions:n=[]}=e;if(!n.length)return!1;const r=[...n].sort(u).map(((t,e)=>(n[e+1]||t)-t)).every((t=>t<2));return(!t||r)&&n.every((t=>w[t]))}))))return ti({context:{validFinishingPositions:Object.values(w)},result:{error:Jn},stack:h});for(const t of s){const o=t.finishingPositions,s=w&&o.map((t=>w[t]?.finishingPositions)).flat(),u=p*o.length,h=I(u),v=2===h&&jo||t.drawType||jo;s&&(g=Math.min(...s)-1);const P=s&&`${Math.min(...s)}-${Math.max(...s)}`,D=t.structureName||P&&t.playoffAttributes?.[P]?.name||t.playoffAttributes?.[0]?.name,T={...{addNameBaseToAttributeName:t.addNameBaseToAttributeName,playoffStructureNameBase:t.playoffStructureNameBase,finishingPositionNaming:t.finishingPositionNaming,finishingPositionLimit:t.finishingPositionLimit,structureId:t.structureId??f?.pop(),playoffAttributes:t.playoffAttributes,structureNameMap:t.structureNameMap,sequenceLimit:t.sequenceLimit,structureName:D},idPrefix:l&&`${l}-po`,appliedPolicies:i,finishingPositionOffset:g,stage:Uo,stageSequence:a,matchUpType:c,drawSize:h,isMock:m,uuids:f},b=({playoffStructures:t,playoffLinks:e})=>{const[n]=t,i=cU({playoffStructureId:n.structureId,finishingPositions:o,sourceStructureId:r});S.push(i),S.push(...e),y.push(...t),U.push({structureId:n.structureId,finishingPositions:o}),g+=u};if(v===jo){const{matchUps:n}=GI({finishingPositionLimit:g+u,idPrefix:l&&`${l}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:h,isMock:m,uuids:f}),i=Fh({structureId:t.structureId??f?.pop(),matchUpFormat:e,stage:Uo,structureName:D,stageSequence:a,matchUps:n});y.push(i);const s=cU({playoffStructureId:i.structureId,finishingPositions:o,sourceStructureId:r});S.push(s),g+=u,U.push({structureId:i.structureId,finishingPositions:o})}else if([Bo,Vo,Uo].includes(v)){const e={playoffAttributes:t.playoffAttributes??n,playoffStructureNameBase:t.playoffStructureNameBase,structureId:t.structureId??f?.pop(),structureName:t.structureName,idPrefix:l&&`${l}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:Uo,roundOffset:0,stageSequence:a,drawSize:h,isMock:m,uuids:f};v===Bo?Object.assign(e,{playoffAttributes:t?.playoffAttributes??n??ss,roundOffsetLimit:3}):v===Vo&&Object.assign(e,{playoffAttributes:t?.playoffAttributes??n??cs,roundOffsetLimit:2});const i=YI(e);if(i.error)return i;if(i.links?.length&&S.push(...i.links),i.structures?.length&&y.push(...i.structures),y.sort(rd),i.structureId){const t=cU({playoffStructureId:i.structureId,finishingPositions:o,sourceStructureId:r});S.push(t),U.push({structureId:i.structureId,finishingPositions:o})}g+=u}else if([qo,ns,Xo,Jo,Ko,es].includes(v)){const e=[f?.pop(),f?.pop()],n={playoffStructureNameBase:t.playoffStructureNameBase,structureId:t.structureId??f?.pop(),playoffAttributes:t.playoffAttributes,idPrefix:l&&`${l}-po`,finishingPositionOffset:g,uuids:e,stage:Uo,structureName:D,matchUpType:c,feedPolicy:d,drawSize:h,isMock:m},i={[qo]:{fmlc:!0,feedRounds:1},[es]:{feedRounds:1},[Xo]:{feedsFromFinal:3},[Jo]:{feedsFromFinal:2},[Ko]:{feedsFromFinal:1}};Object.assign(n,i[v]||{});const{structures:a,links:s}=oU(n),[p]=a,I=cU({playoffStructureId:p.structureId,finishingPositions:o,sourceStructureId:r});S.push(I),S.push(...s),y.push(...a),U.push({structureId:p.structureId,finishingPositions:o}),g+=u}else if([rs].includes(v)){const{structures:e,links:n}=Gh({...T,structureOptions:t.structureOptions||{groupSize:4}});b({playoffStructures:e,playoffLinks:n})}else if([$o].includes(v)){const{structures:t,links:e}=rU(T);b({playoffStructures:t,playoffLinks:e})}else if([zo].includes(v)){const{structures:t,links:e}=aU(T);b({playoffStructures:t,playoffLinks:e})}else if([_o].includes(v)){b({playoffStructures:[Fh({structureId:t.structureId??f?.pop(),structureName:t.structureName,finishingPosition:xp,stage:Uo,stageSequence:a,matchUps:[]})],playoffLinks:[]})}}return{finishingPositionTargets:U,positionRangeMap:w,structures:y,links:S}}function cU({playoffStructureId:t,finishingPositions:e,sourceStructureId:n}){return{linkType:Oo,source:{structureId:n,finishingPositions:e},target:{structureId:t,feedProfile:No,roundNumber:1}}}function uU({value:t,sourceRange:e,targetRange:n}){const r=Math.min(...e),i=Math.max(...e),a=Math.min(...n);return(t-r)*(Math.max(...n)-a)/(i-r)+a}const dU="ELO",pU="NTRP",lU="UTR",mU="WTN",fU={ELO:dU,NTRP:pU,TRN:"TRN",UTR:"UTR",WTN:mU},hU={[dU]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[pU]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[lU]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[mU]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}};function gU(t){const e=cc(t,[{ratings:!0,[nc]:Js}]);if(e.error)return e;const r=t.matchUpType&&[n,i].includes(t.matchUpType)?t.matchUpType:n,a=Object.keys(hU),o=t.targetRatingType&&a.includes(t.targetRatingType)?t.targetRatingType:dU,s=t.ratings[r]?t.ratings[r].reduce(((t,e)=>t.includes(e.scaleName)?t:t.concat(e.scaleName)),[]):[];if(!s)return{error:rr};const c=t.ratings[r]?.find((t=>t.scaleName===o))??t.ratings[r][0];if(s[0]===o)return c;const u=c.scaleName,d=hU[c.scaleName].accessor,p=d?c.scaleValue[d]:c.scaleValue,l=function({sourceRatingType:t,sourceRating:e}){const n=hU[t].range,r=n[0]>n[1],i=hU[dU].range;return uU({value:r?n[0]-e:e,sourceRange:n,targetRange:i})}({sourceRatingType:u,sourceRating:p}),m=function({targetRatingType:t,sourceRating:e}){const n=hU[t].decimalsCount||0,r=hU[t].range,i=r[0]>r[1],a=Math.max(...r),o=uU({targetRange:r,sourceRange:hU[dU].range,value:e}),s=parseFloat(o.toFixed(n));return i?a-s:s}({targetRatingType:o,sourceRating:l});return{convertedRating:m,sourceRating:p}}function IU({participantResults:t,sides:e,score:r}){const i=e.find((({sideNumber:t})=>1===t)),a=e.find((({sideNumber:t})=>2===t)),o=i?.participant?.ratings,s=a?.participant?.ratings;if(o?.[n]&&s?.[n]){const e=dU,{convertedRating:n}=gU({ratings:o,targetRatingType:e}),{convertedRating:c}=gU({ratings:s,targetRatingType:e}),{side1pressure:u,side2pressure:d}=function({side1ConvertedRating:t,side2ConvertedRating:e,score:n}){const r=t>e?t:e,i=t>e?e:t,a=Math.abs(t-e),o=hU[dU].range,s=Math.max(...o),c=(r+0*(s-r))/s*a,u=n?.sets?.reduce(((t,e)=>t+(e?.side1Score??0)),0),d=n?.sets?.reduce(((t,e)=>t+(e.side2Score??0)),0),p=t>e?2:1,l=(u||0)*(i+(1===p?c:0)),m=(d||0)*(i+(2===p?c:0)),f=l+m,h=f?v(l/f):0,g=f?v(m/f):0;return{side1pressure:h,side2pressure:g}}({side1ConvertedRating:n,side2ConvertedRating:c,score:r});u&&t[i?.participantId].pressureScores.push(u),d&&t[a?.participantId].pressureScores.push(d);const p=Math.max(...hU[dU].range),l=v((c-n)/p),m=v((n-c)/p);t[i?.participantId].ratingVariation.push(l),t[a?.participantId].ratingVariation.push(m)}}function UU({winningSide:t,matchUpFormat:e=ba,matchUpStatus:n,tallyPolicy:r,score:i}){const a=[0,0],o=i?.sets,s="number"==typeof t&&t-1,c=Ii(e),u=vU(c?.bestOf??1);if("number"==typeof s&&(n===Lu&&r?.setsCreditForDefaults||n===zu&&r?.setsCreditForWalkovers))a[s]=u;else for(const t of o||[]){const{winningSide:e}=t;e&&(a[e-1]+=1)}return"number"==typeof s&&n===$u&&(+a[1-s]===u&&(a[1-s]-=1),r?.setsCreditForRetirements&&(a[s]=u)),a}function yU({matchUpFormat:t=ba,winningSide:e,matchUpStatus:n,tallyPolicy:r,score:i}){const{sets:a}=i||{};if(!a)return[0,0];const o="number"==typeof e&&e-1,s=Ii(t),c=vU(s?.bestOf??1),u=s?.setFormat?.tiebreakAt||0,p=[[],[]];if("number"==typeof o&&(n===Lu&&r?.gamesCreditForDefaults||n===zu&&r?.gamesCreditForWalkovers)){const t=c*(s?.setFormat?.setTo||0);p[o].push(t)}else a.forEach(((t,e)=>{const n=(t.setNumber||e+1)>c&&s?.finalSetFormat?"finalSetFormat":"setFormat",i=s?.[n]?.based,a=s?.[n].tiebreakSet,{side1Score:o,side2Score:u}=t;PU(i)&&(p[0].push(d(o||0)),p[1].push(d(u||0))),a&&t.winningSide&&!1!==r?.gamesCreditForTiebreakSets&&p[t.winningSide-1].push(1)}));if(n===$u&&"number"==typeof o){const i=a.length>c&&s?.finalSetFormat?"finalSetFormat":"setFormat",l=s?.[i];if(PU(l.based)){const i=l?.setTo||0,m=t=>{if(s&&""!==t)return+t==u-1||+t===u?d(u||0)+1:+t<u?i:u},f=UU({winningSide:e,score:{sets:a},matchUpStatus:n,matchUpFormat:t,tallyPolicy:r});if(p.map((t=>t[o]<=t[1-o])).reduce(((t,e)=>t+(e?1:0)),0)>f[1-o]){const t=p[o].length,e=m(p[1-o][t-1]);e&&(p[o][t-1]=e)}c>p[o].length&&r?.gamesCreditForRetirements&&p[o].push(i)}}return[p[0].reduce(((t,e)=>t+e),0),p[1].reduce(((t,e)=>t+e),0)]}function SU({matchUpFormat:t,score:e}){const n=t?Ii(t):void 0,r=vU(n?.bestOf??1),i=[0,0],a=[0,0];return e?.sets?.forEach(((t,e)=>{const o=(t.setNumber||e+1)>r&&n?.finalSetFormat?"finalSetFormat":"setFormat",s=n?.[o]?.based;if(wU(s)){const{side1Score:e,side2Score:n}=t;e&&(a[0]+=d(e||0)),n&&(a[1]+=d(n||0))}else t.side1TiebreakScore&&(a[0]+=d(t.side1TiebreakScore||0)),t.side2TiebreakScore&&(a[1]+=d(t.side2TiebreakScore||0)),(t.side1TiebreakScore||t.side2TiebreakScore)&&t.winningSide&&(i[t.winningSide-1]+=1)})),{pointsTally:a,tiebreaksTally:i}}function vU(t){return t&&Math.ceil(t/2)||1}function wU(t){return"P"===t}function PU(t){return!wU(t)}function DU({participantIds:t,pressureRating:e,groupingTotal:r,matchUpFormat:a,tallyPolicy:o,perPlayer:s,matchUps:c}){const u={},d=o?.excludeMatchUpStatuses||[],p=c?.filter((e=>(e.tieMatchUps||!d.includes(e.matchUpStatus))&&(!t?.length||2===O(t,[RU(e,0),RU(e,1)]).length))),l=p?.flatMap((({score:t,tieMatchUps:e})=>e?e.filter((({matchUpStatus:t})=>!d.includes(t))).flatMap((({score:t})=>t?.sets?.length??0)):t?.sets?.length??0)),m=l?.reduce(((t,e)=>t+e),0),f=t=>t?.sets?.reduce(((t,e)=>t+(e?.side1Score??0)+(e?.side2Score??0)),0)??0,h=p?.flatMap((({score:t,tieMatchUps:e})=>e?e.filter((({matchUpStatus:t})=>!d.includes(t))).flatMap((({score:t})=>f(t))):f(t))),g=h?.reduce(((t,e)=>t+e),0);for(const t of p??[]){const{matchUpStatus:r,tieMatchUps:c,tieFormat:d,score:p,winningSide:l,sides:m}=t,f=d&&t._disableAutoCalc&&d.collectionDefinitions.every((({scoreValue:t})=>t)),h=l&&TU(t),g=l&&bU(t);if(h||g)if(MU(u,h),MU(u,g),c?.length){s=0;for(const t of c){const{matchUpType:r}=t,a=um(i)(r),s=um(n)(r);t.winningSide&&(t.winningSide===l?(h&&(u[h].tieMatchUpsWon+=1,s&&(u[h].tieSinglesWon+=1),a&&(u[h].tieDoublesWon+=1)),g&&(u[g].tieMatchUpsLost+=1,s&&(u[g].tieSinglesLost+=1),a&&(u[g].tieDoublesLost+=1))):t.winningSide!==l&&(g&&(u[g].tieMatchUpsWon+=1,s&&(u[g].tieSinglesWon+=1),a&&(u[g].tieDoublesWon+=1)),h&&(u[h].tieMatchUpsLost+=1,s&&(u[h].tieSinglesLost+=1),a&&(u[h].tieDoublesLost+=1)))),AU({matchUpFormat:t.matchUpFormat,matchUpStatus:t.matchUpStatus,matchUpType:t.matchUpType,score:t.score,sides:t.sides,winningParticipantId:h,losingParticipantId:g,manualGamesOverride:f,participantResults:u,isTieMatchUp:!0,pressureRating:e,tallyPolicy:o,winningSide:l})}EU({winningParticipantId:h,losingParticipantId:g,participantResults:u,matchUpStatus:r})}else AU({matchUpFormat:t.matchUpFormat??a,matchUpType:t.matchUpType,isTieMatchUp:void 0,winningParticipantId:h,manualGamesOverride:f,losingParticipantId:g,participantResults:u,pressureRating:e,matchUpStatus:r,tallyPolicy:o,winningSide:l,score:p,sides:m});else if(r&&Xu.includes(r)){const e=RU(t,0),n=RU(t,1);e&&(MU(u,e),u[e].matchUpsCancelled+=1),n&&(MU(u,n),u[n].matchUpsCancelled+=1)}else if(c?.length){s=0;for(const t of c){if(t.winningSide){const e=m?.find((({sideNumber:e})=>e===t.winningSide))?.participantId,r=m?.find((({sideNumber:e})=>e===t.winningSide))?.participantId;e&&r&&(MU(u,e),MU(u,r),u[e].tieMatchUpsWon+=1,u[r].tieMatchUpsLost+=1,um(n)(t.matchUpType)?(u[e].tieSinglesWon+=1,u[r].tieSinglesLost+=1):um(i)(t.matchUpType)&&(u[e].tieDoublesWon+=1,u[r].tieDoublesLost+=1))}NU({score:t.score,manualGamesOverride:f,participantResults:u,sides:m})}}else NU({manualGamesOverride:f,participantResults:u,score:p,sides:m});if(f){const t=p?.sets?.reduce(((t,e)=>t+(e?.side1Score??0)),0),e=p?.sets?.reduce(((t,e)=>t+(e.side2Score??0)),0),n=m?.find((({sideNumber:t})=>1===t))?.participantId,r=m?.find((({sideNumber:t})=>2===t))?.participantId;MU(u,n),MU(u,r),n&&(u[n].gamesWon+=t,u[n].gamesLost+=e),r&&(u[r].gamesWon+=e,u[r].gamesLost+=t)}}return function({participantResults:t,groupingTotal:e,matchUpFormat:n,tallyPolicy:r,totalGames:i,perPlayer:a,totalSets:o}){const s=n&&Ii(n)||{},c=s.bestOf,u=c&&Math.ceil(c/2)||1,d=s.setFormat?.setTo,p=Math.pow(10,r?.precision||3);Object.keys(t).forEach((n=>{const s=t[n].setsWon,c=t[n].setsLost,l=r?.groupTotalSetsPlayed||"setsPct"===e?o:a*u||s+c;let m=Math.round(s/l*p)/p;(m===1/0||isNaN(m))&&(m=l);const f=t[n].tieMatchUpsWon,h=f+t[n].tieMatchUpsLost;let g=Math.round(f/h*p)/p;(g===1/0||isNaN(g))&&(g=f);const I=t[n].matchUpsWon,U=I+t[n].matchUpsLost;let y=Math.round(I/U*p)/p;(y===1/0||isNaN(y))&&(y=I);const S=t[n].gamesWon||0,v=t[n].gamesLost||0,w=(a||0)*u*(d||0),P=r?.groupTotalGamesPlayed||"gamesPct"===e?i:Math.max(w,S+v);let D=Math.round(S/P*p)/p;(D===1/0||isNaN(D))&&(D=0);const T=t[n].pointsWon+t[n].pointsLost;let b=Math.round(t[n].pointsWon/T*p)/p;(b===1/0||isNaN(b))&&(b=0),t[n].setsWon=s,t[n].setsLost=c,t[n].setsPct=m,t[n].tieMatchUpsWon=f,t[n].tieMatchUpsPct=g,t[n].matchUpsPct=y,t[n].gamesWon=S,t[n].gamesLost=v,t[n].gamesPct=D,t[n].pointsPct=b,t[n].result=`${t[n].matchUpsWon}/${t[n].matchUpsLost}`}))}({participantResults:u,groupingTotal:r,matchUpFormat:a,tallyPolicy:o,totalGames:g,perPlayer:s,totalSets:m}),{participantResults:u}}function TU(t){return RU(t,t.winningSide-1)}function bU(t){return RU(t,1-(t.winningSide-1))}function RU(t,e){if(!t?.sides)return console.log("no sides:",{matchUp:t}),"foo";const n=t.sides[e];return n?n.participantId:(console.log("No Side",{matchUp:t,index:e}),"foo")}function MU(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 NU({manualGamesOverride:t,participantResults:e,score:n,sides:r}){const{sets:i}=n||{},a=[[],[]],o=[0,0];for(const t of i||[]){const{winningSide:e,side1Score:n,side2Score:r}=t;e&&(o[e-1]+=1),a[0].push(d(n||0)),a[1].push(d(r||0))}const s=[a[0].reduce(((t,e)=>t+e),0),a[1].reduce(((t,e)=>t+e),0)];r.forEach(((n,r)=>{const{participantId:i}=n;i&&(MU(e,i),e[i].setsWon+=o[r],e[i].setsLost+=o[1-r],t||(e[i].gamesWon+=s[r],e[i].gamesLost+=s[1-r]))}))}function AU({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:i,pressureRating:a,matchUpFormat:o,matchUpStatus:s,isTieMatchUp:c,matchUpType:u,tallyPolicy:d,winningSide:p,score:l,sides:m}){const f=p&&p-1,h=1-f;a&&u===n&&IU({participantResults:i,sides:m,score:l}),c||EU({winningParticipantId:t,losingParticipantId:r,participantResults:i,matchUpStatus:s});const g=UU({matchUpStatus:s,matchUpFormat:o,tallyPolicy:d,winningSide:p,score:l}),I=yU({matchUpStatus:s,matchUpFormat:o,tallyPolicy:d,winningSide:p,score:l}),{pointsTally:U}=SU({score:l,matchUpFormat:o});t&&(i[t].setsWon+=g[f],i[t].setsLost+=g[h],e||(i[t].gamesWon+=I[f],i[t].gamesLost+=I[h]),i[t].pointsWon+=U[f],i[t].pointsLost+=U[h]),r&&(i[r].setsWon+=g[h],i[r].setsLost+=g[f],e||(i[r].gamesWon+=I[h],i[r].gamesLost+=I[f]),i[r].pointsWon+=U[h],i[r].pointsLost+=U[f])}function EU({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:r}){e&&(r===zu&&(n[e].walkovers+=1),r===Lu&&(n[e].defaults+=1),r===$u&&(n[e].retirements+=1),[Lu,$u,zu].includes(r)&&(n[e].allDefaults+=1),n[e].matchUpsLost+=1),t&&(n[t].matchUpsWon+=1),e&&t&&(n[e].defeats.push(t),n[t].victories.push(e))}function CU({participantResults:t,participantIds:e,attribute:n}){return OU({participantResults:t,participantIds:e}).reduce(((t,e)=>{const{participantId:r,results:i}=e,a=i?.[n];return!isNaN(a)&&r&&(t[a]?t[a].push(r):t[a]=[r]),t}),{})}function OU(t){return(t.participantIds||Object.keys(t.participantResults)).reduce(((e,n,r)=>(e.push({participantId:n,i:r,results:t.participantResults[n]}),e)),[])}const FU=[{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}],kU={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function xU(t){const{requireCompletion:e=!0,participantResults:n,subOrderMap:r,tallyPolicy:i}=t,a=[];if(e&&!function({participantResults:t,participantsCount:e}){const n=OU({participantResults:t}),r=n.filter((t=>e-1===t.results.matchUpsWon+t.results.matchUpsLost+t.results.matchUpsCancelled));return e===r.length}(t))return{};const o=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(i?.groupOrderKey)?i.groupOrderKey:"matchUpsWon",s=CU({participantResults:n,attribute:o});a.push({attribute:o,groups:s});const c=Object.keys(s).map((t=>parseFloat(t))).sort(((t,e)=>e-t)).map((t=>s[t])).map((e=>{const n=_U({participantIds:e,...t});return a.push(...n.report??[]),n.order})).map(((t,e)=>t.map((t=>t.resolved?t:{...t,subGroup:[e].concat(...t.subGroup??[])})))).flat();let u,d,p=0,l=1;c.forEach(((t,e)=>{e&&(t.resolved||d&&!t.resolved)&&(l+=1),d=t.resolved;const n=parseInt(t.subGroup?.join("")||0);t.resolved?(t.position=e+1,l=t.position):(u&&n>u&&(l+=p,p=0),t.position=l,p+=1),u=n}));const m=T(c.map((({position:t})=>t)));return c.forEach((t=>{const{participantId:e,position:a}=t||{},o=n[e];t.GEMscore=function(t){const e=Array.isArray(i?.GEMscore)?Object.keys(kU).filter((t=>i.GEMscore.includes(t))):Object.keys(kU),n=e.map((e=>(t[e]||0)*Math.pow(10,kU[e].toFixed(3))));return n.reduce(((t,e)=>t+e),0)}(o);const s=m[a];void 0!==t?.position&&(s>1&&(t.ties=s,r&&(t.subOrder=r[e])),t.rankOrder=a,t.groupOrder=a+(t.subOrder||1)-1)})),{groupOrder:c,report:a.flat(1/0).filter(Boolean)}}function _U({participantResults:t,disableHeadToHead:e,participantIds:n,matchUpFormat:r,tallyPolicy:i,matchUps:a}){const o=[],s=[];let c;if(1===n?.length){return{order:[{resolved:!0,participantId:n[0]}]}}if(2===n?.length&&(!i?.headToHead||!i.headToHead.disabled&&!e)){const e=function({participantIds:t,participantResults:e}){if(!t)return;if(e[t[0]].victories.includes(t[1]))return t.map((t=>({resolved:!0,participantId:t})));if(e[t[1]].victories.includes(t[0]))return t.reverse().map((t=>({resolved:!0,participantId:t})))}({participantIds:n,participantResults:t});if(e){const t=e[0].participantId;return s.push({attribute:"head2Head",participantIds:n,headToHeadWinner:t}),{order:e,headToHeadWinner:t,report:s}}}const u=(i?.tallyDirectives||FU).filter((t=>{const e=!(h(t.maxParticipants)&&n?.length>t.maxParticipants);return e||o.push(t),e}));return o.length&&s.push({excludedDirectives:o,participantIds:n}),u.every((({attribute:t,reversed:e,idsFilter:o,groupTotals:u,disableHeadToHead:d})=>(c=function({disableHeadToHead:t,participantIds:e,matchUpFormat:n,groupTotals:r,tallyPolicy:i,attribute:a,idsFilter:o,matchUps:s,reversed:c}){const{participantResults:u}=DU({participantIds:o&&e,groupingTotal:r&&a,matchUpFormat:n,tallyPolicy:i,matchUps:s}),d=CU({participantResults:u,participantIds:e,attribute:a}),p=[{attribute:a,reversed:c,groups:d,idsFilter:o,groupTotals:r}];let l;if(Object.keys(d).length>1&&e.length){const e=Object.keys(d).map((t=>parseFloat(t))).sort(((t,e)=>c?t-e:e-t)).map((t=>d[t])).map((e=>{const r=_U({participantResults:u,disableHeadToHead:t,participantIds:e,matchUpFormat:n,tallyPolicy:i,matchUps:s});return p.push(...r.report??[]),r.order}));l=e.map(((t,e)=>t.map((t=>t.resolved?t:{...t,subGroup:[e].concat(...t.subGroup??[])})))).flat()}return{order:l,report:p}}({disableHeadToHead:d,participantIds:n,matchUpFormat:r,groupTotals:u,tallyPolicy:i,attribute:t,idsFilter:o,matchUps:a,reversed:e}),s.push(c.report),!c.order))),c.order?{order:c.order,report:s}:{order:n?.map((t=>({participantId:t}))),report:s}}function LU({policyDefinitions:t,generateReport:e,pressureRating:n,matchUpFormat:r,matchUps:i=[],subOrderMap:a,perPlayer:s}){if(!i?.length||!yl(i))return{error:me};const c=w(i.map((({structureId:t})=>t)));if(1!==c.length)return ti({result:{error:Jn,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:c}});const u=i.filter((t=>t&&t.matchUpStatus!==Fu)),d=u.length&&w(u.map((({drawPositions:t})=>t)).flat()).length,p=u.filter((t=>Zm({matchUp:t}))).length===u.length;p||(s=0);const l=i.every((({matchUpType:t,tieMatchUps:e})=>t===o&&e?.every((t=>Zm({matchUp:t}))))),m=t?.[Sc],f=i.filter((t=>Zm({matchUp:t})||t.matchUpType===o)),{participantResults:h}=DU({matchUps:f,pressureRating:n,matchUpFormat:r,tallyPolicy:m,perPlayer:s});let g,I;const{groupOrder:U,report:y}=xU({matchUps:f,participantResults:h,participantsCount:d,matchUpFormat:r,subOrderMap:a,tallyPolicy:m});if(n&&function({participantResults:t}){const e=t=>t.reduce(((t,e)=>t+parseFloat(e)),0),n=t=>parseFloat((e(t)/t.length).toFixed(2)),r=Object.keys(t).map((e=>{const r=t[e],{pressureScores:i}=r;return{participantId:e,averagePressure:i?.length?n(i):0}})).sort(((t,e)=>(e.averagePressure||0)-(t.averagePressure||0))).map(((t,e)=>({...t,order:e+1})));for(const e of r)t[e.participantId].pressureOrder=e.order}({participantResults:h}),p&&U)g=y,I=U,U.forEach((t=>{const{participantId:e,groupOrder:n,rankOrder:r,subOrder:i,ties:a,GEMscore:o}=t,s=h[e];Object.assign(s,{groupOrder:n,rankOrder:r,GEMscore:o,subOrder:i,ties:a})}));else{const{groupOrder:t,report:e}=xU({requireCompletion:!1,participantResults:h,participantsCount:d,matchUpFormat:r,tallyPolicy:m,subOrderMap:a,matchUps:i});g=e,I=t,t&&t.forEach((t=>{const{participantId:e,groupOrder:n,GEMscore:r}=t,i=h[e];Object.assign(i,{provisionalOrder:n,GEMscore:r})}))}const S={completedTieMatchUps:l,readableReport:"",participantResults:h,bracketComplete:p,order:[],report:g};if((p||l)&&(S.order=I),e||Pr({tally:!0})){const t=function({matchUps:t,order:e,report:n}){const r={};t.forEach((({sides:t})=>{t.forEach((t=>{t.participantId&&t.participant&&(r[t.participantId]=t.participant.participantName)}))}));const i=[];return Array.isArray(n)&&n.forEach(((t,e)=>{if(t.excludedDirectives?.length){const e=t.excludedDirectives.map((({attribute:t})=>t)).join(", "),n=`${e.length} directives were excluded due to participants limit}`;i.push(n);const r=`Excluded: ${e}`;i.push(r)}else{const n=(e,n)=>parseFloat(t.reversed?e:n)-parseFloat(t.reversed?n:e),a=t.groups?Object.values(t.groups).flat(1/0).length:t.participantIds?.length??0,o=t=>{t.groups&&Object.keys(t.groups).sort(n).forEach((e=>{const n=t.groups[e].map((t=>r[t])).join(", "),a=`${e} ${t.attribute}: ${n}`;i.push(a)}))},s=t.reversed?" in reverse order":"",c=`Step ${e+1}: ${a} particiants were ${t.groups?"grouped":"separated"}${s} by ${t.attribute}`;if(i.push(c),t.idsFilter){const e=`${t.attribute} was calculated considering ONLY TIED PARTICIPANTS`;i.push(e)}o(t)}i.push("----------------------")})),i.push("Final Order:"),e.forEach((t=>{const{participantId:e,resolved:n}=t,a=t.groupOrder||t.provisionalOrder;i.push(`${a}: ${r[e]} => resolved: ${!!n}`)})),i.join("\r\n")}({matchUps:i,report:g,order:I});Pr({tally:!0})&&console.log(t),S.readableReport=t}return S}function BU({positionAssignments:t}){const e=(t||[]).filter(If(Ss)).map((t=>{const{extension:e}=zc({element:t,name:hu}),n=d(e?.value),r=!isNaN(n)&&n;return r&&{participantId:t.participantId,subOrder:r}})).filter(Boolean),n=T(e.map((({subOrder:t})=>t)));return{subOrderMap:Object.assign({},...e.filter((({subOrder:t})=>1===n[t])).map((({participantId:t,subOrder:e})=>({[t]:e}))))}}function VU({positionAssignments:t,tournamentRecord:e,drawDefinition:n,matchUpFormat:r,matchUps:i,event:a}){if(!yl(i))return{error:Jn};if(!t)return{error:Jn};const{policyDefinitions:o}=Ap({policyTypes:[Sc],tournamentRecord:e,drawDefinition:n,event:a}),{subOrderMap:s}=BU({positionAssignments:t}),c=i.length?LU({policyDefinitions:o,matchUpFormat:r,subOrderMap:s,matchUps:i}):void 0;if(c?.error)return c;const{participantResults:u={},bracketComplete:d,report:p}=c??{},l=Object.keys(u);return t.forEach((t=>{const{participantId:e}=t;if(l.includes(e)){_c({element:t,extension:{value:u[e],name:gu}}),u[e].ties||kc({element:t,name:hu})}else kc({element:t,name:gu}),kc({element:t,name:hu})})),Hd({drawDefinition:n}),{...z,participantResults:u,bracketComplete:d,report:p}}function jU({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find((t=>t.matchUpId===e))}}function GU(t){const e=cc(t,[{[Is]:!0,[Cs]:!0}]);if(e.error)return e;const{tournamentParticipants:n,afterRecoveryTimes:r,contextProfile:i,drawDefinition:a,matchUpsMap:o,matchUpId:s,inContext:c,context:u,event:d}=t,{structures:p=[]}=od({drawDefinition:a}),l=t.contextContent||i&&Lp({contextProfile:i,drawDefinition:a});for(const t of p){const{matchUps:e}=Jm({tournamentParticipants:n,afterRecoveryTimes:r,contextContent:l,drawDefinition:a,contextProfile:i,matchUpsMap:o,inContext:c,structure:t,context:u,event:d}),{matchUp:p}=jU({matchUps:e,matchUpId:s});if(p)return{matchUp:p,structure:t}}return{error:le}}function qU(t){return G(t)&&t.notes?G(t.element)&&(j(t.notes)||t.notes?.testing)?(Object.assign(t.element,{notes:t.notes}),{...z}):{error:Jn}:{error:be}}function $U(t){return G(t)?G(t.element)?(t.element.notes&&delete t.element.notes,{...z}):{error:Jn}:{error:be}}const WU={matchUpStatus:Hu,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function HU(t){const e="modifyMatchUpScore";let n,r=t.matchUpFormat,i=t.matchUp;const{matchUpStatusCodes:a,tournamentRecord:s,drawDefinition:c,matchUpStatus:u,removeScore:d,winningSide:p,matchUpId:l,event:m,notes:f,score:h}=t,g=t.appliedPolicies&&Object.keys(t.appliedPolicies).length?t.appliedPolicies:Np({policyTypes:[Nc],tournamentRecord:s,drawDefinition:c,structure:n,event:m})?.appliedPolicies,I=i.matchUpType===o;if(I&&c){if(l&&i.matchUpId!==l){const t=GU({drawDefinition:c,matchUpId:l,event:m});if(!t.matchUp)return{error:le};({matchUp:i,structure:n}=t)}}else i.matchUpId!==l&&console.log("!!!!!");u&&[zu,Vu].includes(u)||d?Object.assign(i,{...WU}):h&&(i.score=h);const U=u&&i?.matchUpStatus===Lu&&u!==Lu;let y;if(u&&(i.matchUpStatus=u),r&&(i.matchUpFormat=r),a&&(i.matchUpStatusCodes=a),p&&(i.winningSide=p),t.removeWinningSide&&(i.winningSide=void 0),!n&&c&&({structure:n}=GU({drawDefinition:c,matchUpId:l,event:m})),!u||i.winningSide||!vf(i)||Xu.includes(u)||[Ou,Wu,Gu].includes(u)||(i.matchUpStatus=ju),(U&&i?.processCodes?.length||u===Lu)&&(y=g?.[Nc]?.processCodes?.incompleteAssignmentsOnDefault),!i.collectionId){const t=n?.structureType===Mo,a=Dl({structure:n});if(Pl({drawDefinition:c,structure:n})||a||t){const u=t=>{r=I?"SET1-S:T100":r??i.matchUpFormat??t?.matchUpFormat??c?.matchUpFormat??m?.matchUpFormat;const e=I?{matchUpTypes:[o]}:void 0,{matchUps:n}=Jm({afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,matchUpFilters:e,drawDefinition:c,structure:t,event:m});return a&&(t.positionAssignments=w(n.flatMap((t=>(t.sides??[]).map((t=>t.participantId)))).filter(Boolean)).map((t=>({participantId:t})))),VU({positionAssignments:t.positionAssignments,tournamentRecord:s,drawDefinition:c,matchUpFormat:r,matchUps:n,event:m})},d=t&&n.structures.find((t=>t?.matchUps.find((t=>t.matchUpId===l)))),p=u(d||n);if(p.error)return ti({result:p,stack:e})}}if(f){const t=qU({element:i,notes:f});if(t.error)return ti({result:t,stack:e})}const S=s?.tournamentId,v=Lr().topics.includes(Bd),P=(v||y)&&hl({drawDefinition:c}),D=P&&cf({matchUpFilters:{matchUpIds:[l]},nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:c,matchUpsMap:P}).matchUps?.[0];if(v&&D&&function({tournamentId:t,inContextMatchUp:e}){e&&Or({payload:{inContextMatchUp:e,tournamentId:t},topic:Bd,key:e.matchUpId})}({tournamentId:S,inContextMatchUp:D}),Array.isArray(y)&&D&&!D.sides?.every((({participantId:t})=>t)))if(u===Lu)i.processCodes=w([...i.processCodes??[],...y]);else for(const t of y||[]){const e=t&&i?.processCodes?.lastIndexOf(t);i?.processCodes?.splice(e,1)}return $d({eventId:m?.eventId,context:e,drawDefinition:c,tournamentId:S,matchUp:i}),{...z}}function zU(t){const{matchUpStatusCodes:e,matchUpStatus:n,structure:r,matchUp:i,dualMatchUp:a,inContextMatchUp:o,autoCalcDisabled:s}=t,c=wf({matchUpStatus:n})||[ku,Cu].includes(n)&&a||s,u=i?.sides?.map((t=>t.participantId)).filter(Boolean).length||o?.sides?.map((t=>t.participantId)).filter(Boolean).length,d="attemptToModifyScore",p=Dl({structure:r})&&1===u||n===Lu&&u||function({structure:t,matchUp:e,inContextMatchUp:n}){const{drawPositions:r}=e,{positionAssignments:i}=ud({structure:t}),a=i?.filter((t=>r?.includes(t.drawPosition)&&t.participantId)),o=n?.sides?.every((t=>t.participantId));return 2===a?.length||o}({structure:r,matchUp:i,inContextMatchUp:o})||!1===t.appliedPolicies?.[Nc]?.requireParticipantsForScoring;if(!p)return ti({result:{error:Kt},stack:d});const l=[zu].includes(n),m=c?n:t.winningSide&&xu||Gu;return ti({result:HU({...t,matchUpStatusCodes:c&&e||[],matchUpStatus:m,removeScore:l}),stack:d})}function YU({collectionGroups:t=[]}){const e=Object.assign({},...t.filter((t=>y(t?.groupValue)&&t?.groupNumber)).map((t=>({[t.groupNumber]:{...t,allGroupMatchUpsCompleted:!0,matchUpsCount:0,sideWins:[0,0],values:[0,0]}}))));return{groupValueGroups:e,groupValueNumbers:Object.keys(e).map((t=>d(t)))}}function KU({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:n,sideTieValues:r,tieMatchUps:i}){const a=i.filter((e=>e.collectionId===t.collectionId)),o=[0,0];let s=[0,0];const c=a.every((t=>Xu.includes(t.matchUpStatus))),{collectionValueProfiles:u,collectionGroupNumber:d,collectionValue:p,matchUpValue:l,winCriteria:m,scoreValue:f,setValue:h}=t,g=d&&e.includes(d),I=[0,0];if(a.forEach((t=>{t.winningSide&&(I[t.winningSide-1]+=1)})),y(l)?a.forEach((t=>{t.winningSide&&(o[t.winningSide-1]+=l)})):y(h)?a.forEach((t=>{t.score?.sets?.forEach((t=>{t.winningSide&&(o[t.winningSide-1]+=h)}))})):y(f)?a.forEach((t=>{t.score?.sets?.forEach((e=>{const{side1TiebreakScore:n=0,side2TiebreakScore:r=0,side1Score:i=0,side2Score:a=0}=e;(t.matchUpStatus===xu||t.winningSide||e.winningSide)&&(i||a?(o[0]+=i,o[1]+=a):(n||r)&&e.winningSide&&(o[e.winningSide-1]+=1))}))})):Array.isArray(u)&&a.forEach((e=>{if(e.winningSide){const n=e.collectionPosition,r=function({collectionDefinition:t,collectionPosition:e}){const n=t.collectionValueProfiles||[],r=n?.find((t=>t.collectionPosition===e));return r?.matchUpValue}({collectionDefinition:t,collectionPosition:n});y(r)&&(o[e.winningSide-1]+=r)}})),y(p)){let e;if(m?.aggregateValue)c&&(y(l||h||f)&&o[0]!==o[1]?e=o[0]>o[1]?1:2:I[0]!==I[1]&&(e=I[0]>I[1]?1:2));else if(m?.valueGoal)e=o.reduce(((t,e,n)=>e>=m.valueGoal?n+1:t),0);else{const n=Math.floor(t.matchUpCount/2)+1;e=I.reduce(((t,e,r)=>e>=n?r+1:t),0)}e&&(g?n[d].values[e-1]+=p:s[e-1]+=p)}else g?(n[d].values[0]+=o[0]||0,n[d].values[1]+=o[1]||0):s=o;g?(n[d].sideWins[0]+=I[0]||0,n[d].sideWins[1]+=I[1]||0,n[d].allGroupMatchUpsCompleted=n[d].allGroupMatchUpsCompleted&&c,n[d].matchUpsCount+=a.length):s.forEach(((t,e)=>r[e]+=t||0))}function QU(t){const{sideAdjustments:e=[0,0],separator:n="-",drawDefinition:r,matchUpsMap:i,structure:a,matchUp:o,event:s}=t;if(!Array.isArray(e)||2!==e.length||isNaN(e.reduce(((t,e)=>t+e))))return{error:Jn};if(!o)return{error:fe};const c=fl({matchUp:o,drawDefinition:r,structure:a,event:s})?.tieFormat||t?.tieFormat;if(!c)return{error:ue};const u=sa({tieFormat:c});if(u.error)return u;const d=c?.collectionDefinitions||[],p=o?.tieMatchUps??[],l=[0,0],{groupValueGroups:m,groupValueNumbers:f}=YU(c);for(const t of d)KU({collectionDefinition:t,groupValueNumbers:f,groupValueGroups:m,sideTieValues:l,tieMatchUps:p});for(const t of f){const e=m[t],{allGroupMatchUpsCompleted:n,matchUpCount:r,winCriteria:i,groupValue:a,sideWins:o,values:s}=e;let c;if(i?.aggregateValue)n&&s[0]!==s[1]&&(c=s[0]>s[1]?1:2);else if(i?.valueGoal)c=s.reduce(((t,e,n)=>e>=i.valueGoal?n+1:t),void 0);else{const t=Math.floor(r/2)+1;c=o.reduce(((e,n,r)=>n>=t?r+1:e),void 0)}c&&(l[c-1]+=a||0)}const h=l.map(((t,n)=>(t||0)+e[n])),g={side1Score:h[0],side2Score:h[1],winningSide:void 0},I=h.join(n),U=h.slice().reverse().join(n);let y;if(c?.winCriteria){const{valueGoal:t,aggregateValue:e,tallyDirectives:n}=c.winCriteria;if(t){const e=h.map(((t,e)=>({sideNumber:e+1,points:t}))).find((({points:e})=>e>=t));y=e?.sideNumber}else if(e){const t=p.every((t=>t.matchUpStatus&&Xu.includes(t.matchUpStatus)||t.winningSide));t&&h[0]!==h[1]&&(y=h[0]>h[1]?1:2)}if(!y&&n){const t=o.matchUpId,e=o.hasContext?o:i?.drawMatchUps?.[t]||r&&GU({inContext:!0,drawDefinition:r,matchUpId:t})?.matchUp;if(e){const{completedTieMatchUps:t,order:n}=LU({matchUps:[e]});if(t&&n?.length){const t=n[0].participantId;y=e.sides.find((({participantId:e})=>e===t))?.sideNumber}}}}return y&&(g.winningSide=y),{scoreStringSide1:I,scoreStringSide2:U,winningSide:y,set:g}}function JU({inContextDualMatchUp:t,drawDefinition:e,tournamentId:n,dualMatchUp:r,eventId:i}){if(r){t||(t=GU({matchUpId:r.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);const{extension:a}=zc({element:e,name:au}),o=la(a?.value||{},!1,!0),s=({displaySideNumber:t,drawPosition:e,sideNumber:n})=>({drawPosition:e,sideNumber:n,displaySideNumber:t});r.sides=t?.sides?.map((t=>{const e=t.participantId,n=e&&o[e]||void 0,{lineUp:i,...a}=r.sides?.find((({sideNumber:e})=>e===t.sideNumber))??{},c=i?.length?i:n;return{...s(t),...a,lineUp:c}})),$d({context:"ensureSidLineUps",matchUp:r,drawDefinition:e,tournamentId:n,eventId:i})}}function ZU(t){if(t)return la(t,!1,!0)}function XU(t){const e=cc(t,[{[ms]:!0}]);if(e.error)return e;return Object.keys(t.tournamentRecords).reduce(((e,n)=>{e.tournamentIdMap[n]=[];const r=t.tournamentRecords[n].events??[],i=r.map((({eventId:t})=>t)),a=r.map((t=>(t.drawDefinitions??[]).map((({drawId:t})=>t)))).flat();return e.tournamentIdMap[n].push(...i,...a),e.eventIds.push(...i),e.drawIds.push(...a),e}),{eventIds:[],drawIds:[],tournamentIdMap:{}})}function ty({tournamentRecords:t,eventId:e,drawId:n}){const{tournamentIdMap:r}=XU({tournamentRecords:t});return(r?Object.keys(r):[]).find((t=>e&&r?.[t].includes(e)||n&&r?.[t].includes(n)))}function ey(t){const{exitWhenNoValues:e,drawDefinition:n,matchUpStatus:r,removeScore:i,matchUpsMap:a,matchUpId:o,event:s}=t,c=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord?.tournamentId]:t.tournamentRecord}||{},u=t.tournamentId||t.tournamentRecord?.tournamentId;c&&ty({tournamentRecords:c,...t});const d=u&&c[u];if(!d)return{error:nt};const p=GU({drawDefinition:n,event:s,matchUpId:o});if(p.error)return p;if(!p.matchUp)return{error:le};const{matchUp:l,structure:m}=p;if(!l.tieMatchUps)return{error:he};JU({tournamentId:d?.tournamentId,eventId:s?.eventId,dualMatchUp:l,drawDefinition:n});const{extension:f}=zc({name:Zc,element:l});if(f?.value){if(!i)return{...z,score:l.score};kc({element:l,name:Zc})}const h=fl({drawDefinition:n,structure:m,matchUp:l,event:s})?.tieFormat;l.tieFormat=ZU(h);const g=QU({drawDefinition:n,matchUpsMap:a,structure:m,matchUp:l,event:s}),{winningSide:I,set:U,scoreStringSide1:y,scoreStringSide2:S}=g,v=U?.side1Score||U?.side2Score;if(e&&!l.score&&!v)return{...z};const w={scoreStringSide1:y,scoreStringSide2:S,sets:U?[U]:[]},P=I&&[1,2].includes(I),D=P&&xu||Df({matchUpStatus:r??l.matchUpStatus,tieMatchUps:l.tieMatchUps,winningSide:l.winningSide,score:w})&&ju||Hu,T=!(!l.winningSide||P),b=l.tieMatchUps.find((({score:t,winningSide:e,matchUpStatus:n})=>t?.sets?.length&&(t.sets[0].side1Score||t.sets[0].side2Score)||n&&Xu.includes(n)||e));let R;if(l.tieFormat&&!P&&!b){const t=fl({drawDefinition:n,structure:m,event:s})?.tieFormat;t&&JSON.stringify(h)===JSON.stringify(t)&&(l.tieFormatId=void 0,l.tieFormat=void 0,R=!0)}return HU({appliedPolicies:t.appliedPolicies,matchUpStatus:D,score:w,removeWinningSide:T,tournamentRecord:d,drawDefinition:n,removeScore:i,winningSide:I,matchUpId:o,matchUp:l,event:s}),{...z,score:w,removeWinningSide:T,tieFormatRemoved:R,winningSide:I}}function ny(t){const e="directParticipants",n=zU(t);if(n.error)return ti({result:n,stack:e});const r=wf({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:i,projectedWinningSide:a,inContextDrawMatchUps:o,tournamentRecord:s,drawDefinition:c,matchUpStatus:d,dualMatchUp:p,matchUpsMap:l,winningSide:m,targetData:f,matchUpId:h,structure:g,matchUp:I,event:U}=t,y=Boolean(I.collectionId),S=Dl({structure:g});let v,w=I.drawPositions;if(y){const{matchUpTieId:n,matchUpsMap:r}=t,a=ey({appliedPolicies:t.appliedPolicies,matchUpId:n,tournamentRecord:s,drawDefinition:c,matchUpsMap:r,event:U});v=a&&{tieMatchUpResult:a};const u=o.find((({matchUpId:t})=>t===n));if(w=u?.drawPositions,!i)return ti({result:{...z,...v},stack:e})}if(S)return ti({result:{...z,...v},stack:e});if(!w)return ti({result:{error:gt},stack:e});{const t=a?a-1:m-1,n=1-t,i=w[t],g=w[n],{targetLinks:{loserTargetLink:I,winnerTargetLink:y,byeTargetLink:S},targetMatchUps:{winnerMatchUpDrawPositionIndex:v,loserMatchUpDrawPositionIndex:P,winnerMatchUp:D,loserMatchUp:T,byeMatchUp:b}}=f;if(D){const t=function({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:n,sourceMatchUpStatus:r,winningDrawPosition:i,tournamentRecord:a,winnerTargetLink:o,sourceMatchUpId:s,drawDefinition:c,winnerMatchUp:u,dualMatchUp:d,matchUpsMap:p,event:l}){const m="directWinner";if(o){const n=u.drawPositions||[],d=n[t],f=o.source.structureId,h=ad({structureId:f,drawDefinition:c});if(h.error)return h;const{structure:g}=h,{positionAssignments:I}=ud({structureId:f,drawDefinition:c}),U=I?.find((t=>t.drawPosition===i)),y=U?.participantId,S=o.target.structureId,{positionAssignments:v}=ud({structureId:S,drawDefinition:c}),w=v?.find((t=>t.participantId===y)),P=w?.drawPosition,D=v?.filter((t=>{const e=n.includes(t.drawPosition),r=!t.participantId&&!t.bye&&!t.qualifier;return e&&r})).map((t=>t.drawPosition)),T=D?.includes(d);if(y&&1===o.target.roundNumber&&T)mg({drawPosition:d,participantId:y,structureId:S,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,drawDefinition:c,matchUpsMap:p,event:l});else if(y&&D?.length){const t=D.pop();t&&mg({participantId:y,structureId:S,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,drawDefinition:c,drawPosition:t,matchUpsMap:p,event:l})}else if(P){const t=og({drawPosition:P,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,sourceMatchUpId:s,drawDefinition:c,matchUpsMap:p});if(t.error)return ti({result:t,stack:m})}else if(g?.stage!==ho){const t="winner target position unavaiallble";return console.log(t),{error:t}}if(g?.seedAssignments&&g.structureId!==S){const t=g.seedAssignments.find((({participantId:t})=>t===y)),e=t?.participantId;t&&e&&tg({eventId:u?.eventId,structureId:S,...t,tournamentRecord:a,drawDefinition:c,participantId:e})}}else{const t=og({matchUpId:u.matchUpId,drawPosition:i,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,sourceMatchUpId:s,drawDefinition:c,matchUpsMap:p});if(t.error)return t}if(d&&n){const t=d.sides?.find((t=>t.sideNumber===n));if(t?.lineUp){const e=d.roundPosition,n=u.roundPosition,r=e===n&&1!==e||Math.floor(e/2)===n?2:1,i=p?.drawMatchUps?.find((({matchUpId:t})=>t===u.matchUpId)),o=[1,2].map((t=>{const e=i.sides?.find((e=>e.sideNumber===t))||{};return{...e,sideNumber:t}}));i.sides=o;const s=i.sides.find((t=>t.sideNumber===r));if(s){const e=t.lineUp?.filter((t=>t?.participantId));s.lineUp=cg({lineUp:e}),$d({tournamentId:a?.tournamentId,eventId:u?.eventId,matchUp:i,context:m,drawDefinition:c})}}}return{...z}}({sourceMatchUpStatus:r&&d||xu,winnerMatchUpDrawPositionIndex:v,sourceMatchUpId:h,inContextDrawMatchUps:o,projectedWinningSide:a,winningDrawPosition:i,tournamentRecord:s,winnerTargetLink:y,drawDefinition:c,winnerMatchUp:D,dualMatchUp:p,matchUpsMap:l,event:U});if(t.error)return ti({result:t,stack:e})}if(T){const t=function(t){const{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:n,projectedWinningSide:r,sourceMatchUpStatus:i,loserDrawPosition:a,tournamentRecord:o,loserTargetLink:s,drawDefinition:c,loserMatchUp:d,dualMatchUp:p,matchUpsMap:l,event:m}=t,f="directLoser",h=s.linkCondition,g=d.drawPositions||[],I=h===xo&&2===d.roundNumber&&Math.min(...g.filter(Boolean)),U=I||g[e],y=I||g[1-e],S=s.source.structureId,{structure:v}=ad({structureId:S,drawDefinition:c}),{matchUps:w}=Jm({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:v,event:m}),P=w.filter((t=>t.drawPositions?.includes(a))).filter((t=>{const e=t.sides.find((t=>t.drawPosition===a)),n=t.matchUpStatus===zu||t.matchUpStatus===Lu&&!vf(t);return e?.sideNumber===t.winningSide&&!n})),D=h===xo&&0===P.length,{positionAssignments:T}=ud({structureId:S,drawDefinition:c}),b=T?.find((t=>t.drawPosition===a)),R=b?.participantId,M=s.target.structureId,{positionAssignments:N}=ud({structureId:M,drawDefinition:c}),A=N?.filter((({drawPosition:t})=>g.includes(t))),E=A?.some((t=>t.participantId===R));if(E)return{...z};const C=A?.filter((t=>{const e=g.includes(t.drawPosition),n=!t.participantId&&!t.bye&&!t.qualifier;return e&&n})).map((t=>t.drawPosition)),O=C?.includes(U),F=s.target.roundNumber>1&&C?.length,k=1===s.target.roundNumber&&O;if(I){const t=function(){const t="loserLinkFedFMLC";return ti(D?{result:_(),stack:t}:{result:x(),stack:t})}();if(t.error)return ti({result:t,stack:f})}else if(k){const t=_();if(t.error)return ti({result:t,stack:f})}else{if(!R||!F)return ti({context:{loserDrawPosition:a,loserTargetLink:s,targetDrawPositionIsUnfilled:O},result:{error:O?yt:Ut},stack:f});{C.sort(u);const t=C[0],e=mg({participantId:R,structureId:M,drawPosition:t,inContextDrawMatchUps:n,sourceMatchUpStatus:i,tournamentRecord:o,drawDefinition:c,matchUpsMap:l,event:m});if(e.error)return ti({result:e,stack:f})}}if(v?.seedAssignments&&v.structureId!==M){const t=v.seedAssignments.find((({participantId:t})=>t===R)),e=t?.participantId;t&&e&&tg({eventId:d?.eventId,structureId:M,...t,tournamentRecord:o,drawDefinition:c,participantId:e})}if(p&&r){const t=p.sides?.find((t=>t.sideNumber===3-r));if(t?.lineUp){const{roundNumber:e,eventId:n}=d,{roundPosition:r}=p,i=1===e?2-r%2:1,a=l?.drawMatchUps?.find((({matchUpId:t})=>t===d.matchUpId)),s=[1,2].map((t=>{const e=a.sides?.find((e=>e.sideNumber===t))||{};return{...e,sideNumber:t}}));a.sides=s;const u=a.sides.find((t=>t.sideNumber===i));u&&(u.lineUp=cg({lineUp:t.lineUp}),$d({tournamentId:o?.tournamentId,matchUp:a,context:f,drawDefinition:c,eventId:n}))}}return{...z};function x(){return ti({result:Ef({drawPosition:y,structureId:M,tournamentRecord:o,drawDefinition:c,event:m}),stack:"assignLoserPositionBye"})}function _(){return ti({result:R?mg({drawPosition:U,participantId:R,structureId:M,inContextDrawMatchUps:n,sourceMatchUpStatus:i,tournamentRecord:o,drawDefinition:c,matchUpsMap:l,event:m}):{error:Xe},stack:"assignLoserDrawPosition"})}}({sourceMatchUpStatus:r&&d||xu,loserMatchUpDrawPositionIndex:P,inContextDrawMatchUps:o,projectedWinningSide:a,loserDrawPosition:g,tournamentRecord:s,loserTargetLink:I,drawDefinition:c,loserMatchUp:T,matchUpsMap:l,dualMatchUp:p,event:U});if(t.error)return ti({result:t,stack:e})}if(b){const t=b.drawPositions||[],n=Ef({drawPosition:Math.min(...t.filter(Boolean)),structureId:S.target.structureId,tournamentRecord:s,drawDefinition:c,event:U});if(n.error)return ti({result:n,stack:e})}}return ti({result:{...z,...v},stack:e})}function ry(t){const e="genPlayoffStructure";if(!t.drawDefinition)return ti({result:{error:ot},stack:e});const n=eU(t);if(n.error)return ti({result:n,stack:e});const{structureId:r,addNameBaseToAttributeName:i,playoffStructureNameBase:s,finishingPositionNaming:c,finishingPositionLimit:u,playoffAttributes:p,playoffPositions:l,roundOffsetLimit:m,tournamentRecord:f,exitProfileLimit:h,roundProfiles:g,roundNumbers:I,idPrefix:U,isMock:y,event:S,uuids:v}=t,w=la(t.drawDefinition,!1,!0),{structure:P}=ad({structureId:r,drawDefinition:w});if(!P)return ti({result:{error:Lt},stack:e});if(P.structureType===Mo||P.structures)return function(t){const e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return ti({result:{error:be},info:"playoffGroups required",stack:e});const{sourceStructureId:n,requireSequential:r,tournamentRecord:i,drawDefinition:o,playoffGroups:s,groupCount:c,groupSize:u,event:d}=t,p=sU({requireSequential:r,sourceStructureId:n,playoffGroups:s,groupCount:c,...t});if(p.error)return ti({result:p,stack:e});const{structures:l=[],links:m=[],finishingPositionTargets:f,positionRangeMap:h}=p,g=f?.map((({finishingPositions:t})=>t)).flat().map((t=>h[t].finishingPositions)).flat();o.structures.push(...l),o.links.push(...m);const{matchUps:I,matchUpsMap:U}=cf({inContext:!0,drawDefinition:o}),y=l.map((({structureId:t})=>t)),S=I?.filter((({structureId:t})=>y.includes(t))).map(Nu),v=U?.drawMatchUps?.filter((({matchUpId:t})=>S?.includes(t)));if(v?.length){const e=fl({drawDefinition:o,event:d})?.tieFormat;e&&v.forEach((n=>{const{tieMatchUps:r}=LI({isMock:t.isMock,tieFormat:e,matchUp:n});Object.assign(n,{tieMatchUps:r,matchUpType:a})}))}const{positionAssignments:w}=cd({structureId:n,drawDefinition:o}),P={};w?.forEach((t=>{const e=zc({element:t,name:gu}),n=e?.extension?.value,r=n?.groupOrder;r&&(P[r]||(P[r]=[]),P[r].push(t.participantId))}));const D=Jg({provisionalPositioning:t.provisionalPositioning,structureId:n,applyPositioning:!0,event:t.event,tournamentRecord:i,drawDefinition:o});return D.error&&D.error?.code!==dt.code?ti({result:D,stack:e}):{structures:l,links:m,positionsPlayedOff:g,drawDefinition:o,...z}}({sourceStructureId:P.structureId,...t,...n,drawDefinition:w});const{playoffRoundsRanges:D,playoffRounds:T}=n,{playoffPositionsReturned:b,error:R,playoffSourceRounds:M,playoffRoundsRanges:N}=tU(t);if(R)return ti({result:{error:R},stack:e});const A=g?.length&&Object.assign({},...g),E=I||"object"==typeof g&&g.map((t=>Object.keys(t))).flat(),C=Array.isArray(E)&&E.map((t=>!isNaN(t)&&d(t))).filter(Boolean);if(C){if(!Array.isArray(C))return ti({result:{error:Jn},context:{validRoundNumbers:C},stack:e});C.forEach((t=>{if(!T?.includes(t))return ti({result:{error:Jn},context:{roundNumber:t},stack:e})}))}l&&l.forEach((t=>{if(!b?.includes(t))return ti({result:{error:Jn},context:{playoffPosition:t},stack:e})}));const O=C||M,F=C?D:N,k=[],x=[];for(const t of O??[]){const n=F?.find((e=>e.roundNumber===t));if(!n)return ti({result:{error:Jn},context:{roundNumber:t},stack:e});const a=n.finishingPositions.length,o=Math.min(...n.finishingPositions)-1,d=2,l=t&&A?.[t]&&d+A[t]-1,f=YI({exitProfile:`0-${t}`,addNameBaseToAttributeName:i,playoffStructureNameBase:s,finishingPositionOffset:o,playoffAttributes:p,exitProfileLimit:h,stage:Uo,roundOffset:0,drawDefinition:w,sequenceLimit:l,stageSequence:d,drawSize:a,idPrefix:U,isMock:y,uuids:v,finishingPositionNaming:c,finishingPositionLimit:u,roundOffsetLimit:m});if(f.error)return ti({result:f,stack:e});const{structures:g,links:I}=f;if(g?.length&&k.push(...g),I?.length&&x.push(...I),f.structureId&&t){const e={linkType:ko,source:{structureId:r,roundNumber:t},target:{structureId:f.structureId,feedProfile:Eo,roundNumber:1}};x.push(e)}}if(!k.length)return ti({result:{error:Jn},info:"No structures generated",stack:e});w.structures.push(...k),w.links.push(...x);const{matchUps:_,matchUpsMap:L}=cf({inContext:!0,drawDefinition:w}),B=k.map((({structureId:t})=>t)),V=_?.filter((({structureId:t})=>B.includes(t))).map(Nu),j=L?.drawMatchUps?.filter((({matchUpId:t})=>V?.includes(t)));if(j?.length){const t=fl({drawDefinition:w,event:S})?.tieFormat;t&&j.forEach((e=>{const{tieMatchUps:n}=LI({matchUp:e,tieFormat:t,isMock:y});Object.assign(e,{tieMatchUps:n,matchUpType:o})}))}const G=_?.filter((t=>Zm({matchUp:t})&&t.structureId===r));G?.forEach((t=>{const{matchUpId:e,score:n,winningSide:r}=t,i=rf({inContextDrawMatchUps:_,drawDefinition:w,matchUpId:e}),a=ny({inContextDrawMatchUps:_,tournamentRecord:f,drawDefinition:w,matchUpsMap:L,winningSide:r,targetData:i,matchUpId:e,structure:P,matchUp:t,score:n,event:S});a.error&&console.log(a.error)}));const q=_?.filter((t=>t.matchUpStatus===Fu&&t.structureId===r));q?.forEach((t=>{const{matchUpId:e}=t,n=rf({inContextDrawMatchUps:_,drawDefinition:w,matchUpId:e}),{targetLinks:{loserTargetLink:r},targetMatchUps:{loserMatchUpDrawPositionIndex:i,loserMatchUp:a}}=n;if(r&&a){const t=r.target.structureId,e=Ef({drawPosition:a.drawPositions[i],structureId:t,tournamentRecord:f,drawDefinition:w,event:S});e.error&&console.log(e.error)}}));const $=[],W=yf({inContextDrawMatchUps:_,drawDefinition:w,matchUpsMap:L}).goesToMap,{structure:H}=ad({drawDefinition:t.drawDefinition,structureId:r}),{matchUps:Y}=Jm({structure:H});return Y.forEach((n=>{const r=W?.loserMatchUpIds[n.matchUpId];if(r&&n.loserMatchUpId!==r){n.loserMatchUpId=r;const i={tournamentId:f?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:n};$.push(i)}const i=W?.winnerMatchUpIds[n.matchUpId];if(i&&n.winnerMatchUpId!==i){n.winnerMatchUpId=i;const r={tournamentId:f?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:n};$.push(r)}})),{structures:k,matchUpModifications:$,links:x,drawDefinition:w,...z}}function iy({element:t}){if(!t)return{error:Jn};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:Jn};return t.timeItems.reduce((e="itemType",n="itemValue",(t,r)=>r[e]?(t[r[e]]=r[n],t):t),{});var e,n}function ay(t){const{duplicateValues:e=!0,creationTime:n=!0,removePriorValues:r,timeItem:i}=t;if(!i)return{error:_n};const a=gp(t);if(a.error)return a;if(!(G(i)&&j(i.itemType)&&Object.keys(i).includes("itemValue")))return{error:kn};if(a.timeItems){if(function({element:t,duplicateValues:e,timeItem:n}){const{itemType:r,itemSubTypes:i,itemValue:a}=n,o=r&&Ip({itemSubTypes:i,itemType:r,element:t})?.timeItem;return o&&JSON.stringify(o?.itemValue)===JSON.stringify(a)&&!e}({element:a,duplicateValues:e,timeItem:i}))return{...z}}else a.timeItems=[];if(i.itemSubTypes&&!i.itemSubTypes.length&&delete i.itemSubTypes,n){const t=(new Date).toISOString();Object.assign(i,{createdAt:t})}r&&(a.timeItems=a.timeItems.filter((({itemType:t})=>i.itemType!==t)));return r&&!i.itemValue||a.timeItems.push(i),{...z}}function oy({creationTime:t=!0,removePriorValues:e,tournamentRecord:n,duplicateValues:r,participantId:i,timeItem:a}){if(!n)return{error:nt};if(!i)return{error:Xe};const o=hp({tournamentRecord:n,participantId:i});return o.error?o:ay({element:o.participant,removePriorValues:e,duplicateValues:r,creationTime:t,timeItem:a})}function sy(t){const{removePriorValues:e,tournamentRecord:n,duplicateValues:r,creationTime:i,timeItem:a}=t;if(!n)return{error:nt};const o=ay({element:n,removePriorValues:e,duplicateValues:r,creationTime:i,timeItem:a});if(o.error)return o;const s=iy({element:n});return Or({payload:{parentOrganisation:n.parentOrganisation,tournamentId:n.tournamentId,timeItemValues:s},topic:Nd}),o}function cy(t){const{removePriorValues:e,duplicateValues:n,creationTime:r,timeItem:i,event:a}=t;return a?ay({removePriorValues:e,duplicateValues:n,element:a,creationTime:r,timeItem:i}):{error:Wt}}function uy(t){return py({...t,itemType:"attachConsolationStructures"})}function dy(t){return py({...t,itemType:"attachPlayoffStructures"})}function py({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:n,drawDefinition:r,structures:i,links:a=[],event:o}){const s="attachStructures";if(!r)return{error:ot};if(!Array.isArray(i)||!Array.isArray(a))return ti({result:{error:Jn},stack:s});const c=t=>[t.source.structureId,t.source.roundNumber||t.source.finishingPositions?.join("|"),t.target.roundNumber].join("|"),u=r.links?.map(c);if(a.some((t=>{const e=c(t);return u?.includes(e)})))return ti({result:{error:dr},info:"playoff structure exists",stack:s});a.length&&r.links?.push(...a);const d=i.map((({structureId:t})=>t)),p=r.structures?.map((({structureId:t})=>t));r.structures=(r.structures??[]).map((t=>d.includes(t.structureId)?i.find((({structureId:e})=>e===t.structureId)):t));const l=i?.filter((({structureId:t})=>!p?.includes(t)));l.length&&r.structures.push(...l),yf({drawDefinition:r});const m=i.map((t=>Jm({structure:t})?.matchUps||[])).flat();Gd({tournamentId:n?.tournamentId,eventId:o?.eventId,drawDefinition:r,matchUps:m});const f=i.map((({structureId:t})=>t));if(Hd({drawDefinition:r,structureIds:f}),e?.length){const t={};e.forEach((e=>{const n=e.matchUp?.matchUpId;n&&(t[n]=e)}));const n=e=>{e.matchUps.forEach((e=>{if(t[e.matchUpId]){const{tieMatchUps:n,...r}=t[e.matchUpId].matchUp;if(Object.assign(e,r),n?.length){const r={};n.forEach((e=>t[e.matchUpId]=e)),e.tieMatchUps.forEach((t=>Object.assign(t,r[t.matchUpId])))}t[e.matchUpId].matchUp=e,$d(t[e.matchUpId])}}))};r.structures.forEach((t=>{if(p?.includes(t.structureId))if(t.structures)for(const e of t.structures)n(e);else n(t)}))}const h=l.map(If("structureId"));if(n){ay({element:n,timeItem:{itemValue:{structureIds:f,drawId:r.drawId},itemType:t}})}return{...z,addedStructureIds:h}}function ly(t){const{structures:e,links:n,matchUpModifications:r,error:i}=ry(t);if(i)return{error:i};const a=t.drawDefinition;return dy({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:r,drawDefinition:a,structures:e,links:n})}function my(t){const e=cc(t,[{_anyOf:{[ms]:!1,[hs]:!1,[Is]:!1,[Ws]:!1},[fs]:!0}]);if(e.error)return e;const n=[],r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r){const e=fy(t,r);if(e.error)return e;n.push(...e?.applied??[]),t.drawDefinition&&Hd({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else{if(!t.tournamentRecords)return{error:nt};{const e=Object.keys(t.tournamentRecords);if(!e.length)return{error:nt};for(const r of e){const e=fy(t,t.tournamentRecords[r]);if(e.error)return e;n.push(...e?.applied??[])}}}return n.length?{...z,applied:n}:{error:ve}}function fy(t,e){const n=Np(t).appliedPolicies??{};e.extensions||(e.extensions=[]);const r=[],i=Object.keys(t.policyDefinitions);if(!i.length)return{error:Ie};for(const e of i)if(!n[e]||t.allowReplacement){const i=t.policyDefinitions[e];if(!i)continue;if(!G(i))return{error:Jn};const{policyName:a,...o}=i;if(!o||!Object.keys(o).length||a&&!j(a))return{error:Jn};n[e]=t.policyDefinitions[e],r.push(e)}if(r?.length){return{..._c({element:e,extension:{name:Yc,value:n}}),applied:r}}return{applied:r,error:ve}}function hy({tournamentRecord:t,drawDefinition:e,flightProfile:n,drawName:r,drawId:i,event:a}){if(!r||"string"!=typeof r)return ti({result:{error:Jn},context:{drawName:r}});n||(n=jm({event:a}).flightProfile);const o=n?.flights?.find((t=>t.drawId===i));if(o){o.drawName=r;Vc({event:a,extension:{name:ru,value:{...n,flights:n.flights}}})}return e&&(e.drawName=r,Hd({tournamentId:t?.tournamentId,drawDefinition:e})),o||e?{...z,flight:o}:{error:ot}}function gy({tournamentRecord:t,drawDefinition:e,drawUpdates:n,drawId:r,event:i}){if(!G(n))return{error:Jn};const a=jm({event:i}).flightProfile,o=n.drawName&&hy({drawName:n.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:a,drawId:r,event:i});if(o?.error)return o?.error;const s=o?.flight||a?.flights?.find((t=>t.drawId===r));if(!s&&!e)return{error:ot};if(s){Vc({event:i,extension:{name:ru,value:{...a,flights:a.flights}}})}return e&&(n.policyDefinitions&&my({policyDefinitions:n.policyDefinitions,drawDefinition:e}),Hd({tournamentId:t?.tournamentId,drawDefinition:e})),{...z}}function Iy({tournamentRecord:t,removeScheduling:e,drawDefinition:n}){if(!n)return{error:ot};const r=hl({drawDefinition:n}),i=t=>r?.drawMatchUps?.find((e=>e.matchUpId===t));for(const a of n.structures||[]){const{positionAssignments:o,stage:s,stageSequence:c}=a;!o||1===c&&[ho,fo].includes(s)||(a.positionAssignments=o.map((t=>(delete t.participantId,t))),a.seedAssignments=[]);const{matchUps:u,isRoundRobin:d}=Jm({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:r,structure:a});for(const r of u){const{matchUpId:a,roundNumber:o}=r,s=r.sides||[],c=i(a);if(c){if(delete c.extensions,delete c.notes,c.matchUpStatus!==Fu&&Object.assign(c,WU),o&&o>1&&c.drawPositions?.length&&!d){const t=s?.map((({drawPosition:t,participantFed:e})=>!e&&t)).filter(Boolean),e=c.drawPositions.map((e=>t.includes(e)?void 0:e));c.drawPositions=e}e?delete c.timeItems:c.timeItems?.length&&(c.timeItems=c.timeItems.filter((t=>t.itemType&&![xl,_l,kl,jl,Bl,Gl].includes(t.itemType)))),$d({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:n,matchUp:c})}}}n.extensions=n.extensions.filter((t=>t.name!==du));return Hd({drawDefinition:n,structureIds:(n.structures||[]).map((({structureId:t})=>t))}),{...z}}function Uy({tournamentRecord:t}){if(!t)return{error:nt};const e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},n={},r=t.events?.map((t=>{const e=t.eventId;return n[e]=t,(t?.drawDefinitions||[]).map((t=>({drawDefinition:t,eventId:e})))})).flat().filter(Boolean);return r.forEach((({drawDefinition:t,eventId:r})=>{let i=0,a=0,o=0;const{allStructuresLinked:s}=rI({drawDefinition:t}),c=n[r],u=(t?.structures||[]).map((e=>{const{stage:n,stageSequence:r,structureId:s}=e,u=So[n],{inContextStructureMatchUps:d}=Tf({drawDefinition:t,structure:e,event:c}),p=d?.filter((({winningSide:t})=>t)),l=p.filter(Boolean).length||0;a+=l,o+=d.length-a;const m=Math.max(p.filter((({roundNumber:t})=>1===t)).map((({roundPosition:t})=>t))),{positionAssignments:f}=cd({structure:e}),h=f?.filter((({participantId:t})=>t));i+=h?.length??0;const g=(f?.length??0)-(h?.length??0),{roundMatchUps:I,roundProfile:U,roundNumbers:y,maxMatchUpsCount:S}=Sl({matchUps:d}),v=U&&Object.keys(U).filter((t=>!U[t].inactiveRound)).map((t=>parseInt(t))),w=U&&Object.keys(U).filter((t=>U[t].inactiveRound)).map((t=>parseInt(t))),P=U&&Object.values(U).every((t=>t.inactiveRound));return{positionsAssignedCount:h?.length??0,maxWinningSideFirstRoundPosition:m,unassignedPositionsCount:g,inactiveStructure:P,maxMatchUpsCount:S,inactiveRounds:w,roundMatchUps:I,activeRounds:v,roundNumbers:y,roundProfile:U,structureId:s,stageSequence:r,orderNumber:u,stage:n}})),p=u.find((t=>2===t.orderNumber&&1===t.stageSequence)),l=u.filter((({inactiveStructure:t})=>!t)).length,{links:m}=ef({structureId:p.structureId,drawDefinition:t}),f=1===d(p.activeRounds[0])&&1===p.activeRounds.length&&1===l,h=u?.every((({inactiveStructure:t})=>t)),g=!m.length&&p.activeRounds.length&&(p.roundProfile[1].inactiveCount||p.inactiveRounds.length),I=t.drawId;i&&!a&&e.positionsNoOutcomes.push(I),h&&e.inactive.push(I),f&&e.matchPlay.push(I),g&&e.canBePruned.push(I);const U={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:o,positionsAssignedCount:i,allStructuresLinked:s,structuresData:u,inactiveDraw:h,isMatchPlay:f,drawId:I};e.drawAnalysis[I]=U})),{...z,drawsAnalysis:e}}function yy({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:n,drawId:r}){if(!e)return{error:nt};if(!n)return{error:ot};let i=[];const{drawsAnalysis:a}=Uy({tournamentRecord:e});if(a.canBePruned.includes(r)){const o=a.matchPlay.includes(r),s=a.drawAnalysis[r],{structures:[c]}=od({stageSequence:1,drawDefinition:n,stage:fo}),u=s.structuresData.find((({structureId:t})=>c.structureId===t)),d=(c.matchUps??[]).sort(((t,e)=>t.roundPosition-e.roundPosition));i=d.filter((({roundNumber:t})=>!u.inactiveRounds.includes(t)));const p=i.map(Nu),l=d.map(Nu).filter((t=>!p.includes(t)));if(o){const e=i.filter((({roundNumber:t})=>!u.inactiveRounds.includes(t))).filter((({winningSide:t})=>t)),n=e.map(Nu),r=p.filter((t=>!n.includes(t)));l.push(...r);const a=e.flatMap((t=>t.drawPositions??[])).filter(Boolean).flat(),o=Object.assign({},...a.map(((t,e)=>({[t]:e+1}))));if(e.forEach((e=>{t?e.drawPositions=e.drawPositions.map((t=>o[t])):delete e.drawPositions})),t){const t=c?.positionAssignments?.filter((t=>a.includes(t.drawPosition))).map((t=>(t.drawPosition=o[t.drawPosition],t)));c.positionAssignments=t}else c.positionAssignments=[];c.matchUps=e,i=e}qd({tournamentId:e?.tournamentId,matchUpIds:l,drawDefinition:n}),Hd({drawDefinition:n})}return{...z,matchUps:i}}function Sy({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:i,qualifier:a,event:o,bye:s}){if(!e)return{error:ot};if(!r)return{error:St};if(!i)return{error:_t};if(s){const n=Ef({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:i,event:o});if(n.error)return n}else{if(a)return{error:ir};{const a=mg({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:i,event:o});if(a.error)return a}}return{...z}}function vy(t){let e=t.matchUpIds??[];const{drawDefinition:n}=t,r=t.structureId??n?.structures?.find((t=>t.matchUps?.some((({matchUpId:t})=>e.includes(t)))))?.structureId??n?.structures?.[0]?.structureId;if(!r)return{error:Lt};const i=n.structures?.find((t=>t.structureId===r));if(!i)return{error:Lt};const a=i?.matchUps,o=a?.find((t=>!!t.roundPosition));if(i.structures||o||i.finishingPosition===ds)return{error:ut};const s=a.filter((({roundNumber:e})=>t.roundNumbers?.includes(e))).map(Nu);return e=e.filter((t=>!s.includes(t))),t.roundNumbers&&!e.length&&(e=s),{existingMatchUps:a,matchUpIds:e,structureId:r,structure:i}}function wy(t){const e=cc(t,[{[Is]:!0},{[ic]:{[Rs]:!1,roundNumbers:!1},[ec]:Jn,[nc]:Zs}]);if(e.error)return e;const{removeIncomplete:n=!1,removeUnAssigned:r=!0,removeCompleted:i=!1,tournamentRecord:o,drawDefinition:s,event:c}=t,u=vy(t);if(u.error)return u;const{structure:d,structureId:p,existingMatchUps:l,matchUpIds:m}=u,f=[],h=l?.filter((({matchUpId:t,score:e,winningSide:a})=>{if(a&&!i)return!1;if(a||vf({score:e})){if(!a&&!n)return!1;f.push(t)}else if(!r)return!1;return m?.includes(t)}))??[],g=h.map(Nu),I=h.map((({tieMatchUps:t})=>t?.map(Nu))).filter(Boolean).flat();if(g.length){d.matchUps=(d.matchUps??[]).filter((({matchUpId:t})=>!g.includes(t))),qd({tournamentId:o?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:c?.eventId,drawDefinition:s});const t=function(t,e=1){return Array.isArray(t)&&t.every(y)?E(Math.min(...t,e),Math.max(...t)+1).filter((e=>!t.includes(e))):[]}(w(d.matchUps.map(If("roundNumber"))));if(t.length){t.reverse();for(const e of t)d.matchUps.forEach((t=>{t.roundNumber&&t.roundNumber>e&&(t.roundNumber-=1,$d({tournamentId:o?.tournamentId,context:["adHoc round deletion"],eventId:c?.eventId,drawDefinition:s,matchUp:t}))}))}if(f.length){d.positionAssignments=w(d.matchUps.flatMap((t=>(t.sides??[]).map((t=>t.participantId)))).filter(Boolean)).map((t=>({participantId:t})));const t=d?.matchUpFormat??s?.matchUpFormat??c?.matchUpFormat,e=u.existingMatchUps.some((t=>t.matchUpType===a))?{matchUpTypes:[a]}:void 0,{matchUps:n}=Jm({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:e,structure:d,event:c});Dl({structure:d})&&(d.positionAssignments=w(n.flatMap((t=>(t.sides??[]).map((t=>t.participantId)))).filter(Boolean)).map((t=>({participantId:t}))));const r=VU({positionAssignments:d.positionAssignments,tournamentRecord:o,drawDefinition:s,matchUpFormat:t,matchUps:n,event:c});r.error&&console.log(r)}Hd({structureIds:[p],eventId:c?.eventId,drawDefinition:s})}return!g.length&&m.length?{error:mr}:{...z,deletedMatchUpsCount:[...g,...I].length}}function Py({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:r,roundNumber:i,event:a}){if(!e)return{error:nt};if(!n)return{error:ot};if(!i)return ti({result:{error:be},info:"roundNumber required"});const o=ad({drawDefinition:n,structureId:r});if(o.error)return o;const s=o.structure;if(s?.structures)return{error:ut};return Dl({structure:s})?function({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:n,roundNumber:r,structure:i,eventId:a}){const o=i?.matchUps??[],s=[],c=[];let d=!1;const p=o.reduce(((t,e)=>{const n=e?.roundNumber;return n?t.includes(n)?t:t.concat(n):t}),[]).sort(u);if(p.includes(r)){const u=o.filter((e=>{const n=e.roundNumber===r&&(!Xu.includes(e.matchUpStatus)||t);return n&&(c.push(e.matchUpId),e.tieMatchUps&&s.push(...e.tieMatchUps.map(Nu))),!n}));if(c.length){qd({matchUpIds:[...s,...c],drawDefinition:e,tournamentId:n,eventId:a});u.some((t=>t.roundNumber===r))||(u.forEach((t=>{t.roundNumber>r&&(t.roundNumber-=1,$d({drawDefinition:e,tournamentId:n,eventId:a,matchUp:t}))})),d=!0),i.matchUps=u}}return{deletedMatchUpsCount:c.length,roundRemoved:d,...z}}({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:a.eventId,drawDefinition:n,roundNumber:i,structure:s}):(console.log("not implemented"),{...z})}function Dy(t){const{suppressNotifications:e,tournamentRecord:n,drawDefinition:r,matchUps:i,event:a}=t;if("object"!=typeof r)return{error:ot};let o=t?.structureId;if(o||1!==r.structures?.length||(o=r.structures?.[0]?.structureId),"string"!=typeof o)return{error:_t};if(!yl(i))return{error:Jn,info:ug("matchUps")};const s=r.structures?.find((t=>t.structureId===o));if(!s)return{error:Lt};const c=s?.matchUps,u=c.find((t=>!!t.roundPosition));if(s.structures||u||s.finishingPosition===ds)return{error:ut};if(k(pf({tournamentRecord:n,inContext:!1})?.matchUps?.map(Nu)??[],i.map(Nu)))return{error:cr,info:"One or more matchUpIds already present in tournamentRecord"};s.matchUps.push(...i);const d=i.map((({tieMatchUps:t})=>t)).filter(Boolean).flat();return e||(Gd({tournamentId:n?.tournamentId,matchUps:[...d,...i],eventId:a?.eventId,drawDefinition:r}),Hd({drawDefinition:r,structureIds:[o]})),{...z}}function Ty({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:r,subOrder:i,event:a}){if(!e)return{error:ot};if(!r)return{error:_t};if(!n)return{error:St};const{structure:s}=ad({drawDefinition:e,structureId:r});if(!s)return{error:Lt};let c=s;s.structures&&s.structureType===Mo&&(c=s.structures?.find((t=>t.positionAssignments?.find((t=>t.drawPosition===n)))));const u=c?.positionAssignments,d=u?.find((t=>t.drawPosition===n));d&&_c({element:d,extension:{name:hu,value:i}});const p=(a?.eventType===o||e.matchUpType===o||(a?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[o]},{matchUps:l}=Jm({structure:c,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:p,event:a});return VU({positionAssignments:u,tournamentRecord:t,drawDefinition:e,matchUpFormat:s?.matchUpFormat??e.matchUpFormat,matchUps:l,event:a}),Hd({drawDefinition:e,structureIds:[r]}),{...z}}var by={__proto__:null,adHocPositionSwap:WI,addAdHocMatchUps:Dy,addDrawDefinitionTimeItem:sI,addPlayoffStructures:ly,addQualifyingStructure:$I,addVoluntaryConsolationStage:fI,addVoluntaryConsolationStructure:_h,alternateDrawPositionAssignment:vg,assignDrawPosition:Sy,assignDrawPositionBye:Ef,attachConsolationStructures:uy,attachPlayoffStructures:dy,attachQualifyingStructure:aI,attachStructures:py,automatedPlayoffPositioning:Jg,automatedPositioning:Qg,deleteAdHocMatchUps:wy,luckyLoserDrawPositionAssignment:hg,modifyDrawDefinition:gy,modifyDrawName:hy,modifySeedAssignment:Zg,pruneDrawDefinition:yy,qualifierDrawPositionAssignment:Xg,qualifierProgression:eI,removeDrawPositionAssignment:Ch,removeRoundMatchUps:Py,removeSeededParticipant:xI,removeStructure:cI,renameStructures:oI,resetDrawDefinition:Iy,resetQualifyingStructure:hI,resetVoluntaryConsolationStructure:Kd,setDrawParticipantRepresentativeIds:Eu,setPositionAssignments:yg,setStructureOrder:nI,setSubOrder:Ty,shiftAdHocRounds:Ug,swapAdHocRounds:Sg,swapDrawPositionAssignments:FI,updateTeamLineUp:pg,withdrawParticipantAtDrawPosition:Oh};function Ry({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:n,finishingRoundLimit:r,policyDefinitions:i,roundNumberLimit:a,tournamentRecord:o,drawDefinition:s,matchUpsLimit:c,requirePlay:u,requireLoss:d,allEntries:p,winsLimit:l,event:m}){if(!s)return{error:ot};const f=[fo,Uo];n&&f.push(ho);const h=m?.eventType?{matchUpTypes:[m.eventType]}:void 0,g=s?.matchUpType?{matchUpTypes:[s.matchUpType]}:void 0,I=e&&m?df({contextFilters:{stages:f},matchUpFilters:h,tournamentRecord:o,inContext:!0,event:m})?.matchUps??[]:ff({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:o,inContext:!0,drawDefinition:s})?.matchUps??[],U=dl({stage:Io,drawDefinition:s}).map((({participantId:t})=>t)),y={},S={},v={},w={};i||(i=Ap({policyTypes:[Uc],tournamentRecord:o,drawDefinition:s,event:m}).policyDefinitions);const P=i?.[Uc];t=t.length&&t||P?.excludedMatchUpStatuses||[],e=e??P?.includeEventParticipants,p=p??P?.allEntries,r=r??P?.finishingRoundLimit,a=a??P?.roundNumberLimit,c=c??P?.matchUpsLimit,void 0===u&&(u=void 0===P?.requirePlay||P.requirePlay),void 0===d&&(d=void 0===P?.requireLoss||P.requireLoss),l=l??P?.winsLimit;for(const e of I){if(u&&e.winningSide&&![1,2].includes(e.winningSide)&&e.matchUpStatus!==Vu)continue;if(e.finishingRound&&r&&e.finishingRound>=r)continue;if(e.finishingRound&&a&&e.finishingRound<=a)continue;const n=e.sides?.find((({sideNumber:t})=>e.winningSide&&t===3-e.winningSide)),i=e.sides?.find((({sideNumber:t})=>e.winningSide&&t===e.winningSide));if(e.sides?.forEach((n=>{const r=n?.participant?.participantId;r&&(v[r]=n.participant,e.matchUpStatus!==Vu||u||(S[r]=n.participant,y[r]||(y[r]=0),e.matchUpStatus&&t.includes(e.matchUpStatus)||(y[r]+=1)))})),n?.participant){const r=n.participant.participantId;S[r]=n.participant,y[r]||(y[r]=0),e.matchUpStatus&&!t.includes(e.matchUpStatus)&&(y[r]+=1)}if(i?.participant){const n=i.participant.participantId;w[n]||(w[n]=0),w[n]+=1,y[n]||(y[n]=0),e.matchUpStatus&&!t.includes(e.matchUpStatus)&&(y[n]+=1)}}const D=o?.participants&&!u&&!d&&p,T=D?((e&&m?m.entries:s.entries)??[]).filter((t=>![el,Zp].includes(t.entryStatus))).map((({participantId:t})=>t)):[],b=Object.keys(S),R=D?(o?.participants??[]).filter((({participantId:t})=>T.includes(t))):d&&Object.values(S)||Object.values(v);return{eligibleParticipants:R.filter((t=>{return e=t.participantId,(!d||b.includes(e))&&(t=>!u||(y[t]||0)>=0)(t.participantId)&&(t=>!l||(w[t]||0)<=l)(t.participantId)&&(t=>!c||y[t]<=c)(t.participantId)&&(t=>!U.includes(t))(t.participantId);var e})).map((t=>({...t,individualParticipants:t.individualParticipantIds?.map((t=>o?.participants?.find((e=>e.participantId===t))))}))),losingParticipantIds:b,...z}}function My(t){const e=cc(t,[{drawDefinition:!0}]);if(e.error)return e;const{drawDefinition:n,roundNumber:r}=t,i=t.structureId??(1===n.structures?.length&&n.structures?.[0]?.structureId);if("string"!=typeof i)return{error:_t};const a=n.structures?.find((t=>t.structureId===i));if(!a)return{error:Lt};let o;const s=a.matchUps??[],c=s?.reduce(((t,e)=>(e.roundPosition&&(o=!0),(e?.roundNumber||0)>t?e.roundNumber:t)),0);if(a.structures||o||a.finishingPosition===ds)return{error:ut};const u=n?.entries?.filter((t=>{const e=t.entryStatus;return al.includes(e)}))??[],d=Math.floor(u?.length/2)||1,p=r??c??1,l=d-(a.matchUps?.filter((t=>t.roundNumber===p))?.length??0),m=l>0?l:0;return{...z,availableMatchUpsCount:m,lastRoundNumber:c,roundMatchUpsCount:d}}function Ny({drawDefinition:t}){const e=zc({name:"participantRepresentatives",element:t});if(e.error)return e;return{representativeParticipantIds:e.extension?.value||[]}}function Ay({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:n}){if(!n)return{error:ot};const{participantIds:r,participantIdMatchUps:i}=function({tournamentParticipants:t,drawDefinition:e,event:n}){if(!e)return{error:ot};const r=la(cf({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:n}).matchUps,!1,!0),i=w(r.reduce(((t,e)=>t.concat(...e.sides.map((t=>t.participantId)).filter(Boolean))),[])),a=Object.assign({},...i.map((t=>{const e=r.filter((e=>e.sides.map((t=>t.participantId)).filter(Boolean).includes(t)));return{[t]:e}})));return{participantIds:i,participantIdMatchUps:a}}({tournamentParticipants:e?.participants,drawDefinition:n}),a=r?.map((e=>{const n=i[e].filter((t=>[xu,Fu].includes(t.matchUpStatus)||t.winningSide)),r=n.map((n=>{const r=n.sides.find((t=>t.bye)),i=n.sides.find((t=>t.participantId===e)).sideNumber;return(n.winningSide||t&&r&&i)===i?n.finishingPositionRange.winner:n.finishingPositionRange.loser})),a=t=>Math.abs(t[0]-t[1]),o=r.reduce(((t,e)=>t&&a(t)<a(e)?t:e),void 0);return{[e]:{relevantMatchUps:n,finishingPositionRanges:r,finishingPositionRange:o}}}))||[];return Object.assign({},...a)}function Ey({tournamentRecords:t,tournamentRecord:e,tournamentId:n,drawId:r}){if(!e&&!t)return{error:nt};if(!r)return{error:Tt};if(!e&&t){if("string"!=typeof n&&!(n=ty({tournamentRecords:t,drawId:r})))return{error:it};if(!(e=t[n]))return{error:nt}}const i=e&&Gm({tournamentRecord:e,drawId:r});return i?.drawDefinition?{drawDefinition:i.drawDefinition,event:i.event,tournamentRecord:e,...z}:ti({result:{error:ct},stack:"findDrawDefinition"})}function Cy(t){const{drawDefinition:e,error:n}=Ey(t);return n?{error:n}:{drawDefinition:la(e)}}function Oy(t){const{inContextDrawMatchUps:e,targetData:n,drawDefinition:r,relevantLink:i}=t;if(i?.linkCondition===xo&&n?.matchUp?.matchUpStatus===Fu)return!1;const{targetMatchUps:{loserMatchUp:a,winnerMatchUp:o},targetLinks:s}=n,c=a&&rf({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),u=c?.targetMatchUps?.loserMatchUp,d=c?.targetMatchUps?.loserMatchUpDrawPositionIndex,p=u?.sides[d]?.participant,l=[Lu,zu].includes(a?.matchUpStatus)&&!p,m=o?.drawPositions?.filter(Boolean).length||0;if(a?.winningSide&&!l||o?.winningSide&&2===m&&(!o.feedRound||![zu,Lu].includes(o?.matchUpStatus)))return!0;const f=o&&rf({matchUpId:o.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),h=c&&Oy({relevantLink:s?.loserTargetLink,targetData:c,inContextDrawMatchUps:e,drawDefinition:r});return!(!(f&&Oy({targetData:f,inContextDrawMatchUps:e,drawDefinition:r}))&&!h)}const Fy={[vc]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ho,fo],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[NI,EI,vI,AI],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}},ky="positionAction",xy="matchUpAction";function _y({actionType:t=ky,appliedPolicies:e,drawDefinition:n,structure:r}){const i=t===ky&&vc||t===xy&&wc,a=t===ky&&Fy||t===xy&&fh,o=i&&(e?.[i]||a?.[i]),s=n.links?.filter((t=>t?.target?.structureId===r?.structureId)),c=s?.map((({target:t})=>t.feedProfile))??[],{enabledStructures:u,disabledStructures:d}=o||{},p=d?.find((t=>{const{stages:e,stageSequences:n,structureTypes:i,feedProfiles:a}=t;return(!a?.length||Array.isArray(a)&&a.some((t=>c.includes(t))))&&(!e?.length||Array.isArray(e)&&e?.includes(r?.stage))&&(!i?.length||Array.isArray(i)&&i?.includes(r?.structureType))&&(!n?.length||Array.isArray(n)&&n.includes(r?.stageSequence))}));return{enabledStructures:u,actionsDisabled:p,actionsPolicy:o}}function Ly({activePositionOverrides:t,activeDrawPositions:e,action:n}){return!(!n||!t.includes(n))||!e.length}function By({enabledStructures:t,drawDefinition:e,structure:n}){if(!1===t)return{};if(!t?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};const{stage:r,stageSequence:i,structureType:a}=n||{},o=e.links?.filter((t=>t?.target?.structureId===n?.structureId)),s=o?.map((({target:t})=>t.feedProfile))||[];return{policyActions:t.find((t=>{const{stages:e,stageSequences:n,structureTypes:o,feedProfiles:c}=t||{},u=!e?.length||Array.isArray(e)&&e.includes(r),d=!n?.length||Array.isArray(n)&&n.includes(i),p=!o?.length||Array.isArray(o)&&o.includes(a),l=!c?.length||Array.isArray(c)&&c.some((t=>s.includes(t)));return d&&p&&l&&t&&u}))}}function Vy({action:t,policyActions:e}){const n=!e?.enabledActions||e?.disabledActions?.length&&e.disabledActions.includes(t);if(n)return!1;return(0===e?.enabledActions.length||e?.enabledActions.includes(t))&&!n}const jy="replaceTieMatchUpParticipantId",Gy="assignTieMatchUpParticipantId",qy="removeTieMatchUpParticipantId",$y="assignMatchUpSideParticipant",Wy="substituteParticipant",Hy="REMOVE_SUBSTITUTION",zy="REPLACE_PARTICIPANT",Yy="REMOVE_PARTICIPANT",Ky="setMatchUpStatus",Qy="SUBSTITUTION",Jy="SCHEDULE",Zy="REFEREE",Xy="STATUS",tS="START",eS="SCORE",nS="END",rS={REPLACE_TEAM_POSITION_METHOD:jy,ASSIGN_TEAM_POSITION_METHOD:Gy,REMOVE_TEAM_POSITION_METHOD:qy,REPLACE_PARTICIPANT:zy,SUBSTITUTION_METHOD:Wy,REMOVE_SUBSTITUTION:Hy,REMOVE_PARTICIPANT:Yy,SCHEDULE_METHOD:Ky,SUBSTITUTION:Qy,SCHEDULE:Jy,PENALTY:"PENALTY",REFEREE:Zy,STATUS:Xy,SCORE:eS,START:tS,END:nS};function iS({restrictQualifyingAlternates:t,structure:e,entry:n}){const{stage:r}=e;if(!n.entryStage||n.entryStage===r||r===ho&&!t||n.entryStage===fo&&r===go)return!0}function aS({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:n,otherFlightEntries:r,drawDefinition:i,structureId:a,sideNumber:o,matchUpId:s,structure:c,matchUp:u,drawId:d,event:p}){const l=[],m=c?.matchUps??[],f=u.sides?.find((t=>t.sideNumber===o)),h=f?.participantId,g=m.filter((({roundNumber:t})=>t===u.roundNumber)),I=i?.entries?.filter((({entryStatus:t})=>t&&il.includes(t))).map(Mu)??[],U=g.map((t=>(t.sides??[]).flatMap(Mu))).flat().filter(Boolean),y=I.filter((e=>!(n.includes(e)||t&&U.includes(e)))),S=e?.filter((t=>y?.includes(t.participantId))).map((t=>la(t,void 0,!0)));S?.forEach((t=>{const e=(i.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),y.length&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},method:$y,type:DI,availableParticipantIds:y,participantsAvailable:S});const v=function({eventEntries:t,structure:e}){return t.filter((t=>t.entryStatus===qp&&iS({structure:e,entry:t}))).sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))).map(Mu)}({eventEntries:p?.entries??[],structure:c});let P=w(I.concat(v));if(r){const t=p?jm({event:p}):void 0,e=t?.flights?.filter((t=>t.drawId!==d)).flatMap((t=>t.drawEntries.filter((t=>t.participantId&&![el,Zp,Xp].includes(t.entryStatus))).map((({participantId:t})=>t)))).filter(Boolean);e?.length&&P.push(...e)}P=P.filter((e=>!(n.includes(e)||y.includes(e)||t&&U.includes(e))));const D=e?.filter((t=>P.includes(t.participantId))).map((t=>la(t,void 0,!0)));if(D?.forEach((t=>{const e=(i.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),D?.sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))),P.length&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},availableParticipantIds:P,participantsAvailable:D,method:$y,type:qp}),!vf(u)&&o&&h){l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},method:"removeMatchUpSideParticipant",type:Yy});const t=t=>t.sides.map(Mu),n=({matchUpId:t})=>t!==u.matchUpId,r=t=>!vf(t),i=u.sides?.find((t=>t.sideNumber!==o))?.participantId,c=[i,...m.filter((({roundNumber:t})=>t!==u.roundNumber)).filter(n).map(t).filter((t=>t.includes(h))).flat()].filter(Boolean),p=t=>!c.flat().includes(t),f=g.filter(r).filter(n).map(t).flat().filter(p);if(f.length){const t=e?.filter((t=>f.includes(t.participantId))).map((t=>la(t,void 0,!0)));l.push({payload:{participantIds:[h],roundNumber:u.roundNumber,structureId:a,sideNumber:o,matchUpId:s,drawId:d},swappableParticipantIds:f,method:"adHocPositionSwap",type:MI,swappableParticipants:t})}}return l}function oS(t){if(!t)return{error:Jn};let{drawDefinition:n,event:i}=t;const{restrictAdHocRoundParticipants:a=!0,policyDefinitions:o,enforceGender:s,participantId:c,sideNumber:u,matchUpId:d}=t,p=t.tournamentRecord??(t.tournamentId&&j(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!p)return{error:nt};if(!d||!j(d))return{error:de};if(u&&![1,2].includes(u))return ti({result:{error:Jn},context:{sideNumber:u}});if(!n){const t=(pf({tournamentRecord:p}).matchUps??[]).find((t=>t.matchUpId===d));i=(p?.events??[]).find((e=>e.eventId===t?.eventId));const e=(i?.drawDefinitions??[]).find((e=>e.drawId===t?.drawId));e&&(n=e)}if(!n)return{error:ot};const l=ih({withIndividualParticipants:!0,tournamentRecord:p}).participants,{drawId:m}=n,{matchUp:f,structure:h}=GU({drawDefinition:n,matchUpId:d,event:i});if(!f)return{error:le};const g=Np({tournamentRecord:p,drawDefinition:n,structure:h,event:i}).appliedPolicies??{};Object.assign(g,o??{});const I=g?.[vc]?.otherFlightEntries,U=g?.[wc]??fh[wc],{enabledStructures:y}=_y({actionType:xy,appliedPolicies:g,drawDefinition:n,structure:h}),{policyActions:S}=By({enabledStructures:y,drawDefinition:n,structure:h}),v=t.matchUpsMap??hl({drawDefinition:n}),w=t.inContextDrawMatchUps??cf({tournamentParticipants:l,inContext:!0,drawDefinition:n,matchUpsMap:v,event:i}).matchUps,P=w?.find((t=>t.matchUpId===d)),D=u&&P?.sides?.find((t=>t.sideNumber===u)),T=P?.sides?.map((t=>t.participantId||t.participant?.participantid)).filter(Boolean)??[],{assignedPositions:b,allPositionsAssigned:R}=ud({structure:h}),{structureId:M}=h??{},N=[];if(!M)return{validActions:N};const A=Dl({structure:h}),E=Boolean(f.collectionId);if(A&&!E){const t=aS({restrictAdHocRoundParticipants:a,tournamentParticipants:l,matchUpParticipantIds:T,otherFlightEntries:I,drawDefinition:n,structureId:M,sideNumber:u,matchUpId:d,structure:h,matchUp:f,drawId:m,event:i});N.push(...t)}const C=Tg({drawDefinition:n,structure:h}),O=b?.filter((t=>t.participantId)).map((t=>t.drawPosition)),F=b?.filter((t=>t.bye)).map((t=>t.drawPosition)),k=f.matchUpStatus===Fu||!E&&f.drawPositions?.reduce(((t,e)=>F?.includes(e)||t),!1);if(k)return{validActions:N,isByeMatchUp:k};Vy({policyActions:S,action:Zy})&&N.push({type:Zy,payload:{matchUpId:d}});const x=!wf({matchUpStatus:f.matchUpStatus}),_=g?.scoring?.structures,L=h?.stage&&_?.stage&&_?.stage[h.stage],B=h?.stageSequence&&L?.stageSequence&&L.stageSequence[h.stageSequence],V=!(g?.scoring?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned||B?.requireAllPositionsAssigned)||R,G=f.sides&&2===f.sides.filter((t=>t?.participantId)).length,q=f.matchUpStatus&&[Vu,Bu].includes(f.matchUpStatus),$=Oy({inContextDrawMatchUps:w,drawDefinition:n,targetData:rf({inContextDrawMatchUps:w,drawDefinition:n,matchUpId:d})}),W=2===P?.drawPositions?.length&&P.drawPositions.every((t=>O?.includes(t)))&&2===P?.sides?.length&&P.sides.every((({participantId:t})=>t)),H=(W||G)&&!(q&&$),Y={method:yI,type:EI,payload:{drawId:m,matchUpId:d,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(x&&N.push({payload:{drawId:m,matchUpId:d,schedule:{}},method:Ky,type:Jy}),Vy({policyActions:S,action:EI})&&(D?.participant||!u&&T?.length)&&N.push(Y),x&&H&&N.push({type:Xy}),V&&H){const{matchUpId:t,matchUpFormat:e}=f,n={drawId:m,matchUpId:t,matchUpFormat:e,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};N.push({info:"set outcome and winningSide",method:Ky,type:eS,payload:n}),Vy({policyActions:S,action:tS})&&N.push({type:tS}),Vy({policyActions:S,action:nS})&&N.push({type:nS})}if(E&&P){const t=function({specifiedPolicyDefinitions:t,inContextDrawMatchUps:n,matchUpParticipantIds:i,matchUpActionsPolicy:a,inContextMatchUp:o,policyActions:s,enforceGender:c,participantId:u,sideNumber:d,matchUpId:p,matchUp:l,drawId:m,side:f}){const h=[],g=o.sides?.find((t=>t.participant)),I=o.gender===ri&&o.sideNumber&&1===o.sides?.filter((t=>t.particiapntId)).length&&g?.participant?.person?.sex,U=o.matchUpType,y=!1!==(c??a?.participants?.enforceGender)?o.gender:void 0,S=o.sides?.flatMap((t=>t.participant?.individualParticipants||t.participant)).filter(Boolean),v=S?.map(Mu),w=o.sides?.filter((t=>!d||t.sideNumber===d)).flatMap((t=>t.participant?.individualParticipants||t.participant)).filter(Boolean),P=w?.map(Mu),D=n?.find((t=>t.matchUpId===o.matchUpTieId)),T=D?.sides?.map((t=>t?.participant?.individualParticipants?.filter((({participantId:t,person:e})=>!P?.includes(t)&&(!y||y===ei||e.sex===y||y===ri&&!I||I&&e.sex!==I))))),b=d?T?.[d-1]:T?.map(((t,e)=>({participants:t,sideNumber:e+1}))),R=d?T?.[d-1]?.map(Mu):T?.map(((t,e)=>({participants:t?.map(Mu),sideNumber:e+1}))),M=d&&(um(e)(U)&&!P?.length||um(r)(U)&&(P?.length??0)<2)||!d&&(um(e)(U)&&(P?.length??0)<2||um(r)(U)&&(P?.length??0)<4),N=R?.filter((t=>!v?.includes(t))),A=b?.filter((({participantId:t})=>N.includes(t)));if(M&&N?.length&&h.push({availableParticipantIds:N,method:Gy,availableParticipants:A,type:DI,payload:{participantId:void 0,tieMatchUpId:p,sideNumber:d,drawId:m}}),!P?.length||vf(l)&&!f?.substitutions?.length||h.push({method:qy,type:Yy,existingParticipantIds:P,payload:{participantId:void 0,tieMatchUpId:p,drawId:m}}),A?.length&&(!d&&P?.length||d&&f?.participant)&&h.push({availableParticipantIds:N,method:jy,availableParticipants:A,type:zy,existingParticipantIds:P,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:p,drawId:m}}),Vy({policyActions:s,action:Hy})&&f?.substitutions?.length){const t=f.participant?.participantType===ap&&[f.participantId]||f.participant?.participantType===sp&&f.participant.individualParticipantIds||[],e=f.substitutions.map((t=>t.participantId)).filter((e=>t.includes(e)));u&&!e.includes(u)||h.push({method:qy,type:Hy,substitutedParticipantIds:e,payload:{participantId:void 0,tieMatchUpId:p,drawId:m}})}const E=t?.[wc],C=E?.substituteWithoutScore,O=E?.substituteAfterCompleted;if(Vy({policyActions:s,action:Qy})&&2===i.length&&(!d&&P?.length||d&&f?.participant)&&(C||vf(l))&&(O||l.matchUpStatus&&!Xu.includes(l.matchUpStatus))&&w?.length&&b.length){const t=w.map(Mu);h.push({info:"list of team players available for substitution",method:Wy,availableParticipantIds:R,existingParticipantIds:t,availableParticipants:b,existingParticipants:w,type:Qy,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:d,matchUpId:p,drawId:m}})}return h}({specifiedPolicyDefinitions:o,inContextDrawMatchUps:w,matchUpParticipantIds:T,matchUpActionsPolicy:U,inContextMatchUp:P,policyActions:S,enforceGender:s,participantId:c,sideNumber:u,matchUpId:d,matchUp:f,drawId:m,side:D});N.push(...t)}return{structureIsComplete:C,validActions:N,isDoubleExit:q,...z}}function sS(t,e){return t.bye||zh(t.seedValue)<zh(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function cS({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:n,inactiveDrawPositions:r,activeDrawPositions:i,positionAssignments:a,returnParticipants:o,byeDrawPositions:s,drawDefinition:c,isByePosition:u,drawPosition:d,structureId:p,structure:l,drawId:m,event:f}){if(i.includes(d))return{};const h=r?.filter((t=>t!==d&&!(u&&s.includes(t)))),g=a?.filter((e=>(e=>!t||e.participantId||e.qualifier||e.bye)(e)&&h?.includes(e.drawPosition)))??[],I=g.map((({drawPosition:t})=>t)),{matchUps:U}=Jm({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:l,event:f}),y=U.filter((({drawPositions:t})=>k(t,I))),S=Object.assign({},...y.map((t=>t.sides?.filter((({sourceDrawPositionRange:t})=>t)).map((({drawPosition:t,sourceDrawPositionRange:e})=>({[t]:e}))))).flat()),v=g.map((t=>t.participantId)).filter(Boolean),w=(n??[]).filter((t=>v.includes(t.participantId))),P=Object.assign({},...w.map((t=>({[t.participantId]:t})))),D=g.map((t=>{const e=P?.[t.participantId],n=S[t.drawPosition];return Xr({...t,participant:o?la(e,!1,!0):void 0,sourceDrawPositionRange:n})}));if(D.length){return{validSwapAction:{payload:{drawId:m,structureId:p,drawPositions:[d]},willDisableLinks:e,method:II,type:MI,availableAssignments:D}}}return{}}function uS(t){const e=cc(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return e;const{policyDefinitions:n,returnParticipants:r=!0,provisionalPositioning:i,tournamentRecord:a,drawDefinition:o,drawPosition:s,event:c}=t,u=t.tournamentParticipants??(a&&ih({withIndividualParticipants:!0,tournamentRecord:a}).participants)??[];let d=ad({structureId:t.structureId,drawDefinition:o});if(d.error)return d;const p=d.containingStructure||d.structure;if(!p)return{error:Lt};const l=p.structureId;if(d=Tf({drawDefinition:o,structureId:l}),void 0===s&&!d.isAdHoc)return{error:St};if(d.isAdHoc)return oS(t);if(d.error)return d;const{drawPositionInitialRounds:m,inactiveDrawPositions:f,activeDrawPositions:h,byeDrawPositions:g}=d,I=Np({tournamentRecord:a,drawDefinition:o,structure:p,event:c}).appliedPolicies??{};Object.assign(I,n??{});const{actionsPolicy:U,enabledStructures:y,actionsDisabled:S}=_y({actionType:ky,appliedPolicies:I,drawDefinition:o,structure:p}),v=U?.activePositionOverrides||[],{sourceStructureIds:P}=tI({finishingPosition:us,targetRoundNumber:1,linkType:Oo,drawDefinition:o,structureId:l})||{};let D;P?.length&&(D=P.every((t=>Tg({structureId:t,drawDefinition:o}))));const T=P.length,b=P.length&&!D,{policyActions:R}=By({enabledStructures:y,drawDefinition:o,structure:p}),M=![ho,fo].includes(p.stage)||1!==p.stageSequence,{drawId:N}=o,A=[],{assignedPositions:E,positionAssignments:C}=ud({structure:p}),O=E?.find((t=>t.drawPosition===s)),F=!!O,k=C?.map((t=>t.drawPosition));if(!k?.includes(s))return{error:yt};const{stage:x,stageSequence:_}=p,L=[x];x===go&&L.push(fo),x===fo&&L.push(go);const B=dl({entryStatuses:il,provisionalPositioning:i,drawDefinition:o,stageSequence:_,structureId:l,stages:L}),V=Vf({drawDefinition:o,stages:L}).assignedParticipantIds??[],j=B.filter((t=>!V.includes(t.participantId))).map((t=>t.participantId)),G=g.includes(s),q=h.includes(s);if(S)return{info:"Actions Disabled for structure",isActiveDrawPosition:q,isDrawPosition:!0,hasPositionAssigned:F,validActions:[],isByePosition:G};if(Vy({policyActions:R,action:DI})&&!q&&C&&!b&&(!O||G)){const{validAssignmentActions:t}=function({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:n,provisionalPositioning:r,tournamentParticipants:i,isWinRatioFedStructure:a,positionAssignments:o,returnParticipants:s,appliedPolicies:c,drawDefinition:u,seedingProfile:d,isByePosition:p,drawPosition:l,structureId:m,event:f}){const{drawId:h}=u,g=[];let I,U,y=[];const S=c?.[Ac]?.validSeedPositions?.ignore;if(!S){const t=Zh({provisionalPositioning:r,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:d,structureId:m});({unplacedSeedParticipantIds:I,unplacedSeedAssignments:U,unfilledPositions:y}=t)}if(y?.length||(y=o.filter((t=>!t.participantId&&!t.bye&&!t.qualifier)).map((t=>t.drawPosition))),p||g.push({payload:{drawId:h,structureId:m,drawPosition:l,isPositionAction:!0},willDisableLinks:n,method:"assignDrawPositionBye",type:CI}),a&&S){const e=o.map((t=>t.participantId)).filter(Boolean),r={structureIds:t},{completedMatchUps:a}=uf({inContext:!0,matchUpFilters:r,drawDefinition:u}),c=w((a??[]).filter((({matchUpType:t})=>f?.eventType!==po||t===po))?.map((({sides:t})=>t?.map(Mu))).flat().filter((t=>t&&!e.includes(t)))),d=s?i?.filter((t=>c?.includes(t.participantId))).map((t=>la(t,void 0,!0))):void 0;return d?.forEach((t=>{const e=(u.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),d?.length&&g.push(Xr({payload:{drawId:h,structureId:m,drawPosition:l},willDisableLinks:n,method:UI,type:DI,availableParticipantIds:c,participantsAvailable:d})),{validAssignmentActions:g}}if(y.includes(l)||p){let t;if(U?.length){const e=U.filter((t=>I?.includes(t.participantId)));e.sort(sS),t=e.map((t=>t.participantId))}else t=e;const r=s?i?.filter((e=>t.includes(e.participantId))).map((t=>la(t,void 0,!0))):void 0;r?.length&&g.push(Xr({payload:{drawId:h,structureId:m,drawPosition:l},willDisableLinks:n,method:UI,type:DI,availableParticipantIds:t,participantsAvailable:r}))}return{validAssignmentActions:g}}({positionSourceStructureIds:P,unassignedParticipantIds:j,possiblyDisablingAction:M,isWinRatioFedStructure:T,tournamentParticipants:u,positionAssignments:C,returnParticipants:r,appliedPolicies:I,drawDefinition:o,isByePosition:G,drawPosition:s,structureId:l,event:c});t?.forEach((t=>A.push(t)))}if(Vy({policyActions:R,action:vI})&&!q){const{validAssignmentActions:t}=function({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:n,returnParticipants:r,appliedPolicies:i,drawDefinition:a,drawPosition:o,structureId:s,drawId:c}){const u=[],d=[],p=[],l=[],m=n.map((t=>t.participantId)).filter(Boolean),f=i?.[vc],h=!f?.disableRoundRestrictions&&t[o],g=f?.requireCompletedStructures,{sourceStructureIds:I,relevantLinks:U}=tI({targetRoundNumber:h,linkType:Fo,drawDefinition:a,structureId:s})||{};I?.length&&l.push(...I);const{sourceStructureIds:y,relevantLinks:S}=tI({targetRoundNumber:h,linkType:Oo,drawDefinition:a,structureId:s})||{};y?.length&&l.push(...y);for(const t of U){const n=a.structures?.find((e=>e.structureId===t.source.structureId));if(n?.stage!==ho)continue;const i=Tg({structureId:t.source.structureId,drawDefinition:a});if(!g||i){const t=n.qualifyingRoundNumber,{matchUps:i}=Jm({matchUpFilters:{roundNumbers:[t],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:n});for(const t of i){const e=t.sides.find((e=>e?.sideNumber===t.winningSide)),n=t.matchUpStatus===Fu&&t.sides?.find((({participantId:t})=>t));if(e||n){const{participantId:t,participant:i}=e||n||{};t&&!m.includes(t)&&(i&&r&&u.push(i),d.push(t))}}}}for(const t of S){const n=a.structures?.find((e=>e.structureId===t.source.structureId));if(n?.stage!==ho)continue;const i=Tg({structureId:t.source.structureId,drawDefinition:a});if(!g||i){const{positionAssignments:t}=cd({structure:n}),i=t?.map((t=>{const e=t.participantId,n=zc({element:t,name:gu}).extension?.value;return n?{participantId:e,groupOrder:n?.groupOrder}:{}})).filter((({groupOrder:t,participantId:e})=>1===t&&!m.includes(e))).map((({participantId:t})=>t))??[];if(i&&d.push(...i),r){const t=e.filter((({participantId:t})=>i.includes(t)));u.push(...t)}}}return d.length&&p.push(Xr({qualifyingParticipants:r?u:void 0,method:"qualifierDrawPositionAssignment",type:vI,qualifyingParticipantIds:d,payload:{qualifyingParticipantId:void 0,drawPosition:o,structureId:s,drawId:c}})),{validAssignmentActions:p,sourceStructureIds:l}}({drawPositionInitialRounds:m,tournamentParticipants:u,positionAssignments:C,returnParticipants:r,appliedPolicies:I,drawDefinition:o,drawPosition:s,structureId:l,drawId:N});t?.forEach((t=>A.push(t)))}const{participantId:$}=O||{},W=$&&u.find((t=>t.participantId===$));if(O){Vy({policyActions:R,action:TI})&&!q&&(A.push({type:TI,method:gI,payload:{drawId:N,structureId:l,drawPosition:s},willDisableLinks:M}),G||A.push({type:PI,method:"withdrawParticipantAtDrawPosition",payload:{drawId:N,structureId:l,drawPosition:s},willDisableLinks:M}),Vy({policyActions:R,action:CI})&&!G&&A.push({type:CI,method:gI,payload:{drawId:N,structureId:l,drawPosition:s,replaceWithBye:!0},willDisableLinks:M}));const t=p.stage===ho||p.stage===fo&&1===p.stageSequence;if(!G&&Ly({activePositionOverrides:v,activeDrawPositions:h,action:AI})&&Vy({policyActions:R,action:AI})&&Jh({drawDefinition:o,structureId:l,drawPosition:s})&&t){const{seedAssignments:t}=pl({returnAllProxies:!0,drawDefinition:o,structure:p}),{seedNumber:e,seedValue:n}=t?.find((t=>t.participantId===$))??{};A.push({type:AI,method:"modifySeedAssignment",participant:W,seedNumber:e,payload:{drawId:N,structureId:l,participantId:$,seedValue:n}})}if(!G&&Ly({activePositionOverrides:v,activeDrawPositions:h,action:RI})&&Vy({policyActions:R,action:RI})&&Jh({drawDefinition:o,structureId:l,drawPosition:s})&&t){const{seedAssignments:t}=pl({returnAllProxies:!0,drawDefinition:o,structure:p}),{seedNumber:e}=t?.find((t=>t.participantId===$))??{};A.push({method:"removeSeededParticipant",type:RI,participant:W,seedNumber:e,payload:{participantId:$,structureId:l,drawId:N}})}if(!G&&$){if(Vy({policyActions:R,action:EI})){const t={type:EI,method:yI,participant:W,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:N}};A.push(t)}if(Vy({policyActions:R,action:NI})){const t={type:NI,method:"modifyParticipantOtherName",participant:W,payload:{participantId:$,otherName:void 0}};A.push(t)}}if(Vy({policyActions:R,action:MI})){const{validSwapAction:t}=cS({possiblyDisablingAction:M,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:h,positionAssignments:C,returnParticipants:r,byeDrawPositions:g,drawDefinition:o,isByePosition:G,drawPosition:s,structureId:l,structure:p,drawId:N});t&&A.push(t)}}if(Vy({policyActions:R,action:wI})&&!b){const{validAlternatesAction:t}=function({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:n,positionAssignments:r,returnParticipants:i,appliedPolicies:a,drawDefinition:o,drawPosition:s,validActions:c,structureId:u,structure:d,drawId:p,event:l}){if(n.includes(s))return{};const m=c.find((t=>t.type===DI))?.availableParticipantIds,f=a?.[vc]?.otherFlightEntries,h=a?.[vc]?.restrictQualifyingAlternates,g=(o.entries??[]).filter((({entryStage:t})=>!h||(d.stage===ho?t===ho:t!==ho))).sort(((t,e)=>(t.entryPosition??1/0)-(e.entryPosition??1/0))).map((({participantId:t})=>t)).filter(Boolean),{allPositionedParticipantIds:I}=sd({drawDefinition:o}),U=r.map((t=>t.participantId)).filter(Boolean),y=g.filter((t=>d.stage&&[ho,fo,Uo].includes(d.stage)?!I?.includes(t):!U.includes(t))),S=(l?.entries??[]).filter((t=>t.entryStatus===qp&&iS({restrictQualifyingAlternates:h,structure:d,entry:t})&&(d.stage&&[ho,fo,Uo].includes(d.stage)?!I?.includes(t.participantId):!U.includes(t.participantId)))).sort(((t,e)=>(t.entryPosition??1/0)-(e.entryPosition??1/0))).map((t=>t.participantId));let v=w(y.concat(S));if(f){const t=l?jm({event:l}).flightProfile:void 0,e=t?.flights?.filter((t=>t.drawId!==p)).map((t=>t.drawEntries.filter((t=>t.participantId&&![el,Zp,Xp].includes(t.entryStatus)&&!g.includes(t.participantId))).map((({participantId:t})=>t)))).flat().filter(Boolean);e?.length&&v.push(...e)}m?.length&&(v=v.filter((t=>!m.includes(t))));const P=i?t?.filter((t=>v.includes(t.participantId))):void 0;if(P?.forEach((t=>{const e=(o.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),P?.sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))),v.length)return{validAlternatesAction:Xr({payload:{drawId:p,structureId:u,drawPosition:s},willDisableLinks:e,method:"alternateDrawPositionAssignment",availableAlternatesParticipantIds:v,type:wI,availableAlternates:P})};return{}}({possiblyDisablingAction:M,tournamentParticipants:u,positionAssignments:C,activeDrawPositions:h,returnParticipants:r,appliedPolicies:I,drawDefinition:o,drawPosition:s,validActions:A,structureId:l,structure:p,drawId:N,event:c});t&&A.push(t)}if(Vy({policyActions:R,action:bI})&&!b&&!q&&C){const{validLuckyLosersAction:t}=function({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:n,isWinRatioFedStructure:r,activeDrawPositions:i,positionAssignments:a,drawDefinition:o,drawPosition:s,structureId:c,structure:u,drawId:d,event:p}){if(i.includes(s)||r&&!e)return{};const{sourceStructureIds:l,targetStructureIds:m}=o.links?.reduce(((t,e)=>{const n=e.source?.structureId,r=e.target?.structureId;return t.sourceStructureIds.includes(n)||t.sourceStructureIds.push(n),t.targetStructureIds.includes(r)||t.targetStructureIds.push(r),t}),{sourceStructureIds:[],targetStructureIds:[]})||{},f=[],h=o.links?.filter((t=>t.target?.structureId===u.structureId))??[];for(const t of h){const e=t?.source?.structureId,{structure:n}=ad({structureId:e,drawDefinition:o}),r={};if(n?.finishingPosition===ds&&(1!==l?.length||1!==m?.length)){const{matchUps:t}=Jm({drawDefinition:o,structure:u,event:p}),{initialRoundNumber:e}=bf({drawPosition:s,matchUps:t}),n=o.links?.find((t=>t.target?.structureId===u?.structureId&&t.target.roundNumber===e)),i=n?.source?.roundNumber;r.roundNumbers=[i]}const{completedMatchUps:i}=Xm({structureId:e,inContext:!0,matchUpFilters:r,drawDefinition:o}),c=a.map((t=>t.participantId)).filter(Boolean),d=i?.filter((({matchUpType:t,winningSide:e})=>e&&(p?.eventType!==po||t===po))).map((({winningSide:t,sides:e})=>t&&e?.[1-(t-1)])).map(Mu).filter((t=>t&&!c.includes(t)));d?.forEach((t=>{f.includes(t)||f.push(t)}))}const g=t?.filter((t=>f?.includes(t.participantId)));if(g?.forEach((t=>{const e=(o.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),f?.length)return{validLuckyLosersAction:{type:bI,method:"luckyLoserDrawPositionAssignment",availableLuckyLosers:g,availableLuckyLoserParticipantIds:f,willDisableLinks:n,payload:{drawId:d,structureId:c,drawPosition:s}}};return{}}({sourceStructuresComplete:D,possiblyDisablingAction:M,isWinRatioFedStructure:T,tournamentParticipants:u,activeDrawPositions:h,positionAssignments:C,drawDefinition:o,drawPosition:s,structureId:l,structure:p,drawId:N});t&&A.push(t)}if(W?.participantType===sp&&Vy({policyActions:R,action:SI})){const{validModifyAssignedPairAction:t}=function({tournamentParticipants:t,returnParticipants:e,drawPosition:n,participant:r,drawId:i,event:a}){const o=a?.entries?.filter((({entryStatus:t})=>[Zp,Xp].includes(t))).map((({participantId:t})=>t))||[];if(o.length){const a=r.individualParticipantIds,s=e?t.filter((({participantId:t})=>o.includes(t))):void 0,c=e?t.filter((({participantId:t})=>a.includes(t))):void 0;return{validModifyAssignedPairAction:Xr({payload:{participantId:r.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:n,drawId:i},method:"modifyPairAssignment",availableIndividualParticipantIds:o,availableIndividualParticipants:s,existingIndividualParticipantIds:a,existingIndividualParticipants:c,type:SI},!1,!1,!0)}}return{}}({tournamentParticipants:u,returnParticipants:r,drawPosition:s,participant:W,drawId:N,event:c});t&&A.push(t)}return{isActiveDrawPosition:q,isDrawPosition:!0,hasPositionAssigned:F,isByePosition:G,validActions:A,...z}}function dS({policyDefinitions:t,appliedPolicies:e,drawType:n}){const r=t?.[Cc]?.drawTypeCoercion,i=e?.[Cc]?.drawTypeCoercion;return("boolean"==typeof r?r:void 0)??(n&&r?.[n])??("boolean"==typeof i?i:void 0)??(n&&i?.[n])??!0}const pS=({drawDefinition:t})=>{const e=cc({drawDefinition:t},[{[Is]:!0}]);if(e.error)return e;const n=t.structures?.find((t=>t.stage===fo&&1===t.stageSequence));if(!n)return ti({result:{error:jt}});const{qualifierPositions:r}=ud({structure:n});return E(0,r.length).sort((()=>Math.random()-.5))};function lS({structureId:t,drawDefinition:e}){if(!e)return{error:ot};if(!j(t))return{error:Jn};const n=ef({drawDefinition:e,structureId:t});if(n.error)return n;const r=n.links.target.flatMap((t=>t.target.feedProfile)).filter(Boolean),i=!O([Co,Eo,Ao,bo],r).length;return{...z,valid:i}}function mS({tournamentRecord:t,drawDefinition:e,stage:n=fo,structureId:r,structure:i}){if(!t)return{error:nt};if(!i&&!e)return{error:ot};if(i||r||1!==e?.structures?.filter((t=>t.stage===n)).length||(i=e.structures.find((t=>t.stage===n))),!i&&!r)return{error:_t};const{error:a,positionAssignments:o}=cd({drawDefinition:e,structureId:r,structure:i});return{positionAssignments:o??[],structureId:i?.structureId,error:a}}function fS({participantsCount:t,participantCount:e}){if(!(t=t??e))return{error:Jn};const n=I(t);return n?{drawSize:n}:ti({result:{error:Jn},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function hS(t){let{drawSizeProgression:e=!1,policyDefinitions:n,drawSize:r}=t||{};const{requireParticipantCount:i=!0,tournamentRecord:a,drawDefinition:o,event:s}=t||{},c="getSeedsCount",u=t?.participantsCount??t?.participantCount;if(!n){const t=Ap({tournamentRecord:a,drawDefinition:o,event:s});if(t.error)return ti({result:t,stack:c});n=t.policyDefinitions}const d=y(u);if(u&&!d)return ti({result:{error:Jn},context:{participantsCount:u},stack:c});if(i&&!d)return ti({result:{error:on},stack:c});if(isNaN(r)){if(!u)return ti({result:{error:Dt},stack:c});({drawSize:r}=fS({participantsCount:u}))}const p=i&&u||r;if(p&&p>r)return{error:pn};const l=n?.[Ac];if(!l)return{error:Se};const m=l.seedsCountThresholds;if(!m)return{error:Nt};void 0!==l.drawSizeProgression&&(e=l.drawSizeProgression);return{seedsCount:m.filter((t=>e?t.drawSize<=r:r===t.drawSize)).reduce(((t,e)=>u&&u>=e.minimumParticipantCount?e.seedsCount:t),0)}}function gS({consideredEntries:t,policyDefinitions:e,tournamentRecord:n,appliedPolicies:r,participantMap:i,enforceGender:a,participants:o,event:s}){if(o&&i||!n||({participants:o,participantMap:i}=ih({tournamentRecord:n})),!o)return{error:Ze};if(!Array.isArray(o))return{error:Jn};if(!s)return{error:$t};const c=e?.[wc]??r?.[wc]??fh[wc],u=!1!==(a??c?.participants?.enforceGender),{eventType:d,gender:p}=s,l=d===uo,m=d===lo&&cp||l&&sp||ap,f=Object.assign({},...(t??s.entries??[]).map((t=>({[t.participantId]:t.entryStatus})))),h=Object.keys(f),g=o.filter((t=>h.includes(t.participantId))).filter((t=>{const e=function({participant:t,participantType:e,eventType:n,entryStatusMap:r}){const i=r[t.participantId],a=n&&[uo,lo].includes(n)&&t.participantType===ap&&(Gf(i)||i===el);return t.participantType!==e&&!a}({participant:t,participantType:m,eventType:d,entryStatusMap:f}),n=function(t){const{participant:e,participantMap:n,eventGender:r,mismatch:i,isDoubles:a,genderEnforced:o}=t,s=!i&&a&&w(e?.individualParticipantIds?.map((t=>n?.[t]?.participant?.person?.sex)).filter(Boolean)??[])||[],c=!r||!s?.length||ei===r||[ni,ai].includes(r)&&s[0]===r||ri===r&&(1===s.length&&1===e.individualParticipantIds?.length||2===s.length),u=e?.person?.sex,d=!e?.person||!r||[ei,ri].includes(r)||[ni,ai].includes(r)&&u===r;return!o||c&&d}({genderEnforced:u,participantMap:i,eventGender:p,participant:t,isDoubles:l,mismatch:e});return e||!n}));if(g.length){const t=g.map((t=>t.participantId));return{error:Yt,invalidParticipantIds:t}}return{...z,valid:!0}}var IS={__proto__:null,addGoesTo:yf,allPlayoffPositionsFilled:bg,checkValidEntries:gS,findDrawDefinition:Cy,getAssignedParticipantIds:Vf,getAvailableMatchUpsCount:My,getAvailablePlayoffProfiles:eU,getDrawDefinitionTimeItem:Up,getDrawParticipantRepresentativeIds:Ny,getDrawStructures:od,getDrawTypeCoercion:dS,getEligibleVoluntaryConsolationParticipants:Ry,getMatchUpsMap:hl,getParticipantIdFinishingPositions:Ay,getPositionAssignments:mS,getPositionsPlayedOff:XI,getRandomQualifierList:pS,getSeedingThresholds:Hh,getSeedsCount:hS,getStructureSeedAssignments:pl,getTeamLineUp:Hm,getValidGroupSizes:qh,isAdHoc:Dl,isCompletedStructure:Tg,isValidForQualifying:lS,positionActions:uS};function US({hasExistingDrawDefinition:t,qualifyingProfiles:e,appliedPolicies:n,qualifyingOnly:r,tieFormat:i,idPrefix:a,isMock:o,uuids:s}){const c=[],u=[],d=[],p=(t,e)=>t.stageSequence-e.stageSequence,l=(t,e)=>t.roundTarget-e.roundTarget;let f,h=0,g=0,I=1;for(const U of e.sort(l)){const l=U.structureProfiles||[];I=U.roundTarget||I;let S,v,w,P=1,D=0;for(const c of(l||[]).sort(p)){let p=m(c.drawSize||c.participantsCount);const{qualifyingRoundNumber:g,structureOptions:U,matchUpFormat:T,structureName:b,structureId:R,drawType:M}=c,N=c.matchUpType,A=c.qualifyingPositions||yS({drawSize:p,qualifyingRoundNumber:g});let E,C,O;if(!y(p))return ti({result:{error:Dt},stack:"generateQualifyingSTructures"});const F=e.length>1?`${I}-`:"",k=l.length>1||F?P:"",x=b||(F||k?`${xh(ho)} ${F}${k}`:xh(ho));if(M===rs){const{structures:e,groupCount:u,maxRoundNumber:d}=Gh({structureName:c.structureName||x,structureId:R||s?.pop(),hasExistingDrawDefinition:t,stage:ho,structureOptions:U,appliedPolicies:n,qualifyingOnly:r,stageSequence:P,matchUpType:N,roundTarget:I,tieFormat:i,drawSize:p,idPrefix:a,isMock:o,uuids:s});D=u,E=d,C=e[0],f=[1]}else({drawSize:p,matchUps:O,roundLimit:E}=GI({qualifyingRoundNumber:g,qualifyingPositions:A,matchUpType:N,drawSize:p,idPrefix:a,isMock:o,uuids:s})),C=Fh({structureName:c.structureName||x,structureId:R||s?.pop(),qualifyingRoundNumber:E,hasExistingDrawDefinition:t,stage:ho,qualifyingOnly:r,matchUpFormat:T,stageSequence:P,matchUpType:N,roundLimit:E,tieFormat:i,matchUps:O}),I&&_c({extension:{name:pu,value:I},element:C}),D=O?.filter((t=>t.roundNumber===E))?.length||0;if(P>1){const{link:t}=_I({sourceStructureId:v,sourceRoundNumber:S,targetStructureId:C.structureId,finishingPositions:w===Oo?[1]:void 0,linkType:w});d.push(t),h+=(p||0)-D}else h+=p||0;w=M===rs?Oo:Fo,v=C.structureId,S=E,i&&(O=Jm({structure:C})?.matchUps||[],O?.forEach((t=>{const{tieMatchUps:e}=LI({tieFormat:i,matchUp:t,isMock:o});Object.assign(t,{tieMatchUps:e,matchUpType:N})}))),u.push(C),P+=1}g+=D,c.push({qualifiersCount:D,finalQualifyingRoundNumber:S,finalQualifyingStructureId:v,finishingPositions:f,roundTarget:I,linkType:w}),I+=1}return{qualifiersCount:g,qualifyingDrawPositionsCount:h,qualifyingDetails:c,structures:u,...z,links:d}}function yS({drawSize:t,qualifyingRoundNumber:e}){let n=t,r=0;for(;r<e;)n=Math.floor(n/2),r+=1;return n}function SS(t){const{drawTypeCoercion:e,enforceMinimumDrawSize:n}=t,r=d(t.drawSize);let i=e&&t.drawType!==_o&&("boolean"==typeof e||e<=2)&&2===r&&jo||t.drawType||jo;const a=ps.includes(i);if(r&&a)if(e&&("boolean"==typeof e&&r<4||r<=e))i=jo;else if(r<4&&n)return{...ti({context:{enforceMinimumDrawSize:n,drawSize:r,drawType:i},result:{error:wt},stack:"getCoercedDrawType"}),drawType:i};return{drawType:i}}function vS({structureName:t,matchUpType:e,idPrefix:n,drawSize:r,isMock:i,uuids:a}){const o=[],{matchUps:s}=zI({linkFedFinishingRoundNumbers:[1],drawSize:r+1,matchUpType:e,idPrefix:n,isMock:i}),c=Fh({structureName:t||xh(fo),structureId:a?.pop(),stageSequence:1,stage:fo,matchUpType:e,matchUps:s});o.push(c);const u=r/2,{matchUps:d}=zI({finishingPositionOffset:u,idPrefix:n&&`${n}-c`,drawSize:r-1,isConsolation:!0,matchUpType:e,isMock:i,uuids:a}),p=Fh({structureName:xh(os),matchUps:d,structureId:a?.pop(),stage:go,stageSequence:2,matchUpType:e});o.push(p);const{matchUps:l}=GI({idPrefix:n&&`${n}-p1t2`,drawSize:2,matchUpType:e,isMock:i}),m=Fh({structureName:xh(as),matchUps:l,structureId:a?.pop(),stageSequence:3,stage:Uo,matchUpType:e});o.push(m);const f=function({mainStructure:t,consolationStructure:e,deciderStructure:n}){const r=e.matchUps.reduce(((t,e)=>(e.drawPositions||[]).filter(Boolean).length&&!t.includes(e.roundNumber)?t.concat(e.roundNumber):t),[]),i=t.matchUps.reduce(((t,e)=>!t||e.roundNumber>t?e.roundNumber:t),void 0),a=e.matchUps.reduce(((t,e)=>!t||e.roundNumber>t?e.roundNumber:t),void 0);return[...r.map(((n,i)=>{const a=r.indexOf(n)%2?Eo:Co;return{linkType:ko,source:{roundNumber:1+i,structureId:t.structureId},target:{feedProfile:a,roundNumber:n,structureId:e.structureId}}})),{linkType:Fo,source:{roundNumber:a,structureId:e.structureId},target:{feedProfile:Eo,roundNumber:i,structureId:t.structureId}},{linkType:Fo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Eo,roundNumber:1,structureId:n.structureId}},{linkType:ko,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Eo,roundNumber:1,structureId:n.structureId}}]}({mainStructure:c,consolationStructure:p,deciderStructure:m});return{structures:o,links:f,...z}}function wS(t){const{qualifyingRoundNumber:e,finishingPositionOffset:n,qualifyingPositions:r,matchUpType:i,idPrefix:a,drawSize:o,isMock:s,uuids:c}=t;if(!y(o)||o<2)return{matchUps:[],roundsCount:0};if(p(o))return GI(t);const u=function(t){const e=d(t);let n=e%2?e+1:e;const r=!!(Math.ceil(n/2)%2),i=[{participantsCount:n,preFeedRound:r}];for(;n>2;){const t=Math.ceil(n/2),e=1===t,r=!(e||!(t%2));n=!e&&r?t+1:t;const a=!!(2!==n&&Math.ceil(n/2)%2);i.push({participantsCount:n,preFeedRound:a,feedRound:r})}return i}(o),l=u.shift(),m=E(1,(l?.participantsCount||0)+1).map((t=>({drawPosition:t})));let f=[],h=1;({matchUps:f}=jI({roundNumber:h,matchUpType:i,idPrefix:a,matchUps:f,isMock:s,nodes:m,uuids:c})),h++;let g=t.roundLimit||e;for(const t of u){const e=t.participantsCount/2,n=E(1,e+1);r&&e===r&&(g=h-1);const i=n.map((t=>{const e=VI({roundPosition:t,roundNumber:h,idPrefix:a,uuids:c});return{roundPosition:t,roundNumber:h,matchUpId:e}}));f.push(...i),h++}const I=h-1;return f=Uf({finishingPositionOffset:n,lucky:!0,roundsCount:I,roundLimit:g,matchUps:f}),g&&(f=f.filter((t=>t.roundNumber<=g))),{matchUps:f,roundsCount:I,roundLimit:g}}function PS(t){const{playoffAttributes:e,stageSequence:n=1,stage:r=fo,tieFormat:i,matchUpType:a,drawSize:o,uuids:s}=t,c=t.structureId||(()=>{if(!t.isMock&&!t.idPrefix)return;return`${t.drawDefinition.drawId}-s-0`})()||s?.pop(),u=t.appliedPolicies??Np(t),d=t.policyDefinitions?.[Ec]||u?.[Ec];t.skipRounds=t.skipRounds||o<=4&&(d?.feedFromMainFinal?0:1)||0;const p=t.structureName??e?.[0]?.name??xh(fo),l={[_o]:()=>({structures:[Fh({finishingPosition:us,stageSequence:n,structureName:p,matchUps:[],matchUpType:a,structureId:c,stage:r})],links:[],...z}),[Wo]:()=>{const{matchUps:e}=wS(t);return{structures:[Fh({stageSequence:n,structureName:p,matchUpType:a,structureId:c,matchUps:e,stage:r})],links:[],...z}},[jo]:()=>(()=>{const{matchUps:e}=GI(t);return{structures:[Fh({stageSequence:n,structureName:p,matchUpType:a,structureId:c,tieFormat:i,matchUps:e,stage:r})],links:[],...z}})(),[Go]:()=>vS(t),[Bo]:()=>YI({...t,roundOffsetLimit:3,playoffAttributes:e??ss}),[Vo]:()=>YI({...t,roundOffsetLimit:2,playoffAttributes:e??cs}),[Uo]:()=>YI(t),[Lo]:()=>{const{matchUps:t}=zI({drawSize:o,uuids:s,matchUpType:a});return{structures:[Fh({stageSequence:n,structureName:p,matchUpType:a,structureId:c,stage:fo,tieFormat:i,matchUps:t})],links:[],...z}},[$o]:()=>rU(t),[qo]:()=>oU({...t,feedRounds:1,fmlc:!0}),[ts]:()=>oU({...t,feedRounds:1}),[Yo]:()=>oU({...t,feedsFromFinal:1}),[Qo]:()=>oU({...t,feedsFromFinal:2}),[Zo]:()=>oU({...t,feedsFromFinal:3}),[ns]:()=>oU(t),[Ho]:()=>aU(t),[rs]:()=>Gh(t),[is]:()=>function(t){const{drawDefinition:e,structureOptions:n,requireSequential:r}=t,i={structureName:xh(fo),...t,stage:fo},{structures:a,groupCount:o,groupSize:s}=Gh(i);if(o<1)return{error:Hn};const c=n?.playoffGroups||[{finishingPositions:[1],structureName:xh(Uo)}],[u]=a,{structures:d,links:p}=sU({sourceStructureId:u.structureId,requireSequential:r,drawDefinition:e,playoffGroups:c,groupCount:o,...t});return d&&a.push(...d),{...z,structures:a,links:p}}(t)};return{generators:l}}function DS(t){const{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:i,qualifyingOnly:a,staggeredEntry:o,drawDefinition:s,tieFormat:c,isMock:u,uuids:l}=t||{},m=d(t.drawSize),f=t.drawTypeCoercion??dS({appliedPolicies:i,drawType:t.drawType}),h=SS({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:f,drawSize:m});if(h.error)return h;const g=h.drawType,I=[],U=[],y=t?.matchUpType??n,S=s?.structures?.filter((({stage:t})=>t===ho));S&&I.push(...S);const v=S?.map((({structureId:t})=>t)),w=s?.structures?.find((({stage:t,stageSequence:e})=>t===fo&&1===e)),P=s?.links?.filter((t=>t.target.structureId===w?.structureId&&v?.includes(t.source.structureId))),D=(t,e)=>{if(t.linkType===Oo&&e?.structures){const n=t.source.finishingPositions||[];return e.structures.length*n.length}if(t.linkType===Fo&&e?.matchUps?.length){const n=t.source.roundNumber;return e.matchUps.filter((({roundNumber:t})=>t===n)).length}},T=S?.map((t=>{const e=P?.find((e=>e.target.structureId===t.structureId)),n=cd({structure:t})?.positionAssignments?.length??0;if(!e)return n;const r=e?.source.structureId,i=s.structures?.find((t=>t.structureId===r));return n-(D(e,i)||0)})).filter(Boolean).reduce(((t,e)=>t+e),0),b=P?.map((t=>{const e=t.source.structureId,n=S?.find((t=>t.structureId===e));return D(t,n)})).filter(Boolean).reduce(((t,e)=>t+e),0),R=!(!w||w?.matchUps?.length);if(S?.length&&!R)return{error:ur};const M=!S?.length&&t.qualifyingProfiles,N=M?.length&&US({idPrefix:t.idPrefix,qualifyingProfiles:M,appliedPolicies:i,qualifyingOnly:a,tieFormat:c,isMock:u,uuids:l});if(N?.error)return N;const{qualifyingDrawPositionsCount:A,qualifyingDetails:E,qualifiersCount:C}=N||{qualifyingDrawPositionsCount:T,qualifiersCount:b};A&&(N?.structures&&I.push(...N.structures),N?.links&&U.push(...N.links)),Object.assign(t,Xr({drawSize:m,matchUpType:y,tieFormat:c}));const O=g!==_o&&(!m||m<2||!o&&![Lo,Wo].includes(g)&&([is,rs].includes(g)&&m<3||![rs,is].includes(g)&&!p(m)));if(O&&!A)return ti({context:{drawSize:m,invalidDrawSize:O},result:{error:wt},stack:"generateDrawStructuresAndLinks"});const{generators:F,error:k}=PS(t);if(k)return{error:k};const x=F[g];if(!x)return{error:ht};const _=x?.();if(_.error)return _;const{structures:L,links:B}=_;if(L?.length){const t=L.find((({stage:t,stageSequence:e})=>t===fo&&1===e));if(w&&t)if(R){const e=t.structureId;if(t.structureId=w.structureId,B?.length)for(const t of B)t.source.structureId===e&&(t.source.structureId=w.structureId),t.target.structureId===e&&(t.target.structureId=w.structureId)}else if(!r)return{error:ur};I.push(...L)}I.sort(rd),B?.length&&U.push(...B);const V=_.structures.find((({stage:t,stageSequence:e})=>t===fo&&1===e));for(const t of E||[]){const{finalQualifyingRoundNumber:e,finalQualifyingStructureId:n,roundTarget:r,finishingPositions:i,linkType:a}=t,o=V&&_I({targetStructureId:V.structureId,sourceStructureId:n,sourceRoundNumber:e,finishingPositions:i,targetEntryRound:r,linkType:a})?.link;if(o?.error)return o;o&&U.push(o)}return P&&U.push(...P),{...z,qualifyingResult:{qualifyingDrawPositionsCount:A,qualifiersCount:C},structures:I,links:U}}function TS(t){const{modifyOriginal:e=!0,stageSequence:r=1,isMock:i}=t||{},a="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return ti({result:{error:ot},stack:a});const o=e?t.drawDefinition:la(t.drawDefinition,!1,!0);let{tieFormat:s,matchUpType:c}=t;if(s){const t=sa({tieFormat:s});if(t.error)return t}s=ZU(s??fl({drawDefinition:o})?.tieFormat),c=c??(o.matchUpType||n),t.tieFormat=s,t.matchUpType=c;const u=sh({drawDefinition:o,stage:fo});t.drawSize=t.drawSize??u,!u&&t.drawSize&&lI({drawSize:t.drawSize,drawDefinition:o,stageSequence:r,stage:fo});const d=hl({drawDefinition:o}).drawMatchUps.map(Nu),p=DS(t);if(p.error)return ti({result:p,stack:a});const{structures:l,links:m,qualifyingResult:f}=p;o.structures=l,o.links=m;const h=Math.max(t.qualifiersCount??0,f?.qualifiersCount||0);if(f?.qualifyingDrawPositionsCount){if(!sh({stage:ho,drawDefinition:o})){const t=lI({drawSize:f.qualifyingDrawPositionsCount,stage:ho,drawDefinition:o});if(t.error)return t}}if(h){const t=mI({qualifiersCount:h,drawDefinition:o,stage:fo});if(t.error)return t}const g=t.drawSize??u;Object.assign(t,Xr({drawSize:g,matchUpType:c,tieFormat:s}));const{matchUps:I,matchUpsMap:U}=cf({drawDefinition:o});s&&I?.forEach((t=>{if(!d.includes(t.matchUpId)){const{tieMatchUps:e}=LI({tieFormat:s,matchUp:t,isMock:i});Object.assign(t,{tieMatchUps:e,matchUpType:c})}}));const{inContextDrawMatchUps:y}=yf({drawDefinition:o,matchUpsMap:U});return Hd({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:o}),{inContextDrawMatchUps:y,drawDefinition:o,matchUpsMap:U,...z,structures:l,matchUps:I,links:m}}function bS(t){const{removePriorValues:e,tournamentRecord:n,participantId:r,scaleItem:i}=t;let a,o;if(!MS({scaleItem:i}))return{error:jn};if(r&&Array.isArray(n.participants)&&(o=n.participants.find((t=>t.participantId===r)),o)){if(o.participantType===ip&&i?.eventType!==lo)return{error:jn};const t=NS({removePriorValues:e,participant:o,scaleItem:i});if(t.error)return t;a=!t.valueChanged;const{topics:r}=Lr();r.includes(bd)&&Or({topic:bd,payload:{tournamentId:n.tournamentId,participants:[o]}})}return a&&{...z,info:nr,existingValue:i?.scaleValue}||o&&{...z,newValue:i?.scaleValue}||{error:en}}function RS(t){const{scaleItemsWithParticipantIds:e=[],removePriorValues:n,tournamentRecord:r,auditData:i,context:a}=t;if(!r)return{error:nt};if(!r.participants)return{error:Ze};let o=0;const s={},c=[];for(const t of e){const e=t?.participantId;if(Array.isArray(t?.scaleItems))for(const n of t.scaleItems){if(!MS({scaleItem:n}))return{error:jn};Array.isArray(s[e])||(s[e]=[]),s[e].push(n)}}for(const t of r.participants){const{participantId:e}=t||{};if(Array.isArray(s[e]))for(const r of s[e]){if(t.participantType===ip&&r?.eventType!==lo)return ti({context:{participantId:e,scaleItem:r,participantType:t.participantType},info:"Invalid participantType for eventType",result:{error:jn}});NS({participant:t,scaleItem:r,removePriorValues:n}),c.push(t),o++}}const u=o?void 0:qn,{topics:d}=Lr();if(d.includes(bd)&&o&&Or({topic:bd,payload:{tournamentId:r.tournamentId,participants:c}}),a){const{eventId:t,drawId:e,...n}=a,i=n.scaleAttributes?.scaleType&&[n.scaleAttributes.scaleType];if(Object.keys(n).length){const a={itemType:md,itemValue:n};if(i&&(a.itemSubTypes=i),e||t){const{drawDefinition:n,event:i}=Gm({tournamentRecord:r,eventId:t,drawId:e});e&&sI({drawDefinition:n,timeItem:a}),t&&cy({event:i,timeItem:a})}else sy({tournamentRecord:r,timeItem:a})}}return i&&d.includes(gd)&&Or({topic:gd,payload:i}),Xr({...z,modificationsApplied:o,info:u})}function MS({scaleItem:t}){const e=t&&Object.keys(t),n=["scaleType","eventType","scaleName"];return!!(n.filter((t=>e?.includes(t))).length===n.length)}function NS({removePriorValues:t,participant:e,scaleItem:n}){if(!e)return{error:Je};const r=n&&Object.keys(n),i=["scaleType","eventType","scaleName"];if(!(i.filter((t=>r.includes(t)&&n[t])).length===i.length))return{error:jn};const a=(new Date).toISOString();e.timeItems||(e.timeItems=[]);const{scaleItem:o}=$f({scaleAttributes:n,participant:e}),s=t=>[void 0,null,""].includes(t),c=!(s(o?.scaleValue)&&s(n.scaleValue))&&JSON.stringify(o?.scaleValue)!==JSON.stringify(n.scaleValue);if(c){const{scaleType:r,eventType:i,scaleName:o}=n,s=[mc,r,i,o].join("."),c=Xr({itemValue:n.scaleValue,itemDate:n.scaleDate,createdAt:a,itemType:s});n.scaleId&&(c.itemSubTypes=[n.scaleId]),t&&(e.timeItems=e.timeItems.filter((t=>t.itemType!==s))),e.timeItems.push(c)}return{...z,valueChanged:c,newValue:n.scaleValue}}function AS(t){const{tournamentRecord:e,modifiedScaleValues:n,removePriorValues:r}=t,i=cc(t,[{[hs]:!0},{modifiedScaleValues:!0,[nc]:Js}]);if(i.error)return i;for(const t in n){const i=bS({scaleItem:n[t],removePriorValues:r,tournamentRecord:e,participantId:t});if(i.error)return i}return{...z}}function ES(t){const{tournamentRecord:e,scaleAttributes:n,participantId:r}=t,i=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!r)return{error:Xe};const{participant:a,tournamentId:o}=hp({tournamentRecords:i,tournamentRecord:e,participantId:r});return a?{...$f({participant:a,scaleAttributes:n}),tournamentId:o}:{error:en}}const CS={nSpread:400,diffThreshold:.125,kCalc:(t=0)=>250/Math.pow(t+5,.4),kMultiplier:function(t=3,e=2){const n=t/e;return isNaN(n)?CS.kDefault():n},kDefault:()=>1};function OS(t){let{winnerRating:e,loserRating:n}=t;const{ratings:r=hU,winnerCountables:i=1,loserCountables:a=0,ratingType:o=dU,maxCountables:s,countables:c}=t||{},u=r?.[o];if(!u)return{error:be};const d=u.range||t.ratingRange;e=e||u.defaultInitialization,n=n||u.defaultInitialization;const p=d[0]>d[1],l=u.decimalsCount||0,m=p?d.slice().reverse():d,f=(t,e)=>parseFloat(e)>=Math.min(...t)&&parseFloat(e)<=Math.max(...t);f(d,e)&&f(d,n)||(f(d,e)||(e=u.defaultInitialization),f(d,n)||(n=u.defaultInitialization));const h=uU({targetRange:hU[dU].range,sourceRange:m,value:p?d[0]-e:e}),g=uU({targetRange:hU[dU].range,sourceRange:m,value:p?d[0]-n:n}),I=(t,e)=>1/(1+Math.pow(10,(e-t)/CS.nSpread)),U=I(h,g),y=I(g,h),S=CS.kCalc(i),v=CS.kCalc(a),w=CS.kMultiplier(s,c),P=h+w*S*(1-U),D=g+w*v*(0-y),T=uU({sourceRange:hU[dU].range,value:P,targetRange:m}),b=uU({sourceRange:hU[dU].range,value:D,targetRange:m}),R=p?d[0]-T:T;let M=parseFloat(R.toFixed(l));const N=p?d[0]-b:b;let A=parseFloat(N.toFixed(l));const E=Math.max(...d)?Math.abs(e-n)/Math.max(...d):0;return(T>b&&E>CS.diffThreshold||M<0||A<0)&&(M=e,A=n),{newWinnerRating:M,newLoserRating:A}}function FS(t){const e=cc(t,[{[hs]:!0},{matchUpIds:!0,[nc]:Zs,[$s]:pe},{ratingType:!1,[Xs]:t=>hU[t]}]);if(e.error)return e;const{updateParticipantRatings:n,removePriorValues:r=!0,tournamentRecord:i,ratingType:a=dU,refreshDynamic:o,considerGames:s,drawDefinition:c,matchUpIds:u,asDynamic:d}=t,p=hU[a],{accessor:l}=p,m={},f=(t.matchUps||o&&ff({drawDefinition:c,tournamentRecord:i,inContext:!0,matchUpFilters:{matchUpStatuses:Xu}}).matchUps||pf({matchUpFilters:{matchUpIds:u,matchUpStatuses:Xu},tournamentRecord:i,inContext:!0}).matchUps)??[],h=`${a}.${dc}`,g=d?h:a;f.sort(mf);for(const t of f){const{endDate:e,matchUpFormat:c,score:u,sides:d,winningSide:p}=t,f=t.matchUpType,U={eventType:f,scaleName:a,scaleType:lc},y={scaleName:h,eventType:f,scaleType:lc},S=Object.assign({},...(d??[]).map((t=>{const{sideNumber:e,participant:n}=t;return e&&{[e]:[n?.participantId,...n?.individualParticipantIds??[]].filter(Boolean).flat()}}))),v=Object.assign({},...Object.values(S).flat().map((t=>{const n=!o||m[t]?ES({scaleAttributes:y,tournamentRecord:i,participantId:t}).scaleItem:void 0,r=ES({tournamentRecord:i,scaleAttributes:U,participantId:t}).scaleItem,a=l?{[l]:void 0}:void 0;return t&&{[t]:n??r??{scaleName:g,eventType:f,scaleDate:e,scaleType:lc,scaleValue:a}}}))),w=c?Ii(c):{},P=w?.bestOf||1,D=s?P&(w?.setsTo||1):P,T=u?.sets&&(I=u.sets,I?.reduce(((t,e)=>(e.winningSide&&(t[e.winningSide-1]+=1),t)),[0,0])||[0,0])||1===p&&[1,0]||[0,1],b=p?S[p]:[],R=p?S[3-p]:[];for(const t of b){const e=v[t]?.scaleValue,n="object"==typeof e?e[l]:e;for(const r of R){const i=v[r]?.scaleValue,o="object"==typeof i?i[l]:i,s=p?T[p]:[0,0],c=p?T[3-p]:[0,0],{newWinnerRating:u,newLoserRating:d}=OS({winnerCountables:s,loserCountables:c,maxCountables:D,winnerRating:n,loserRating:o,ratingType:a}),m=l?{...e,[l]:u}:u,f=l?{...i,[l]:d}:d;v[t].scaleValue=m,v[r].scaleValue=f,v[t].scaleName=g,v[r].scaleName=g}}Object.assign(m,v),n&&AS({tournamentRecord:i,modifiedScaleValues:m,removePriorValues:r})}var I;const U=f.map((({matchUpId:t})=>t));return{...z,modifiedScaleValues:m,outputScaleName:g,processedMatchUpIds:U}}function kS(t){const{matchUpIds:e=[],drawDefinition:n,roundNumber:r,newRound:i,isMock:a,event:s}=t;if("object"!=typeof n)return{error:ot};let{participantIdPairings:c,matchUpsCount:u}=t;const d=My(t);if(d.error)return ti({result:d});const{lastRoundNumber:p,availableMatchUpsCount:l=0,roundMatchUpsCount:m=0}=d;if(u){if(u>m&&!1!==t.restrictMatchUpsCount)return ti({result:{error:Jn,info:"matchUpsCount error",context:{roundMatchUpsCount:m}}})}else i?u=m:l>0&&(u=l);if(c&&!Array.isArray(c)||u&&!y(u)||e&&!Array.isArray(e)||!c&&!u)return{error:Jn,info:"matchUpsCount or pairings error"};if(u&&!1!==t.restrictMatchUpsCount&&u>32)return{error:Jn,info:"matchUpsCount must be less than 33"};if(r&&!t.ignoreLastRoundNumber&&r-1>(p||0))return{error:Jn,info:"roundNumber error"};const f=r??(i&&(p??0)+1||p||1);c=c??E(0,u).map((()=>({participantIds:[void 0,void 0]})));const h=c?.map(((r,i)=>{const a=r?.participantIds??[void 0,void 0];a.push(void 0,void 0);const o=a.slice(0,2).map(((t,e)=>Xr({sideNumber:e+1,participantId:t}))),s=e[i]??(e=>{if(!t.idPrefix)return;return`${n.drawId}-${t.idPrefix??"ah"}-${f}-${e}`})(i)??ha();return{roundNumber:f,matchUpStatus:Hu,matchUpId:s,sides:o}}));if(h?.length){const t=fl({drawDefinition:n,event:s})?.tieFormat;t&&h.forEach((e=>{const{tieMatchUps:n}=LI({tieFormat:t,matchUp:e,isMock:a});Object.assign(e,{tieMatchUps:n,matchUpType:o})}))}return{roundNumber:f,matchUpsCount:h?.length??0,matchUps:h,...z}}function xS(t){return t.participantIdPairings.map((({participantIds:t})=>t.sort().join("|"))).sort().join("/")}function _S({valueSortedPairings:t,stipulated:e=[],pairingValueMap:n,deltaObjects:r,valueObjects:i,actorsCount:a}){const o=[].concat(...e),s=[];let c=0;e.filter(Boolean).forEach((t=>{const[e,r]=t,i=LS(e,r),a=n[i];s.push({participantIds:t,value:a}),c+=n[i]}));x(t,a).map((t=>P(t).map((t=>({...t,value:t.value+Math.random()*Math.round(Math.random())}))))).flat().forEach((t=>{const e=t.pairing.split("|");if(!e.reduce(((t,e)=>o.includes(e)||t),!1)){o.push(...e);const n=t.value;c+=n,s.push({participantIds:e,value:n})}})),s.sort(((t,e)=>t.value-e.value));const u=s.reduce(((t,e)=>{const[n,i]=e.participantIds,a=LS(n,i),o=r[a];return o>t?o:t}),0),d=s.reduce(((t,e)=>{const[n,r]=e.participantIds,a=LS(n,r),o=i[a];return o>t?o:t}),0);return{value:c,participantIdPairings:s,maxDelta:u,maxDiff:d}}function LS(t,e){return[t,e].sort(eh).join("|")}function BS({participantIds:t}){const e={},n=[];t.forEach((r=>{e[r]=t.filter((t=>t!==r)),e[r].forEach((t=>{const e=LS(t,r);n.includes(e)||n.push(e)}))}));const r=Object.assign({},...n.map((t=>({[t]:0}))));return{uniquePairings:n,possiblePairings:e,deltaObjects:r}}function VS(t){const{tournamentParticipants:e,adHocRatings:n={},possiblePairings:r,uniquePairings:i,maxIterations:a,minimizeDelta:o,deltaObjects:s,valueObjects:c,eventType:u,scaleName:d,salted:p}=t;i.forEach((t=>{const r=function({tournamentParticipants:t,adHocRatings:e,eventType:n,scaleName:r,pairing:i}){const a=hU[r]?.defaultInitialization??0;return i.split("|").map((r=>{if(n===co){const n=t?.find((t=>t.participantId===r))?.individualParticipantIds;return n?n?.map((t=>e[t]||a)):2*a}return e[r]||a}))}({tournamentParticipants:e,adHocRatings:n,scaleName:d,eventType:u,pairing:t}),i="number"==typeof p&&p||.5,a=p&&(Math.round(Math.random())?i:-1*i)||0,o=Math.abs(r[0]-r[1])+a,l=Math.abs(r[0]-r[1]);s[t]=l,c[t]||(c[t]=0),c[t]+=o?Math.pow(o,2):0}));const l=i.map((t=>({pairing:t,value:c[t]}))).sort(((t,e)=>t.value-e.value)),{pairingValues:m}=function({possiblePairings:t,valueObjects:e}){const n={};for(const e of Object.keys(t)){const i=t[e].map((t=>r(e,t)));n[e]=i.sort(((t,e)=>t.value-e.value))}function r(t,n){const r=LS(t,n);return{opponent:n,value:e[r]}}return{pairingValues:n}}({possiblePairings:r,valueObjects:c}),{candidate:f,candidatesCount:h,deltaCandidate:g,iterations:I}=function({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:n,valueObjects:r,deltaObjects:i}){const a=Object.assign({},...e.map((t=>({[t.pairing]:t.value})))),o=Object.keys(n);let s=[];const c=_S({actorsCount:o.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:i,valueObjects:r}),u=[xS(c)];s.push(c);let d,p=c.value,l=c,m=1,f=0,h=o.length;do{h-=1,d=o.length*n[o[0]].length}while(d>t&&h>5);const g=[];o.forEach((t=>{n[t].slice(0,h).forEach((n=>{f+=1;const c=LS(t,n.opponent);if(!g.includes(c)){const d=_S({stipulated:[[t,n.opponent]],actorsCount:o.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:i,valueObjects:r});if(!u.includes(xS(d))){u.push(xS(d)),s.push(d);const{maxDelta:t,value:e}=d;t<l.maxDelta&&(l=d),(e<p||e===p&&Math.round(Math.random()))&&(p=e),g.push(c),m+=1}}})),s=s.filter((t=>Math.abs(t.value-p)<5))})),s.sort(((t,e)=>t.maxDiff-e.maxDiff));const I=N(s);return{candidatesCount:m,deltaCandidate:l,maxIterations:t,iterations:f,candidate:I}}({valueSortedPairings:l,maxIterations:a,pairingValues:m,deltaObjects:s,valueObjects:c}),{participantIdPairings:U}=o?g:f;return{participantIdPairings:U,candidatesCount:h,deltaCandidate:g,iterations:I,candidate:f}}const jS=100,GS=100,qS=4e3;function $S(t){const{encounterValue:e=jS,sameTeamValue:n=GS,maxIterations:r=qS,updateParticipantRatings:i,generateMatchUps:a=!0,ignoreLastRoundNumber:o,iterationMatchUps:s,tournamentRecord:c,dynamicRatings:u,refreshDynamic:d,participantIds:p,drawDefinition:l,roundNumber:m,structureId:f,matchUpIds:h,eventType:g,scaleName:I,idPrefix:U,isMock:y,salted:S,event:v}=t;if(!l)return{error:ot};if(!t.structure&&!f)return{error:Lt};const P=t.structure||ad({drawDefinition:l,structureId:f}).structure;if(!G(P))return{error:Vt};if(!p?.length)return{error:an};const D=[...s??[],...P?.matchUps??[]],{encounters:T}=function({matchUps:t}){const e=[];for(const n of t){const t=n.sides.map(Mu);if(2===t.length){const[n,r]=t,i=LS(n,r);e.includes(i)||e.push(i)}}return{encounters:e}}({matchUps:D}),b=c?.participants??[];let R={};if(u){const t=w(P?.matchUps?P.matchUps.map((({roundNumber:t})=>t)):[]),e=Math.max(...t,0);if(e){const t=P?.matchUps?.filter((({roundNumber:t})=>t===e)).map((({matchUpId:t})=>t)),n=FS({ratingType:I??v?.category?.ratingType,updateParticipantRatings:i,tournamentRecord:c,asDynamic:!0,refreshDynamic:d,drawDefinition:l,matchUpIds:t});if(n.error)return n;n.modifiedScaleValues&&(R=n.modifiedScaleValues)}}const{valueObjects:M}=function({encounters:t,tournamentParticipants:e,encounterValue:n,sameTeamValue:r}){const i={};for(const e of t)i[e]||(i[e]=0),i[e]+=n;const a=e?.filter((({participantType:t})=>t===cp));if(a)for(const t of a){const e=t.individualParticipantIds??[],{uniquePairings:n}=BS({participantIds:e});for(const t of n)i[t]||(i[t]=0),i[t]+=r}return{valueObjects:i}}({tournamentParticipants:b,encounterValue:e,sameTeamValue:n,encounters:T}),{uniquePairings:N,possiblePairings:A,deltaObjects:E}=BS({participantIds:p}),C={tournamentParticipants:b,possiblePairings:A,uniquePairings:N,maxIterations:r,adHocRatings:Object.values(R).length?R:t.adHocRatings,deltaObjects:E,valueObjects:M,eventType:g,scaleName:I,salted:S},{candidatesCount:O,participantIdPairings:F,deltaCandidate:k,iterations:x,candidate:_}=VS(C);if(!O)return{error:Wn};let L,B;if(a){const t=kS({structureId:P?.structureId,ignoreLastRoundNumber:o,participantIdPairings:F,newRound:!0,drawDefinition:l,roundNumber:m,matchUpIds:h,idPrefix:U,isMock:y,event:v});if(t.error)return t;L=t.roundNumber,B=t.matchUps}const{maxDelta:V,maxDiff:j}=_;return{roundNumber:L,participantIdPairings:F,modifiedScaleValues:R,candidatesCount:O,deltaCandidate:k,...z,iterations:x,matchUps:B,maxDelta:V,maxDiff:j}}function WS(t){const{drawType:e=jo,attachConsolation:n=!0,applyPositioning:r=!0,tournamentRecord:i,staggeredEntry:a,automated:o,placeByes:s,isMock:c,event:u}=t;let d=t?.drawDefinition;if(!d)return{error:ot};const p=Io,l=dl({stageSequence:1,drawDefinition:d,stage:p}),m=[rs,Go,is].includes(e)?l.length:I(l.length);if(!a&&e===Lo&&l.length<2||e===rs&&l.length<3)return{error:wt};let{tieFormat:f,matchUpType:h}=t;if(f){const t=sa({tieFormat:f});if(t.error)return t}f=ZU(f??fl({drawDefinition:d})?.tieFormat),h=h??d.matchUpType;const{structures:g}=od({stageSequence:1,drawDefinition:d,stage:p});if(g.length>1)return{error:Zt};if(g?.[0]?.matchUps?.length)return{error:dr};const U=g?.[0]?.structureId;Object.assign(t,Xr({structureName:t.structureName??xh(Io),structureId:U,matchUpType:h,tieFormat:f,drawSize:m,stage:p}));const y=PS(t);if(y.error)return y;const S=y.generators[e];if(!S)return{error:ht};const v=S?.();if(v.error)return v;const{structures:w,links:P}=v,D=w.map((t=>Jm({structure:t}).matchUps)).flat();f&&D.forEach((t=>{const{tieMatchUps:e}=LI({matchUp:t,tieFormat:f,isMock:c});Object.assign(t,{tieMatchUps:e,matchUpType:h})})),r&&n||(d=la(d,!1,!0)),d.links||(d.links=[]),P.length&&d.links.push(...P);const T=w.map((({structureId:t})=>t));d.structures||(d.structures=[]);const b=d.structures.map((({structureId:t})=>t));d.structures=d.structures.map((t=>T.includes(t.structureId)?w.find((({structureId:e})=>e===t.structureId)):t));const R=w.filter((({structureId:t})=>!b.includes(t)));return R.length&&d.structures.push(...R),o&&Qg({seedingProfile:t.seedingProfile,applyPositioning:r,tournamentRecord:i,drawDefinition:d,structureId:U,placeByes:s,drawSize:m,event:u}),n&&Hd({drawDefinition:d}),{links:P,structures:w,...z}}function HS(t){const{winnerFirst:e=!0,setTBlast:n=!0,addOutcomeString:r,reversed:i=!1,matchUpStatus:a,matchUpFormat:o,autoComplete:s,winningSide:c,sets:u}=t;if(!u)return{error:be,info:"missing sets"};const d=o&&Ii(o),{bestOf:p,finalSetFormat:l,setFormat:m}=d??{},f=i||!(!e||!c||1===c),g=r?function({matchUpStatus:t}){const e={[$u]:"RET",[zu]:"WO",[Bu]:"DF/DF",[Vu]:"WO/WO",[Wu]:"SUS",[Cu]:"ABN",[Lu]:"DEF",[_u]:"DR"};return t&&e[t]||""}({matchUpStatus:a}):"",I=u?.sort(zS).map((function(t){const e=p&&t.setNumber===p&&l?l:m,r=(I=t,h(I?.side1TiebreakScore)||h(I?.side2TiebreakScore)),i=e?.tiebreakSet||!(t=>h(t?.side1Score)||h(t?.side2Score))(t)&&r,{side1Score:a,side2Score:o,side1TiebreakScore:c,side2TiebreakScore:u}=t,d=c||(h(c)||r&&s?0:""),g=u||(h(u)||r&&s?0:"");var I;if(i){return`[${(f?[g,d]:[d,g]).join("-")}]`}const U=r?Math.min(d,g):"",y=U===d?1:2,S=h(U)?`(${U})`:"",v=a||(h(a)||s?0:""),w=o||(h(o)||s?0:""),P=t=>n||y!==t?"":S,D=`${v}${P(1)}`,T=`${w}${P(2)}`,b=n&&r?`(${U})`:"";let R=f?`${[T,D].join("-")}${b}`:`${[D,T].join("-")}${b}`;["-"," "].includes(R)&&(R="");return R})).filter(Boolean).join(" ")||"";return g?2===c?`${g} ${I}`:`${I} ${g}`:I}function zS(t,e){return t.setNumber-e.setNumber}function YS(t){if(!t?.score)return{error:be};const{sets:e}=t.score,n=e.map((t=>{const{side1TiebreakScore:e,side2TiebreakScore:n,winningSide:r,side1Score:i,side2Score:a,setNumber:o}=t;return Xr({winningSide:r?3-r:void 0,side1TiebreakScore:n,side2TiebreakScore:e,side1Score:a,side2Score:i,setNumber:o})})),r=t?.setTBlast;return{reversedScore:{sets:n,scoreStringSide1:HS({setTBlast:r,sets:n}),scoreStringSide2:HS({sets:n,reversed:!0,setTBlast:r})},...z}}var KS={__proto__:null,generateScoreString:HS,generateTieMatchUpScore:QU,reverseScore:YS};function QS({matchUp:t}){const{extension:e}=zc({name:su,element:t});if(!e)return{error:rr};const{history:n=[],undoHistory:r=[]}=e.value;return{history:n,undoHistory:r,...z}}function JS(t){if(!t)return{error:be};const{matchUp:e,updateScore:n}=t;if(!e)return{error:fe};const r=QS({matchUp:e})?.history||[];if(!Array.isArray(r))return{error:Jn,info:"history is not an array"};const{matchUpFormat:i}=e;if(!i)return{error:se};if(!Di({matchUpFormat:i}))return{error:oe};const a=Ii(i),{bestOf:o,finalSetFormat:s,setFormat:c}=a,u=["0","15","30","40","A","G"],d={sets:[]};let p,l,m=[],f=[0,0],h=1,g=0,I=0;const U=t=>[1,2].includes(t),S=()=>(g+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:g,games:[]});let v={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},w={winningSide:void 0,points:[]},P=S(),D=0;for(const t of r){D+=1,l=d.sets.length+1===o;const e=l&&s?s:c,{tiebreakAt:n,setTo:r,NoAD:i,tiebbreakFormat:a}=e,g=P.side1Score===n&&P.side1Score===P.side2Score,T=!!e.tiebreakSet,b=T?e.tiebreakSet:a,{tiebreakTo:R,NoAD:M}=b||{},N=()=>{p=void 0,f=[0,0],h=3-h,P.side1TiebreakScore="",P.side2TiebreakScore="",P.side1PointScore="",P.side2PointScore="",I=0},A=t=>{P.winningSide=t;const{s:e,...n}=P;d.sets.push(n),v={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},w={winningSide:void 0,points:[]},P=S(),N()},E=t=>{w.winningSide=t;const{g:e,...n}=w;P.games.push(n),v={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},w={winningSide:void 0,points:[]},N();P[`side${t}Score`]+=1},C=t=>{v.winningSide=t;const{p:e,...n}=v;w.points.push(n),v={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},I=0;const r=t-1;if(g||T){f[r]+=1,p=f.reduce(((t,e)=>t+e))%4/4>.5?h:3-h,P[`side${t}TiebreakScore`]=f[r],P[`side${3-t}TiebreakScore`]=f[1-r];const e=M?1:2;if(f[r]>=R&&f[r]>=f[1-r]+e)return E(t),{gameCompleted:!0}}else if(4===f[1-r]&&3===f[r]?f[1-r]-=1:f[r]+=1,P.side1PointScore=u[f[0]],P.side2PointScore=u[f[1]],5===f[r]||4===f[r]&&f[1-r]<3||i&&4===f[r])return E(t),{gameCompleted:!0}};if(U(t.srv)&&(h=t.srv),["p","s","g","o"].includes(t.u)&&m.push(t.u),t.shotOutcome){v.shots.push(t);if("SERVE"===t.shotType&&["OUT","NET"].includes(t.shotOutcome)&&(I+=1),2===I){C(3-h)}}if(U(t.p)||y(t.pointNumber)){const e=C(t.winningSide||t.p);if(e?.gameCompleted)continue}if(U(t.g)||y(t.gameNumber)){const e=t.winningSide||t.g;w.winningSide=e;const n=`side${e}Score`,a=`side${3-e}Score`;m.length&&(m.includes("p"),m=[]),E(e);if(P[n]===r&&P[n]-P[a]>=(i?1:2)&&(A(e),l))break}if(U(t.s)||y(t.setNumber)){if(A(t.winningSide||t.s),m.length&&(m.includes("p"),m.includes("g"),m=[]),l)break}}return D!==r.length&&console.log({error:"Match completed with excess history"}),(P.side1Score||P.side2Score||P.games.length||P.side1TiebreakScore||P.side2TiebreakScore)&&d.sets.push(P),d.scoreStringSide1=HS({...d,matchUpFormat:i}),d.scoreStringSide2=HS({...d,matchUpFormat:i,reversed:!0}),h=p||h,n&&(e.score=d),{...z,servingSide:h,score:d}}function ZS({undoHistory:t,history:e,matchUp:n}){return _c({element:n,extension:{value:{history:e,undoHistory:t},name:su}})}function XS({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:Pe};const{history:n=[]}=QS({matchUp:t});return n.push({srv:e}),ZS({matchUp:t,history:n})}function tv({matchUp:t}){return ZS({matchUp:t})}function ev({matchUp:t,point:e}){if(!e||!t)return{error:be};if("object"!=typeof e)return{error:Jn,context:{point:e}};const{history:n=[]}=QS({matchUp:t});return n.push(e),ZS({matchUp:t,history:n})}function nv({matchUp:t,game:e}){if("object"!=typeof e)return{error:Jn,context:{game:e}};const{history:n=[]}=QS({matchUp:t});return n.push(e),ZS({matchUp:t,history:n})}function rv({matchUp:t,shot:e}){if("object"!=typeof e)return{error:be};const{history:n=[]}=QS({matchUp:t});return n.push(e),ZS({matchUp:t,history:n})}function iv({matchUp:t,set:e}){if("object"!=typeof e)return{error:be};const{history:n=[]}=QS({matchUp:t});return n.push(e),ZS({matchUp:t,history:n})}function av({matchUp:t}){const{history:e=[],undoHistory:n=[]}=QS({matchUp:t});return n.length&&e.push(n.pop()),ZS({matchUp:t,history:e,undoHistory:n})}function ov({matchUp:t}){const{history:e=[],undoHistory:n=[]}=QS({matchUp:t});return n.push(e.pop()),ZS({matchUp:t,history:e,undoHistory:n})}const sv={};var cv={__proto__:null,addGame:nv,addPoint:ev,addSet:iv,addShot:rv,calculateHistoryScore:JS,clearHistory:tv,redo:av,setServingSide:XS,umo:sv,undo:ov};const uv=" ",dv="DEF",pv=["RET",dv,"WO","WO/WO","ABN","SUS","INT"],lv="DEFAULTED",mv="WALKOVER",fv="ABANDONED",hv="SUSPENDED",gv="RETIRED",Iv="INTERRUPTED",Uv=[gv,lv,mv],yv="()",Sv="[]",vv=["up","left","shift+tab"],wv=["enter","down","tab","right"],Pv="backspace",Dv=["r","d","w","a","s","i"],Tv="space",bv=["[","("],Rv=[...vv,...wv,Tv,"]"],Mv="-",Nv="-",Av=["/"],Ev=["0","1","2","3","4","5","6","7","8","9"].concat(Dv),Cv=Ev.map((t=>`shift+${t}`)),Ov=[Mv,Pv].concat(Rv,Av),Fv=[Ev,Cv,Ov].join(","),kv=[Fv,vv,wv,["=","+","num_1","num_2","shift+=","shift+-"]].join(",");[].concat(...Ev,...Ev,...Ov,...Ev,...Ev,...Ev,...Ev,...Ev,...Ev);const xv={OUTCOMEKEYS:Dv,SIDE1KEYS:Ev,SIDE2KEYS:Cv,MODIFIERS:Ov,PROMPT:"Enter Score",MOVEUP:vv,MOVEDOWN:wv,HOTKEYS:kv};function _v({scoreString:t,lowSide:e,outcome:n}){if(({scoreString:t}=Lv({scoreString:t})),2===e){return t+((t&&t[t.length-1])!==uv?uv:"")+n}return n+uv+t}function Lv({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(const n of pv){const r=t?.indexOf(n);0===r?t=t.slice(n.length+1).trim()+uv:r>0&&(t=t.slice(0,r)),r>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function Bv({analysis:t,scoreString:e,sets:n,lowSide:r}){let i,a;if(!e)return{scoreString:e,sets:n};const{scoreString:o,removed:s}=Lv({scoreString:e});if(e=o,s)return{scoreString:e,sets:n,outcomeRemoved:!0};let c=n[n.length-1]||{};const u=Object.values(c).filter((t=>void 0!==t)).length;c.setNumber&&1===u&&(c=(n=n.slice(0,n.length-1))[n.length-1]||{});const{tiebreakSet:d}=t.setFormat,{tiebreakTo:p,NoAD:l}=d||{},{isTiebreakEntry:m}=Vv({brackets:Sv,scoreString:e}),f=function(t){const e=t.split("").reduce(((t,e,n)=>(e.match(/\d+/g)&&t.push(n),t)),[]);return e.pop()}(e);if(f>=0){i=e.slice(0,f);const{isTiebreakEntry:o}=Vv({brackets:yv,scoreString:i}),{lastOpenBracketIndex:s,isTiebreakEntry:u}=Vv({brackets:Sv,scoreString:i}),d=i&&i[i.length-1].trim(),h=i&&!isNaN(d);let g=t.isIncompleteSetScore;if(m&&u){const t=i.slice(s+1).split(Nv),n=t?.length>0&&void 0!==t[0]&&!isNaN(parseInt(t[0]))&&parseInt(t[0])||void 0,a=t?.length>1&&void 0!==t[1]&&parseInt(t[1])||void 0,o=[n,a];if(a){const t=1===r?1:0;o[t]=(o?.[1-t]||0)+(l?1:2),(o[t]||0)<p&&(o[t]=p),i=e.slice(0,s+1),i+=o.join(Nv)}else void 0!==n?(i=e.slice(0,s+1),i+=n):(i=e.slice(0,s),g=!0);c.side1TiebreakScore=o[0]||0,c.side2TiebreakScore=o[1]||0}if(i.length||(i=void 0),g){const e=c.side1Score?.toString();if(e){const t=e?.slice(0,e.length-1);c.side1Score=!isNaN(t)&&parseInt(t)||void 0,void 0===c.side1Score&&(c.side2Score=void 0)}t.isTimedSet?(a=c.side1Score?n:n?.slice(0,n.length-1)||[],a[n.length-1]=c):a=n?.slice(0,n.length-1)||[]}else if(h){const e=c.side2Score?.toString(),r=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){const t=e?.slice(0,e.length-1);c.side2Score=!isNaN(t)&&parseInt(t)||void 0}else{const t=r?.slice(0,r.length-1);c.side1Score=!isNaN(t)&&parseInt(t)||void 0}t.isTimedSet?c.side1Score?(a=n||[],a[n.length-1]=c):a=n?.slice(0,n.length-1)||[]:(a=n||[],a[n.length-1]=c),a[a.length-1]&&Object.assign(a[a.length-1],{winningSide:void 0})}else o?(a=n||[],Object.assign(a[a.length-1]||{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(m&&!u?a=n?.slice(0,n.length-1)||[]:(a=n,a[n.length-1]=c),m||(a[a.length-1].side2Score=0,a[a.length-1].winningSide=void 0));return{scoreString:i,sets:a}}return{scoreString:e,sets:n}}function Vv({brackets:t=yv,scoreString:e}){if(!e)return{};const[n,r]=t.split(""),i=e.split(""),a=Math.max(...C(n,i));return{isTiebreakEntry:a>Math.max(...C(r,i)),lastOpenBracketIndex:a}}function jv(t){const{lowValue:e=0,NoAD:n=!1,tiebreakTo:r}=t||{};return e+1>=r?e+(n?1:2):parseInt(r)}function Gv({matchUpFormat:t,matchUpStatus:e,winningSide:n,sets:r}){const i=Ii(t),{bestOf:a}=i,o=Math.ceil(a/2),s=r?.reduce(((t,e)=>{const{winningSide:n}=e;return n&&t[n-1]++,t}),[0,0]);let c=s?.indexOf(o)+1||void 0;return Uv.includes(e)&&n&&(c=n),{matchUpWinningSide:c}}function qv({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:n,isTiebreakSet:r,isDecidingSet:i,isTimedSet:a,set:o}){if(!o)return{error:be,info:"missing set"};e=e||n&&Ii(n);const s=i&&e.finalSetFormat||e?.setFormat||{},{side1Score:c,side2Score:u}=o,{setTo:d,tiebreakAt:p}=s,l=c||u,m=$v({set:o}),f=Math.abs(c-u),h=c>=d||u>=d,g=r||c>=d&&u>=d||p&&p<d&&(c===p||u===p),I=t||g&&(1===m&&o.side1TiebreakScore>o.side2TiebreakScore||2===m&&o.side2TiebreakScore>o.side1TiebreakScore),U=!g&&s.NoAD||g||r&&s.tiebreakFormat?.NoAD?1:2;return!(!(a&&l||h&&(f>=U||g)||r)||g&&!I)}function $v({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 Wv({analysis:t,set:e}){const n=$v({set:e}),{isDecidingSet:r,isTiebreakSet:i,matchUpScoringFormat:a}=t;return qv({matchUpScoringFormat:a,isDecidingSet:r,isTiebreakSet:i,set:e})&&n}function Hv({lowSide:t,value:e,sets:n,scoreString:r,winningSide:i,matchUpStatus:a}){let o;return"r"===e?r?(o=!0,r=_v({scoreString:r,lowSide:t,outcome:"RET"}),i=2===t?1:2,a=gv):(o=!0,r=_v({scoreString:r,lowSide:t,outcome:dv}),i=2===t?1:2,a=lv):"d"===e?(o=!0,r=_v({scoreString:r,lowSide:t,outcome:dv}),i=2===t?1:2,a=lv):"w"===e?(o=!0,n=[],r="WO",i=2===t?1:2,a=mv):"s"===e&&r?(o=!0,r=_v({scoreString:r,lowSide:t,outcome:"SUS"}),a=hv,i=void 0):"a"===e?(o=!0,r=_v({scoreString:r,lowSide:t,outcome:"ABN"}),a=fv,i=void 0):"i"===e&&r&&(o=!0,r=_v({scoreString:r,lowSide:t,outcome:"INT"}),a=Iv,i=void 0),{updated:o,sets:n,scoreString:r,matchUpStatus:a,winningSide:i}}function zv({matchUpFormat:t,scoreString:e,winningSide:n,value:r,sets:i}){const a=(i?.filter((t=>t?.winningSide))?.length||0)+(n?0:1),o=Ii(t),s=a===o?.bestOf,c=s&&o?.finalSetFormat||o?.setFormat||{},u=c?.timed,d=s&&i[o?.bestOf-1],p=d?.winningSide,{isTiebreakEntry:l}=Vv({brackets:yv,scoreString:e}),{isTiebreakEntry:m}=Vv({brackets:Sv,scoreString:e}),f=l||m,h=!!c.tiebreakSet,g=e?.[e.length-1]?.trim(),I=e&&!isNaN(g),U=!f&&g===Mv,y=l&&bv.includes(g),S=m&&bv.includes(g),v=m&&g===Nv,w=e?.split(""),[P]=Sv.split(""),D=w&&Math.max(...C(P,w)),T=w&&Math.max(...C(Nv,w)),b=w&&T>D,R=i[i.length-1]?.winningSide,M=i?.length&&!R,N=pv.find((t=>e?.indexOf(t)>=0)),A=!isNaN(r),E=r===Tv,O=Rv.includes(r),F=e?.split("").find((t=>bv.includes(t))),k=O&&m&&!S&&(v||!function({scoreString:t}){if(!t)return!1;const e=t&&t[t.length-1].trim(),n=t&&!isNaN(e),[r,i]=Sv.split(""),a=t.split(""),o=Math.max(...C(r,a)),s=Math.max(...C(i,a)),c=Math.max(...C(Nv,a));return n&&o>s&&c>o}({scoreString:e}));return{isTiebreakSetValue:h&&A,matchUpScoringFormat:o,setNumber:a,setFormat:c,matchTiebreakHasJoiner:b,isGameScoreEntry:M,isSpace:E,isCloser:O,isTiebreakCloser:O&&F&&f&&I,isDecidingSet:s,isTiebreakSet:h,isTimedSet:u,isNumericEnding:I,isNumericValue:A,hasOpener:F,hasOutcome:N,finalSet:d,finalSetIsComplete:p,lastSetIsComplete:R,isInvalidSetTiebreakValue:E&&f&&y,isInvalidMatchTiebreakValue:k,isTiebreakEntry:f,isSetTiebreakEntry:l,isMatchTiebreakEntry:m,isIncompleteSetScore:U,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:S,isPartialMatchTiebreakValue:v}}function Yv(t){let{lowSide:e=1,value:n}=t,{scoreString:r,sets:i,winningSide:a,matchUpStatus:o}=t;const{matchUpFormat:s,shiftFirst:c,auto:u=!0}=t;let p,l;const m=c&&2===e||!c&&1===e;if(!Fv.includes(n))return{updated:!1,info:"invalid key"};c&&(e=3-e);const{matchUpWinningSide:f}=Gv({sets:i,winningSide:a,matchUpStatus:o,matchUpFormat:s});a=f;const h=zv({value:n,winningSide:a,scoreString:r,sets:i,matchUpFormat:s});if(Av.includes(n)&&(n=Mv),h.hasOpener&&h.isTiebreakEntry&&!h.isTiebreakSet&&m&&0===d(n)&&(h.isTiebreakCloser=!0),Rv.includes(n)&&h.hasOpener&&(n=""),Rv.includes(n)&&(n=Tv),h.lastSetIsComplete){const t=r?.length&&r[r.length-1];r&&" "!==t&&(r+=" ")}if(h.isTimedSet)({info:l,sets:i,scoreString:r,updated:p,matchUpStatus:o,winningSide:a}=function(t){let{sets:e,info:n,scoreString:r,winningSide:i,matchUpStatus:a}=t;const{analysis:o,lowSide:s,value:c}=t;let u,p;e?.length||c===Pv||(e=[{setNumber:1}]);const l=e.length-1;if(Dv.includes(c)){const t=e[e.length-1]||{},{side1Score:d,side2Score:p}=t;d&&!p?n="missing side2Score":o.finalSetIsComplete||i?n="final set is already complete":o.isIncompleteSetScore?n="incomplete set scoreString":o.isIncompleteSetScore||({sets:e,scoreString:r,winningSide:i,matchUpStatus:a,updated:u}=Hv({lowSide:s,value:c,sets:e,scoreString:r,matchUpStatus:a,winningSide:i}))}else if(c===Pv){if(({scoreString:r,sets:e,outcomeRemoved:p}=Bv({analysis:o,scoreString:r,sets:e})),""===r?.trim()&&(r=r.trim()),r||(e=[]),p){const t=e[e.length-1]||{},{side1Score:n,side2Score:r}=t;if(n&&r){const i=(n>r?1:r>n&&2)||void 0;i&&(t.winningSide=i,e.push({setNumber:e.length+1}))}}a=void 0,i=void 0,u=!0}else if(o.hasOutcome)n="has outcome";else{if(i)return{sets:e,scoreString:r,winningSide:i,matchUpStatus:a,updated:!1,info:"matchUp is complete"};if(c===Tv){const t=e[e.length-1]||{},{side1Score:n,side2Score:a}=t,s=(n>a?1:a>n&&2)||void 0;!s||i||o.isIncompleteSetScore||(e[e.length-1].winningSide=s,e.push({setNumber:e.length+1}),r+=" ",u=!0)}else if(c===Mv&&void 0!==e[l].side1Score&&void 0===e[l].side2Score&&r&&o.isNumericEnding)r+="-",e[l].side2Score=0,a=void 0,i=void 0,u=!0;else if(!isNaN(c)){let t;if(void 0===e[l].side2Score){const n=d((e[l].side1Score||0).toString()+c).toString().slice(0,2);e[l].side1Score=d(n),t=e[l].side1Score.toString(),u=!0}else{const n=d((e[l].side2Score||0).toString()+c).toString().slice(0,2);e[l].side2Score=d(n),t=[e[l].side1Score,e[l].side2Score].join("-"),u=!0}if(u){const n=(e.slice(0,l)||[]).filter((t=>t)).map((t=>{const{side1Score:e,side2Score:n}=t;return[e,n].join("-")})).join(" ");r=n?n+" "+t:t}}}return{sets:e,scoreString:r,winningSide:i,matchUpStatus:a,info:n,updated:u}}({analysis:h,lowSide:e,scoreString:r,sets:i,matchUpStatus:o,winningSide:a,value:n}));else if(Dv.includes(n))h.finalSetIsComplete||a?l="final set is already complete":h.isTiebreakEntry||h.isIncompleteSetScore?h.isTiebreakEntry||h.isIncompleteSetScore?l="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:n}):({sets:i,scoreString:r,matchUpStatus:o,winningSide:a,updated:p}=Hv({lowSide:e,sets:i,scoreString:r,matchUpStatus:o,winningSide:a,value:n}));else if(n===Pv)p=!0,({scoreString:r,sets:i}=Bv({analysis:h,scoreString:r,sets:i,lowSide:e})),r||(i=[]),o=void 0,a=void 0;else if(h.hasOutcome)l="has outcome";else if(n!==Mv||h.isMatchTiebreakEntry)if(n===Nv&&h.isMatchTiebreakEntry&&!h.isSetTiebreakEntry)h.matchTiebreakHasJoiner?l="existing joiner":h.isNumericEnding&&(p=!0,r+=Nv);else if([Mv,Nv].includes(n))l="invalid location for joiner";else{if(a)return{updated:!1,info:"matchUp is complete"};if(h.isIncompleteSetScore)h.isNumericValue&&({sets:i,scoreString:r,updated:p}=function({analysis:t,scoreString:e,sets:n,value:r}){let i;if(!n?.length)return{sets:[]};const a=n[n.length-1];r=d(r);const{validSide2Score:o,requiresTiebreak:s}=function({analysis:t,set:e={},value:n}){const r=t.isDecidingSet&&t.matchUpScoringFormat.finalSetFormat||t.matchUpScoringFormat.setFormat,{tiebreakAt:i,setTo:a,NoAD:o}=r,{side1Score:s}=e;let c,u;return c=i&&i<a?s===i?n<=a:n<=i:s===a?o?n<a:n<=a+1:s===a-1?o?n<=a:n<=a+1:s===a+1?n===a||n===a-1:n<=a,c&&(u=i&&i<a?s===a&&n===i||s===i&&n===a:s>=a&&n>=a&&s!==n),{validSide2Score:c,requiresTiebreak:u}}({analysis:t,set:a,value:r});if(o){i=!0,e=(e||"")+r,a.side2Score=r;const o=Wv({analysis:t,set:n[n.length-1]});a.winningSide=o||void 0,s?e+=yv.split("")[0]:t.isDecidingSet||(e+=uv)}return{sets:n,scoreString:e,updated:i}}({analysis:h,scoreString:r,sets:i,value:n}));else if(h.isInvalidMatchTiebreakValue)l="invalid matchUp tiebreak character";else if(h.isInvalidSetTiebreakValue)l="invalid set tiebreak character";else if(h.isTiebreakCloser){const t=h.isSetTiebreakEntry?yv:Sv,e=t.split("").reverse()[0],n=t.split("")[0],a=i[i.length-1],{tiebreakFormat:o}=h.setFormat,{tiebreakTo:s,NoAD:c}=o||{},u=$v({set:a});if(!h.isTiebreakSet){const t=parseInt(r.split(n).reverse()[0]),e=jv({lowValue:t,tiebreakTo:s,NoAD:c});1===u?(a.side1TiebreakScore=e,a.side2TiebreakScore=t):(a.side1TiebreakScore=t,a.side2TiebreakScore=e)}r=(r||"")+e,h.isDecidingSet||(r+=uv);const d=Wv({analysis:h,set:a});a.winningSide=d||void 0,p=!0}else if(h.isTiebreakSetValue)({info:l,scoreString:r,sets:i,updated:p}=function({analysis:t,auto:e,lowSide:n,scoreString:r="",sets:i,value:a}){let o,s;const{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Sv.split("");if(t.isMatchTiebreakEntry||(r+=p),i[t.setNumber-1]){const{lastOpenBracketIndex:t}=Vv({brackets:Sv,scoreString:r}),p=(r.slice((t??0)+1)+(e?"":a)).split(Nv);if((p[n-1]?.length||0)>=2)s="tiebreak digit limit";else if(e){1===n&&(p[0]=(p[0]||"")+a),2===n&&(p[1]=(p[1]||"")+a);const e=[p[0]||0,p[1]||0].map((t=>d(t))),s=1===n?1:0;e[s]=e[1-s]+(u?1:2),e[s]<c&&(e[s]=c);const l=i[i.length-1];l.side1TiebreakScore=e[0],l.side2TiebreakScore=e[1],r=r.slice(0,(t??0)+1),r+=e.join(Nv),o=!0}else{const t=[p[0]||0,p[1]||0].map((t=>d(t))),e=i[i.length-1];e.side1TiebreakScore=t[0],e.side2TiebreakScore=t[1],r+=a,o=!0}}else{const t=jv({lowValue:d(a||0),tiebreakTo:c,NoAD:u}),e=[d(a),t];2===n&&e.reverse();const s={side1TiebreakScore:e[0],side2TiebreakScore:e[1],setNumber:i?.length+1||1};i.push(s),r+=e.join(Nv),o=!0}return{info:s,scoreString:r,sets:i,updated:o}}({analysis:h,auto:u,lowSide:e,scoreString:r,sets:i,value:n}));else if(h.isSetTiebreakEntry){const[t]=yv.split(""),e=Math.max(...C(t,r.split(""))),i=r.slice(e+1),a=i&&0===d(i),o=d(i?i+n:n),{tiebreakFormat:s}=h.setFormat,{tiebreakTo:c,NoAD:u}=s||{};!a&&i.length<2?u&&o>c-1?l="invalid low value for NoAD tiebreak":(p=!0,r=(r||"")+n):l=a?"tiebreak begins with zero":"tiebreak digit limit"}else if(h.isCloser)l=`invalid key: ${n}`;else if(h.isGameScoreEntry)l="game scoreString entry";else if(h.lastSetIsComplete||!i.length){p=!0;const{scoreString:t,set:a}=function({analysis:t,lowSide:e,scoreString:n,value:r}){const{setTo:i,tiebreakAt:a,NoAD:o}=t?.setFormat||{},s=r===parseInt(a||i);if(a&&a<i&&r>a)return{scoreString:n};if(o&&r===i||r>i)return{scoreString:n};const c=s?r+1:r+1===i?r+(o?1:2):i,u=[r,c];2===e&&u.reverse();const d=yv.split("")[0];n=(n||"")+(u.join(Mv)+(s?d:uv));const p={side1Score:u[0],side2Score:u[1]},l=Wv({analysis:t,set:p});return p.winningSide=l||void 0,{scoreString:n,set:p}}({analysis:h,lowSide:e,scoreString:r,value:d(n)});a&&(a.setNumber=i?.length+1||1),i=i?.concat(a).filter(Boolean)||[a],r=t||void 0}else console.log("error: unknown outcome")}else(!h.isSetTiebreakEntry||h.isSetTiebreakEntry&&!h.isNumericEnding)&&(p=!0,({scoreString:r,sets:i}=Bv({analysis:h,scoreString:r,sets:i,lowSide:e})),o=void 0);if(p){i=i?.filter(Boolean);const{matchUpWinningSide:t}=Gv({sets:i,winningSide:a,matchUpStatus:o,matchUpFormat:s});return a=t,!t||o&&![Hu,Gu].includes(o)?!r||a||[hv,fv,Iv].includes(o)||(o=void 0):(o="COMPLETED",i=i.filter((t=>{const{side1Score:e,side2Score:n,side1TiebreakScore:r,side2TiebreakScore:i}=t;return e||n||r||i}))),{updated:p,scoreString:r,sets:i,winningSide:a,matchUpStatus:o,info:l}}return{updated:p,scoreString:r,sets:i,winningSide:a,matchUpStatus:o,info:l}}const Kv="\\d+-\\d+",Qv="\\d+-\\d+\\(\\d+\\)",Jv="\\[\\d+-\\d+\\]",Zv=new RegExp(`(${Kv}),`,"g"),Xv=new RegExp(`(${Qv}),`,"g"),tw=[Kv,Qv,Jv,"\\d+-\\d+\\(\\d+-\\d+\\)"],ew=["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"].map((t=>{const e=t.split("").map((t=>tw[t])).join(" ");return new RegExp(`^${e}$`)}));function nw(t){return!t||ew.some((e=>e.test(t)))}function rw(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function iw(t){const e=(n=t,n?.split("-").join("").split("/").join(""));var n;if(/^\d+$/.test(e)&&2===e.length){const t=e.split("");return 1===Math.abs(t.reduce(((t,e)=>+t-+e)))}return!1}function aw(t,e){const n=[t.slice(e,e+2),e?t.slice(0,1):t.slice(2)].map((t=>parseInt(t.join(""))));e&&n.reverse();const r=n;if(Math.abs(r.reduce(((t,e)=>+t-+e)))>=2)return r.join("-")}function ow(t){return 2===t.length?t.split("").join("-"):([", ",",","/"," "].forEach((e=>t=t.split(e).join("-"))),t=t.replace(/-{2,}/,"-"))}function sw(t){return t.startsWith("(")&&t.endsWith(")")}function cw(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;const e=C("-",t.split(""));if(!e.length)return t;const n=t.split("-"),r=!(n.length%2),i=!!(e.length%2);if(r&&i&&e.length>n.length/2){e.filter(((t,e)=>e%2)).forEach((e=>{t=t.substring(0,e)+" "+t.substring(e+1)}))}return t}function uw({score:t}){const e=t.split(""),n=[];let r;const i=()=>r=[void 0,void 0,void 0],a=()=>{let t=`${r[0]}-${r[1]}`;return r[2]&&(t+=` (${r[2]})`),i(),r.push(r),t};i();const o=()=>void 0!==r[0]&&void 0!==r[1]&&Math.abs(parseInt(r[0])-parseInt(r[1]));for(;e.length;){const t=e.shift(),i=h(t)&&parseInt(t),s=void 0!==r[0]&&void 0!==r[1];if(h(i)){if(void 0===r[0]){r[0]=i;continue}if(void 0===r[1]&&(r[1]=i,o())){n.push(a()),r=[void 0,void 0];continue}if(s&&1===e.length&&h(e[0])){const t=e.pop();r[0]=r[0].toString()+r[1].toString(),r[1]=t,n.push(a()),r=[void 0,void 0]}s&&o()}}return{sets:n}}function dw(t){const e=t.indexOf("1"),n=t.split(""),r=n.every((t=>!isNaN(t)));if(r&&3===t.length&&0===e){const t=aw(n,e);if(t)return t}if(r&&7===t.length&&e>3){const t=aw(n.slice(4),e-4);if(t)return`${n[0]}-${n[1]} ${n[2]}-${n[3]} ${t}`}}function pw(t){let{score:e}=t;const{applied:n,matchUpStatus:r}=t,i=e?.toString().split(""),a=i?.every((t=>h(t))),o=t=>Math.abs(t[0]-t[1]);if("number"==typeof e||a){e=e.toString().toLowerCase(),a&&(e=i.join(""));const t=a?i.map((t=>parseInt(t))):e.split("").map((t=>parseInt(t))),{sets:r}=uw({score:e});if(t.length,3===e.length&&1===o(t.slice(0,2))){const[r,i,a]=t;e=`${r}-${i}(${a})`,n.push("numericTiebreakPattern1")}else if(3===e.length&&1===t[0]){const[r,i,a]=t;e=`[${r}${i}-${a}]`,n.push("numericTiebreakPattern2")}else if(4===e.length&&1===o(t.slice(0,2))&&"987654".split("").includes(t[0].toString())){const[r,i,a,o]=t;e=`${r}-${i}(${Math.min(a,o)})`,n.push("numericTiebreakPattern3")}else if(4===e.length&&1===t[0]&&1===t[2]){const[r,i,a,o]=t;e=`[${r}${i}-${a}${o}]`,n.push("bigSuper")}else if(4===e.length){const[r,i,a,o]=t;e=`${r}${i} ${a}${o}`,n.push("split4")}else if(5===e.length&&1===o(t.slice(0,2))){const[r,i,a,o,s]=t;e=`${r}-${i}(${a}) ${o}-${s}`,n.push("numericTiebreakPattern4")}else if(5===e.length&&1===o(t.slice(3))){const[r,i,a,o,s]=t;e=`${r}-${i} ${a}-${o}(${s})`,n.push("numericTiebreakPattern5")}else if(7===t.length)if(o(t.slice(0,2))>1&&o(t.slice(2,4))>1&&1===t[4]){const[r,i,a,o,s,c,u]=t;e=`${r}-${i} ${a}-${o} [${s}${c}-${u}]`,n.push("numericTiebreakPattern6")}else if(1===o(t.slice(0,2))&&o(t.slice(3,5))>1&&o(t.slice(5,7))>1){const[r,i,a,o,s,c,u]=t;e=`${r}-${i}(${a}) ${o}-${s} ${c}-${u}`,n.push("numericTiebreakPattern7")}else if(o(t.slice(0,2))>1&&1===o(t.slice(2,4))&&o(t.slice(5,7))>1){const[r,i,a,o,s,c,u]=t;e=`${r}-${i} ${a}-${o}(${s}) ${c}-${u}`,n.push("numericTiebreakPattern8")}else if(o(t.slice(0,2))>1&&o(t.slice(2,4))>1&&1===o(t.slice(4,6))){const[r,i,a,o,s,c,u]=t;e=`${r}-${i} ${a}-${o} ${s}-${c}(${u})`,n.push("numericTiebreakPattern9")}else e=e.slice(0,2)+" "+e.slice(2,4)+" "+e.slice(4),n.push("numericMatchTiebreakPattern");else if(e.length%2){const t=dw(e);t&&e!==t&&n.push("parsedSuperPattern"),e=t??e}else{const r=x(e.split(""),2).map((t=>t.join(""))),i=r.map((t=>{const[e,n]=t.split("").map((t=>parseInt(t))),r=e>n?1:2;return Math.abs(e-n)>1&&r||-1*r})),a=i.reduce(((t,e)=>t>0&&e>0),1),o=T(i),s=T(i.map((t=>Math.abs(t)))),c=i[0]<0,u=!c&&i[1]<0;if(i[0]>0&&i[1]>0&&i[0]!==i[1])e=[r.slice(0,2).join(" "),r.slice(2).join("-")].join(" "),n.push("numeric3rdSetTiebreakPattern");else if(a)e=r.join(" "),n.push("chunkSplit");else if(6===t.length){if(2===o[1]||2===o[2])if(Object.values(s).includes(3)){const[r,a,o,s,c,u]=t,d=i.reduce(((t,e,n)=>e<0?n:t),void 0);if(0===d){e=`${r}-${a}(${Math.min(o,s)}) ${c}-${u}`,n.push("chunkSplitTiebreak1")}else if(1===d){e=`${r}-${a} ${o}-${s}(${Math.min(c,u)})`,n.push("chunkSplitTiebreak2")}else e=`${r}-${a} ${o}-${s}`,n.push("chunkSplitTrimExtraneous")}else e=r.join(" "),n.push("chunkSplit")}else if(8===t.length){const[n,r,a,o,s,d,p,l]=t;c||u?1===t[5]&&(e=c?`${n}-${r}(${a}) ${o}-${s} [${d}${p}-${l}]`:`${n}-${r} ${a}-${o}(${s}) [${d}${p}-${l}]`):(i[0],i[1])}}}return{score:e,applied:n,matchUpStatus:r}}function lw(t){const e=[0,0],n=[],r=t.split(" "),i=/(\d+)-(\d+)/;r.forEach((t=>{if(i.test(t)){const r=t.match(i).slice(1).map((t=>parseInt(t))),a=r[0]>r[1]?1:r[1]>r[0]&&2;a&&(e[a-1]+=1,n.push(a))}}));const a=e[0]>e[1]?1:e[1]>e[0]&&2,o=e[0]>0&&e[0]===e[1],s=e.reduce(((t,e)=>t+e),0);return{setsWon:e,setsTied:o,setWinners:n,totalSets:s,winningSide:a}}const mw={handleTiebreakSlashSeparation:function({score:t}){const e=new RegExp(/\(\d+\/\d+\)/g),n=t.match(e);for(const e of n||[]){const n=e.replace("/","-");t=t.replace(e,n)}return{score:t}},handleSetSlashSeparation:function({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}},punctuationAdjustments:function({score:t,applied:e}){t=function(t){const e="[];",n="()",r=e+n,i=[e[0],n[0]],a=Object.assign({},...r.split("").map((t=>({[t]:0}))));let o="";const s=t.split("").map((t=>{const s=r.includes(t)&&t,c=i.includes(s);if(c&&s)return a[s]+=1,o=s,t;if(!c&&s&&o&&s!==o){a[o]-=1;const t=e.includes(o)&&e||n.includes(o)&&n||"",r=t.split("").find((t=>t!==o));if(!t.includes(s))return a[s]||(o=""),r;a[o]||(o="")}return t})).join("");return t!==s?s:t}(t);const n=/\)(\d+)/g;if(n.test(t))for(const e of t.match(n)){const n=e.replace(")",") ");t=t.replace(e,n)}const r=/\(([\d- ]+)\)/,i=(t=(t=t.replace(/\)\//g,") / ")).replace(/\/\)/g,")")).match(/\(([\d- ]+)\)/g);for(const e of i||[]){const[n]=e.match(r).slice(1),i=n.replace(/ /g,"");t=t.replace(e,`(${i})`)}let a=/\(\(\d-\d\)\)/g;if(a.test(t)){const e=t.match(a);e.length&&e.forEach((e=>{const n=e.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(e,n)}))}if(a=/\(\((\d)\)\)/g,a.test(t)){const e=t.match(a);e.length&&e.forEach((e=>{const n=e.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(e,n)}))}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));const o=new RegExp(/[-,]{2,}/g);t=t.replace(o,"-"),["- "," -"].forEach((e=>{const n=new RegExp(`(\\d+)${e}(\\d+)`,"g"),r=t.match(n);r&&r.forEach((n=>t=t.replace(n,n.split(e).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," "));const s=/\(\d+, \)/g;if(s.test(t)){t.match(s).forEach((e=>{const[n]=e.match(/\((\d+), \)/).slice(1);2===n.length?t=t.replace(e,`(${n})`):1===n.length&&"6"===n&&(t=t.replace(e,"(6-0)"))}))}const c=/\((\d+)\/\)/g;if(c.test(t)){t.match(c).forEach((e=>{const[n]=e.match(/\((\d+)\/\)/).slice(1);t=2===n.length?t.replace(e,`(${n})`):1===n.length&&"6"===n?t.replace(e,"(6-0)"):t.replace(e,`(${n})`)}))}const u=/\d\/\d\/,/g;if(u.test(t)){t.match(u).forEach((n=>{const[r]=n.match(/(\d\/\d)\/,/).slice(1);t=t.replace(n,`${r},`),e.push("slashComma")}))}const d=/\(\/(\d+)\)/g;if(d.test(t)){t.match(d).forEach((e=>{const[n]=e.match(/\(\/(\d+)\)/).slice(1);t=2===n.length?t.replace(e,`(${n})`):1===n.length&&parseInt(n)<6?t.replace(e,`(6-${n})`):t.replace(e,`(${n})`)}))}let p,l,m,f,h;const g=()=>{h=T(t.split("")),l=h["("]===(h[")"]||0)+1,p=(h["("]||0)+1===h[")"],m=h["["]===h["]"]+1,f=l&&!m};g();const I=/(\d+-\d+\(\d+)0,/;if(I.test(t)){const[e]=t.match(I).slice(1);t=t.replace(I,e+")")}if(h["("]===h[")"]&&h["("]>1){const e=t.split(")(").join(") (").split(" ");t=e.every(sw)?e.map((t=>{const e=t.slice(1,t.length-1);return e.length>2?e:t})).join(" "):e.join(" ")}g();const U=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!U&&!y)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some((t=>h[t]))&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&1===h["("]&&1===h[")"]&&"[]/,".split("").some((t=>h[t]>1))&&(t=t.slice(1,t.length-1)),t.startsWith("(")&&t.endsWith("))")&&(t=t.slice(1,t.length-1)),h["("]>(h[")"]||0)&&"("===t[t.length-1]&&(t=t.slice(0,t.length-1)+")",g()),1!==h["("]||h[")"]||"("!==t[0]||(t+=")",g()),h["("]>(h[")"]||0)&&"(("===t.slice(0,2)&&(t=t.slice(1)),p){if(/^9\d/.test(t))t="("+t.slice(1);else if("("!==t[0])t="("+t;else{const e=[];let n=0;for(const r of t.split("").reverse())")"===r&&(n?e.push("("):n+=1),"("===r&&(n-=1),e.push(r);e.reverse(),t=e.join("")}g()}if(h[")"]>(h["("]||0)&&")"===t[0]&&(t="("+t.slice(1),g()),f&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",g()),!f||t.endsWith(")")&&!t.startsWith("((")||(t+=")",g()),f){let e="",n=0;for(const r of t.split(""))"("===r&&(n?e+=")":n+=1),")"===r&&(n-=1),e+=r;t=e}if(g(),m&&!l&&(t+="]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),g()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),g(),1===h[")"]&&!h["("]&&t.endsWith(")")&&(t=t.slice(0,t.length-1)),t.startsWith("(")&&t.endsWith(")")&&1===h["("]&&1===h[")"]&&(t=t.slice(1,t.length-1),g()),/^\([\d ]+.*[\d ]+\)$/.test(t)&&h["("]===h[")"]){const e=t.slice(1,t.length-1);(t=>{const e=t.indexOf("("),n=t.indexOf(")");return e>=0&&n>=0&&e<n})(e)&&(t=e,g())}return{score:t,applied:e}},handleGameSeparation:function({score:t}){const e=new RegExp(/^\d+\/\d+/),n=t.split(" ");n.some((t=>e.test(t)))&&(t=n.map((t=>e.test(t)?t.replace("/","-"):t)).join(" "));const r=/^(\d+), *(\d+)$/;if(r.test(t)){const[e,n]=t.match(r).slice(1);t=[e,n].join("-")}return{score:t}},joinFloatingTiebreak:function({score:t}){if("string"!=typeof t)return{score:t};const e=t=>t?.split("-").join("").split("/").join(""),n=t=>t.split("[").join("(").split("]").join(")");let r=(t=t.split(", ").join(" ")).split(" ");t=r.map((t=>{const e=/^-(\d+)$/;if(e.test(t)){const[n]=t.match(e).slice(1);if(2===n.length)return n.split("").join("-")}return t})).join(" "),r=t.split(" ");const i=r.filter(rw);let a=0,o="";for(const t of i){const n=C(t,r).filter((t=>!a||t>a))[0],i=r.slice(a,n-1),s=r[n-1],c=e(s);if(/^\d+$/.test(c)&&2===c.length){const e=c.split(""),r=Math.abs(e.reduce(((t,e)=>+t-+e)));if(1===r){o+=[i.join(" "),[s,t].join("")].join(" "),a=n+1}else if(0===r){const r=Math.max(...e);if([4,5,6,7,8,9].includes(r)){const e=[r,[6,4].includes(r)?r+1:r-1].sort().reverse().join("-");o+=[i.join(" "),[e,t].join("")].join(" "),a=n+1}}}}if(i.length&&o.length){return o=[o,r.slice(a).join(" ")].join(" "),{score:o.trim()}}if(2===r.length&&["(","["].some((t=>r[1].includes(t)))){const t=e(r[0]).split("");if(1===Math.abs(t.reduce(((t,e)=>+t-+e),0)))return r[1]=n(r[1]),{score:r.join("")}}const s=r.map((t=>function(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}(t)?"bracket":iw(t)&&"set"));if(s.includes("set")&&s.includes("bracket")){let t,e="";return r.forEach(((r,i)=>{"bracket"===s[i]&&"set"===t?(r=n(r),e+=r):e+=` ${r}`,t=s[i]})),{score:e.trim()}}let c;r=t.split(" ");let u=r.map((t=>{const e=new RegExp(/^(\d+)-(\d+)$/);if(e.test(t)){const[n,r]=t.match(e).slice(1),i=Math.abs([n,r].reduce(((t,e)=>+t-+e))),a=Math.max(n,r);if(1===i)return c="tiebreakSet",c;if(i>=2&&a>=7&&"tiebreakSet"===c)return c="tiebreak",c}}));const d=C("tiebreak",u);if(d.length){let e="";r.forEach(((t,n)=>{d.includes(n)?e+=`(${t}) `:d.includes(n+1)?e+=`${t}`:e+=`${t} `})),t=e.trim()}const p=/(\d+-\d+)\((\d+)-(\d+)\)$/;if(p.test(t)){const[e,n,r]=t.match(p).slice(1),i=Math.max(n,r)>=10;!iw(e)&&i&&(t=t.replace(p,`${e} [${n}-${r}]`))}return u=[],t=t.split(" ").map((t=>{const e=/^\((.*)\)$/,n=e.test(t),r=(new RegExp(Jv).test(t)?"super":new RegExp(Qv).test(t)&&"tiebreak")||new RegExp(Kv).test(t)&&"standard"||"unknown";return u.push(r),"standard"===r&&n?t.match(e)[1]:t})).join(" "),{score:t}},handleBracketSpacing:function({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map((t=>t.trim())).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map((t=>t.trim())).join(")")),[Zv,Xv].forEach((n=>{const r=t.match(n);r?.length&&(r.forEach((e=>{t=t.replace(e,e.slice(0,e.length-1)+" ")})),e.push("setsEndComma"))})),{score:t=t.split(" ").filter(Boolean).map(cw).join(" "),applied:e}},handleSpaceSeparator:function({score:t}){if(t.includes(",")){const e=t.split(",").map((t=>t.trim())),n=t=>/\d \d/.test(t);e.every(n)&&(t=e.map((t=>{const e=/\d+ \d+/g;for(const n of t.match(e)){const[e,r]=n.match(/(\d+) (\d+)/).slice(1);t=t.replace(n,`${e}-${r}`)}return t})).join(" "))}if(t.includes(" ")){const e=t.replace(/[ ,]/g,"");e.split("").every((t=>h(t)))&&4===e.length&&(t=e)}return{score:t}},separateScoreBlocks:function({score:t,applied:e}){return"string"!=typeof t?{score:t}:{score:t=t.toLowerCase().split(" ").map((t=>{if(/^\d+$/.test(t)&&t.length>2){const n=t.indexOf("1");if(t.length%2){if(3===t.length&&0===n){const r=aw(t.split(""),n);return e.push("getSuper"),r}}else{const{score:n,applied:r}=pw({score:t,applied:[]});n!==t&&(t=n,e.push(...r))}}return t})).join(" "),applied:e}},matchKnownPatterns:function({score:t,applied:e}){for(const n of[".",","," ","/"]){const r=new RegExp(`^(\\d+)\\${n}(\\d+)$`);if(r.test(t)){const i=t.match(r).slice(1).map((t=>parseInt(t))),a=Math.abs(i[0]-i[1]);a<=10&&a>=2&&(t=t.split(n).join("-"),e.push("variedJoinerPattern"))}}t.includes(";")&&(t=t.split(";").join(" "),e.push("semicolon set separation"));const n=/(^|\s)(\d)\/(\d)(\d)\/(\d)(\(|$)/;if(n.test(t)){const[r,i,a,o,s,c]=t.match(n).slice(1);t=t.replace(n,`${r}${i}-${a} ${o}-${s}${c}`),e.push("smashSlashPattern")}/.*\s6[/-]+$/.test(t)&&(t+="0",e.push("incompleteFinalSetPattern"));const r=/\(6,\)/g;r.test(t)&&(t=t.replace(r,"(6, 0)"),e.push("missingZeroPattern1"));const i=/^\d{3,}\(/,a=/\(\d+\)\d+/;[i,a].forEach((()=>{const n=t.split(" ");t=n.map((t=>(i.test(t)&&(t=t.replace("("," (")),a.test(t)&&(t=t.replace(")",") ")),t))).join(" "),e.push("spaceConsiderationPatterns")}));const o=cw(t);o!==t&&(t=o,e.push("deDashMash"));const s=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(s.test(t)){const[n,r,i]=t.match(s).slice(1),[a,o]=r.split("");t=`${n}-${a} ${o}-${i}`,e.push("smashSetPattern")}const c=/^(\d+)[ -](\d+)$/,u=/^([\d -]+)\/([\d -]+)$/;if(u.test(t)){const[n,r]=t.match(u).slice(1),i=n.trim(),a=r.trim();if(c.test(i)&&c.test(a)){const n=i.match(c).slice(1,3).join("-"),r=a.match(c).slice(1,3).join("-");t=`${n} ${r}`,e.push("slashSeparationPattern")}}const d=/^([\d -]+),([\d -]+)$/;if(d.test(t)){const[n,r]=t.match(d).slice(1),i=n.trim(),a=r.trim();if(c.test(i)&&c.test(a)){const n=i.match(c).slice(1,3).join("-"),r=a.match(c).slice(1,3).join("-");t=`${n} ${r}`,e.push("commaSeparationPattern")}}const p=/^\d \d,/;if(p.test(t)){const n=t.match(p)[0],r=n.slice(0,n.length-1).split(" ").join("-");t=t.replace(n,r),e.push("singleSetCommaSeparationPattern")}let l=0;const m=/(\d+)-(\d{2})-(\d+)/;for(;m.test(t)&&l<3;){const[n,r,i]=t.match(m).slice(1),a=r.split(""),o=`${n}-${a[0]} ${a[1]}-${i}`;t=t.replace(m,o),e.push("noSetSeparationPattern"),l+=1}const f=t.match(/(^|\s)7-6\s(\d+)\s/g);if(f?.length){const n=/(^|\s)7-6\s(\d+)\s/;f.forEach((r=>{const i=r.match(n).slice(2)[0];t=t.replace(r,`7-6(${i}) `),e.push("floatingTiebreakPattern1")}))}let h=t.match(/\d \d /);h?.forEach((n=>{const r=n.slice(0,n.length-1).split(" ").join("-");t=t.replace(n,r),e.push("spaceSeparatedSetPattern1")})),h=t.match(/ \d \d$/),h?.forEach((n=>{const r=" "+n.slice(1).split(" ").join("-");t=t.replace(n,r),e.push("spaceSeparatedSetPattern2")}));const g=/^\d, *\d\/\d, *\d/;if(g.test(t)){const n=t.match(g)[0],r=n.split("/").map((t=>`(${t})`)).join(" ")+" ";t=t.replace(n,r),e.push("slashCommaSetPattern")}const I=/\(6-\)/g;I.test(t)&&(t=t.replace(I,"(6-0)"),e.push("missingZeroPattern2"));const U=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(U.test(t)){const n=t.match(U),r=/(?<!-)(\d+)\/(\d+)(?!-)/;let i=t;n.forEach((t=>{const[e,n]=t.match(r).slice(1),a=`${e}-${n}`;i=i.replace(t,a)})),t=i,e.push("slashSetPattern")}const y=/(.*)\s(1\d)\s(\d+)$/;if(y.test(t)){const[n,r,i]=t.match(y).slice(1);n.replace(/\D/g,"").length>=4&&(t=n+` ${r}${i}`,e.push("spaceSeparatedSuperPattern"))}const S=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(const n of t.match(S)||[]){const[r,i,a,o]=n.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[s,c]=i.split("-").map((t=>parseInt(t)));1===Math.abs(s-c)&&(t=t.replace(n,`${r}${i}(${a})${o}`),e.push("spaceSeparatedSetPattern"))}const v=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(const n of t.match(v)||[]){const r=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[i,a,o]=n.match(r).slice(1),[s,c]=i.split("-").map((t=>parseInt(t)));1===Math.abs(s-c)&&(t=t.replace(n,`${i}(${a})${o}`),e.push("floatingTiebreakPattern2"))}const w=/(^|\s)(\d \d)\(/g;for(const n of t.match(w)||[]){const r=/(^|\s)(\d \d)\(/,[i,a]=n.match(r).slice(1);t=t.replace(n,`${i}${a.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}},removeDanglingBits:function({score:t,attributes:e}){(t.endsWith(" am")||t.endsWith(" pm"))&&(t=""),t=t.replace(/[A-Za-z]+/g,"").trim(),[".",","].some((e=>t.endsWith(e)))&&(t=t.slice(0,t.length-1));const n="()/-".split("").some((e=>t.includes(e)));if(/ \d$/.test(t)&&n){e={removed:t.slice(t.length-2).trim()},t=t.slice(0,t.length-2)}const r=/(.*)[A-Za-z]+$/;if(r.test(t)){const e=t.match(r).slice(1)[0];t=e.trim()}return{score:t,attributes:e}},removeErroneous:function({score:t,applied:e}){if("string"!=typeof t)return{score:t};if([3,4].includes(t.length)&&dw(t)){return{score:dw(t)}}return{score:t=t.toLowerCase().split(" ").map((t=>{if(!/^\d+$/.test(t)||1!==t.length)return t;e.push("removeErroneous1")})).filter(Boolean).join(" "),applied:e}},handleWalkover:function({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}},properTiebreak:function({score:t,matchUpStatus:e}){let n=t?.split(" ");t=n.map((t=>{if(t.endsWith("]")){const e=t.split("[");if(iw(e[0]))return e[0]+`(${e[1].slice(0,e[1].length-1)})`}return t})).join(" ");const r=new RegExp(/(\([\d ]+\))/g);if(r.test(t))for(const e of t.match(r)){const n=e.replace(" ","-");let r=n.match(/\((.*)\)/)?.[1];if(h(r)&&r?.[0]>2)if([2,4].includes(r.length))r=r.split("").join("-");else if(3===r.length){const t=r.indexOf("1");r=aw(r.split(""),t)}t=t.replace(e,`(${r})`)}n=t?.split(" ");let i=new RegExp(/^(\d[-/]+\d)\((\d+)[-/]+(\d+)\)$/);const a=n.length-1;t=n.map(((t,n)=>{const r=[void 0,"","COMPLETED"].includes(e)||n!==a;if(i.test(t)&&r){const[e,n,r]=Array.from(t.match(i)).slice(1);return`${e}(${Math.min(n,r)})`}return t})).join(" "),n=t?.split(" "),i=new RegExp(/^(\d{2})\((\d+)\)$/),t=n.map((t=>{if(i.test(t)){const[e,n]=Array.from(t.match(i)).slice(1),r=e.split("");return`${r[0]}-${r[1]}(${n})`}return t})).join(" "),n=t?.split(" "),i=new RegExp(/^\((\d[-/]+\d)\)(\d+)$/),t=n.map((t=>{if(i.test(t)){const[e,n]=Array.from(t.match(i)).slice(1);return iw(e)?`${e}(${n})`:e}return t})).join(" "),n=t?.split(" "),i=new RegExp(/^1-0\((\d+)\)$/),t=n.map((t=>{if(i.test(t)){const[e]=t.match(i).slice(1);return`[${e<9?10:parseInt(e)+2}-${e}]`}return t})).join(" ");const o=/\((\d)+0 /;if(o.test(t)){const e=t.match(o)[1];t=t.replace(o,`(${e}) `)}return{score:t}},handleNumeric:pw,handleRetired:function({score:t,profile:e,applied:n}){t=t?.toString().toLowerCase();const r=/^(.*\d+.*)(ret|con)+[A-Za-z ]*$/;if(r.test(t)){const[e]=t.match(r).slice(1);return n.push("handleRetired"),{score:e.trim(),matchUpStatus:"retired",applied:n}}const i=e?.matchUpStatuses?.retired,a=["rtd",...Array.isArray(i)?i:[i].filter(Boolean)].find((e=>t?.endsWith(e)));return a?(n.push("handleRetired"),{matchUpStatus:"retired",score:t?.replace(a,"").trim(),applied:n}):{score:t}},containedSets:function({score:t,attributes:e,identifier:n}){if("string"!=typeof t)return{score:t,identifier:n};const r=new RegExp(/\([\d,/ ]+\)/g),i=t.match(r);for(const e of i||[]){const n=e.match(/^\((.*)\)$/),r=n?.slice(1)?.[0],i=t.split(e)[0].split(")").reverse()[0].replace(/\D/g,"");if(2===r?.length&&i?.length>=2){const t=i.slice(i.length-2).split("").map((t=>parseInt(t)));if(1===Math.abs(t[0]-t[1]))continue}const a=cw(ow(r));t=t.replace(e,`(${a})`).trim()}const a=new RegExp(/\[[\d,/ ]+\]/g),o=t.match(a);o?.forEach((e=>{const n=ow(e.match(/^\[(.*)\]$/)[1]);t=t.replace(e,`(${n}) `).trim()}));const s=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&[")","]"].some((e=>t.endsWith(e)))&&s.some((e=>t.includes(e)))){let e="";const n=t.split(/[)\]]/).filter(Boolean).map((t=>(t.startsWith(",")&&(t=t.slice(1)),t.trim()))),r=n.every((t=>t.includes(",")||rw(t))),i=n.every((t=>t.includes("/")||rw(t))),a=n.every((t=>t.includes("-")||rw(t))),o=(r?",":a&&"-")||i&&"/";if(o){let r;n.forEach((t=>{if(t.startsWith("("))if("set"===r&&(e+=" "),t.includes(o))e+=t.slice(1).split(o).map((t=>t.trim())).join("-"),r="set";else{const n=t.slice(1);e+=`(${n}) `,r="tiebreak"}else if(t.startsWith("[")){const n=t.slice(1).split(o).map((t=>parseInt(t.trim()))),i=Math.min(...n);e+="set"===r?`(${i}) `:`[${n.join("-")}] `,r="tiebreak"}})),t=e.trim()}}const c=T(t.split(""));1===c["("]&&1===c[")"]&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),1===c["-"]&&iw(t)&&h(e?.removed)&&(t+=`(${e.removed})`,e.removed=void 0));const u=/\(\)/g;return u.test(t)&&(t=t.replace(u,"").trim()),{score:t}},sensibleSets:function({score:t,matchUpStatus:e,attributes:n}){const r=[];let i;const a=t.split(" "),o=a.length;t=a.map(((t,n)=>{if(new RegExp(Qv).test(t)){const n=t.slice(3),r=t.slice(0,3),i=r.split("-");if(!iw(r)&&!e){const t=Math.max(...i),e=[t,t-1];r.indexOf(t)&&e.reverse();return e.join("-")+n}}else if(2===t.length&&h(t))return t.split("").join("-");t=cw(t);const a=(new RegExp(`^${Jv}$`).test(t)?"super":new RegExp(`^${Qv}$`).test(t)&&"tiebreak")||new RegExp(`^${Kv}$`).test(t)&&"standard"||"unknown";if(r.push(a),o>1&&"standard"===a&&n<2){const[e,r]=t.split("-"),a=Math.abs(parseInt(e)-parseInt(r)),o=Math.max(e,r),s=Math.min(e,r),c=[parseInt(e),parseInt(r)].indexOf(s);if(o>9&&a>2){const e=o.toString().split(""),r=e.find((t=>parseInt(t)>s||n&&parseInt(t)<=i))??e[0];r&&(t=c?[r,s].join("-"):[s,r].join("-"))}o>(i||0)&&(i=o)}if("standard"===a){const[n,r]=t.split("-");if(!Math.abs(parseInt(n)-parseInt(r))&&"RETIRED"!==e)return""}return t})).filter(Boolean).join(" ");const{setsWon:s,setWinners:c,totalSets:u}=lw(t);if(1===u&&"6"===n?.removed&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...s)>=2&&c[0]===c[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...s)>2){const e=[0,0];t=t.split(" ").map(((t,n)=>(e[c[n]]+=1,Math.max(...e)>2?void 0:t))).filter(Boolean).join(" ")}return{score:t,profile:r}},stringScore:function({score:t}){return{score:t=t?.toString().toLowerCase()||""}},superSquare:function({score:t}){const{setsTied:e,winningSide:n}=lw(t),r=/\s\((\d+)\)$/;if(!n&&e&&r.test(t)){const e=t.match(r).slice(1)[0],n=e<=8?10:e+2;t=t.replace(r,` [${n}-${e}]`)}const i=t.split(" "),a=i[i.length-1];if(!a.includes("-")||a.indexOf("(")>0)return{score:t};let o=a.split("(").join("").split(")").join("").split("-");if(!o.every((t=>h(t))))return{score:t};if("76"===o[0]){const e=2===o[1].length?Math.min(...o[1].split("").map((t=>parseInt(t)))):o[1];t=[...i.slice(0,i.length-1),`7-6(${e})`].join(" ")}else{o=o.map((t=>parseInt(t)));const e=Math.max(...o);let n=Math.abs(o[0]-o[1]);if(e>=10){if(n>2&&o.every((t=>+t>=10))){const t=o.map((t=>t===e?t-10:10)).sort();n=Math.abs(t[0]-t[1]),n>2&&(o=t)}t=[...i.slice(0,i.length-1),`[${o.join("-")}]`].join(" ")}else 3===i.length&&e>=7&&n>2&&(t=[...i.slice(0,i.length-1),`[${o.join("-")}]`].join(" "))}return{score:t}},setBuilder:uw,excisions:function({score:t}){const e=new RegExp(/^\[\d+\](.*)$/);e.test(t)&&(t=t.match(e).slice(1)[0].trim());const n=/\(,/g;return n.test(t)&&(t=t.replace(n,"(")),{score:t}},replaceOh:function({score:t,applied:e}){return"string"!=typeof t?{score:t}:(t.toLowerCase().includes("o")&&(t=t.toLowerCase().split(" ").map((t=>t.split("o").join("0"))).join(" "),e.push("replaceOh")),{score:t,applied:e})}};let fw={};const hw=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],gw=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function Iw(t){if(!t.score)return{error:Jn};const{score:e,sheetName:n,identifier:r,fileName:i,stepLog:a,fullLog:o,profile:s}=t,c=[];let u,d,p,l=[],m=e;const f=t=>{t.forEach((t=>{p=mw[t]({profile:s,identifier:r,matchUpStatus:u,attributes:d,applied:l,score:m});const e=p.score!==m;e&&c.push({method:t,score:p.score}),a&&(o||e||p.matchUpStatus!==u)&&(u?console.log({score:p.score,matchUpStatus:u},t):console.log({score:p.score},t)),p.matchUpStatus&&(u=p.matchUpStatus),p.attributes&&(d=p.attributes),p.applied&&(l=p.applied),m=p.score}))};f(hw);let h=nw(m);return h||(m=e.toString().replace(/\D/g,""),d?.removed&&(d.removed=void 0),f(gw),h=nw(m),h||(m="")),l.forEach((t=>{fw[t]||(fw[t]=0),fw[t]+=1})),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:d,isValid:h,score:m}}function Uw({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i}){const a=i?.sets??[],o=(a?.filter((t=>t?.winningSide))||[]).reduce(((t,e)=>{const{winningSide:n}=e;if(!n)return t;return t[n-1]++,t}),[0,0]),s=r?r-1:void 0,c=void 0!==s?1-s:void 0,u=void 0!==s&&o[s],d=void 0!==c&&o[c],p=e?Ii(e):void 0,l=Math.max(...o),m=T(o)[l],f=p?.setFormat?.timed||p?.finalSetFormat?.timed,h=p?.bestOf,g=h&&Math.ceil(h/2)||1,I=n??t,U=I&&[Lu,$u,zu].includes(I),y=!p||!a.length||a.every(((t,e)=>{const n=e+1,r=n===h,i=n===a.length,{side1Score:o,side2Score:s,side1TiebreakScore:c,side2TiebreakScore:u,winningSide:d}=t,l=Math.max(o??0,s??0),m=c??u,{finalSetFormat:f,setFormat:g}=p,I=r&&f||g;if(m){const{tiebreakTo:t,NoAD:e}=I?.tiebreakFormat||{},n=Math.max(c??0,u??0);if(e&&n>t)return!1;if(n<t&&d){if(i&&!U)return!1;if(!i)return!1}}if(!I.setTo)return!0;return!(!I.noTiebreak&&l>I.setTo+1)})),S=(!e||l===g)&&1===m&&o.indexOf(l)+1||void 0;return{valid:!(!y||!(r&&u>d&&r===S||r&&U||!r&&!S&&(![xu,Lu,$u,zu].includes(I)||f&&I===xu)))}}function yw({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i}){if("object"!=typeof i)return{error:Jn};const{sets:a,scoreStringSide1:o,scoreStringSide2:s}=i,c="scoreString must be a string!";if(void 0!==o&&"string"!=typeof o)return{error:Jn,info:c};if(void 0!==s&&"string"!=typeof s)return{error:Jn,info:c};if(void 0!==a&&!Array.isArray(a))return{error:Jn,info:ug("sets")};if(a?.length){const o=a.map((t=>t?.setNumber)).filter(Boolean);if(o.length!==w(o).length)return{error:Jn,info:"setNumbers not unique"};for(const t of a){const{side1Score:e,side2Score:n,side1TiebreakScore:r,side2TiebreakScore:i,side1PointScore:a,side2PointScore:o,winningSide:s,setNumber:c}=t;if(![[e,n],[r,i],[a,o]].filter((t=>t.some((t=>![void 0,null].includes(t))))).every((t=>t.every((t=>y(t))))))return{error:Jn,info:"non-numeric values"};if(![c,s].filter((t=>![void 0,null].includes(t))).every((t=>y(t))))return{error:Jn,info:"non-numeric values"};if(s&&![1,2].includes(s))return{error:Jn,info:"winningSide must be 1 or 2"}}const{valid:s}=Uw({existingMatchUpStatus:t,matchUpStatus:n,matchUpFormat:e,winningSide:r,score:i});if(!s)return{error:_e,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}const Sw=t=>{const{isSide1:e,lowValue:n,setTo:r,tiebreakAt:i,NoAD:a}=t;if(void 0===n)return!1;let o,s=d(n);s?.toString().length>2&&(s=parseInt(s.toString().slice(0,2))),i&&i<r&&s>i&&(s=i),a&&!i?(s>r&&(o=r),o=s<r?r:r-1):o=s+1<r&&r||i&&i<r&&s===i&&r||!i&&s+2||r+1;return[e?s:o,e?o:s]},vw=t=>{const{isSide1:e,lowValue:n,tiebreakTo:r,tiebreakNoAd:i}=t;if(void 0===n)return!1;let a="string"==typeof n?parseInt(n):n;a?.toString().length>2&&(a=parseInt(a.toString().slice(0,2))),i&&a>r-1&&(a=r-1);const o=function(t){const{lowValue:e,NoAD:n,tiebreakTo:r}=t,i=n?1:2;if(e+1>=r)return e+i;return r}({lowValue:a,NoAD:i,tiebreakTo:r});return[e?a:o,e?o:a]};function ww({tiebreakTo:t=7,scoreString:e=""}){return e?.split(" ").filter(Boolean).map(((e,n)=>function({set:e,setNumber:n}){const r=/\[([^)]+)\]/,i=/\(([^)]+)\)/.exec(e),a=r.exec(e),o=e?.startsWith("[")&&a&&a[1].split("-").map((t=>parseInt(t))),s=i&&e.replace(i[0],"")||a&&e.replace(a[0],"")||e,c=!o&&s.split("-").map((t=>parseInt(t))),u=o?(o[0]>o[1]?1:o[0]<o[1]&&2)||void 0:(c[0]>c[1]?1:c[0]<c[1]&&2)||void 0,d=i?i[1]:void 0,p=(d&&vw({lowValue:d,isSide1:2===u,tiebreakTo:t}))??[],[l,m]=c||[],[f,h]=o||p||[];return{side1Score:l,side2Score:m,side1TiebreakScore:f,side2TiebreakScore:h,winningSide:u,setNumber:n}}({set:e,setNumber:n+1})))}function Pw(t){const{setObject:e,matchUpScoringFormat:n}=t;if(!e)return{error:De};const{setNumber:r}=e||{},{bestOf:i,exactly:a}=n||{},o=i||a,s=!(!r||!o||r!==o),c=s&&n?.finalSetFormat||n?.setFormat,u=!!c?.tiebreakSet,d=!!c?.timed,p=!u&&!d,l=!!(r&&o&&r<=o),m=[e?.side1Score,e?.side2Score],f=[e?.side1PointScore,e?.side2PointScore],h=[e?.side1TiebreakScore,e?.side2TiebreakScore],g=m.filter((t=>void 0!==t)).length,I=f.filter((t=>void 0!==t)).length,U=h.filter((t=>void 0!==t)).length,y=m?.filter((t=>!isNaN(t))).length,S=h?.filter((t=>!isNaN(t))).length,{tiebreakAt:v}=c||{},w=v&&2===m.filter((t=>t>=v)).length,P=w&&((m[0]>m[1]?1:m[1]>m[0]&&2)||void 0),D=!(!S||y),T=!!e?.winningSide,{error:b,result:R}=function({setObject:t,setFormat:e,sideGameScores:n,sideTiebreakScores:r}){if(!t)return{result:!1,error:De};const i=!!e?.tiebreakSet,a=!!e?.timed;if(!e||i||a)return{result:!1,error:Jn};const o=2===n?.filter((t=>!isNaN(t))).length;if(!o)return{result:!1,error:xe};const{setTo:s,tiebreakAt:c,tiebreakFormat:u,NoAD:d}=e||{},p=!(!s||!n?.find((t=>t>=s)));if(!p)return{result:!1,error:xe};const l=[1,2].includes(t?.winningSide);if(!t||!l)return{result:!1,error:Le};const m=t?.winningSide-1,f=1-m,h=n[m],g=n[f],I=h-g;if(!(h>g))return{result:!1,error:{message:"winningSide game scoreString is not high"}};const U=c&&u,y=2===r?.filter((t=>!isNaN(t))).length,S=r?.[m],v=r?.[f],w=c&&2===n.filter((t=>t>=c)).length;if(U){const{NoAD:t,tiebreakTo:e}=u;if(w){if(I>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!y)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(e))return{result:!1,error:{message:"tiebreakTo error"}};if(!!(!e||!r?.find((t=>t>=e))))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};if(h>(c<s?s:s+1))return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!S||!v||S<v)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};const n=S-v;if(n&&v>=e-1&&n<(t?1:2))return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(h>s&&!w)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}const P=d?1:2,D=g>=s-1,T=I&&D&&!w&&I<P;if(T)return{result:!1,error:{message:"invalid winning game scoreString (3)"}};if(I>P&&h>s)return{result:!1,error:{message:"invalid winning game scoreString (4)"}};return{result:!0}}({sideTiebreakScores:h,sideGameScores:m,setFormat:c,setObject:e}),{error:M,result:N}=function({setObject:t,setFormat:e,sideTiebreakScores:n}){if(!t)return{result:!1,error:De};const r=!!e?.tiebreakSet,i=!!e?.timed;if(!e||!r||i)return{result:!1,error:{message:"not tiebreak set"}};const a=[1,2].includes(t?.winningSide);if(!t||!a)return{result:!1,error:Le};const{tiebreakSet:o}=e||{},{NoAD:s,tiebreakTo:c}=o||{},u=2===n?.filter((t=>!isNaN(t))).length;if(!u)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(c))return{result:!1,error:{message:"tiebreakTo error"}};const d=!!n?.find((t=>t>=c));if(!d)return{result:!1,error:{message:"invalid tiebreak scores (2)"}};const p=t?.winningSide-1,l=1-p,m=n[p],f=n[l];if(!m||!f||m<f)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};const h=s?1:2,g=m-f,I=f>=c-1;if(g&&I&&g<h)return{result:!1,error:{message:"invalid tiebreak scores (3)"}};return{result:!0}}({sideTiebreakScores:h,setObject:e,setFormat:c}),A=p&&!D&&R||u&&D&&N||d,E=l&&!(u&&!D)&&!(p&&D)&&(!T||A),C=function({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:n,isTimedSet:r,setObject:i}){if(!i)return;const a=$v({set:i});return qv({matchUpScoringFormat:t,set:i,isDecidingSet:e,isTiebreakSet:n,isTimedSet:r})&&a||void 0}({isTimedSet:d,matchUpScoringFormat:n,isDecidingSet:s,isTiebreakSet:D,setObject:e}),O={expectTiebreakSet:u,expectTimedSet:d,hasTiebreakCondition:w,isCompletedSet:T,isDecidingSet:s,isTiebreakSet:D,isValidSet:E,isValidSetNumber:l,isValidSetOutcome:A,leadingSide:P,setFormat:c,sideGameScores:m,sideGameScoresCount:g,sidePointScores:f,sidePointScoresCount:I,sideTiebreakScores:h,sideTiebreakScoresCount:U,winningSide:C};return void 0!==e?.winningSide&&(D?(O.isValidTiebreakSetOutcome=N,N||(O.tiebreakSetError=M)):(O.isValidStandardSetOutcome=R,R||(O.standardSetError=b))),O}var Dw={__proto__:null,addGame:nv,addPoint:ev,addSet:iv,addShot:rv,analyzeScore:Uw,analyzeSet:Pw,calculateHistoryScore:JS,checkScoreHasValue:vf,checkSetIsComplete:qv,clearHistory:tv,generate:KS,generateScoreString:HS,generateTieMatchUpScore:QU,getSetComplement:Sw,getTiebreakComplement:vw,helpers:{__proto__:null,keyValueScore:Yv,parseMatchUpFormat:Ii,stringifyMatchUpFormat:li,tidyScore:Iw},isValidMatchUpFormat:Di,keyValueScore:Yv,mutate:cv,parseMatchUpFormat:Ii,parseScoreString:ww,query:{__proto__:null,analyzeScore:Uw,analyzeSet:Pw,checkScoreHasValue:vf,checkSetIsComplete:qv,getSetComplement:Sw,getTiebreakComplement:vw,isValidMatchUpFormat:Di,parseScoreString:ww,validateScore:yw,validateTieFormat:sa},redo:av,reverseScore:YS,setServingSide:XS,stringifyMatchUpFormat:li,tidyScore:Iw,umo:sv,undo:ov,validateScore:yw,validateTieFormat:sa};function Tw(t){const e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:n,appliedPolicies:r,qualifyingOnly:i,drawEntries:a,structureId:o,tieFormat:s,idPrefix:c,isMock:u,event:d}=t,p=t.qualifyingProfiles,l=p?.length?US({hasExistingDrawDefinition:!0,uuids:t.uuids,qualifyingProfiles:p,appliedPolicies:r,qualifyingOnly:i,tieFormat:s,idPrefix:c,isMock:u}):void 0;if(l?.error)return l;e.structures=e.structures?.filter((({structureId:t})=>t!==n)),e.links=e.links?.filter((({source:t})=>t.structureId!==n));const{qualifiersCount:m,qualifyingDrawPositionsCount:f,qualifyingDetails:h}=l??{};f&&(l?.structures&&e.structures?.push(...l.structures),l?.links&&e.links?.push(...l.links));const g=e.structures?.find((({stage:t,stageSequence:e})=>t===fo&&1===e)),{qualifiersCount:I}=oh({stageSequence:1,drawDefinition:e,structureId:o,stage:fo});let U=mI({qualifiersCount:Math.max(m??0,I??0),drawDefinition:e,stage:fo});if(U.error)return U;if(U=lI({drawSize:f,stage:ho,drawDefinition:e}),U.error)return U;!function({drawDefinition:t,drawEntries:e,event:n}){for(const r of(e??[]).filter((({entryStage:t})=>t===ho))){dh({...r,entryStage:r.entryStage??fo,drawDefinition:t,event:n})}}({drawDefinition:e,drawEntries:a,event:d});const y=function({mainStructure:t,qualifyingDetails:e,drawDefinition:n}){for(const r of e||[]){const{finalQualifyingRoundNumber:e,finalQualifyingStructureId:i,roundTarget:a,finishingPositions:o,linkType:s}=r,c=t&&_I({targetStructureId:t.structureId,sourceStructureId:i,sourceRoundNumber:e,finishingPositions:o,targetEntryRound:a,linkType:s})?.link;if(c?.error)return c;c&&(n.links||(n.links=[]),n.links.push(c))}return{error:void 0}}({mainStructure:g,qualifyingDetails:h,drawDefinition:e});return y.error?y:{drawDefinition:e,structureId:o}}function bw(t){let{participantIds:e}=t;const n=t.drawDefinition?.entries?.filter((e=>{const n=e.entryStatus;return!t.restrictEntryStatus||al.includes(n)})).map(Mu)??[];if(e){const t=e.filter((t=>!n?.includes(t)));if(t?.length)return ti({result:{error:He},info:{invalidParticipantIds:t}})}else e=n;return t.roundsCount&&!1!==t.restrictRoundsCount&&t.roundsCount>e.length-1&&(!t.enableDoubleRobin||t.roundsCount>2*(e.length-1))?{error:Jn,info:"Not enough participants for roundsCount"}:t.roundsCount&&!1!==t.restrictRoundsCount&&t.roundsCount>31?{error:Jn,info:"roundsCount must be less than 32"}:{participantIds:e}}function Rw(t){const e=[],{roundsCount:n=1,drawDefinition:r,matchUpsCount:i,structureId:a,idPrefix:o,isMock:s,event:c}=t;let u;const d=bw(t);if(d.error)return d;for(const d of E(1,n+1)){const n=kS({restrictMatchUpsCount:t.restrictMatchUpsCount,ignoreLastRoundNumber:!!u,newRound:!u,drawDefinition:r,matchUpsCount:i,structureId:a,roundNumber:u,idPrefix:o,isMock:s,event:c});if(n.error)return ti({result:n,info:{iteration:d}});n.matchUps?.length&&e.push(...n.matchUps),u=(n?.roundNumber??1)+1}return{matchUps:e}}function Mw({scaleType:t=lc,scaleAccessor:e,participant:n,scaleName:r,eventType:i}){const a=n&&$f({scaleAttributes:{eventType:i??so,scaleType:t,scaleName:r},participant:n}),o=a?.scaleItem?.scaleValue;return e&&G(o)?o[e]:o}function Nw(t){const e=function(t){if(t.roundsCount&&"number"!=typeof t.roundsCount)return{error:Jn,info:"roundsCount must be a number"};if("object"!=typeof t.drawDefinition||t.drawDefinition.drawType&&t.drawDefinition.drawType!==_o)return{error:at};if(!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds))return{error:Jn,info:"Missing Entries"};return{error:void 0}}(t);if(e?.error)return e;const n=bw(t);if(n.error)return n;const r=function(t){if(t.structureId)return t.structureId;const e=t.drawDefinition,n=e?.structures?.filter((t=>1===t.stageSequence))?.reduce(((t,e)=>{const n=e.stage&&So[e.stage];return Dl({structure:e})&&n>(So[t?.stage]||1)?e:t}),void 0),r=e?.structures?.find((t=>t.structureId===n?.structureId));if(!r)return{error:Lt};return Dl({structure:r})?{structure:r}:{error:at}}(t);if(r.error)return r;let i=function(t){const{tournamentRecord:e,participantIds:n,scaleName:r,eventType:i,adHocRatings:a={}}=t,o=t.scaleAccessor??hU[r]?.accessor,s=e.participants??[];for(const t of n??[]){const e=s?.find((e=>e.participantId===t));let n=Mw({scaleName:`${r}.${dc}`,participant:e,eventType:i});!n&&r&&(n=Mw({scaleAccessor:o,participant:e,scaleName:r,eventType:i})),n&&!a[t]&&(a[t]=n)}return a}(t);const a=t.tournamentRecord?.isMock??t.isMock,o=t.eventType??t.event?.eventType,s=[],c=[];let u;for(const e of E(1,(t.roundsCount??1)+1)){const d=$S({...t,participantIds:n.participantIds,structure:r.structure,ignoreLastRoundNumber:!0,iterationMatchUps:s,adHocRatings:i,roundNumber:u,eventType:o,isMock:a});if(d.error)return d;const{matchUps:p,...l}=d;l.modifiedScaleValues&&(i=l.modifiedScaleValues),c.push({...l,iteration:e,matchUpsCount:p?.length}),u=(l?.roundNumber??1)+1,p?.length&&s.push(...p)}return{...z,matchUps:s,roundResults:c}}function Aw(t){const{tournamentRecord:e,drawDefinition:n,structureId:r,idPrefix:i,isMock:a,event:o}=t,s=o?.entries?.filter((({entryStage:t,entryStatus:e})=>(!t||t===fo)&&e&&al.includes(e))),c=s?.map(Mu),u=s?Math.floor(s.length/2):0;if(t.automated)return function(t){const{restrictEntryStatus:e,generateMatchUps:n,structureId:r,matchUpIds:i,scaleName:a,scaleAccessor:o}=t.drawMatic??{},s=Nw({...t,eventType:t.drawMatic?.eventType??t.matchUpType,generateMatchUps:n??!0,scaleAccessor:o??t.scaleAccessor,scaleName:a??t.scaleName,participantIds:t.participantIds,roundsCount:t.roundsCount,restrictEntryStatus:e,structureId:r,matchUpIds:i});return s.error?s:(s?.matchUps?.length&&Dy({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:s.matchUps,event:t.event,structureId:r}),{...z})}({...t,participantIds:c});{const s=Rw({roundsCount:t.roundsCount,drawDefinition:n,matchUpsCount:u,idPrefix:i,isMock:a,event:o});if(s.error)return s;s.matchUps?.length&&Dy({matchUps:s.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:n,structureId:r,event:o})}return{...z}}function Ew({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:n,scaleSortMethod:r,stageSequence:i,entries:a,event:o,stage:s}){if(!e)return{error:nt};return{scaledEntries:(a=a??o?.entries??[]).filter((t=>(!s||!t.entryStage||t.entryStage===s)&&(!i||!t.entryStageSequence||t.entryStageSequence===i)&&al.includes(t.entryStatus))).map((t=>{const{participantId:r}=t,{scaleItem:i}=ES({tournamentRecord:e,scaleAttributes:n,participantId:r});return{...t,...i}})).filter((t=>{const e=t.scaleValue;return!!(r||!isNaN(e)&&parseFloat(e))&&e})).sort(r||function(e,n){return t?c(n)-c(e):c(e)-c(n)})};function c(e){return parseFloat(e.scaleValue||(t?-1:1e5))}}function Cw(t){const e="prepareStage",{drawDefinition:n}=t,{structures:r}=od({stageSequence:t.stageSequence||1,roundTarget:t.roundTarget,stage:t.stage,drawDefinition:n}),i=t.preparedStructureIds||[],a=r?.find((({structureId:t})=>!i.includes(t)));if(!a)return ti({result:{error:Lt},stack:e});const o=a?.structureId,{seedsCount:s,stageEntries:c,seedLimit:u}=function(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length);e>t.drawSize&&(e=t.drawSize);const n=function({entries:t,stage:e,stageSequence:n,roundTarget:r}){return t.filter((t=>{const i=zc({name:pu,element:t})?.extension?.value;return(!t.entryStage||t.entryStage===e)&&(!n||!t.entryStageSequence||t.entryStageSequence===n)&&(!r||!i||i===r)&&il.includes(t.entryStatus)}))}(t);e>n.length&&(e=n.length);const{seedLimit:r}=function({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:n,participantsCount:r,participantCount:i,appliedPolicies:a,drawDefinition:o,seedingProfile:s,structureId:c,seedsCount:u}){r=r??i;const d=ad({drawDefinition:o,structureId:c});if(d.error)return d;const p=d.structure;if(!p)return{error:Lt};const{positionAssignments:l}=ud({structure:p}),m=l?.length||0;if(u>m)return{error:Mt};const f=p.structures?.length,h=y(s?.groupSeedingThreshold)&&s?.groupSeedingThreshold,g=Wh({roundRobinGroupsCount:f,drawSize:m})?.seedGroups,{seedsCount:I}=hS({policyDefinitions:a,requireParticipantCount:t,drawSizeProgression:n,participantsCount:r,drawSize:m});return I&&a?.[Ac]&&u>I&&e&&(u=I),p.seedLimit=u,p.seedAssignments=E(1,u+1).map((t=>{const e=g?.find((e=>e.includes(t))),n=e&&Math.min(...e);return{participantId:void 0,seedNumber:t,seedValue:h&&t>=h?n:t}})),Hd({drawDefinition:o,structureIds:[c]}),{...z,seedLimit:u}}({enforcePolicyLimits:t.enforcePolicyLimits??!0,appliedPolicies:t.appliedPolicies,participantsCount:n.length,seedingProfile:t.seedingProfile,drawDefinition:t.drawDefinition,structureId:t.structureId,seedsCount:e});r&&r<e&&(e=r);return{seedsCount:e,stageEntries:n,seedLimit:r}}({...t,structureId:o});(t.seededParticipants||t.event||t.seedingScaleName)&&function(t){const{seededParticipants:e,seedingScaleName:n,entries:r,event:i}=t,a=r.map(Mu);e?function(t){const{provisionalPositioning:e,enteredParticipantIds:n,seededParticipants:r,tournamentRecord:i,appliedPolicies:a,drawDefinition:o,seedingProfile:s,structureId:c,structure:u,event:d}=t,p=u?Kh({provisionalPositioning:e,appliedPolicies:a,drawDefinition:o,seedingProfile:s,structure:u}):void 0;r.filter((({participantId:t})=>n.includes(t))).filter((t=>!t.seedNumber||t.seedNumber<=r.length)).sort(((t,e)=>t.seedNumber<e.seedNumber?-1:t.seedNumber<e.seedNumber?1:0)).forEach((t=>{const{participantId:n,seedNumber:r,seedValue:a}=t;tg({provisionalPositioning:e,tournamentRecord:i,drawDefinition:o,seedingProfile:s,participantId:n,seedBlockInfo:p,structureId:c,seedNumber:r,seedValue:a,event:d})}))}({...t,enteredParticipantIds:a}):(i||n)&&function(t){let e=t.seedsCount;const{provisionalPositioning:n,enteredParticipantIds:r,seedAssignmentProfile:i,assignSeedsCount:a,tournamentRecord:o,drawDefinition:s,seedByRanking:c,seedingProfile:u,structureId:d,event:p}=t,{categoryName:l,ageCategoryCode:m}=p?.category||{};const f=function(t){const{tournamentRecord:e,seedingScaleName:n,stageSequence:r,entries:i,stage:a,event:o}=t,{categoryName:s,ageCategoryCode:c}=o?.category||{},u=o?.eventType,d={scaleName:n||s||c||o.eventId,scaleType:fc,eventType:u};return Ew({scaleAttributes:d,tournamentRecord:e,stageSequence:r,entries:i,stage:a}).scaledEntries}({...t})||c&&function(t){const{tournamentRecord:e,stageSequence:n,event:r,entries:i,stage:a}=t,{categoryName:o,ageCategoryCode:s}=r?.category||{},c=r?.eventType,u={scaleName:o||s,scaleType:pc,eventType:c};return Ew({scaleAttributes:u,tournamentRecord:e,stageSequence:n,entries:i,stage:a}).scaledEntries}({...t}),h=f?.length??0;h<e&&(e=h);f?.filter((({participantId:t})=>r.includes(t))).slice(0,a||e).forEach(((t,e)=>{const r=e+1,{participantId:a,scaleValue:c}=t;tg({provisionalPositioning:n,tournamentRecord:o,drawDefinition:s,seedingProfile:u,participantId:a,structureId:d,seedNumber:r,seedValue:i?.[r]||c||r,event:p})}))}({...t,enteredParticipantIds:a})}({...t,seedsCount:s,structure:a,structureId:o});const d=!1!==t.automated&&t.drawType!==_o&&!(t.qualifyingOnly&&t.stage!==ho),p=(r?.length||0)>1,l=d?function(t){const e="object"==typeof t.automated&&t.automated.seedsOnly,n=Qg({...t,seedsOnly:e});if(n.error)return n;const r=n?.positionAssignments,i=n?.positioningReport;return{conflicts:n.conflicts,positionAssignments:r,positioningReport:i}}({...t,multipleStructures:p,seedLimit:u,structureId:o}):{};return l?.error?ti({result:l,stack:e}):{...l,stageEntries:c,structureId:o,seedsCount:s}}function Ow(t){const e=TS({...t,modifyOriginal:!1});if(e.error)return e;const n=e.drawDefinition,{suppressDuplicateEntries:r=!0,ignoreStageSpace:i,appliedPolicies:a,qualifyingOnly:o,seedingProfile:s,participants:c,drawEntries:u,placeByes:p,drawSize:l,drawType:m,entries:f}=t,h=[];let g=[];const I=function(t){const{ignoreStageSpace:e,drawDefinition:n,drawEntries:r,drawType:i,entries:a}=t;for(const o of a){if(r&&o.entryStage&&o.entryStage!==fo)continue;const a=dh({...o,ignoreStageSpace:e??i===_o,entryStage:o.entryStage??fo,event:t.event,drawDefinition:n,drawType:i});if(r&&a.error)return a}return{error:void 0}}({ignoreStageSpace:i,drawDefinition:n,drawEntries:u,drawType:m,entries:f});if(I.error)return I;const U=m===Wo?0:d(t.seedsCount??0),y=Cw({...t,qualifyingOnly:!l||o,appliedPolicies:a,drawDefinition:n,seedingProfile:s,participants:c,stage:fo,seedsCount:U,placeByes:p,drawSize:l,entries:f});if(y.error&&!y.conflicts)return y;y.positioningReport?.length&&h.push({[fo]:y.positioningReport});const S=y.structureId;return y.conflicts&&(g=y.conflicts),m===_o&&t.roundsCount&&Aw({...t,drawDefinition:n,structureId:S}),{drawDefinition:n,positioningReports:h,conflicts:g,structureId:S}}function Fw(t){let e=t.structureIds;const{tournamentRecord:n,drawDefinition:r,matchUpFormat:i,structureId:a,matchUpId:o,event:s}=t,c=cc(t,[{[Is]:!0,[ys]:!0}]);if(c.error)return c;if(!Di({matchUpFormat:i}))return{error:ne};if(o){const t=GU({drawDefinition:r,matchUpId:o,event:s});if(t.error)return t;const e=t.matchUp;if(e?.matchUpType===po)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:he};e&&(e.matchUpFormat=i,$d({tournamentId:n?.tournamentId,eventId:s?.eventId,context:"setMatchUpFormat",drawDefinition:r,matchUp:e}))}else if(Array.isArray(e)){if(s?.eventType===po)return{error:qt};for(const t of e){const e=ad({drawDefinition:r,structureId:t});if(e.error)return e;e.structure&&(e.structure.matchUpFormat=i)}}else if(a){if(s?.eventType===po)return{error:qt};const t=ad({drawDefinition:r,structureId:a});if(t.error)return t;t.structure&&(t.structure.matchUpFormat=i)}else r&&(r.matchUpFormat=i);return e=e??(a?[a]:void 0),Hd({drawDefinition:r,structureIds:e}),{...z}}function kw({existingQualifyingStructures:t,tournamentRecord:e,drawDefinition:n,matchUpFormat:r,matchUpType:i,tieFormat:a,event:o}){if(r||a){if(!(r&&o?.matchUpFormat===r||o?.tieFormat&&a&&JSON.stringify(o.tieFormat)===JSON.stringify(a))){if(a){const e=function({tieFormat:t}){const e=sa({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(const e of t.collectionDefinitions)e.collectionId||(e.collectionId=ha());return{tieFormat:t}}({tieFormat:a});if(e.error)return e;const r=t?.every((t=>t.tieFormat));t?.length&&!r||(n.tieFormat=e.tieFormat??a)}else if(r){const t=Fw({tournamentRecord:e,drawDefinition:n,matchUpFormat:r,event:o});if(t.error)return{info:"matchUpFormat or tieFormat error",error:t.error}}i&&(n.matchUpType=i)}}return{error:void 0}}function xw(t){const e=cc(t,[{[Ns]:!0,_anyOf:{[ms]:!1,[hs]:!1,[Is]:!1,[Ws]:!1}}]);if(e.error)return e;let n;const r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r)return _w(t,r);if(!t.tournamentRecords)return{error:nt};{const e=Object.keys(t.tournamentRecords);if(!e.length)return{error:nt};for(const r of e){const e=_w(t,t.tournamentRecords[r]);if(e.error)return e;n=!0}}return n?{...z}:{error:we}}function _w(t,e){const n=Np(t).appliedPolicies??{};if(n[t.policyType]){if(delete n[t.policyType],Object.keys(n).length){_c({element:e,extension:{name:Yc,value:n}})}else kc({element:e,name:Yc});return{...z}}return{error:we}}var Lw={__proto__:null,attachPolicies:my,findPolicy:Bp,getAppliedPolicies:Np,getPolicyDefinitions:Ap,mutate:{__proto__:null,attachPolicies:my,removePolicy:xw},query:{__proto__:null,findPolicy:Bp,getAppliedPolicies:Np,getPolicyDefinitions:Ap},removePolicy:xw};const Bw={[Ac]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[is]:{positioning:bo},[rs]:{positioning:bo}},positioning:"SEPARATE"},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}]}};function Vw({appliedPolicies:t,policyDefinitions:e,drawDefinition:n,stack:r}){if(e&&"object"!=typeof e)return ti({info:"policyDefinitions must be an object",result:{error:Jn},stack:r});const i={[Mc]:t?.[Mc]};return e?function({policyDefinitions:t,appliedPolicies:e,policiesToAttach:n,drawDefinition:r}){for(const r of Object.keys(t))JSON.stringify(e?.[r])!==JSON.stringify(t[r])&&(n[r]=t[r]);Object.keys(n).length&&(my({policyDefinitions:n,drawDefinition:r}),e&&Object.assign(e,n))}({policyDefinitions:e,appliedPolicies:t,policiesToAttach:i,drawDefinition:n}):i.avoidance&&my({drawDefinition:n,policyDefinitions:i}),t?.[Ac]||e?.[Ac]||(my({policyDefinitions:Bw,drawDefinition:n}),t&&Object.assign(t,Bw)),{error:void 0}}function jw(t){const{tournamentRecord:e,policyDefinitions:n,appliedPolicies:r,matchUpFormat:i,matchUpType:a,tieFormat:o,drawType:s,stack:c,event:u}=t,d=t.drawId?u?.drawDefinitions?.find((e=>e.drawId===t.drawId)):void 0,p=d?.structures?.find((t=>t.stage===fo&&1===t.stageSequence))?.structureId,l=d?d.structures?.filter((t=>t.stage===ho)):[],m=1===l?.length&&!l[0].matchUps?.length&&l[0].structureId;d&&s!==d.drawType&&(d.drawType=s);const f=d??function(t){const{drawId:e=ha(),processCodes:n,matchUpType:r,drawType:i}=t??{},a={matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]};return Object.assign(a,{processCodes:n,matchUpType:r,drawType:i,drawId:e})}({processCodes:t.processCodes,drawId:t.drawId,drawType:s}),h=kw({existingQualifyingStructures:l,tournamentRecord:e,drawDefinition:f,matchUpFormat:i,matchUpType:a,tieFormat:o,event:u});if(h.error)return ti({result:h,stack:c});const g=Vw({appliedPolicies:r,policyDefinitions:n,drawDefinition:f,stack:c});return g.error?g:{drawDefinition:f,structureId:p,existingDrawDefinition:d,existingQualifyingPlaceholderStructureId:m}}function Gw(t){const{tournamentRecords:e}=t||{};if("object"!=typeof e||!Object.keys(e).length)return{error:et};const n=[],r={},i={},a={},o=[],s={},c=[];for(const u of Object.values(e)){const{participantIdsWithConflicts:e,mappedMatchUps:d,participantMap:p,participants:l,matchUps:m,derivedEventInfo:f,derivedDrawInfo:h}=ih({...t,tournamentRecord:u});Object.assign(s,d),Object.assign(r,p),Object.assign(i,f),Object.assign(a,h),n.push(...l??[]),o.push(...m??[]),e?.forEach((t=>{c.includes(t)||c.push(t)}))}return{participantIdsWithConflicts:c,derivedEventInfo:i,derivedDrawInfo:a,participantMap:r,mappedMatchUps:s,participants:n,...z,matchUps:o}}function qw({tournamentRecord:t,participantId:e}){if(!t)return{error:nt};if(!e)return{error:Xe};const n=[e].concat((t.participants??[]).filter((t=>t?.participantType&&[cp,sp].includes(t.participantType)&&t.individualParticipantIds?.includes(e))).map((t=>t.participantId)));return{eventDetails:(t.events??[]).filter((t=>k((t?.entries??[]).map((t=>t.participantId)),n))).map((t=>({eventName:t.eventName,eventId:t.eventId})))}}function $w({tournamentRecord:t,participantId:e}){if(!t)return{error:nt};if(!e)return{error:Xe};const{participants:n}=ih({participantFilters:{participantTypes:[cp,sp,op]},tournamentRecord:t});return(n??[]).filter((t=>t.individualParticipantIds?.includes(e))).reduce(((t,e)=>{const n=e.participantType;return n&&(t[n]||(t[n]=[]),t[n].push(e)),t}),{})}function Ww({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:nt};if("object"!=typeof t)return{error:Yn,context:{participantFilters:t}};const n=pf({tournamentRecord:e,contextFilters:{eventIds:t.eventIds}}).matchUps??[],r=Object.assign({},...n.map((t=>({[t.matchUpId]:t})))),i=n.filter((({schedule:t})=>t&&Object.keys(t).length)),a=Sf({tournamentRecord:e,matchUps:n}).sourceMatchUpIds??[],o={};for(const t of i){const{sides:e}=t;let n;const i=e?.map((e=>{if(e.participant)return[e.participant].concat(...e.participant.individualParticipants||[]);a[t.matchUpId]&&!n&&(n=(a[t.matchUpId]||[]).map((t=>r[t])).filter((({winningSide:t,bye:e})=>!t&&!e)))})).filter(Boolean).flat()??[];for(const e of i){const{participantId:n}=e;o[n]||(o[n]={potentialMatchUps:[],participant:e,matchUps:[]}),o[n].matchUps.push(t)}const s=n?.map((({sides:t})=>t)).flat().map((({participant:t})=>t&&[t].concat(...t.individualParticipants||[]))).filter(Boolean).flat()||[];for(const e of s){const{participantId:n}=e;o[n]||(o[n]={potentialMatchUps:[],participant:e,matchUps:[]}),o[n].potentialMatchUps.push(t)}}return{participantSchedules:Object.values(o).filter((({participant:e})=>!(t.participantIds&&!t.participantIds.includes(e.participantId)||t.participantTypes&&!t.participantTypes.includes(e.participantType)))),...z}}function Hw({tournamentRecord:t,participantId:e}){if(!t)return{error:nt};if(!e)return{error:Xe};const{participant:n}=hp({tournamentRecord:t,participantId:e});if(!n)return{error:en};const{timeItem:r}=Ip({itemType:ep,element:n});return r&&r.itemValue===rp&&rp}var zw={__proto__:null,filterParticipants:nh,getCompetitionParticipants:Gw,getPairedParticipant:Wm,getParticipantEventDetails:qw,getParticipantMembership:$w,getParticipantScaleItem:ES,getParticipantSchedules:Ww,getParticipantSignInStatus:Hw,getParticipantTimeItem:vp,getParticipants:ih,getScaleValues:gc,participantScaleItem:$f,validateLineUp:dg};function Yw({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:nt};const{appliedPolicies:r}=Np({tournamentRecord:t}),i=r?.[Nc];return(i?.matchUpFormats||[]).filter((({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n)))}function Kw({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:nt};const{appliedPolicies:r}=Np({tournamentRecord:t}),i=r?.[Cc];return(i?.allowedDrawTypes||[]).filter((({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n)))}function Qw({tournamentRecord:t}){if(!t)return{error:nt};const e=(t?.participants??[]).reduce(((t,e)=>{const{participantId:n}=e;return(e.penalties??[]).forEach((e=>{const{penaltyId:r}=e||{};t[r]?t[r].participants.push(n):t[r]={...e,participantIds:[n]}})),t}),{});return{penalties:Object.values(e)}}function Jw({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:et};const e=[];for(const n of Object.values(t)){const{penalties:t}=Qw({tournamentRecord:n});e.push(...t??[])}return{penalties:e}}function Zw({event:t}){return{eventInfo:(({eventId:t,eventName:e,eventType:n,eventLevel:r,surfaceCategory:i,matchUpFormat:a,category:o,gender:s,startDate:c,endDate:u,ballType:d,discipline:p,onlineResources:l,notes:m})=>({eventId:t,eventName:e,eventType:n,eventLevel:r,surfaceCategory:i,matchUpFormat:a,category:o,gender:s,startDate:c,endDate:u,ballType:d,discipline:p,onlineResources:l,notes:m}))(t)}}const Xw={[Tc]:{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}}}};function tP(t){const{tournamentRecord:e}=t??{};if(!e)return{error:nt};const n=(({tournamentId:t,tournamentRank:e,tournamentStatus:n,formalName:r,tournamentName:i,promotionalName:a,onlineResources:o,localTimeZone:s,activeDates:c,startDate:u,endDate:d,hostCountryCode:p,venues:l,notes:m,updatedAt:f})=>({tournamentId:t,tournamentRank:e,tournamentStatus:n,formalName:r,tournamentName:i,promotionalName:a,onlineResources:o,localTimeZone:s,activeDates:c,startDate:u,endDate:d,hostCountryCode:p,venues:l,notes:m,updatedAt:f}))(e),r=ih({participantFilters:{participantRoles:[gh,Sh,Uh,yh,wh]},policyDefinitions:Xw,tournamentRecord:e}),i=r?.participants??[];i&&(n.tournamentContacts=i);const a=Qf({tournamentRecord:e})?.publishState,o=a?.tournament?.status?.publishedEventIds||[],s=[];for(const n of e.events??[])if(!t?.usePublishState||o.includes(n.eventId)){const t=Zw({event:n}).eventInfo;t&&s.push(t)}return n.timeItemValues=iy({element:e}),n.publishState=a?.tournament,n.eventInfo=s,{tournamentInfo:la(Xr(n),!1,!0),...z}}function eP({tournamentRecords:t}){if(!G(t))return{error:et};const e=Object.keys(t??{}).reduce(((e,n)=>{const r=t[n],{tournamentInfo:{startDate:i,endDate:a}}=tP({tournamentRecord:r}),o=i&&new Date($i(i));(!e.startDate||o&&o<e.startDate)&&(e.startDate=o);const s=a&&new Date($i(a));return(!e.endDate||s&&s>e.endDate)&&(e.endDate=s),e}),{startDate:void 0,endDate:void 0}),n=e.startDate&&$i(e.startDate.toISOString()),r=e.endDate&&$i(e.endDate.toISOString());return n&&r?{startDate:n,endDate:r}:{error:Me}}function nP({tournamentRecord:t,participantFilters:e}){if(!t)return{error:nt};let n=t.participants||[];e&&(n=nh({participants:n,participantFilters:e,tournamentRecord:t}));const r={};return n.forEach((t=>{t.person&&(t=>{if(t.person){const{personId:e}=t.person;r[e]?r[e].participantIds.push(t.participantId):r[e]={...t.person,participantIds:[t.participantId]}}})(t)})),{tournamentPersons:Object.values(r)}}function rP(t){const e=cc(t,[{[hs]:!0}]);if(e.error)return e;const n=t.finishingPositionRangeBounsPoints||{},r={},i=t=>{const e=t?.individualParticipants?.map((t=>1===t.teams?.length&&t.teams[0]));return 1===t?.teams?.length&&t?.teams?.[0]||e?.[0].participantId===e?.[1].participantId&&e?.[0]},{matchUps:a,participants:o}=ih({participantFilters:{participantTypes:[ap]},withRankingProfile:!0,withStatistics:!0,...t});for(const t of o??[]){if(t.participantType===ip)continue;"draw-0-3"===t.draws?.[0]?.drawId&&console.log(t.participantType,t.draws[0].finishingPositionRange);const e=i(t);if(e)for(const i of t?.draws??[]){const t=i?.finishingPositionRange?.join("-");if(t&&n?.[t]){const a=e?.participantId,o=i?.drawId;r[`${a}|${o}|${t}`]=n[t]}}}const s=t=>({teamName:t,standingPoints:0,pointsPlayed:0,pointsPct:0,points:0,bonus:0,diff:0,loss:0,win:0}),c=(t,e,n)=>{void 0===t[e]&&(t[e]=0),t[e]+=n},u={},d={};for(const t of a??[]){const{sides:e,matchUpFormat:n}=t,r=n&&Ii(n);if(2===e?.length&&r.setFormat?.timed&&(!r.finalSetFormat||r.finalSetFormat?.timed))for(const n of e){const e=i(n.participant),r=e?.participantId,a=n.participant?.participantId,o=e?.participantName,p=n.sideNumber,l=n.participant?.individualParticipantIds||a&&[a]||[];if(l.forEach((t=>{t&&!u[t]&&(u[t]=s(o))})),r&&p){d[r]||(d[r]=s(o));const e=[...l.map((t=>u[t])),d[r]];t.winningSide&&(p===t.winningSide?e.forEach((t=>c(t,"win",1))):e.forEach((t=>c(t,"loss",1))));const n=t.score?.sets||[];for(const t of n){const n=t?.[`side${3-p}Score`]||0,r=t?.[`side${p}Score`]||0,i=r-n;e.forEach((t=>c(t,"pointsPlayed",r+n))),e.forEach((t=>c(t,"points",r))),e.forEach((t=>c(t,"diff",i)))}}}}for(const t of Object.keys(r)){const[e]=t.split("|");d[e]&&(d[e].bonus+=r[t],d[e].pointsPct=parseFloat((d[e].points/d[e].pointsPlayed).toFixed(2)),d[e].standingPoints=d[e].win+d[e].bonus)}for(const t of Object.keys(u))u[t].pointsPct=parseFloat((u[t].points/u[t].pointsPlayed).toFixed(2));return{...z,individualResults:u,teamResults:d}}function iP(t){const e=t.participants?.filter((({participantType:t})=>t===cp)),n=2===e?.length,r=1===t.events?.length&&t.events[0],i=1===r?.drawDefinitions?.length&&r.drawDefinitions[0],a=1===i?.structures?.length&&i.structures[0],o=2===a?.positionAssignments?.length;return!!(r.tieFormat&&n&&o)}function aP({tournamentRecord:t}){if(!t)return{error:nt};const{drawsAnalysis:e}=Uy({tournamentRecord:t}),n={isDual:iP(t),drawsAnalysis:e},r=ih({tournamentRecord:t});return r.missingParticipantIds?.length&&(n.missingParticipantIds=r.missingParticipantIds),{...z,analysis:n}}function oP(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||"object"==typeof e&&e[t]}function sP(t){const{participation:e={},awardProfiles:n,startDate:r,eventType:i,drawSize:a,drawType:o,category:s,endDate:c,level:u}=t,{participationOrder:d,flightNumber:p,rankingStage:l}=e;return{awardProfile:n.find((t=>(t=>!r&&!c||!t.dateRanges||t.dateRanges.some((t=>{const e=!r||!t.startDate||new Date(r)>new Date(t.startDate),n=!c||!t.endDate||new Date(c)<=new Date(t.endDate);return e&&n})))(t)&&(!t.maxFlightNumber||p<=t.maxFlightNumber)&&(!t.drawTypes?.length||t.drawTypes?.includes(o))&&(!t.drawSizes?.length||t.drawSizes.includes(a))&&(!t.stages?.length||t.stages.includes(l))&&(!t.levels?.length||t.levels.includes(u))&&(!t.maxDrawSize||a<=t.maxDrawSize)&&(!t.drawSize||t.drawSize===a)&&(!t.maxLevel||u<=t.maxLevel)&&(!p||!t.flights?.flightNumbers?.length||t.flights.flightNumbers.includes(p))&&(!t.participationOrder||t.participationOrder===d)&&(!t.category?.ageCategoryCodes||t.category.ageCategoryCodes.includes(s?.ageCategoryCode))&&(!t.eventTypes?.length||t.eventTypes?.includes(i))))}}function cP({participantWon:t,flightNumber:e,valueObj:n,drawSize:r,flights:i,level:a}){const o=(t,e)=>{const n=t?.value||t?.v||(y(t)?t:0),r=oP(a,t?.level),i=((t,e)=>{if(t){if(Array.isArray(e)){const n=e.find((e=>e.flight===t||e.f===t));return n.value||n.v}if("object"==typeof e){const n=e.flights||e.f;if(Array.isArray(n))return n[t-1]}}})(e,r);return{value:i||y(r)&&r||n}};let s,c,u,d,p=0;const l=(t?"won":!1===t&&"lost")||void 0;if(Array.isArray(n)){let t=n.find((t=>t.drawSize===r||t.drawSizes?.includes(r))),i=n.find((t=>t.drawSize&&t.threshold&&r>t.drawSize)),a=n.find((t=>!t.drawSize&&!t.drawSizes?.length));void 0!==l&&(t=t?.[l],i=i?.[l],a=a?.[l]),c=o(t,e).value,u=o(i,e).value,d=o(a,e).value,p=c||u||d,s=c&&t.requireWin||u&&i.requireWin||a?.requireWin}else if("object"==typeof n){let t=n?.drawSizes?.[r],i=n;void 0!==l&&(t=t?.[l],i=i?.[l]),c=o(t,e).value,d=o(i,e).value,p=c||d,s=c?t.requireWin:i?.requireWin}else y(n)&&void 0===l&&(p=n);return e&&i?.pct?.[e]&&(p=Math.round(p*i.pct[e])),{awardPoints:p,requireWin:s}}function uP({participantFilters:t,policyDefinitions:e,tournamentRecord:n,level:r}){if(!n)return{error:nt};const{policyDefinitions:i}=Ap({policyTypes:[Pc],tournamentRecord:n}),a=e?.[Pc]??i?.[Pc];if(!a)return{error:Ie};const o=a.awardProfiles;let s=a.requireWinFirstRound;const c=a.requireWinForPoints,{participants:u,derivedEventInfo:d,derivedDrawInfo:p,mappedMatchUps:l}=ih({withRankingProfile:!0,participantFilters:t,tournamentRecord:n}),m=u?.filter((t=>t.draws?.length)),f={},h={},g={};for(const t of m??[]){const{participantType:e,participantId:i,person:a,draws:u}=t;for(const m of u){const{drawId:u,structureParticipation:I,eventId:U}=m,y=d[U],S=p[u],v=S?.drawType,{category:P,eventType:D}=y||{},T=m.startDate||y.startDate||n.startDate,b=m.endDate||y.endDate||n.endDate;if(D===lo&&i!==ip)continue;let R;if(o){let n,d=c,p=0,m=0,U=0;for(const a of I){const{finishingPositionRange:c,participationOrder:u,participantWon:f,flightNumber:h,rankingStage:g,winCount:I}=a;p+=I||0;const y=S?.drawSize,{awardProfile:M}=sP({awardProfiles:o,participation:a,eventType:D,startDate:T,category:P,drawSize:y,drawType:v,endDate:b,level:r});if(M){if(!y)continue;const t=Array.isArray(c)&&Math.max(...c),e=w(c||[]).join("-"),i=t&&g!==ho&&c?.includes(y);void 0!==M.requireWinForPoints&&(d=M.requireWinForPoints),void 0!==M.requireWinFirstRound&&(s=M.requireWinFirstRound);const{finishingPositionPoints:a={},finishingPositionRanges:o,finishingRound:p,pointsPerWin:l,flights:S}=M,v=Array.isArray(M.perWinPoints)?M.perWinPoints?.find((t=>t.participationOrders?.includes(u))):M.perWinPoints,P=a.participationOrders;let D,T=0;if((!P||P.includes(u))&&o&&t){const e=o[t];e&&({awardPoints:T,requireWin:D}=cP({flightNumber:h,valueObj:e,drawSize:y,flights:S,level:r}))}if(!T&&p&&1===u&&t){const e=p[t];e&&({awardPoints:T,requireWin:D}=cP({participantWon:f,flightNumber:h,valueObj:e,drawSize:y,flights:S,level:r}))}if(i&&void 0!==s&&(d=s),void 0!==D&&(d=D),T>m&&(!d||I)&&(m=T,n=t),!T&&l&&I&&(U+=I*l,n=e),!T&&I&&v){const t=oP(r,v?.level);t?U+=I*t:v.value&&(U+=I*v.value)}}if(R=m+U,e===ip){const e=(t.matchUps||[]).filter((({structureId:t})=>t===a.structureId));for(const{matchUpId:t}of e){const e=l[t],n=e.sides.find((t=>t.participantId===i)).sideNumber;if(e.winningSice===n)for(const t of e.tieMatchUps)t.winningSide}}}if(U||m){const t={winCount:p,positionPoints:m,rangeAccessor:n,perWinPoints:U,eventType:D,drawId:u,points:R},r=a?.personId;r?(f[r]||(f[r]=[]),f[r].push(t)):e===sp?(g[i]||(g[i]=[]),g[i].push(t)):e===ip&&(h[i]||(h[i]=[]),h[i].push(t))}}}}return{participantsWithOutcomes:m,personPoints:f,pairPoints:g,teamPoints:h,...z}}var dP={__proto__:null,analyzeDraws:Uy,analyzeTournament:aP,getAggregateTeamResults:rP,getAllowedDrawTypes:Kw,getAllowedMatchUpFormats:Yw,getAppliedPolicies:Np,getCompetitionDateRange:eP,getCompetitionPenalties:Jw,getPolicyDefinitions:Ap,getTournamentInfo:tP,getTournamentPenalties:Qw,getTournamentPersons:nP,getTournamentPoints:uP,getTournamentStructures:Dg,getTournamentTimeItem:Sp};function pP(t){if(!t)return{};const e=[],n=t.tieFormatName,i=t.collectionDefinitions?.map((t=>{const{matchUpType:n,matchUpFormat:i,matchUpCount:a,category:o,gender:s}=t;e.includes(i)||e.push(i);const c=o?.ageCategoryCode;return[a,n===r?"D":"S",c,i,s].join(";")})).join("|");return{tieFormatName:t&&n||"UNNAMED",matchUpFormats:e,tieFormatDesc:i}}function lP({considerations:t={},descendant:e,ancestor:n}){const r={},i={},{matchUpFormats:a,tieFormatDesc:o}=pP(e),{matchUpFormats:s,tieFormatDesc:c}=pP(n),u=w((a??[]).filter((t=>!(s??[]).includes(t))).concat((s??[]).filter((t=>!(a??[]).includes(t))))),d=!(!t?.collectionName||e.collectionDefinitions.map((({collectionName:t})=>t)).join("|")===n.collectionDefinitions.map((({collectionName:t})=>t)).join("|")),p=!(!t?.collectionOrder||e.collectionDefinitions.map((({collectionOrder:t})=>t)).join("|")===n.collectionDefinitions.map((({collectionOrder:t})=>t)).join("|")),l=Object.assign({},...(e?.collectionDefinitions||[]).map((t=>({[t.collectionId]:t})))),m=Object.assign({},...(n?.collectionDefinitions||[]).map((t=>({[t.collectionId]:t}))));r.collectionIds=F(Object.keys(l),Object.keys(m)),i.collectionIds=F(Object.keys(m),Object.keys(l)),r.collectionsValue=mP(l),i.collectionsValue=mP(m),r.groupsCount=n?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),i.groupsCount=r.groupsCount?-1*r.groupsCount:0;const f=r.collectionsValue.totalValue-i.collectionsValue.totalValue,h=r.collectionsValue.totalMatchUps-i.collectionsValue.totalMatchUps,g=i.collectionsValue.assignmentValues.length!==r.collectionsValue.assignmentValues.length,I=i.collectionsValue.assignmentValues.some(((t,e)=>{const n=r.collectionsValue.assignmentValues[e];return!n||(t.valueKey!==n.valueKey||(t.value!==n.value||!!Array.isArray(t.value)&&t.value.every(((t,e)=>n.value[e]===t))))})),U=d||p||c!==o||g||I||0!==f,y=[...i.collectionsValue.invalidValues,...r.collectionsValue.invalidValues],S=y.length&&y;return{matchUpFormatDifferences:u,matchUpCountDifference:h,descendantDifferences:r,ancestorDifferences:i,orderDifference:p,valueDifference:f,nameDifference:d,descendantDesc:o,ancestorDesc:c,...z,different:U,invalid:S}}function mP(t){const e=[],n=[];let r=0;return{totalValue:Object.keys(t).sort(eh).reduce(((i,a)=>{const o=t[a],{collectionValueProfiles:s,collectionValue:c,matchUpCount:u,matchUpValue:d,scoreValue:p,setValue:l}=o,m={collectionValueProfiles:s,collectionValue:c,matchUpValue:d,scoreValue:p,setValue:l},f=Object.keys(m).filter((t=>![void 0,null].includes(m[t])&&(!Array.isArray(m[t])||m[t].length>0)));1!==f.length&&e.push({collectionId:a});const h=f[0];if(h){const t="collectionValueProfiles"===h?Object.values(s):m[h];n.push({valueKey:h,value:t})}return r+=u,s?.length?i+s.reduce(((t,e)=>t+e.value),0):u?y(d)?i+d*u:y(p)?i+p*u:y(l)?i+l*u:i+c:i}),0),totalMatchUps:r,invalidValues:e,assignmentValues:n}}function fP(t){Object.assign(t,{inContext:!0});const{matchUp:e,error:n}=hP(t);return{matchUp:la(e,!0,!0),error:n}}function hP({participantsProfile:t,afterRecoveryTimes:e,tournamentRecord:n,contextContent:r,contextProfile:i,drawDefinition:a,nextMatchUps:o,matchUpId:s,inContext:c,eventId:u,drawId:d,event:p}){if(!n)return{error:nt};if("string"!=typeof s)return{error:de};if(!a||!p){const t=(pf({tournamentRecord:n,nextMatchUps:o}).matchUps??[]).find((t=>t.matchUpId===s));if(!t)return{error:le};({eventId:u,drawId:d}=t),({event:p,drawDefinition:a}=Gm({tournamentRecord:n,eventId:u,drawId:d}))}if(!a)return{error:ct};i&&!r&&(r=Lp({tournamentRecord:n,contextProfile:i}));const l={surfaceCategory:p?.surfaceCategory??n.surfaceCategory,indoorOutDoor:p?.indoorOutdoor??n.indoorOutdoor,endDate:p?.endDate??n.endDate,tournamentId:n.tournamentId,eventId:u??p?.eventId,drawId:d},{participants:m=[]}=Mp({participantsProfile:t,tournamentRecord:n,contextProfile:i,inContext:c});if(o){const t=(ff({context:c?l:void 0,participants:m,afterRecoveryTimes:e,contextContent:r,contextProfile:i,drawDefinition:a,nextMatchUps:o,inContext:c,event:p}).matchUps??[]).find((t=>t.matchUpId===s));if(!t)return{error:le};const n=a?.structures?.find((e=>e.structureId===t.structureId));return{drawDefinition:a,structure:n,matchUp:t}}{const{matchUp:t,structure:n}=GU({context:c?l:void 0,tournamentParticipants:m,afterRecoveryTimes:e,contextContent:r,drawDefinition:a,contextProfile:i,matchUpId:s,inContext:c,event:p});return{matchUp:t,structure:n,drawDefinition:a}}}function gP({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,structure:i,eventId:a,drawId:o,event:s}){if(!t)return{error:nt};if(!(o||s||n||r))return ti({result:{error:be},stack:"getTieFormat"});a&&!s&&(s=t.events?.find((t=>t.eventId===a)));const c=fP({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:o,event:s});if(r&&c?.error)return c;if(!e&&c?.drawDefinition&&(e=c?.drawDefinition),!(i=i??c?.structure)&&n&&!r){if(!e)return{error:Tt};const t=ad({drawDefinition:e,structureId:n});if(t.error)return t;i=t.structure}const u=(i?.tieFormat||i?.tieFormatId)&&fl({structure:i,drawDefinition:e,event:s})?.tieFormat,d=(e?.tieFormat||e?.tieFormatId)&&fl({drawDefinition:e,event:s})?.tieFormat,p=fl({event:s})?.tieFormat,l=fl({matchUp:c?.matchUp,drawDefinition:e,structure:i,event:s})?.tieFormat;return{...z,matchUp:c?.matchUp,structureDefaultTieFormat:ZU(u),eventDefaultTieFormat:ZU(p),drawDefaultTieFormat:ZU(d),tieFormat:ZU(l),structure:i}}var IP={__proto__:null,compareTieFormats:lP,getTieFormat:gP,tieFormatGenderValidityCheck:si,validateCollectionDefinition:oa};function UP({tournamentRecord:t,outcomes:e}){if(!t)return{error:nt};if(!e?.length)return{error:be,info:"Missing outcomes"};const n=e.reduce(((t,e)=>{const{drawId:n,eventId:r}=e;return r&&n&&(t[r]?t[r].includes(n)||t[r].push(n):t[r]=[n]),t}),{}),r=Object.keys(n),i=t.events?.filter((t=>r.includes(t.eventId)));return{publishedEventIds:i.filter((t=>{const e=Yf({event:t}),{drawDetails:r,drawIds:i}=e??{},{eventId:a}=t;return n[a].filter((t=>{const n=r?Object.keys(e.drawDetails).filter((t=>Kf({drawId:t,drawDetails:r}))):[];return i?.includes(t)||n.includes(t)})).length})).map((t=>t.eventId)),eventIdPublishedDrawIdsMap:n}}function yP({dates:t=[],extension:e}){if(!e)return!1;if("boolean"==typeof e.value&&e.value)return!0;if(!t.length)return!1;const n=G(e.value)?e.value?.dates:void 0;if(Array.isArray(n)){if(!n?.length)return!1;return!!n.filter((e=>!t.length||t.includes(e))).length}}function SP({convertExtensions:t,ignoreDisabled:e,venue:n,court:r}){const i={...la(r,t,!0),venueId:n.venueId},{extension:a}=zc({name:Jc,element:r});if(e&&a){const t=G(a.value)?a.value?.dates:void 0,e=!0===a?.value?[]:i.dateAvailability.map((e=>{const n=e.date;if(n&&!t.includes(n))return e})).filter(Boolean);i.dateAvailability=e}return{inContextCourt:i}}function vP(t){const{convertExtensions:e,ignoreDisabled:n,venueIds:r=[],dates:i}=t,a=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},o=[],s=[],c=[],u=[];return Object.keys(a).filter((e=>!t.tournamentId||e===t.tournamentId)).forEach((t=>{const d=a[t];for(const t of d.venues??[])if(!r.length||r.includes(t.venueId)){if(n){const{extension:e}=zc({name:Jc,element:t});if(e?.value)continue}o.includes(t.venueId)||(u.push(la(t,e,!0)),o.push(t.venueId));for(const r of t.courts??[])if(!s.includes(r.courtId)){if(n){const{extension:t}=zc({name:Jc,element:r});if(yP({extension:t,dates:i}))continue}const{inContextCourt:a}=SP({convertExtensions:e,ignoreDisabled:n,venue:t,court:r});c.push(a),s.push(r.courtId)}}})),{courts:c,venues:u,...z}}function wP({tournamentRecords:t,requireCourts:e,dates:n}){if("object"!=typeof t||!Object.keys(t).length)return{error:et};return Object.keys(t).reduce(((r,i)=>{const a=t[i],{venues:o}=function({convertExtensions:t,tournamentRecord:e,ignoreDisabled:n,dates:r}){if(!e)return{error:et};const i=la(e.venues??[],t).filter((t=>{if(!n)return t;const{extension:e}=zc({name:Jc,element:t});return!e?.value&&t})).filter(Boolean),a=i.reduce(((e,i)=>{const a=(i?.courts||[]).filter((t=>{if(!n&&!r?.length)return t;const{extension:e}=zc({name:Jc,element:t});return yP({extension:e,dates:r})})).filter(Boolean).map((e=>{const{inContextCourt:r}=SP({convertExtensions:t,ignoreDisabled:n,venue:i,court:e});return r}));return a.length?e.concat(a):e}),[]);return{venues:i,courts:a}}({tournamentRecord:a,dates:n});return o?.forEach((t=>{const{venueId:n,courts:i}=t;(!e||i?.length)&&!r.venueIds.includes(n)&&(r.venues.push(t),r.venueIds.push(n))})),r}),{venues:[],venueIds:[]})}function PP({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:nt};const n=t.events||[],r=t?.participants||[],{tournamentInfo:i}=tP({tournamentRecord:t}),{venues:a}=vP({tournamentRecord:t}),o=n.map((n=>{const{eventId:i}=n,a=Zw({event:n}).eventInfo,o=Vp({tournamentRecord:t,event:n}).scheduleTiming,s=(n.drawDefinitions||[]).map((a=>{const s=(({drawId:t,drawName:e,matchUpFormat:n,updatedAt:r})=>({matchUpFormat:n,updatedAt:r,drawName:e,drawId:t}))(a),{abandonedMatchUps:c,completedMatchUps:u,upcomingMatchUps:d,pendingMatchUps:p}=uf({requireParticipants:!0,tournamentParticipants:r,context:{eventId:i},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:o,drawDefinition:a,event:n});return{drawInfo:s,matchUps:{abandonedMatchUps:c,completedMatchUps:u,upcomingMatchUps:d,pendingMatchUps:p}}})),c=Yf({event:n});return Object.assign(a,{drawsData:s,publish:c}),a}));return{allEventData:{tournamentInfo:i,venuesData:a,eventsData:o}}}function DP({publishStatus:t,drawId:e}){return t?.drawDetails?t.drawDetails?.[e]?.publishingDetail?.published:!t?.drawIds||t.drawIds.includes(e)}const TP="PUBLIC",bP={PUBLIC_DISPLAY:TP,ADMIN_DISPLAY:"ADMIN"};function RP(t){const{tournamentParticipants:e=[],includePositionAssignments:n,policyDefinitions:r,tournamentRecord:i,inContext:o=!0,usePublishState:s,status:c=am,pressureRating:u,refreshResults:d,contextProfile:p,drawDefinition:l,noDeepCopy:m,sortConfig:f,context:h,event:g}=t;if(!l)return{error:ot};const I=(({matchUpFormat:t,updatedAt:e,drawType:n,drawName:r,drawId:i})=>({matchUpFormat:t,updatedAt:e,drawName:r,drawType:n,drawId:i}))(l);I.display=zc({element:l,name:tu}).extension?.value;const U={};let y,S;const{allStructuresLinked:v,sourceStructureIds:w,hasDrawFeedProfile:P,structureGroups:D}=rI({drawDefinition:l});if(!v)return{error:Gt};const T=t?.eventPublishState??Qf({event:g}).publishState,b=t?.publishStatus??Yf({event:g,status:c}),R=T?.status?.drawDetails?.[l.drawId],M=!!T?.status?.published,N=R?.structureDetails;let A=!1,E=!1;const C=D.map((c=>{const m={},v=c.map((t=>{const{structure:e}=ad({drawDefinition:l,structureId:t}),{seedAssignments:n}=pl({drawDefinition:l,structure:e});return e?.stage===fo&&1===e.stageSequence&&(y=n),e?.stage===ho&&(U[e.stageSequence??0]=n),e})).sort(((t,e)=>rd(t,e,f))).map((n=>{if(!n)return;const c=n?.structureId;let f=[];n.stage&&[fo,go,Uo].includes(n.stage)&&(f=y),n?.stage===ho&&(f=U[n.stageSequence??0]);const{matchUps:v,roundMatchUps:D,roundProfile:T}=Jm({seedAssignments:n?.seedAssignments?.length?void 0:f,context:{drawId:I.drawId,...h},hydrateParticipants:t.hydrateParticipants,participantsProfile:t.participantsProfile,tournamentParticipants:e,policyDefinitions:r,tournamentRecord:i,usePublishState:s,publishStatus:b,contextProfile:p,drawDefinition:l,inContext:o,structure:n,event:g}),{positionAssignments:R}=cd({structure:n});let M=R?.filter(If(Ss)).map((t=>{const e=zc({element:t,name:gu})?.extension?.value,{drawPosition:n,participantId:r}=t;return E=!0,{participantResult:e,participantId:r,drawPosition:n}}));if(v.length&&(!M?.length&&t.allParticipantResults||d&&!n.structures)){const{subOrderMap:t}=BU({positionAssignments:R}),e=v.some((t=>t.matchUpType===a))?v.filter((t=>t.matchUpType===a)):v,i=LU({matchUpFormat:n.matchUpFormat,matchUps:e,policyDefinitions:r,pressureRating:u,subOrderMap:t});S=i?.report,M=R?.filter(If(Ss)).map((t=>{const{drawPosition:e,participantId:n}=t;return E=!0,{participantResult:n&&i?.participantResults?.[n],participantId:n,drawPosition:e}}))}const N=n?(({stageSequence:t,structureName:e,structureType:n,matchUpFormat:r,stage:i})=>({stageSequence:t,structureName:e,structureType:n,matchUpFormat:r,stage:i}))(n):{},C=zc({element:n,name:tu}).extension?.value;N.display=C?.[TP]??C,N.sourceStructureIds=w[c],N.hasDrawFeedProfile=P[c],N.positionAssignments=R,N.structureActive=v.reduce(((t,e)=>{const n=[Vu,Bu,ju,xu,ku,Lu,$u,zu].includes(e.matchUpStatus);return t||n||!!e.winningSide||!!e.score?.scoreStringSide1}),!1);const O=v.reduce(((t,e)=>t&&[Fu,xu,$u,zu,Lu,Cu].includes(e.matchUpStatus)),!!v.length);return N.structureCompleted=O,m[c]=O,N.structureActive&&(A=!0),{...N,participantResults:M,seedAssignments:f,roundMatchUps:D,roundProfile:T,structureId:c,report:S}}));return v.forEach((t=>{n||delete t.positionAssignments,t.sourceStructuresComplete=t.sourceStructureIds?.every((t=>m[t]))})),v})),O=C.flat().filter((t=>!s||N?.[t?.structureId]?.published||!0));return I.drawActive=A,I.participantPlacements=E,I.drawGenerated=O?.reduce(((t,e)=>t||!!e?.roundMatchUps),!1),I.drawCompleted=O?.reduce(((t,e)=>t&&e.structureCompleted),!0),I.drawPublished=s?M&&DP({publishStatus:b,drawId:I.drawId}):void 0,{structures:!s||I.drawPublished?m&&O||la(O,!1,!0):void 0,drawInfo:m?I:la(I,!1,!0),...z}}function MP(t){const{includePositionAssignments:e,participantsProfile:n,policyDefinitions:r,usePublishState:i,status:a=am,contextProfile:o,sortConfig:s}=t,c=cc(t,[{tournamentRecord:!0},{[rc]:{event:!1,eventId:!1}}]);if(c.error)return c;const u=la(t.tournamentRecord,!1,!0),d=t.event?void 0:Gm({tournamentRecord:u,eventId:t.eventId}).event,p=t.event?la(t.event,!1,!0):d&&la(d,!1,!0)||void 0;if(!p)return{error:Wt};const{eventId:l}=p,{tournamentId:m,endDate:f}=u,h=Yf({event:p,status:a}),g=Qf({event:p}).publishState??{},I=!!g?.status?.published,{participants:U}=ih({withEvents:!1,withDraws:!1,policyDefinitions:r,...n,tournamentRecord:u}),S=p.drawDefinitions||[],v=!i||I?S.filter((({drawId:t})=>!i||DP({publishStatus:h,drawId:t}))).map((n=>(({drawInfo:t,structures:e})=>({...t,structures:e}))(RP({allParticipantResults:t.allParticipantResults,hydrateParticipants:t.hydrateParticipants,context:{eventId:l,tournamentId:m,endDate:f},pressureRating:t.pressureRating,refreshResults:t.refreshResults,includePositionAssignments:e,tournamentParticipants:U,eventPublishState:g,noDeepCopy:!0,policyDefinitions:r,tournamentRecord:u,usePublishState:i,contextProfile:o,drawDefinition:n,publishStatus:h,sortConfig:s,event:p})))).map((({structures:t,...e})=>{const n=t?.filter((({stage:t,structureId:n})=>(({structureId:t,drawId:e})=>{if(!i)return!0;const n=h?.drawDetails?.[e]?.structureDetails;return!n||!Object.keys(n).length||n[t]?.published})({structureId:n,drawId:e.drawId})&&(({stage:t,drawId:e})=>{if(!i)return!0;const n=h?.drawDetails?.[e]?.stageDetails;return!n||!Object.keys(n).length||n[t]?.published})({stage:t,drawId:e.drawId}))).map((t=>(({drawId:t,structure:e})=>{if(!i)return e;const n=h?.drawDetails?.[t]?.structureDetails?.[e.structureId]?.roundLimit;if(y(n)){const t=E(1,n+1),r={},i={};for(const n of t)e.roundMatchUps[n]&&(r[n]=e.roundMatchUps[n],i[n]=e.roundProfile[n]);e.roundMatchUps=r,e.roundProfile=i}return e})({drawId:e.drawId,structure:t})));return{...e,structures:n}})).filter((t=>t.structures?.length)):void 0,w=(Array.isArray(u.venues)?u.venues:[]).map((t=>(({venueData:t})=>({...t}))(Vm({venueId:t.venueId,tournamentRecord:u})))),P=(({eventId:t,eventName:e,eventType:n,eventLevel:r,surfaceCategory:i,matchUpFormat:a,category:o,gender:s,startDate:c,endDate:u,ballType:d,discipline:p})=>({eventId:t,eventName:e,eventType:n,eventLevel:r,surfaceCategory:i,matchUpFormat:a,category:o,gender:s,startDate:c,endDate:u,ballType:d,discipline:p}))(p);P.display=zc({element:p,name:tu}).extension?.value;const{tournamentInfo:D}=tP({tournamentRecord:u}),T={tournamentInfo:D,venuesData:w,eventInfo:P,drawsData:v};return T.eventInfo.publishState=g,T.eventInfo.published=g?.status?.published,{...z,eventData:T,participants:U}}var NP={__proto__:null,bulkUpdatePublishedEventIds:UP,getAllEventData:PP,getCourtInfo:Bm,getDrawData:RP,getEventData:MP,getEventPublishStatus:Yf,getPublishState:Qf,getTournamentPublishStatus:zf,getVenueData:Vm};function AP({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:n,matchUp:r}){const{individualParticipantIds:i}=Xd(r);n=n??r.schedule?.timeAfterRecovery;const a=e=>{t[e]||(t[e]=[]),t[e]=w(t[e].concat(...i))},o=t=>{n&&(!e[t]||n>e[t])&&(e[t]=n)},s=r.winnerTo?.matchUpId||r.winnerMatchUpId;s&&(n&&o(s),a(s));const c=r.loserTo?.matchUpId||r.loserMatchUpId;c&&(n&&o(c),a(c)),r.sidesTo?.length&&r.sidesTo.forEach((({matchUpId:t})=>{t&&(n&&o(t),a(t))}))}function EP(t){const e=cc(t,[{[Bs]:!0}]);if(e.error)return e;const{matchUpPotentialParticipantIds:n,dateScheduledMatchUpIds:r=[],scheduleCompletedMatchUps:i,matchUpNotBeforeTimes:a,matchUpScheduleTimes:o,orderedMatchUpIds:s,clearDate:c,matchUps:u}=t,d=o?Object.keys(o):[],p=(s??[]).map((t=>u.find((e=>e.matchUpId===t)))).filter(Boolean).filter((t=>{const e=!c&&(r.includes(t.matchUpId)||d.includes(t.matchUpId)),n=[Fu,Lu,xu,Cu,$u,zu,Vu,Bu].includes(t?.matchUpStatus);return i||!e&&!t.winningSide&&!n})),l=n&&a?p.reduce(((t,e)=>{const{drawId:r,tournamentId:i}=e;return t.matchUpMap[i]||(t.matchUpMap[i]={}),t.matchUpMap[i][r]?t.matchUpMap[i][r].push(e):t.matchUpMap[i][r]=[e],AP({matchUpPotentialParticipantIds:n,matchUpNotBeforeTimes:a,matchUp:e}),t}),{matchUpMap:{}}).matchUpMap:{};return{matchUpsToSchedule:p,matchUpMap:l}}function CP({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:n,matchUpFormat:r,categoryName:i,categoryType:a,tournamentId:o,eventType:s,eventId:c}){if(!Di({matchUpFormat:r}))return{error:ne};let u;return Object.keys(n).filter((t=>!o||t===o)).forEach((t=>{if(u)return;const e=n[t],o=c?Gm({tournamentRecord:e,eventId:c})?.event:void 0;return u=Tm({tournamentRecord:e,matchUpFormat:r,categoryName:i,categoryType:a,eventType:s,event:o}),u?.averageMinutes||u?.recoveryMinutes})),{recoveryMinutes:u?.recoveryMinutes||t,averageMinutes:u?.averageMinutes||e,typeChangeRecoveryMinutes:u?.typeChangeRecoveryMinutes||u?.recoveryMinutes||t}}function OP(t){const e=cc(t,[{[rc]:{tournamentRecords:!1,tournamentRecord:!1}},{rounds:!0,[nc]:Zs}]);if(e.error)return e;const{scheduleCompletedMatchUps:n,periodLength:r=30}=t,i=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{};if("object"!=typeof i)return{error:et};const a={},o=[],s=t.rounds.toSorted(((t,e)=>(t.sortOrder??0)-(e.sortOrder??0))),c=t.containedStructureIds??Object.assign({},...Object.values(i).map((t=>Zd({tournamentRecord:t}).containedStructures))),u=t.matchUps??lf({nextMatchUps:!0,tournamentRecords:i}).matchUps;let d=0;const l={},m={},f={},h=s.flatMap((t=>{const e=t.periodLength||r,s=[];c?.[t.structureId]?s.push(...c[t.structureId]):s.push(t.structureId);let h=u?Qm({tournamentIds:[t.tournamentId],roundNumbers:[t.roundNumber],matchUpIds:t.matchUpIds,eventIds:[t.eventId],drawIds:[t.drawId],processContext:!0,structureIds:s,matchUps:u}).sort(mf):[];const{segmentNumber:g,segmentsCount:I}=t.roundSegment||{};if(y(g)&&p(h?.length)&&p(I)&&g>0&&g<=I&&I<h?.length&&!t.matchUpIds?.length){const t=h.length/I,e=t*(g-1);h=h.slice(e,e+t)}const U=i[t.tournamentId],S=Gm({drawId:t.drawId,tournamentRecord:U}).event,v=[];for(const t of h){const e=t.matchUpFormat;e&&(a[e]||(a[e]=[],a[e].push(t)),v.push(e))}for(const r of v){const{eventType:a,category:s}=S??{},{categoryName:c,ageCategoryCode:u}=s??{},{typeChangeRecoveryMinutes:p,recoveryMinutes:g,averageMinutes:I,error:U}=CP({categoryName:c??u,categoryType:s?.categoryType,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:i,matchUpFormat:r,eventType:a});if(U)return{error:U,round:t};const y=h.filter((t=>(n||!Xu.includes(t.matchUpStatus))&&t.matchUpStatus!==Fu)).map(Nu);y.forEach((t=>{f[t]={typeChangeRecoveryMinutes:p,recoveryMinutes:g,averageMinutes:I},l[t]=g,m[t]=I})),o.push(...y),d=Math.max(I||0,d);return{roundPeriodLength:e,recoveryMinutes:g,averageMinutes:I,matchUpIds:y,hash:`${I}|${e}`}}}));return{scheduledRoundsDetails:h,greatestAverageMinutes:d,matchUpFormatCohorts:a,recoveryMinutesMap:l,averageMinutesMap:m,orderedMatchUpIds:o,minutesMap:f,...z}}function FP({schedulingProfile:t,venueIds:e,eventIds:n,drawIds:r}){const i=[],a=t?.map((t=>{const a=$i(t?.scheduleDate);if(!a)return void i.push(`Invalid date: ${t?.scheduledDate}`);const o=(t?.venues||[]).map((t=>{const{rounds:a,venueId:o}=t,s=e?.includes(o);if(!s)return void i.push(`Missing venueId: ${o}`);const c=a.filter((t=>{const e=n.includes(t.eventId)&&r.includes(t.drawId);return e||i.push(`Invalid eventId: ${t.eventId} or drawId: ${t.drawId}`),e}));return c.length?{venueId:o,rounds:c}:void 0})).filter(Boolean);return o.length&&a&&{...t,venues:o}})).filter(Boolean);return{updatedSchedulingProfile:a,modifications:i.length,issues:i}}function kP({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:Jn};const{venueIds:n,tournamentsMap:r}=function(t){const e=t?.tournamentRecords&&Object.values(t?.tournamentRecords)||[],n={},{venueIds:r,eventIds:i,drawIds:a,structureIds:o,tournamentIds:s}=e.reduce(((t,e)=>{const{tournamentIds:r,tournamentMap:i,structureIds:a,venueIds:o,eventIds:s,drawIds:c}=function(t){const{tournamentRecord:e={},tournamentMap:n={},requireCourts:r}=t,i=[],a=[],o=[],s=[],c=(e?.venues||[]).map((({venueId:t,courts:e})=>(!r||e?.length)&&t)),u=e?.tournamentId;if(u){i.push(u),n[u]={};const t=e?.events||[];for(const e of t){const t=e.eventId;o.push(t),n[u][t]={};const r=t=>parseInt(t);for(const i of e.drawDefinitions||[]){const e=i.drawId;s.push(e),n[u][t][e]={};const{structures:o}=od({drawDefinition:i});for(const i of o||[]){const o=i.structureId,{matchUps:s}=Jm({structure:i}),{roundMatchUps:c}=Sl({matchUps:s}),d=c&&Object.keys(c).map(r);if(n[u][t][e][o]=d,a.push(o),i.structures?.length)for(const r of i.structures)a.push(r.structureId),n[u][t][e][r.structureId]=d}}}}return{tournamentMap:n,tournamentIds:i,structureIds:a,venueIds:c,eventIds:o,drawIds:s}}({tournamentRecord:e});return o.forEach((e=>{t.venueIds.includes(e)||t.venueIds.push(e)})),t.tournamentIds.push(...r),t.structureIds.push(...a),t.eventIds.push(...s),t.drawIds.push(...c),Object.assign(n,i),t}),{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:n,tournamentIds:s,structureIds:o,venueIds:r,eventIds:i,drawIds:a}}({tournamentRecords:t});let i,a;const o=e.every((t=>{const{scheduleDate:e,venues:o}=t;return!!Ci(e)&&o.every((t=>{const{venueId:e,rounds:o}=t;if("string"!=typeof e)return a="venueId should be a string",!1;if(!Array.isArray(o))return a="rounds should be an array",!1;if(!n.includes(e))return i=Mn,!1;const s=o.every((t=>{if(!t)return a="empty round",!1;const{roundSegment:e,tournamentId:n,structureId:i,roundNumber:o,eventId:s,drawId:c}=t,u=r?.[n]?.[s]?.[c]?.[i],d=u?.includes(o);d||(a="Invalid rounds");const{segmentNumber:l,segmentsCount:m}=e||{},f=!e||y(l)&&p(m)&&l<=m;return f||(a="Invalid segment"),d&&f}));return!!s}))}));return o||i||(i=Jn),{valid:!!o,error:i,info:a}}function xP({tournamentRecords:t,tournamentRecord:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:et};const{extension:n}=zc({element:e,name:fu,tournamentRecords:t,discover:!0});let r=n?.value||[];if(r.length){const{venueIds:n}=wP({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:a}=XU({tournamentRecords:t}),{updatedSchedulingProfile:o,modifications:s,issues:c}=FP({schedulingProfile:r,venueIds:n,eventIds:i,drawIds:a});if(s){r=o;const n=_P({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r});return n.error?n:{schedulingProfile:r,modifications:s,issues:c}}}return{schedulingProfile:r,modifications:0}}function _P({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n}){const r=kP({tournamentRecords:t,schedulingProfile:n});if(r.error)return r;if(!n)return kc({element:e,name:fu,tournamentRecords:t,discover:!0});return _c({tournamentRecords:t,discover:!0,extension:{name:fu,value:n}})}function LP(t){const{tournamentRecord:e}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){const{modifications:t,issues:r}=xP({tournamentRecords:n,tournamentRecord:e});return{success:!t,modifications:t,issues:r}}const{venueIds:r}=wP({tournamentRecords:n}),{eventIds:i,drawIds:a}=XU({tournamentRecords:n}),{updatedSchedulingProfile:o,modifications:s,issues:c}=FP({schedulingProfile:t.schedulingProfile,venueIds:r,eventIds:i,drawIds:a});return s?{..._P({schedulingProfile:o,tournamentRecords:n}),modifications:s,issues:c}:{...z,modifications:s,issues:c}}function BP(t){const{scheduleDates:e=[],tournamentRecords:n,periodLength:r=30}=t??{};if("object"!=typeof n)return{error:rt};if(!Array.isArray(e))return{error:Jn};if(!e.every(Ci))return{error:Oe};const i=[];let a=0;const o={},{schedulingProfile:s}=xP({tournamentRecords:n});if(!s)return{issues:i,...z};const{matchUps:c}=lf({nextMatchUps:!0,tournamentRecords:n});for(const t of s){const{scheduleDate:s,venues:u=[]}=t;if(!e?.length||e.includes(s))for(const t of u||[])if(t){const{rounds:e}=t,u=[],{orderedMatchUpIds:d,scheduledRoundsDetails:p}=OP({tournamentRecords:n,periodLength:r,matchUps:c,rounds:e}),{matchUpDependencies:l}=Sf({tournamentRecords:n,matchUps:c}),m=t=>{let e;return p?.find(((n,r)=>{const i=n.matchUpIds.includes(t);return i&&(e=r),i})),e};if(d?.forEach(((t,e)=>{const n=O(d.slice(e+1),l?.[t]?.matchUpIds||[]);n.length&&u.push({matchUpId:t,shouldBeAfter:n})})),u.length){a+=u.length;const t=u.map((({matchUpId:t,shouldBeAfter:e})=>{const n=m(t),r=w(e.map(m));return o[s]||(o[s]={}),o[s][n]||(o[s][n]=[]),r.forEach((t=>{o[s][n].includes(t)||o[s][n].push(t)})),{matchUpId:t,matchUpRoundIndex:n,earlierRoundIndices:r,shouldBeAfter:e}}));i.push(...t)}}}const u={matchUpIdShouldBeAfter:Object.assign({},...i.map((t=>{const{matchUpId:e,shouldBeAfter:n,earlierRoundIndices:r}=t;return{[e]:{earlierRoundIndices:r,shouldBeAfter:n}}})))};return{issuesCount:a,profileIssues:u,roundIndexShouldBeAfter:o,...z}}function VP(t){const{tournamentRecords:e,requestType:n}=t,r=cc(t,[{[ms]:!0}]);if(r.error)return r;const i={};for(const t of Object.values(e)){const{extension:e}=zc({element:t,name:uu}),r=e?.value||[];for(const t of r){const{personId:e,requests:r}=t||{};i[e]||(i[e]=[]);for(const t of r)n&&t.requestType!==n||i[e].push(t)}}return{personRequests:i,...z}}function jP(t){const{containerStructureId:e,roundSegment:n,isRoundRobin:r,tournamentId:i,roundNumber:a,structureId:o,eventId:s,drawId:c}=t,u=r?e:o,d=[i,s,c,u,a].join("|");return Xr({structureId:u,roundSegment:n,tournamentId:i,roundNumber:a,eventId:s,drawId:c,id:d})}function GP({round:t,matchUps:e,events:n,tournamentRecords:r}){const i=n.find((e=>e.eventId===t.eventId)),{eventType:a,category:o,categoryType:s}=i||{},{categoryName:c,ageCategoryCode:u}=o||{},d=T(e.map((({matchUpFormat:t})=>t)));let p=0;return Object.keys(d).forEach((e=>{const n=d[e],i=CP({categoryName:c||u,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:r,matchUpFormat:e,categoryType:s,eventType:a});if(i.error)return i;const o=i.averageMinutes*n;isNaN(p)||(p+=o)})),{roundMinutes:p}}function qP(t){const e=t.length,n=t.filter((({sides:t})=>t?.some((({bye:t})=>t)))).length||0,r=t.filter((({winningSide:t,matchUpStatus:e})=>t||Xu.includes(e))).length||0,i=t.filter((({schedule:t,matchUpStatus:e})=>t?.scheduledDate&&t?.scheduledTime&&e!==Fu)).length||0,a=e-n;return{unscheduledCount:a-i,incompleteCount:a-i,scheduledCount:i,completedCount:r,matchUpsCount:e,isScheduled:a===i,isComplete:a===r,byeCount:n}}function $P({tournamentRecords:t,schedulingProfile:e,tournamentRecord:n,withRoundId:r}){if(n&&!t){if("object"!=typeof n)return{error:rt};t={[n.tournamentId]:n}}if(e){const n=kP({tournamentRecords:t,schedulingProfile:e});if(n.error)return n}if(!e&&t){const n=xP({tournamentRecords:t});if(n.error)return n;e=n.schedulingProfile}if(!e)return{error:rr};const i={};return{profileRounds:e.map((({venues:t,scheduleDate:e})=>t.map((({rounds:t})=>t.map((t=>{const n=jP(t);return n.roundSegment?.segmentsCount&&(i[n.id]=n.roundSegment.segmentsCount),Xr({id:r?n.id:void 0,scheduleDate:e,...n})})))))).flat(1/0),segmentedRounds:i}}function WP({courtPrefix:t="C|",minRowsCount:e,courtsData:n}){if(!Array.isArray(n))return{error:Jn};const r=n?.reduce(((t,e)=>{const n=e.matchUps||[],r=Math.max(0,...n.map((t=>t.schedule.courtOrder||0)));return r>t?r:t}),1),i=E(0,e?Math.max(e,r):r).map((t=>({matchUps:E(0,n.length).map((e=>{const r=n[e],{courtId:i,venueId:a}=r;return{schedule:{courtOrder:t+1,venueId:a,courtId:i}}}))})));return n.forEach(((t,e)=>{for(const n of t.matchUps){const t=n.schedule?.courtOrder;t&&(i[t-1].matchUps[e]=n)}})),{courtPrefix:t,rows:i.map(((e,n)=>Object.assign({rowId:`rowId-${n+1}`},...e.matchUps.map(((e,n)=>({[`${t}${n}`]:e}))))))}}var HP={__proto__:null,courtGridRows:WP,findVenue:km,getMatchUpsToSchedule:EP,getPersonRequests:VP,getProfileRounds:$P,getScheduledRoundsDetails:OP,getSchedulingProfile:xP,getSchedulingProfileIssues:BP,publicFindCourt:Lm};function zP({policyDefinitions:t,drawDefinition:e,drawSize:n,drawId:r,event:i,stage:a}){if(!i)return{error:$t};const{entries:o,stageEntries:s}=Mh({drawDefinition:e,drawId:r,stage:a,event:i}),c=s.length,{drawSize:u}=fS({participantsCount:c}),d=hS({drawSize:n??u,participantsCount:c,policyDefinitions:t});if(d.error)return ti({result:d,stack:"getEntriesAndSeedsCount"});const{seedsCount:p}=d;return{entries:o,seedsCount:p,stageEntries:s}}function YP(t){const{entries:e=[],entryStatus:n,stage:r}=t;return Math.max(...e.filter((t=>!(r&&r!==t.entryStage||n&&t.entryStatus!==n||isNaN(t.entryPosition)))).map((({entryPosition:t})=>d(t||0))),0)}var KP={__proto__:null,getEntriesAndSeedsCount:zP,getMaxEntryPosition:YP};function QP({tournamentRecords:t,extensionName:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:et};const n=[];let r;for(const i of Object.values(t)){const{extension:t}=zc({element:i,name:e});t&&!r&&(n.push({params:{extension:t,discover:!0},method:"addExtension"}),r=!0);const a=i.events??[];for(const t of a){const{eventId:r}=t,{extension:i}=zc({name:e,element:t});i&&n.push({params:{eventId:r,extension:i},method:"addEventExtension"})}}return{methods:n}}function JP({tournamentRecords:t}){return QP({extensionName:mu,tournamentRecords:t})}const ZP="ADULT",XP="JUNIOR",tD="WHEELCHAIR",eD={[Rc]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[i]:30,default:60}}]},defaultDailyLimits:{[n]:2,[i]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[ba],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[tD],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:[ZP,tD],minutes:{default:60,[i]:30}},{categoryTypes:[XP],minutes:{default:60,[i]: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:[ZP,tD],minutes:{default:30}},{categoryTypes:[XP],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:[ZP,XP],minutes:{default:30}},{categoryTypes:[tD],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}};function nD({tournamentRecord:t,matchUpFormats:e,categoryType:n,event:r}){if(!r)return{error:$t};let i,a=[];if(e?.length){const t=[];a=e.map((e=>{const n="string"==typeof e?{matchUpFormat:e}:e;if(!t.includes(n?.matchUpFormat)&&Di({matchUpFormat:n?.matchUpFormat}))return t.push(n.matchUpFormat),n})).filter(Boolean)}else{const{policy:e}=Bp({policyType:Nc,tournamentRecord:t,event:r});if(e?.matchUpFormats)a=e?.matchUpFormats;else{const{extension:t}=zc({name:mu,element:r});let e,n;({matchUpAverageTimes:e,matchUpRecoveryTimes:n}=t?.value?t.value:eD[Rc]),a=w([...(e||[]).map((t=>t.matchUpFormatCodes)),...(n||[]).map((t=>t.matchUpFormatCodes))].flat()).map((t=>({matchUpFormat:t}))),i="default scheduling policy in use"}}const{eventType:o,eventId:s,category:c}=r,u=c?.categoryName??c?.ageCategoryCode??s;if(!s)return{error:$t};return Xr({eventMatchUpFormatTiming:a.map((({matchUpFormat:e,description:i})=>({matchUpFormat:e,description:i,...Tm({tournamentRecord:t,matchUpFormat:e,categoryName:u,categoryType:n,eventType:o,event:r})}))),info:i})}function rD(t){const e=cc(t,[{[hs]:!0},{[Xs]:t=>Di({matchUpFormat:t}),[ec]:ne,[ys]:!0}]);if(e.error)return e;const{tournamentRecord:n,matchUpFormat:r,event:i}=t,{extension:a}=zc({name:mu,element:i}),o=a?.value,{extension:s}=zc({element:n,name:mu}),c=s?.value,u=[o?.matchUpAverageTimes&&dm({...o,matchUpFormat:r}),c?.matchUpAverageTimes&&dm({...c,matchUpFormat:r})].find((t=>t));return{matchUpFormat:r,recoveryTimes:[o?.matchUpRecoveryTimes&&pm({...o,matchUpFormat:r}),c?.matchUpRecoveryTimes&&pm({...c,matchUpFormat:r})].find((t=>t)),averageTimes:u}}function iD({tournamentRecords:t}){return QP({extensionName:lu,tournamentRecords:t})}const aD=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter((e=>t.includes(e))).filter((t=>e[t])).length;function oD({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!yl(e))return{error:me};if(!Array.isArray(t))return{error:Jn};const n=e.filter(Boolean).filter((({schedule:e})=>aD({schedule:e,scheduleAttributes:t}))).reduce(((t,e)=>{const{schedule:n}=e,r=$i(n?.scheduledDate),i=qi(n?.scheduledTime);return r&&i&&(t[r]?t[r].push(e):t[r]=[e]),t}),{});return Object.keys(n).forEach((t=>{n[t].sort(((t,e)=>Yi(qi(t.schedule?.scheduledTime),qi(e.schedule?.scheduledTime))))})),{...z,scheduledMatchUps:n}}function sD({schedulingProfile:t,matchUps:e=[]}){const n={},r=({eventId:t,drawId:e,structureId:n,roundNumber:r})=>`${t}|${e}|${n}${r}`;if(t?.length){t.map((({venues:t})=>t.map((({rounds:t})=>t)))).flat().forEach((t=>{t.sort(((t,e)=>(t.sortOrder||0)-(e.sortOrder||0))).forEach((({eventId:t,drawId:e,structureId:i,roundNumber:a},o)=>{const s=r({eventId:t,drawId:e,structureId:i,roundNumber:a});n[s]=o}))}))}const i=[],a={noScheduledDate:[]};for(const t of e){const e=t.schedule||{},n=e.scheduledDate&&$i(e.scheduledDate)||e.scheduledTime&&$i(e.scheduledTime)||"noScheduledDate";a[n]||(a[n]=[]),a[n].push(t)}const o=Object.keys(a).sort();for(const t of o){const e=a[t],o={noScheduledTime:[]};for(const t of e){const e=t.schedule||{},n=e.scheduledTime&&qi(e.scheduledTime)||"noScheduledTime";o[n]||(o[n]=[]),o[n].push(t)}for(const t of Object.keys(o)){const e=o[t].sort(((t,e)=>(t.roundNumber||0)-(e.roundNumber||0)));o[t]=e}const s=Object.keys(o).sort();for(const t of s){const e=o[t];e.sort(((t,e)=>(n[r(t)]||0)-(n[r(e)]||0))),i.push(...e)}}return i}function cD(t){let{participants:e,contextContent:n,participantMap:r}=t;const{tournamentAppliedPolicies:i,scheduleVisibilityFilters:a,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,usePublishState:p,contextFilters:l,matchUpFilters:m,contextProfile:f,nextMatchUps:h,tournamentId:g,inContext:I,context:U,event:y}=t;if(!y)return{error:$t};const{eventId:S,eventName:v,endDate:w,eventType:P,category:D,gender:T}=y??{},b={...U,...Xr({surfaceCategory:y.surfaceCategory??d?.surfaceCategory,indoorOutDoor:y.indoorOutdoor??d?.indoorOutdoor,tournamentId:g??d?.tournamentId,endDate:w??d?.endDate,eventName:v,eventType:P,category:D,eventId:S,gender:T})};let R;!e&&d&&({participants:e,participantMap:r,groupInfo:R}=Mp({participantsProfile:o,useParticipantMap:u,tournamentRecord:d,contextProfile:f,inContext:I})),f&&!n&&(n=Lp({policyDefinitions:c,tournamentRecord:d,contextProfile:f,event:y}));const M=Yf({event:y});return{...(y.drawDefinitions??[]).reduce(((u,g)=>{const U=uf({hydrateParticipants:t.hydrateParticipants,context:b,tournamentAppliedPolicies:i,scheduleVisibilityFilters:a,tournamentParticipants:e,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,usePublishState:p,contextContent:n,contextFilters:l,matchUpFilters:m,participantMap:r,publishStatus:M,contextProfile:f,drawDefinition:g,nextMatchUps:h,inContext:I,event:y}),S=Object.keys(U);return S?.forEach((t=>{Array.isArray(U[t])&&(u[t]||(u[t]=[]),u[t]=u[t].concat(U[t]))})),u}),{}),...z,groupInfo:R}}function uD(t){if(!t?.tournamentRecord)return{error:nt};let e=t.contextContent;const{scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:o,inContext:s=!0,usePublishState:c,contextFilters:u,matchUpFilters:d,contextProfile:p,nextMatchUps:l,context:m}=t,f=t.tournamentId??o.tournamentId,h=o?.events??[],{participants:g,participantMap:I,groupInfo:U}=Mp({participantsProfile:r,tournamentRecord:o,contextProfile:p,inContext:s});p&&!e&&(e=Lp({policyDefinitions:a,tournamentRecord:o,contextProfile:p}));const{appliedPolicies:y}=Np({tournamentRecord:o}),S=u?.eventIds??[];return{...h.filter((t=>!S.includes(t.eventId))).map((h=>{const U=jm({event:h}).flightProfile,S={eventDrawsCount:U?.flights?.length||h.drawDefinitions?.length||0,...m};return cD({hydrateParticipants:t.hydrateParticipants,context:S,tournamentAppliedPolicies:y,scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:o,usePublishState:c,contextFilters:u,contextProfile:p,contextContent:e,matchUpFilters:d,participantMap:I,participants:g,tournamentId:f,nextMatchUps:l,inContext:s,event:h})})).reduce(((t,e)=>{const n=e&&Object.keys(e).filter((t=>!["success","matchUpsMap"].includes(t)));return n?.forEach((n=>{Array.isArray(e[n])&&(t[n]||(t[n]=[]),t[n]=t[n].concat(e[n]),void 0!==t.matchUpsCount?t.matchUpsCount+=e[n].length:t.matchUpsCount=e[n].length)})),t}),{matchUpsCount:0}),groupInfo:U,participants:g}}function dD({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:n,tournamentRecords:r,useParticipantMap:i,policyDefinitions:a,usePublishState:o,matchUpFilters:s,contextFilters:c,nextMatchUps:u,inContext:d}){if("object"!=typeof r||!Object.keys(r).length)return{error:et};const p=Object.keys(r).map((i=>{const p=r[i];return uD({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:n,policyDefinitions:a,tournamentRecord:p,usePublishState:o,matchUpFilters:s,contextFilters:c,nextMatchUps:u,inContext:d})})),l={},m={};return{...p.reduce(((t,e)=>(Object.keys(e).forEach((n=>{if("groupInfo"===n)Object.assign(m,e[n]);else if("participants"===n)for(const t of e[n]??[])l[t.participantId]=t;else Array.isArray(e[n])&&(t[n]||(t[n]=[]),t[n]=t[n].concat(e[n]))})),t)),{}),groupInfo:m,mappedParticipants:l}}function pD(t){if("object"!=typeof t?.tournamentRecords||!Object.keys(t?.tournamentRecords).length)return{error:et};const{courts:e,venues:n}=vP(t),r=xP(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:a,alwaysReturnCompleted:o,activeTournamentId:s,tournamentRecords:c,withCourtGridRows:u,minCourtGridRows:d,usePublishState:p,status:l=am,sortCourtsData:m}=t,f=s??jr()??Object.keys(c)[0],h=p?zf({tournamentRecord:c[f],status:l}):void 0,g=o?dD({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[xu]},contextFilters:t.contextFilters}).completedMatchUps:[];if(p&&!h?.orderOfPlay?.published)return{completedMatchUps:g,dateMatchUps:[],courtsData:[],venues:n};let I,U;p&&({drawIds:I,detailsMap:U}=function({tournamentRecords:t}){const e={},n=[];for(const r of Object.values(t))for(const t of r.events??[]){const r=Yf({event:t}),i=r?.drawDetails;G(i)?(Object.assign(e,i),n.push(...Object.keys(i).filter((t=>Kf({drawId:t,drawDetails:i}))))):r?.drawIds?.length&&n.push(...r.drawIds)}return{drawIds:n,detailsMap:e}}({tournamentRecords:c})),I?.length&&(t.contextFilters||(t.contextFilters={}),t.contextFilters?.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter((t=>I.includes(t))):t.contextFilters.drawIds=I),h?.eventIds?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter((t=>h.eventIds.includes(t))):t.matchUpFilters.eventIds=h.eventIds),h?.scheduledDates?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter((t=>h.scheduledDates.includes(t))):t.matchUpFilters.scheduledDates=h.scheduledDates),o&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(xu)||t.matchUpFilters.excludeMatchUpStatuses.push(xu):t.matchUpFilters.excludeMatchUpStatuses=[xu]);const{completedMatchUps:y,upcomingMatchUps:S,pendingMatchUps:v,groupInfo:w,mappedParticipants:P}=dD({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters});let D=[...S??[],...v??[]];!U||I?.length&&!Object.keys(U).length||(D=D.filter((t=>{const{drawId:e,structureId:n,stage:r}=t;if(!U?.[e]?.publishingDetail?.published)return!1;const i=Object.keys(U[e].stageDetails??{});if(i.length){const t=i.filter((t=>!U[e].stageDetails[t].published)),n=i.filter((t=>U[e].stageDetails[t].published));return(!t.length||!t.includes(r))&&(!(!n.length||!n.includes(r))||t.length&&!t.includes(r)&&!n.length)}const a=Object.keys(U[e].structureDetails??{});if(a.length){const t=a.filter((t=>!U[e].structureDetails[t].published)),r=a.filter((t=>U[e].structureDetails[t].published));return(!t.length||!t.includes(n))&&(!(!r.length||!r.includes(n))||t.length&&!t.includes(n)&&!r.length)}return!0})));const T=i?sD({matchUps:D,schedulingProfile:r}):D,b=e?.map((t=>{const e=function({courtId:t}){const e=(a?T.concat(y??[]):T).filter((e=>e.schedule?.courtId===t||e.schedule?.allocatedCourts?.map((({courtId:t})=>t)).includes(t)));return m?sD({matchUps:e,schedulingProfile:r}):e}(t);return{surfaceCategory:t?.surfaceCategory??"",matchUps:e,...t}})),R={completedMatchUps:o?g:y,mappedParticipants:t.hydrateParticipants?void 0:P,dateMatchUps:T,courtsData:b,groupInfo:w,venues:n};if(u){const{rows:t,courtPrefix:e}=WP({minRowsCount:d,courtsData:b});R.courtPrefix=e,R.rows=t}return{...R,...z}}function lD({tournamentRecords:t,tournamentId:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:et};let n;return Object.keys(t).filter((t=>!e||t===e)).forEach((e=>{const r=t[e],{matchUpDailyLimits:i}=function(t){const e=cc(t,[{[hs]:!0}]);if(e.error)return e;const{tournamentRecord:n}=t,{policy:r}=Bp({policyType:Rc,tournamentRecord:n}),{extension:i}=zc({element:n,name:lu}),a=i?.value?.dailyLimits,o=r?.defaultDailyLimits;return{matchUpDailyLimits:a||o}}({tournamentRecord:r});n=i})),{matchUpDailyLimits:n}}function mD(t){let{matchUps:e}=t;const{singlesForDoubles:r,tournamentRecord:a,drawDefinition:o,excludeMargin:s,exclusionRule:c,zoneDoubling:u,matchUpType:d,scaleName:p,eventId:l,zonePct:m,drawId:f,event:h}=t;if(!a&&!e)return{error:nt};if(d&&![n,i].includes(d))return{error:Jn,info:{matchUpType:d}};if(e&&!yl(e))return{error:Jn,context:{matchUps:e}};const g=hU[p],I=g?.ascending??t.ascending??!1,U=g?.accessor??t.valueAccessor,S=Array.isArray(g?.range)?Math.abs(g.range[0]-g.range[1]):0,v=y(m)&&S?(m??0)*S:t.zoneMargin??S,w={withScaleValues:!0,withCompetitiveness:!0},P={matchUpTypes:d?[d]:[n,i]},D=a?.participants;e?.[0]?.hasContext?f?e=e.filter((t=>t.drawId===f)):l&&(e=e.filter((t=>t.eventId===l))):void 0===e&&(e=f&&!o&&[]||!f&&l&&!h&&[]||f&&ff({inContext:!0,drawDefinition:o,contextFilters:P,contextProfile:w,participants:D})?.matchUps||!f&&l&&df({inContext:!0,contextFilters:P,contextProfile:w,participants:D,event:h})?.matchUps||pf({tournamentRecord:a,contextFilters:P,contextProfile:w})?.matchUps||[]),d&&(e=e.filter((t=>t.matchUpType===d)));const T=e.filter((({winningSide:t,score:e,sides:n,matchUpStatus:r})=>![$u,Lu,zu,_u,Cu].includes(r??"")&&vf({score:e})&&2===n?.length&&t)),b=function({excludeMargin:t,exclusionRule:e,valueAccessor:n,ascending:r,scaleName:i,matchUps:a}){const o={affirmative:[],negative:[],excluded:[]};for(const s of a){const{matchUpType:a,sides:c,score:u,winningSide:d}=s;if(!d)continue;if(e&&(!e.valueAccessor||!e.range))return{info:"exclusionRule requires valueAccessor and range",error:be};const p=d-1,l=fD({exclusionRule:e,valueAccessor:n,matchUpType:a,scaleName:i,sides:c});if(e){const t=l.map((({exclusionValues:t})=>t)).flat();if(t.length){o.excluded.push({scoreString:u?.scoreStringSide1,exclusionValues:t,winningSide:d,sideValues:l});continue}}if(l.filter((t=>![void 0,"",null].includes(t.value))).length<2){o.excluded.push({scoreString:u?.scoreStringSide1,missingValues:!0,winningSide:d,sideValues:l});continue}const m=l[p].value-l[1-p].value,f=parseFloat(t||0),h=f&&Math.abs(m)<f;if(h){o.excluded.push({scoreString:u?.scoreStringSide1,excludeMargin:t,winningSide:d,excludeGap:h,sideValues:l,valuesGap:m});continue}const g=r?m:-1*m,I=1===d?u?.scoreStringSide1:u?.scoreStringSide2;g>0?o.affirmative.push({winningScoreString:I,winningSide:d,sideValues:l,valuesGap:m,score:u}):o.negative.push({winningScoreString:I,winningSide:d,sideValues:l,valuesGap:m,score:u})}const s=o.affirmative.length+o.negative.length,c=s&&o.affirmative.length/s*100;return o.percent=c?Math.round(100*c)/100:0,o}({matchUps:T,excludeMargin:s,exclusionRule:c,valueAccessor:U,ascending:I,scaleName:p}),R=!u||um(n)(d)?v:2*(v||0),M=v?T.map((({competitiveProfile:t,matchUpType:e,score:n,sides:i})=>{const a=fD({singlesForDoubles:r,valueAccessor:U,matchUpType:e,scaleName:p,sides:i}),o=Math.abs(a[0].value-a[1].value);return{competitiveness:t?.competitiveness,valuesGap:o,score:n}})).filter((({valuesGap:t})=>t<=R)):[],N=function({zoneData:t}){const e={[Op]:[],[Fp]:[],[kp]:[]};for(const n of t){const{competitiveness:t,score:r,valuesGap:i}=n;e[t]&&e[t].push({score:r,valuesGap:i})}return e}({zoneData:M}),A=N&&[].concat(Object.values(N)).flat().length,E=A&&Object.assign({},...Object.keys(N).map((t=>({[t]:Math.round(1e4*N[t].length/A)/100})))),C=T.length-(M?.length||0);return{...z,relevantMatchUps:T,zoneDistribution:E,zoneData:M,accuracy:b,nonZone:C}}function fD({singlesForDoubles:t,exclusionRule:e,valueAccessor:n,matchUpType:r,scaleName:i,sides:a}){const o=e?.range.sort(),s=t=>{const n=t?.[e?.valueAccessor];return{exclude:e&&n>=o[0]&&n<=o[1],exclusionValue:n}};return a.sort(((t,e)=>t.sideNumber-e.sideNumber)).map((({participant:e})=>{const a=[],o=e?.individualParticipants;if(o?.length){const c=[];let u=0;for(const e of o){const{scaleValue:o,value:d}=hD({singlesForDoubles:t,valueAccessor:n,participant:e,matchUpType:r,scaleName:i}),{exclude:p,exclusionValue:l}=s(o);p&&a.push(l),c.push(o),d&&!isNaN(u)?u+=d:u=void 0}return{participantName:e.participantName,exclusionValues:a,scaleValues:c,value:u}}if(e){const{scaleValue:o,value:c}=hD({singlesForDoubles:t,valueAccessor:n,matchUpType:r,participant:e,scaleName:i}),{exclude:u,exclusionValue:d}=s(o);return u&&a.push(d),{participantName:e.participantName,exclusionValues:a,scaleValue:o,value:c}}return{}}))}function hD({singlesForDoubles:t,valueAccessor:e,matchUpType:r,participant:i,scaleName:a}){const o=t?n:r,s=i?.rankings?.[o]?.find((t=>t.scaleName===a)),c=i?.ratings?.[o]?.find((t=>t.scaleName===a)),u=(c||s)?.scaleValue;return{scaleValue:u,value:e?u?.[e]:u}}function gD({collectionDefinitions:t=[],collectionGroups:e=[]}){let n=0;const{groupValueNumbers:r}=YU({collectionGroups:e});let i;for(const e of t||[]){const{collectionValueProfiles:t,collectionGroupNumber:a,collectionValue:o,matchUpCount:s,matchUpValue:c,scoreValue:u,setValue:d}=e,p=a&&r.includes(a);if(y(d||u))i=!0;else{if(p)continue;if("number"==typeof o&&y(o))n+=o;else if(Array.isArray(t)&&t?.length)for(const e of t)n+=e.matchUpValue;else"number"==typeof c&&y(c)&&(n+=(s??0)*c)}}for(const t of e)n+=t.groupValue??0;if(i||!n)return{aggregateValue:!0,...z};return{valueGoal:Math.floor(n/2)+1,...z}}function ID(t){const{timeStamp:e,schedule:n,matchUp:r}=t,i=cc(t,[{[Gs]:!0}]);if(i.error)return i;const{itemValue:a,timeStamp:o}=Mm({timeItems:r?.timeItems||[],itemType:Vl});return!n||o&&e&&new Date(o).getTime()>new Date(e).getTime()?{homeParticipantId:a}:n}function UD({matchUps:t,matchUpId:e}){if(!yl(t))return{error:Jn};const n=t.find((t=>t.matchUpId===e)),{drawId:r,eventId:i,structureId:a,tournamentId:o}=n||{};return{matchUpId:e,drawId:r,eventId:i,structureId:a,tournamentId:o}}function yD(t,e){if(!G(t))return{error:Jn};if(!Array.isArray(e))return{error:Jn};const n={};for(const{param:r,error:i,attr:a}of e){const e=SD({params:t,param:r,attr:a,error:i});if(e?.error)return e;n[r]=e}return n}function SD({params:t,param:e,attr:n,error:r}){if(e===ks&&G(t.drawDefinition)&&j(t.structureId)){const e=(t.drawDefinition.structures??[]).find((({structureId:e})=>e===t.structureId));return!e.length&&r?{error:r}:{structure:e}}if(e===Gs){const e=hP({...t,...n});return e.error&&r?{...e,error:r}:e}return{error:rr,info:{param:e}}}function vD(t){const{structureId:e,matchUpId:n,event:r}=t;let i=t.drawDefinition;const a=cc(t,[{[hs]:!0},{[rc]:{[Ts]:!1,[Cs]:!1,[qs]:!1,[Ws]:!1}}]);if(a[$s])return a;const o=yD(t,[{[Hs]:Gs,[$s]:be}]),s=o?.matchUp;if(n&&s?.error)return s;!i&&s?.drawDefinition&&(i=s?.drawDefinition);let c=s?.structure;if(!c&&e&&!n){if(!i)return{error:Tt};const t=ad({drawDefinition:i,structureId:e});if(t.error)return t;c=t.structure}const u=c?.matchUpFormat,d=i?.matchUpFormat,p=r?.matchUpFormat;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:p,drawDefaultMatchUpFormat:d,matchUpFormat:s?.matchUp?.matchUpFormat||u||d||p}}function wD({profileBands:t,tournamentRecord:e,matchUps:n}){if(!yl(n))return{error:me};const r=!t&&Bp({policyType:yc,tournamentRecord:e}).policy,i=t||r?.profileBands||_p[yc].profileBands,a=n.filter((({winningSide:t})=>t)),o=a.map(Ml),s=Al(o).reduce(((t,e)=>((t,e)=>(t[Rl(e,i)]+=1,t))(t,e)),{[Op]:0,[Fp]:0,[kp]:0,[Ep]:0}),c=Object.keys(s).reduce(((t,e)=>(s[e]||0)+t),0),u=Object.keys(s).map((t=>{const e=parseFloat((s[t]/c).toFixed(4));return{[t]:100*e}})),d=a.filter((({matchUpStatus:t})=>t===Cp)).length;return u.push({[Cp]:100*parseFloat((d/c).toFixed(4))}),{competitiveBands:Object.assign({},...u),...z}}const{stageOrder:PD}=ls;function DD(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(PD[t?.stage]||0)-(PD[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function TD({excludeScheduleDateProfileRounds:t,excludeScheduledRounds:e,excludeCompletedRounds:n,inContextMatchUps:r,tournamentRecords:i,schedulingProfile:a,tournamentRecord:o,withSplitRounds:s,matchUpFilters:c,scheduleDate:u,withRoundId:d,venueId:p,context:l}){if(r&&!Array.isArray(r||"object"!=typeof r[0]))return{error:Jn,inContextMatchUps:r};if(o&&!i){if("object"!=typeof o)return{error:rt};i={[o.tournamentId]:o}}const m="object"!=typeof i||!Object.keys(i).length;if((p||u||!r||!a&&(t||n||a||s))&&m)return{error:et};const f=Object.assign({},...Object.values(i??{}).map((({venues:t=[],tournamentId:e})=>({[e]:t?.map((({venueId:t})=>t))})))),h=Object.values(i??{}).map((({events:t=[],tournamentId:e,startDate:n,endDate:r})=>t.map((t=>({...t,validVenueIds:f[e],startDate:t.startDate??n,endDate:t.endDate??r}))))).flat(),{segmentedRounds:g,profileRounds:I}=i&&(t||n||a||s)&&$P({tournamentRecords:i,schedulingProfile:a})||{},U=t&&Object.assign({},...I.map((t=>({[t.id]:t})))),y=r||i&&lf({tournamentRecords:i,matchUpFilters:c})?.matchUps||[],S=[],v=y&&Object.values(y.reduce(((t,e)=>{const n=jP(e).id,r=g?.[n],i=[...t[n]?.matchUps??[],e],{containerStructureId:a,stageSequence:o,structureName:s,tournamentId:c,isRoundRobin:u,matchUpType:p,roundNumber:l,roundOffset:m,structureId:f,eventName:h,roundName:I,drawName:U,eventId:y,drawId:S}=e,v=u?a:f;return{...t,[n]:{id:d?n:void 0,structureId:v,stageSequence:o,segmentsCount:r,structureName:s,tournamentId:c,matchUpType:p,roundNumber:l,roundOffset:m,eventName:h,roundName:I,drawName:U,matchUps:i,eventId:y,drawId:S}}}),{})).map((t=>{const{minFinishingSum:e,winnerFinishingPositionRange:n}=(t.matchUps||[]).reduce(((t,e)=>{const n=(e.finishingPositionRange?.winner||[]).reduce(((t,e)=>t+e),0),r=(e.finishingPositionRange?.winner||[]).join("-")||"";return!t.minFinishingSum||n<t.minFinishingSum?{minFinishingSum:n,winnerFinishingPositionRange:r}:t}),{minFinishingSum:0,winnerFinishingPositionRange:""});const r=t.segmentsCount;if(r){const a=t.matchUps.length/r;return x(t.matchUps.sort(((t,e)=>t.roundPosition-e.roundPosition)),a).map(((a,o)=>{const{unscheduledCount:s,incompleteCount:c,matchUpsCount:u,isScheduled:d,isComplete:p,byeCount:m}=qP(a),f=GP({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return Xr({...t,...l,roundSegment:{segmentsCount:r,segmentNumber:o+1},winnerFinishingPositionRange:n,unscheduledCount:s,incompleteCount:c,minFinishingSum:e,matchUpsCount:u,isScheduled:d,roundTiming:f,isComplete:p,byeCount:m,matchUps:a})}))}const{unscheduledCount:a,incompleteCount:o,matchUpsCount:s,isScheduled:c,isComplete:u,byeCount:d}=qP(t.matchUps),p=GP({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return Xr({...t,...l,winnerFinishingPositionRange:n,unscheduledCount:a,incompleteCount:o,minFinishingSum:e,matchUpsCount:s,isScheduled:c,roundTiming:p,isComplete:u,byeCount:d})})).flat().filter((r=>{if(t){const e=$i(t),n=d?r.id:jP(r).id;if(e&&U[n]&&$i(U[n].scheduleDate)===e)return!1}const{isComplete:i,isScheduled:a}=r,s=!n||!i,c=!e||!a,l=p||u?h?.find((({eventId:t})=>t===r.eventId)):void 0,m=l?.startDate??o?.startDate,f=l?.endDate??o?.endDate,g=!u||!m||new Date(u)>=new Date(m),I=!u||!f||new Date(u)<=new Date(f),y=g&&I,v=!p||l?.validVenueIds.includes(p),w=s&&c&&v&&y;return w||S.push(r),w})).sort(DD)||[];return{...z,rounds:v,excludedRounds:S}}function bD(t){const{matchUp:e,sideNumber:n,setNumber:r,isTiebreakValue:i,isPointValue:a}=t||{};let{matchUpFormat:o}=t||{};if(!e)return{error:fe};o=o||e?.matchUpFormat;const s=Ii(o),c=!!e?.winningSide,u=e.score?.sets,d=u?.length,p=r&&r-1,l=!!u?.find(((t,e)=>t.setNumber===r&&e===p)),m=u?.filter((t=>t?.winningSide))||[],f=m?.length||0,h=r&&u?.slice(r)||[],g=!!(d&&r&&h?.reduce(((t,e)=>(!e||!e.side1Score&&!e.side2Score&&!e.side1TiebreakScore&&!e.side2TiebreakScore&&!e.side1PointScore&&!e.side2PointScore)&&t),!0)),I=r<=d&&u.find((t=>t.setNumber===r)),U=I&&Pw({setObject:I,matchUpScoringFormat:s}),{isCompletedSet:y,sideGameScores:S,sideTiebreakScores:v}=U||{},w=!!(I&&!y&&g||r&&r===d+1&&!c),P=[1,2].includes(n),D=P?n-1:0,b=I&&P&&(!i&&!a&&void 0!==S[D]&&S[D]||i&&void 0!==v[D]&&v[D]),R=!!b,M=m?.map((t=>Pw({setObject:t,matchUpScoringFormat:s}).isValidSetOutcome)).reduce(((t,e)=>t&&e),!0),N=m.reduce(((t,e)=>{const{winningSide:n}=e;return t[n-1]++,t}),[0,0]),A=e?.winningSide,E=A&&A-1,C=1-E,O=N[E],F=N[C],k=Math.max(...N),x=T(N)[k],{bestOf:_,exactly:L}=s??{},B=k===(_&&Math.ceil(_/2)||L||1)&&1===x&&N.indexOf(k)+1||void 0,V=O>F&&A===B;return{completedSetsHaveValidOutcomes:M,validMatchUpWinningSide:V,calculatedWinningSide:B,matchUpScoringFormat:s,validMatchUpOutcome:B&&M&&V,isLastSetWithValues:g,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:P,hasExistingValue:R,existingValue:b,isExistingSet:l,isActiveSet:w,...U}}function RD({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,usePublishState:c,contextFilters:u,contextContent:d,matchUpFilters:p,participantMap:l,publishStatus:m,contextProfile:f,drawDefinition:h,nextMatchUps:g,tournamentId:I,inContext:U,context:y,event:S}){const{eventId:v,eventName:w,endDate:P,eventType:D,category:T,gender:b}=S??{},R={...y,...Xr({surfaceCategory:S?.surfaceCategory??s?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??s?.indoorOutdoor,endDate:P??S?.endDate??s?.endDate,tournamentId:I??s?.tournamentId,eventName:w,eventType:D,category:T,eventId:v,gender:b})};let M;!t?.length&&s&&({participants:t,participantMap:l,groupInfo:M}=Mp({participantsProfile:r,useParticipantMap:o,tournamentRecord:s,contextProfile:f,inContext:U})),S&&f&&!d&&(d=Lp({policyDefinitions:a,tournamentRecord:s,contextProfile:f,drawDefinition:h,event:S}));return{...uf({context:R,tournamentAppliedPolicies:e,scheduleVisibilityFilters:n,tournamentParticipants:t,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:s,usePublishState:c,participantMap:l,contextContent:d,contextFilters:u,matchUpFilters:p,publishStatus:m,contextProfile:f,drawDefinition:h,nextMatchUps:g,inContext:U,event:S}),groupInfo:M}}function MD({tournamentRecord:t,venueId:e,venueIds:n}){if(!t)return{error:nt};return{courts:(t.venues||[]).filter((t=>e?t.venueId===e:!n||n.includes(t.venueId))).map((t=>{const{venueId:e}=t,n=la(t.courts||[]);return n.forEach((t=>Object.assign(t,{venueId:e}))),n})).flat()}}var ND={__proto__:null,getCompetitionVenues:wP,getCourts:MD,getVenuesAndCourts:vP,publicFindVenue:xm};function AD({tournamentRecord:t,event:e}){if(!t)return{error:nt};if(!e)return{error:$t};const n=e.entries||[],r=t.participants||[],i=e.category?.categoryName||e.category?.ageCategoryCode,{eventType:a}=e,o=n.map((t=>t.participantId));let s,c,u;return{entryScaleAttributes:r.filter((t=>o.includes(t.participantId))).map((t=>{const{participantId:e,participantName:n,name:r}=t;let o={scaleType:rm,eventType:a,scaleName:i};const d=$f({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:nm,eventType:a,scaleName:i};const p=$f({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:em,eventType:a,scaleName:i};const l=$f({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;return s=!(!s&&!d),c=!(!c&&!p),u=!(!u&&!l),{participantId:e,participantName:n||r,seed:d,ranking:p,rating:l}})),hasSeededParticipants:s,hasRankedParticipants:c,hasRatedParticipants:u}}function ED({tournamentRecord:t,withScaleValues:e,scaleEventType:n,inContext:r,eventIds:i,drawIds:a,context:o}){if(!t)return{error:nt};const{tournamentId:s}=t,c=(t.events??[]).filter((({eventId:t})=>!i||Array.isArray(i)&&i.includes(t))).map((t=>{const e=t.drawDefinitions?.map(Au);if(a?.length&&!O(a,e).length)return;const n=la(t);return r&&Object.assign(n,{tournamentId:s}),o&&Object.assign(n,o),n})).filter(Boolean),u={};if(e){const e=ih({withScaleValues:!0,tournamentRecord:t}).participantMap,r=t=>t.reduce(((t,e)=>t+parseFloat(e)),0);for(const t of c){const i=n??t.eventType,o=t.eventId;u[o]||(u[o]={ratingsStats:{},ratings:{},ranking:{},draws:{}});const s=(t.entries??[]).filter((({entryStatus:t})=>al.includes(t))).map(Mu),c=t=>{if(t?.ratings?.[i])for(const e of t?.ratings?.[i]??[]){const t=e.scaleName;u[o].ratings[t]||(u[o].ratings[t]=[]);const n=hU[t]?.accessor;if(n){const r=parseFloat(e.scaleValue?.[n]);r&&u[o].ratings[t].push(r)}}if(t?.rankings?.[i])for(const e of t?.rankings?.[i]??[]){const t=e.scaleName;u[o].ranking[t]||(u[o].ranking[t]=[]),e.scaleValue&&u[o].ranking[t].push(e.scaleValue)}};for(const t of s){const n=e?.[t]?.participant;if(n?.participantType!==ap)for(const t of n?.individualParticipantIds??[]){const n=e?.[t]?.participant;c(n)}else c(n)}const d=u[o].ratings;for(const t of Object.keys(d)){const e=d[t];if(!e.length)continue;const n=l(e)?.toFixed(2);u[o].ratingsStats[t]={avg:parseFloat((r(e)/e.length).toFixed(2)),median:n?parseFloat(n):void 0,max:Math.max(...e),min:Math.min(...e)}}const p=(t,n)=>{const r=e=>{if(u[o].draws?.[t]&&e?.ratings?.[i])for(const n of e?.ratings?.[i]??[]){const e=n.scaleName;u[o].draws[t]?.ratings[e]||(u[o].draws[t].ratings[e]=[]);const r=hU[e]?.accessor;if(r){const i=parseFloat(n.scaleValue?.[r]);i&&u[o].draws[t].ratings[e].push(i)}}if(u[o].draws?.[t]&&e?.rankings?.[i])for(const n of e?.rankings?.[i]??[]){const e=n.scaleName;u[o].draws[t]?.ranking[e]||(u[o].draws[t].ranking[e]=[]);const r=n.scaleValue;r&&u[o].draws[t].ranking[e].push(r)}};for(const t of n.filter(Boolean)){const n=e?.[t]?.participant;if(n?.participantType!==ap)for(const t of n?.individualParticipantIds??[]){const n=e?.[t]?.participant;r(n)}else r(n)}},m=[],f=t=>a?.length&&a.includes(t)||m.includes(t);for(const e of t.drawDefinitions??[]){const t=e.drawId;if(f(t))continue;const n=Vf({drawDefinition:e}).assignedParticipantIds??[];u[o].draws[t]||(u[o].draws[t]={ratingsStats:{},ratings:{},ranking:{}}),m.push(t),p(t,n)}const h=jm({event:t}).flightProfile;for(const t of h?.flights??[]){const e=t.drawId;if(f(e))continue;p(e,t.drawEntries.map(Mu))}for(const t of m){const e=u[o].draws[t].ratings;for(const n of Object.keys(e)){const i=e[n];if(!i.length)continue;const a=l(i)?.toFixed(2);u[o].draws[t].ratingsStats[n]={avg:parseFloat((r(i)/i.length).toFixed(2)),median:a?parseFloat(a):void 0,max:Math.max(...i),min:Math.min(...i)}}}}}return Xr({eventScaleValues:u,events:c,...z})}function CD({tournamentRecord:t,drawDefinition:e,context:n,event:r}){if(!t)return{error:nt};if(!r)return{error:$t};const i=la(r);n&&Object.assign(i,n);return Xr({drawDefinition:e&&i.drawDefinitions?.find((({drawId:t})=>e.drawId===t)),event:i})}var OD={__proto__:null,addGoesTo:yf,allCompetitionMatchUps:lf,allDrawMatchUps:ff,allEventMatchUps:df,allPlayoffPositionsFilled:bg,allTournamentMatchUps:pf,analyzeDraws:Uy,analyzeMatchUp:bD,analyzeTournament:aP,bulkUpdatePublishedEventIds:UP,calculateWinCriteria:gD,categoryCanContain:aa,checkMatchUpIsComplete:Zm,checkValidEntries:gS,compareTieFormats:lP,competitionScheduleMatchUps:pD,courtGridRows:WP,credits:function(){return"\n This project would not have been possible without the generous input and patience\n of tournament organizers and directors who worked with early versions of CourtHive/TMX.\n\n Thanks to Miro, Pavel, Ivan, Mladen, Zdenko, Antonia, Jakov, Kreso, Barry, Jeff, Bobby... to name just a few. \n\n The project would not have even begun without the support of Miro, or the introduction by Sretchko.\n The project would not have succeeded without the enthusiasm of Randy and Bruce.\n Thanks to serendipity and Luca and the ensuing TODS conversations with ITF.\n Thanks to Scott and Jake for sanity checks, suggestions, and camaraderie.\n Thanks to Zoran for inspiring the async support and getting into the weeds with subscriptions.\n Thanks to Dave for backing the conversion of TMX 1.x source into the factory repository.\n Thanks to Vuk and Pavle and Rich and Chris and Deepa for the direct engagement with the APIs.\n Thanks to Joe for repeatedly challenging me and the many pointers to useful tooling.\n Thanks to Shannon for the validation of the approach from his deep domain experience.\n Thanks to Nikola for the ongoing camaraderie and explorations of what we can do with TODS.\n\n And a special thanks to my family for putting up with the long days and weeks and months of coding\n and conversations at all hours.\n "},drawMatchUps:RD,eventMatchUps:cD,filterMatchUps:Qm,filterParticipants:nh,findDrawDefinition:Cy,findExtension:zc,findVenue:km,getAggregateTeamResults:rP,getAllDrawMatchUps:cf,getAllEventData:PP,getAllStructureMatchUps:Jm,getAllowedDrawTypes:Kw,getAllowedMatchUpFormats:Yw,getAppliedPolicies:Np,getAssignedParticipantIds:Vf,getAvailableMatchUpsCount:My,getAvailablePlayoffProfiles:eU,getCategoryAgeDetails:ra,getCheckedInParticipantIds:cm,getCompetitionDateRange:eP,getCompetitionMatchUps:dD,getCompetitionParticipants:Gw,getCompetitionPenalties:Jw,getCompetitionVenues:wP,getCourtInfo:Bm,getCourts:MD,getDrawData:RP,getDrawDefinitionTimeItem:Up,getDrawParticipantRepresentativeIds:Ny,getDrawStructures:od,getDrawTypeCoercion:dS,getEligibleVoluntaryConsolationParticipants:Ry,getEntriesAndSeedsCount:zP,getEvent:CD,getEventData:MP,getEventMatchUpFormatTiming:nD,getEventProperties:AD,getEventPublishStatus:Yf,getEventStructures:Pg,getEventTimeItem:yp,getEvents:ED,getFlightProfile:jm,getHomeParticipantId:ID,getLinkedTournamentIds:Pu,getMatchUpCompetitiveProfile:El,getMatchUpContextIds:UD,getMatchUpDailyLimits:lD,getMatchUpDailyLimitsUpdate:iD,getMatchUpDependencies:Sf,getMatchUpFormat:vD,getMatchUpFormatTiming:Tm,getMatchUpFormatTimingUpdate:JP,getMatchUpScheduleDetails:qm,getMatchUpType:zm,getMatchUpsMap:hl,getMatchUpsStats:wD,getMatchUpsToSchedule:EP,getMaxEntryPosition:YP,getModifiedMatchUpFormatTiming:rD,getPairedParticipant:Wm,getParticipantEventDetails:qw,getParticipantIdFinishingPositions:Ay,getParticipantMembership:$w,getParticipantResults:DU,getParticipantScaleItem:ES,getParticipantSchedules:Ww,getParticipantSignInStatus:Hw,getParticipantTimeItem:vp,getParticipants:ih,getPersonRequests:VP,getPolicyDefinitions:Ap,getPositionAssignments:mS,getPositionsPlayedOff:XI,getPredictiveAccuracy:mD,getProfileRounds:$P,getPublishState:Qf,getRandomQualifierList:pS,getRoundMatchUps:Sl,getRounds:TD,getScaleValues:gc,getScaledEntries:Ew,getScheduledRoundsDetails:OP,getSchedulingProfile:xP,getSchedulingProfileIssues:BP,getSeedingThresholds:Hh,getSeedsCount:hS,getStructureSeedAssignments:pl,getTeamLineUp:Hm,getTieFormat:gP,getTimeItem:Ip,getTournamentIds:Hc,getTournamentInfo:tP,getTournamentPenalties:Qw,getTournamentPersons:nP,getTournamentPoints:uP,getTournamentPublishStatus:zf,getTournamentStructures:Dg,getTournamentTimeItem:Sp,getValidGroupSizes:qh,getVenueData:Vm,getVenuesAndCourts:vP,isAdHoc:Dl,isCompletedStructure:Tg,isValidForQualifying:lS,isValidMatchUpFormat:Di,matchUpActions:oS,participantScaleItem:$f,participantScheduledMatchUps:oD,positionActions:uS,publicFindCourt:Lm,publicFindVenue:xm,tallyParticipantResults:LU,tieFormatGenderValidityCheck:si,tournamentMatchUps:uD,validMatchUp:Ul,validMatchUps:yl,validateCollectionDefinition:oa,validateLineUp:dg};function FD(t){const e="validateAndDeriveDrawValues",{appliedPolicies:n,policyDefinitions:r}=function(t){const{tournamentRecord:e,event:n}=t,r=Np({tournamentRecord:e,event:n}).appliedPolicies??{},i=la(t.policyDefinitions??{},!1,!0);return{appliedPolicies:r,policyDefinitions:i}}(t),i=function({enforceGender:t,policyDefinitions:e,appliedPolicies:n}){return t??e?.[wc]?.participants?.enforceGender??n?.[wc]?.participants?.enforceGender}({...t,policyDefinitions:r,appliedPolicies:n}),a=function({considerEventEntries:t=!0,drawEntries:e,eventEntries:n,qualifyingOnly:r}){return(r&&[]||kD(e)||(t?n:[])).filter((({entryStage:t})=>!t||t===fo))}(t),o=function(t){const{consideredEntries:e,appliedPolicies:n,policyDefinitions:r,enforceGender:i,participantMap:a,participants:o,event:s}=t;return s&&o&&gS({consideredEntries:e,policyDefinitions:r,appliedPolicies:n,participantMap:a,enforceGender:i,participants:o,event:s})}({...t,consideredEntries:a,appliedPolicies:n});if(o?.error)return ti({result:o,stack:e});const s=function(t){const e=!t.drawSize&&t.consideredEntries.length&&![_o,Go,Lo,rs,is].includes(t.drawType??"")&&I(t.consideredEntries.length);return e||t.drawSize&&d(t.drawSize)||!1}({...t,consideredEntries:a}),c=function(t){const{policyDefinitions:e,appliedPolicies:n,enforceMinimumDrawSize:r=!0,drawSize:i}=t,a=t.drawTypeCoercion??dS({drawType:t.drawType,policyDefinitions:e,appliedPolicies:n}),o=SS({drawType:t.drawType,enforceMinimumDrawSize:r,drawTypeCoercion:a,drawSize:i});return o.error?o:{drawType:o.drawType}}({...t,appliedPolicies:n,policyDefinitions:r,drawSize:s});if(c.error)return ti({result:c,stack:e});const u=c.drawType;if(isNaN(s)&&u!==_o)return ti({result:{error:Dt},stack:e});const p=r?.[Ac]??n?.[Ac],l=t.seedingProfile??p?.seedingProfile?.drawTypes?.[u??""]??p?.seedingProfile;t.seedingProfile&&(r[Ac]||(r[Ac]={...Bw[Ac]}),r[Ac].seedingProfile=l);const m=function(t){const{tournamentRecord:e,event:n,ignoreAllowedDrawTypes:r,drawType:i}=t,a=!r&&e&&Kw({tournamentRecord:e,categoryType:n?.category?.categoryType,categoryName:n?.category?.categoryName});if(a?.length&&!a.includes(i))return{error:vt};return{...z}}({...t,drawType:u});return m?.error?ti({result:m,stack:e}):{drawSize:s,drawType:u,enforceGender:i,seedingProfile:l,appliedPolicies:n,policyDefinitions:r}}function kD(t){return t?.filter((t=>t.entryStatus&&[...al,Qp].includes(t.entryStatus)))}function xD(t){const{voluntaryConsolation:e,tournamentRecord:n,event:r}=t,i="generateDrawDefinition",{participants:a,participantMap:o}=ih({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:n}),s=kD(r?.entries)??[],c=FD({...t,participantMap:o,participants:a,eventEntries:s});if(c.error)return ti({result:c,stack:i});const{appliedPolicies:u,policyDefinitions:d,drawSize:p,drawType:l,enforceGender:m,seedingProfile:f}=c,h=r?.eventType,g=t.matchUpType??h,I=function(t){const{existingDrawDefinition:e,hydrateCollections:n,enforceGender:r,tieFormatName:i,matchUpType:a,eventType:o,isMock:s,event:c}=t;let{tieFormat:u,matchUpFormat:d}=t;if(a===po&&o===po){const t=e?.structures?.find((({stage:t})=>t===fo))?.tieFormat;u=u||t||i&&c?.tieFormat?.tieFormatName===i&&c.tieFormat||i&&ao({namedFormat:i,hydrateCollections:n,isMock:s,event:c})||c?.tieFormat||ao({event:c,isMock:s,hydrateCollections:n}),d=void 0}else d||(u=void 0,c?.matchUpFormat||(d=ba));if(u){const t=sa({gender:c?.gender,enforceGender:r,tieFormat:u});if(t.error)return t}return{tieFormat:u,matchUpFormat:d}}({...t,enforceGender:m,eventType:h,matchUpType:g});if(I.error)return ti({result:I,stack:i});const{matchUpFormat:U,tieFormat:y}=I;if(t.drawId&&"string"!=typeof t.drawId)return ti({result:{error:Jn},stack:i});const S=function(t){const e="generateOrGetExisting",n=[],r=[],i=jw(t);if(i.error)return ti({result:i,stack:e});const a=i.existingDrawDefinition;let o=i.drawDefinition??{},s=i.structureId;const c=t.drawEntries??t.eventEntries??[],u=i.existingQualifyingPlaceholderStructureId&&Tw({...t,...i})||Ow({...t,...i,entries:c});return u.error?ti({result:u,stack:e}):(u.positioningReports?.length&&n.push(...u.positioningReports??[]),u.conflicts?.length&&r.push(...u.conflicts??[]),o=u.drawDefinition,s=u.structureId,{existingDrawDefinition:a,positioningReports:n,drawDefinition:o,structureId:s,conflicts:r,entries:c})}({...t,policyDefinitions:d,tournamentRecord:n,appliedPolicies:u,matchUpFormat:U,seedingProfile:f,participants:a,eventEntries:s,matchUpType:g,tieFormat:y,drawSize:p,drawType:l,event:r});if(S.error)return ti({result:S,stack:i});const{existingDrawDefinition:v,positioningReports:w,drawDefinition:P,structureId:D,conflicts:T,entries:b}=S;if(!P)return ti({result:{error:Jn},stack:i});const R=function(t){const{qualifyingPlaceholder:e,existingDrawDefinition:n,positioningReports:r,qualifyingProfiles:i,appliedPolicies:a,qualifyingOnly:o,drawDefinition:s,seedingProfile:c,participants:u,structureId:d,tieFormat:p,entries:l,stack:m}=t,f=e&&!i?.length&&!n,h=[];if(i){const e=(t,e)=>t.stageSequence-e.stageSequence,n=(t,e)=>t.roundTarget-e.roundTarget,d=[];let p=1;i.sort(n);for(const n of i){if(!Array.isArray(n.structureProfiles))return ti({info:ug("structureProfiles"),result:{error:be},stack:m});p=n.roundTarget||p;const i=n.structureProfiles?.sort(e)||[];let f=1;for(const e of i){const{qualifyingRoundNumber:n,qualifyingPositions:i,seededParticipants:m,seedingScaleName:g,seedsCount:I=0,seedByRanking:U,placeByes:y,drawSize:S}=e,v=Cw({...t,seedingProfile:e.seedingProfile??c,stageSequence:f,qualifyingRoundNumber:n,preparedStructureIds:d,qualifyingPositions:i,seededParticipants:m,stage:ho,seedingScaleName:g,appliedPolicies:a,drawDefinition:s,qualifyingOnly:o,seedByRanking:U,participants:u,roundTarget:p,seedsCount:I,placeByes:y,drawSize:S,entries:l});if(v.error)return v;v.structureId&&d.push(v.structureId),f+=1,v.conflicts?.length&&h.push(...v.conflicts),v.positioningReport?.length&&r.push({[ho]:v.positioningReport})}p+=1}}else if(d&&f){const t=Fh({structureName:xh(ho),stage:ho,qualifyingOnly:o,tieFormat:p}),{link:e}=_I({sourceStructureId:t.structureId,targetStructureId:d,sourceRoundNumber:0,linkType:Oo});s.structures||(s.structures=[]),s.structures.push(t),s.links||(s.links=[]),s.links.push(e)}return{qualifyingConflicts:h,error:void 0}}({...t,existingDrawDefinition:v,positioningReports:w,appliedPolicies:u,drawDefinition:P,seedingProfile:f,participants:a,structureId:D,entries:b,params:t,stack:i});if(R.error)return R;const{qualifyingConflicts:M}=R;return P.drawName=t.drawName??(l&&xh(l)),p&&"object"==typeof e&&p>=4&&_h({...e,drawDefinition:P,matchUpType:g}),{existingDrawDefinition:!!v,qualifyingConflicts:M,positioningReports:w,drawDefinition:P,structureId:D,...z,conflicts:T}}function _D({scaleAttributes:t,scaledEntries:e,stageEntries:n,seedsCount:r,scaleName:i}){if(!t)return{error:be,info:"missing scaleAttributes"};const a=Object.assign({},...(e||[]).slice(0,r).map((({participantId:t},e)=>({[t]:e+1}))));i=i||t.scaleName;const o=(new Date).toISOString();return{scaleItemsWithParticipantIds:n.map((({participantId:e})=>({scaleItems:[{scaleValue:a[e],eventType:t.eventType,scaleType:fc,scaleName:i,scaleDate:o}],participantId:e})))}}var LD={__proto__:null,adHocPositionSwap:WI,addAdHocMatchUps:Dy,addDrawDefinitionTimeItem:sI,addFinishingRounds:Uf,addGoesTo:yf,addPlayoffStructures:ly,addQualifyingStructure:$I,addVoluntaryConsolationStage:fI,addVoluntaryConsolationStructure:_h,allPlayoffPositionsFilled:bg,alternateDrawPositionAssignment:vg,assignDrawPosition:Sy,assignDrawPositionBye:Ef,attachConsolationStructures:uy,attachPlayoffStructures:dy,attachQualifyingStructure:aI,attachStructures:py,autoSeeding:function({tournamentRecord:t,drawDefinition:e,policyDefinitions:n,scaleAttributes:r,scaleName:i,drawSize:a,drawId:o,event:s,stage:c,sortDescending:u,scaleSortMethod:d}){const p=zP({policyDefinitions:n,drawDefinition:e,drawSize:a,drawId:o,event:s,stage:c});if(p.error)return p;const{entries:l,seedsCount:m,stageEntries:f}=p;if(!f||!m)return{error:Jn};const h=Ew({tournamentRecord:t,scaleAttributes:r,scaleSortMethod:d,sortDescending:u,entries:l,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:g}=_D({scaleAttributes:r,scaledEntries:h,stageEntries:f,seedsCount:m,scaleName:i});return{scaleItemsWithParticipantIds:g}},automatedPlayoffPositioning:Jg,automatedPositioning:Qg,checkValidEntries:gS,deleteAdHocMatchUps:wy,drawMatic:Nw,findDrawDefinition:Cy,generateAdHocMatchUps:kS,generateAdHocRounds:Rw,generateAndPopulatePlayoffStructures:ry,generateDrawDefinition:xD,generateDrawMaticRound:$S,generateDrawStructuresAndLinks:DS,generateDrawTypeAndModifyDrawDefinition:TS,generateQualifyingStructure:qI,generateVoluntaryConsolation:WS,getAssignedParticipantIds:Vf,getAvailableMatchUpsCount:My,getAvailablePlayoffProfiles:eU,getDrawDefinitionTimeItem:Up,getDrawParticipantRepresentativeIds:Ny,getDrawStructures:od,getDrawTypeCoercion:dS,getEligibleVoluntaryConsolationParticipants:Ry,getMatchUpsMap:hl,getParticipantIdFinishingPositions:Ay,getPositionAssignments:mS,getPositionsPlayedOff:XI,getRandomQualifierList:pS,getSeedingThresholds:Hh,getSeedsCount:hS,getStructureSeedAssignments:pl,getTeamLineUp:Hm,getValidGroupSizes:qh,isAdHoc:Dl,isCompletedStructure:Tg,isValidForQualifying:lS,luckyLoserDrawPositionAssignment:hg,modifyDrawDefinition:gy,modifyDrawName:hy,modifySeedAssignment:Zg,mutate:by,positionActions:uS,pruneDrawDefinition:yy,qualifierDrawPositionAssignment:Xg,qualifierProgression:eI,query:IS,removeDrawPositionAssignment:Ch,removeRoundMatchUps:Py,removeSeededParticipant:xI,removeStructure:cI,renameStructures:oI,resetDrawDefinition:Iy,resetQualifyingStructure:hI,resetVoluntaryConsolationStructure:Kd,setDrawParticipantRepresentativeIds:Eu,setPositionAssignments:yg,setStructureOrder:nI,setSubOrder:Ty,shiftAdHocRounds:Ug,swapAdHocRounds:Sg,swapDrawPositionAssignments:FI,updateTeamLineUp:pg,withdrawParticipantAtDrawPosition:Oh};function BD({tournamentRecord:t,drawDefinition:e,participantId:n,entryPosition:r,skipRefresh:i,event:a}){if(!t)return{error:nt};if(!n)return ti({result:{error:Xe},stack:"setEntryPositions"});if(void 0!==r&&!Number.isSafeInteger(r))return{error:Jn,entryPosition:r};(a?.entries||[]).forEach((t=>{t.participantId===n&&(t.entryPosition=r)})),(e?.entries||[]).forEach((t=>{t.participantId===n&&(t.entryPosition=r)}));const o=t=>{t.entries.forEach((t=>{t.entryPosition===r&&t.participantId!==n&&(t.entryPosition+=.1)}))};return i||(a?.entries&&(o(a),a.entries=jf({entries:a.entries})),e?.entries&&(o(e),e.entries=jf({entries:e.entries}))),{...z}}function VD({tournamentRecord:t,entryPositions:e,drawDefinition:n,event:r}){if(!t)return{error:nt};if(!Array.isArray(e))return{error:Jn};for(const i of e){const{participantId:e,entryPosition:a}=i,o=BD({skipRefresh:!0,tournamentRecord:t,drawDefinition:n,participantId:e,entryPosition:a,event:r});if(o.error)return o}return r?.entries&&(r.entries=jf({entries:r.entries})),n?.entries&&(n.entries=jf({entries:n.entries})),{...z}}function jD(t){const{participantId:e}=t;return e&&"string"!=typeof e?{error:Jn,participantId:e}:GD({...t,participantIds:[e].filter(Boolean)})}function GD({tournamentRecord:t,drawDefinition:e,participantIds:n,stageSequence:r,stage:i=fo,eventId:a,event:o}){if(!t)return{error:nt};if(!Array.isArray(n))return{error:Jn,participantIds:n};if(!o)return{error:$t};if(o){const t=qD({element:o,participantIds:n,stageSequence:r,stage:i});if(t.error)return t}if(e){const t=qD({element:e,participantIds:n,stageSequence:r,stage:i});if(t.error)return a?ti({context:{drawPromotionError:t.error,drawId:e.drawId},result:{...z},stack:"promoteAlternates"}):t}return{...z}}function qD({participantIds:t,stageSequence:e,element:n,stage:r}){const i=(n.entries||[]).filter((t=>t.entryStatus===qp)),a=(n.entries||[]).filter((e=>t.includes(e.participantId))),o=i.reduce(((t,e)=>{const{entryPosition:n}=e;return isNaN(n)&&t||(!t||n<t.entryPosition)&&e||t}),void 0),s=a.length?a:[o].filter(Boolean);if(!s?.length)return{error:mn};const c=s.filter((({entryStatus:t})=>t!==qp));if(c.length)return{error:ln,invalidEntryStatus:c};const u=s.filter((({entryStage:t})=>t&&t!==r));if(u.length)return{error:fn,invalidStage:u};const p=e&&s.filter((t=>t.stageSequence!==e));if(p?.length)return{error:hn,invalidStageSequence:p};for(const t of s){t.entryStatus=Wp;const e=t?.entryPosition;isNaN(e)||n.entries.forEach((t=>{t.entryStatus===qp&&t.entryPosition>e&&(t.entryPosition=t.entryPosition-1)}));const r=Math.max(...n.entries.filter((t=>t.entryStatus===Wp&&!isNaN(t.entryPosition))).map((({entryPosition:t})=>d(t||0))),0);t.entryPosition=r||0}return{...z}}function $D({autoEntryPositions:t=!0,participantIds:e,drawDefinition:n,drawId:r,stages:i,event:a}){if(!a)return{error:$t};if(!r)return{error:Tt};if(!e?.length)return{error:an};if(k(Vf({drawDefinition:n,stages:i}).assignedParticipantIds??[],e))return{error:un};const o=t=>{const n=t.participantId;return!e.includes(n)},{flightProfile:s}=jm({event:a}),c=s?.flights?.find((t=>t.drawId===r));return c?.drawEntries&&(c.drawEntries=c.drawEntries.filter(o),t&&(c.drawEntries=jf({entries:c.drawEntries}))),n?.entries&&(n.entries=n.entries.filter(o),t&&(n.entries=jf({entries:n.entries}))),{...z}}function WD(t){const e="addParticipant",{allowDuplicateParticipantIdPairs:n,returnParticipant:r,disableNotice:i,pairOverride:a,participant:o}=t,s=t.tournamentId?t.tournamentRecords?.[t.tournamentId]:t.tournamentRecord??(t.activeTournamentId&&t.tournamentRecords?.[t.activeTournamentId]);if(!s)return{error:nt};if(!o)return ti({result:{error:Je},stack:e});o.participantId||(o.participantId=ha()),s.participants||(s.participants=[]);const{participantId:c,individualParticipantIds:u}=o;if(s.participants.reduce(((t,e)=>e.participantId===c||t),!1))return{error:nn};const{participantType:d,participantRole:p}=o;if(!d||!Object.keys(up).includes(d))return{error:Ke,participantType:d};if(!p)return{error:Qe};const l=s.participants||[],m=l.filter((t=>t.participantType===ap)).map((t=>t.participantId));if(d!==ap&&o.person)return{error:Jn,person:o.person};if(u&&!Array.isArray(u))return{error:Jn,individualParticipantIds:u};if(d===sp){if(o.person)return{error:Jn,person:o.person};if(!o.individualParticipantIds)return ti({result:{error:an},stack:e});if(2!==o.individualParticipantIds.length&&!a)return ti({info:"PAIR must be 2 individualParticipantIds",result:{error:ze},stack:e});{const t=l.filter((t=>t.participantType===ap)).map((t=>t.participantId));if(!Array.isArray(o.individualParticipantIds))return ti({result:{error:ze},stack:e});const n=o.individualParticipantIds.reduce(((e,n)=>t.includes(n)&&e),!0);if(!n)return ti({result:{error:ze},stack:e})}const t=l.filter((t=>t.participantType===sp)).map((t=>({individualParticipantIds:t.individualParticipantIds,participant:t}))),i=o.participantType===sp&&t.find((t=>2===O(t.individualParticipantIds,o.individualParticipantIds).length));if(i&&!n)return{...z,existingParticipant:!0,participant:r&&la(i.participant)};if(!o.participantName){const t=l.filter((t=>o.individualParticipantIds?.includes(t.participantId)));let e=t.map((t=>t.person?.standardFamilyName)).filter(Boolean).join("/");1===t.length&&(e+="/Unknown"),o.participantName=e}}else if(d===ap){if(!o.person?.standardFamilyName||!o.person?.standardGivenName)return{error:cn};if(!o.participantName){const t=`${o.person.standardFamilyName.toUpperCase()}, ${o.person.standardGivenName}`;o.participantName=t}}else{if(!d||![cp,op].includes(d))return{error:Ke};if(u||(o.individualParticipantIds=[]),o.individualParticipantIds?.length)for(const t of o.individualParticipantIds){if("string"!=typeof t)return ti({result:{participantId:t,error:Jn},stack:e});if(!m.includes(t))return ti({result:{participantId:t,error:en},stack:e})}}s.participants.push(o),i||Or({payload:{tournamentId:s.tournamentId,participants:[o]},topic:ld});return Xr({participant:r&&la(o),...z})}function HD({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:n,participants:r=[]}){if(!n)return{error:nt};n.participants||(n.participants=[]);const i=n.participants.map((t=>t.participantId))||[];r.forEach((t=>{t.participantId||(t.participantId=ha())}));const a=r.filter((t=>!i.includes(t.participantId))),o=r.filter((t=>i.includes(t.participantId))),s=a.filter((t=>t.participantType===ap)),c=a.filter((t=>t.participantType!==ap)),u=s.concat(...c),d=[];if(u.length){for(const e of u){const r=WD({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:n,participant:e});if(r.error)return r;r.success&&!r.existingParticipant&&d.push(r.participant)}d.length&&Or({topic:ld,payload:{tournamentId:n.tournamentId,participants:d}});const r={participants:e&&la(d),addedCount:d.length,...z};return o.length&&Object.assign(r,{notAdded:o,info:dn}),Xr(r)}return{info:"No new participants to add",addedCount:0,...z}}function zD(t){const e=cc(t,[{[hs]:!0,[Ws]:!0}]);if(e.error)return e;const{allowDuplicateParticipantIdPairs:n,entryStatus:r=qp,participantIdPairs:a=[],entryStage:o=fo,tournamentRecord:s,drawDefinition:c,event:u,uuids:d}=t;if(u.eventType!==i)return{error:qt};const p=[],l=new Map;for(const t of s.participants??[]){const{participantType:e,participantId:n,person:r,individualParticipantIds:i}=t;e===ap&&r?.sex?l.set(n,r.sex):e===sp&&i&&p.push(i)}const m=a.filter((t=>{if(2!==t.length)return!0;if(!u.gender||u.gender===ei)return!1;if(!l.has(t[0])||!l.has(t[1]))return!0;const e=t.map((t=>l.get(t)));let n=u.gender===ni&&(e[0]!==ni||e[1]!==ni)||u.gender===ai&&(e[0]!==ai||e[1]!==ai);return u.gender===ri&&(e.sort(eh),e[0]===ai&&e[1]===ni||(n=!0)),n}));if(m.length)return{error:ze,invalidParticipantIdPairs:m};const f=a.map((t=>({participantId:d?.pop()??ha(),participantRole:Ih,individualParticipantIds:t,participantType:sp}))),h=n?f:f.filter((t=>!p.find((e=>2===O(e,t.individualParticipantIds).length))));let g,I=[];if(h){const t=HD({allowDuplicateParticipantIdPairs:n,participants:h,returnParticipants:!0,tournamentRecord:s});if(t.error)return t;I=t.participants||[],g=t.info}const U=hh({participantIds:a.map((t=>{const e=I.find((e=>2===O(e.individualParticipantIds,t).length));if(e)return e;const{participant:n}=Wm({tournamentRecord:s,participantIds:t});return n})).map((t=>t.participantId)),tournamentRecord:s,drawDefinition:c,entryStatus:r,entryStage:o,event:u});h.length&&Or({payload:{participants:h},topic:ld});return{...U,info:g,newParticipantIds:h.map(Mu)}}function YD({entryStatus:t=Wp,unpairedParticipantIds:e=[],participantIdPairs:n=[],entryStage:r=fo,tournamentRecord:i,event:a}){if(!i)return{error:nt};if(!a)return{error:$t};const o=i.participants??[],s=o.filter((t=>t.participantType===ap)).map((t=>t.participantId)),c=e.concat(...n).flat(1/0).filter((t=>!s.includes(t)));if(c.length)return{error:ze,invalidParticipantIds:c};const u=n.filter((t=>2!==t.length));if(u.length)return{error:ze,invalidParticipantIdPairs:u};const d=o.filter((t=>t.participantType===sp)).map((t=>t.individualParticipantIds)),p=n.filter((t=>!d.find((e=>2===O(e,t).length)))).map((t=>({participantType:sp,participantRole:Ih,individualParticipantIds:t}))),l=HD({participants:p,tournamentRecord:i});if(l.error)return l;const m=n.map((t=>{const{participant:e}=Wm({tournamentRecord:i,participantIds:t});return e})).map((e=>({participantId:e,entryStatus:t,entryStage:r}))),f=e.map((t=>({entryStatus:Zp,participantId:t,entryStage:r})));return a.entries=(a.entries??[]).filter((t=>t.entryStage===r)),a.entries=a.entries.concat(...m,...f),{...z}}var KD={__proto__:null,addDrawEntries:ph,addEventEntries:hh,addEventEntryPairs:zD,destroyPairEntries:Eh,destroyPairEntry:Ah,getEntriesAndSeedsCount:zP,getMaxEntryPosition:YP,modifyEntriesStatus:qf,modifyEventEntries:YD,mutate:{__proto__:null,addDrawEntries:ph,addEventEntries:hh,addEventEntryPairs:zD,destroyPairEntries:Eh,destroyPairEntry:Ah,modifyEntriesStatus:qf,modifyEventEntries:YD,promoteAlternate:jD,promoteAlternates:GD,removeDrawEntries:$D,removeEventEntries:mh,setEntryPosition:BD,setEntryPositions:VD},promoteAlternate:jD,promoteAlternates:GD,query:KP,removeDrawEntries:$D,removeEventEntries:mh,setEntryPosition:BD,setEntryPositions:VD};const QD={COLLEGE_D3:{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}},COLLEGE_DEFAULT:{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}},COLLEGE_JUCO:{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}},DOMINANT_DUO:Na,DOMINANT_DUO_MIXED:wa,LAVER_CUP:Fa,TEAM_DOUBLES_3_AGGREGATION:Ia,TIME_TENNIS_DUAL:Pa,TIME_TENNIS_PRO_CIRCUIT:va,USTA_BREWER_CUP:Da,USTA_OZAKI_CUP:Ta,USTA_COLLEGE:Aa,USTA_GOLD_TEAM_CHALLENGE:ga,USTA_INTERSECTIONAL:Sa,USTA_LEVEL_1:Ea,USTA_SECTION_BATTLE:ya,USTA_SOUTHERN_LEVEL_5:Ua,USTA_TOC:ka,USTA_WTT_ITT:Ca,USTA_ZONAL:Oa};function JD({suppressNotifications:t,tournamentRecord:e,internalUse:n,event:r}){if(!e)return{error:nt};if(e.events||(e.events=[]),!r)return{error:$t};const{startDate:i,endDate:a}=e;if(!n&&(r.entries?.length||r.drawDefinitions?.length)){const t=Xr({drawDefinitions:!!r.drawDefinitions?.length,entries:!!r.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:Jn,context:t}}const o={eventType:so,drawDefinitions:[],entries:[],startDate:i,endDate:a,...r};if(r.eventType===lo)if(r.tieFormat){const t=sa({tieFormat:r.tieFormat});if(t.error)return t}else if(r.tieFormatName){if(!QD[r.tieFormatName])return{context:{tieFormatName:r.tieFormatName},error:Jn};const t=ao({isMock:e?.isMock,namedFormat:r.tieFormatName,event:r});o.tieFormat=t}o.eventId||(o.eventId=ha());const s=e.events.reduce(((t,e)=>t||e.eventId===o.eventId),void 0);if(s)return{error:Ht};{const n=o;if(e.events.push(n),!t){const{topics:t}=Lr();if(t.includes(pd)){const t=df({event:r}).matchUps??[];Gd({tournamentId:e?.tournamentId,eventId:r.eventId,matchUps:t})}const{drawDefinitions:n,...i}=r;for(const t of n||[])Wd({drawDefinition:t});!function({tournamentId:t,event:e}){e&&Or({payload:{tournamentId:t,event:e},key:e.eventId,topic:fd})}({tournamentId:e?.tournamentId,event:i})}return{...z,event:o}}}function ZD(t){const e=cc(t,[{[ic]:{[Os]:!0,[Us]:!0}},{[hs]:!0}]);if(e.error)return e;const n=t.tieFormat||ao({namedFormat:t.tieFormatName}),r=t.uuids||[fa(n.collectionDefinitions.length)],i={[ni]:[],[ai]:[]};if(t.addEntriesFromTeams){const e=t.tournamentRecord.participants?.filter((t=>t.participantType===ip)),n=e?.flatMap((t=>t.individualParticipantIds??[]));for(const e of t.tournamentRecord.participants??[])if(n?.includes(e.participantId)){const t=e.person?.sex;t&&[ni,ai].includes(t)&&i[t].push(e.participantId)}}const a=[];for(const e of n.collectionDefinitions??[]){const n=r?.pop()?.toString()||ha(),o=e.matchUpType,s=e.gender,c={matchUpFormat:e.matchUpFormat,eventName:e.collectionName,category:e.category,gender:s,eventType:o,eventId:n};if(t.addEntriesFromTeams){const e=o===uo?Zp:t.entryStatus||Wp,n=s===ri?[...i[ni],...i[ai]]:i[s]??[];if(n.length){const t=hh({participantIds:n,entryStatus:e,event:c});if(t.error)return t}}if(a.push(c),!1!==t.addEvents){const e=JD({internalUse:!0,tournamentRecord:t.tournamentRecord,event:c});if(e.error)return e}}return{...z,events:a}}function XD({removePriorValues:t=!0,status:e=am,statusObject:n,event:r}){if(!G(n))return{error:Jn};const i=Yf({event:r,status:e}),a=`${im}.${om}`;return cy({timeItem:{itemValue:{[e]:{...i,...n}},itemType:a},removePriorValues:t,event:r})}function tT(t){const e=cc(t,[{[hs]:!0,[Ws]:!0},{eventDataParams:!1,[nc]:Js}]);if(e.error)return e;const{includePositionAssignments:n,removePriorValues:r,tournamentRecord:i,status:a=am,event:o,drawIdsToRemove:s,drawIdsToAdd:c}=t,{appliedPolicies:u}=Np({tournamentRecord:i,event:o}),d={...u,...t.policyDefinitions},p=o?.drawDefinitions?.map((({drawId:t})=>t))??[],l=t.drawDetails?Object.keys(t.drawDetails):[],m=l.length?[]:t.drawIds,f=(c??[]).concat(...s??[],...m??[],...l),h=f.filter((t=>!p.includes(t)));if(h.length)return ti({result:{error:ct},context:{invalidDrawIds:h}});const g=Yf({event:o,status:a}),I=Object.keys(g?.drawDetails||{}).filter((t=>p.includes(t))).reduce(((t,e)=>(t[e]=g.drawDetails[e],t)),{});for(const e of p)if(f.length&&!f.includes(e)||(s?.includes(e)||m?.length&&!m.includes(e)?I[e]={...I[e],publishingDetail:{published:!1}}:(c?.includes(e)||m?.includes(e)||!m?.length)&&(I[e]={...I[e],publishingDetail:{published:!0}})),t.drawDetails?.[e]){const n=t.drawDetails[e];let r=n.structureDetails??I[e].structureDetails;const i=n.stageDetails??I[e].stageDetails??{},{structureIdsToRemove:a=[],structureIdsToAdd:s=[],publishingDetail:c={},stagesToRemove:u=[],stagesToAdd:d=[]}=n;if((s||d)&&(c.published=!0),I[e]={publishingDetail:c,structureDetails:r,stageDetails:i},s.length||a.length){const t=(o?.drawDefinitions?.find((t=>t.drawId===e))?.structures??[]).map((({structureId:t})=>t)),n=(s??[]).concat(a??[]).filter((e=>!t.includes(e)));if(n.length)return ti({result:{error:Lt},context:{invalidStructureIds:n}});r=r??{};for(const e of t)a.includes(e)?r[e]={published:!1}:r[e]={published:!0};I[e].structureDetails=r}const p=(o?.drawDefinitions?.find((t=>t.drawId===e))?.structures??[]).map((({stage:t})=>t));if(d.length){for(const t of d)i[t]={published:!0};for(const t of p)i[t]||(i[t]={published:!1})}if(d.length||u.length){for(const t of u)i[t]={published:!1};for(const t of p)i[t]||(i[t]={published:!0})}(d.length||u.length)&&(I[e].stageDetails=i)}XD({statusObject:{drawDetails:I},removePriorValues:r,status:a,event:o});const{topics:U}=Lr(),y=U.includes(Cd),S=y||t.returnEventData?MP({includePositionAssignments:n,...t.eventDataParams,usePublishState:!0,tournamentRecord:i,policyDefinitions:d,event:o})?.eventData:void 0;return y&&Or({payload:{eventData:S,tournamentId:i.tournamentId},topic:Cd}),{...z,eventData:S}}const eT="deleteDrawDefinitions",nT="autoSchedulingAudit",rT="deleteEvents",iT={AUTO_SCHEDULING_AUDIT:nT,DELETE_EVENTS:rT,DELETE_DRAW_DEFINITIONS:eT};function aT(t){if(!t.tournamentRecord)return{error:nt};const e="deleteDrawDefinitions";let n=t.drawIds??[],r=t.event;const{autoPublish:i=!0,tournamentRecord:a,auditData:o,eventId:s,force:c}=t,{appliedPolicies:u}=Np({tournamentRecord:a,event:r}),d={...u,...t.policyDefinitions},p=Array.isArray(n)?n[0]:void 0;if(!r){const t=Gm({tournamentRecord:a,eventId:s,drawId:p});if(t.error)return t;r=t.event}const l=[],m=[],f=[];if(!r?.drawDefinitions)return ti({info:"event has no drawDefinition",result:{...z},stack:e});const h=r.drawDefinitions.map((({drawId:t})=>t));if(n.length||(n=h),n=n.filter((t=>h.includes(t))),!n.length)return ti({info:"nothing to do; no matching drawIds in event.",result:{...z},stack:e});const g=la(jm({event:r}).flightProfile,!1,!0),I=({participantId:t,drawPosition:e,qualifier:n,bye:r})=>({bye:r,qualifier:n,drawPosition:e,participantId:t}),U=c??u?.[Nc]?.allowDeletionWithScoresPresent?.drawDefinitions,y=Yf({event:r})??{};let S,v=y.drawIds??(y.drawDetails&&Object.keys(y.drawDetails))??[];const w=[],P=r.drawDefinitions.filter((t=>{if(n.includes(t.drawId)){const e=ff({event:r,drawDefinition:t})?.matchUps??[];if(e.some((({score:t})=>vf({score:t})))&&!U)return w.push(t.drawId),!0;const{drawId:n,drawType:i,drawName:c}=t,u=g?.flights?.find((e=>e.drawId===t.drawId));u&&(u.drawEntries=u.drawEntries?.filter((t=>al.includes(t.entryStatus)))),v.includes(n)&&(v=v.filter((t=>t!==n)),S=!0);const d=od({stageSequence:1,drawDefinition:t,stage:fo})?.structures?.[0],p=d?mS({structureId:d.structureId,tournamentRecord:a,drawDefinition:t}):void 0,h=p?.positionAssignments?.map(I),y=od({stage:ho,drawDefinition:t})?.structures,P=y?.length?y.map((e=>{const n=e.stageSequence,r=mS({structureId:e.structureId,tournamentRecord:a,drawDefinition:t}),i=r?.positionAssignments.map(I);return{positionAssignments:i,stageSequence:n}})):void 0,D={action:eT,payload:{drawDefinitions:[t],eventId:s??r?.eventId,auditData:o}};f.push(D),l.push(Xr({tournamentId:a.tournamentId,eventId:s??r?.eventId,qualifyingPositionAssignments:P,positionAssignments:h,auditData:o,drawType:i,drawName:c,drawId:n})),e?.forEach((({matchUpId:t})=>m.push(t)))}return!n.includes(t.drawId)}));if(w.length&&!c)return ti({context:{drawIdsWithScoresPresent:w},result:{error:mr},stack:e});if(r.drawDefinitions=P,g){Vc({event:r,extension:{name:ru,value:g}})}if(LP({tournamentRecord:a}),S){const t={};for(const e of v)t[e]=y.drawDetails?.[e]??{published:!0};const e=XD({statusObject:{drawDetails:t},event:r});if(e.error)return{error:e.error}}if(f.length)if(Br(gd)){const t=a.tournamentId;Or({topic:gd,payload:{tournamentId:t,detail:f}});const e=Ip({element:r,itemType:eu});ay({element:r,timeItem:{itemType:eu,itemValue:(e?.timeItem?.itemValue||0)+1},removePriorValues:!0})}else!function({appliedPolicies:t,event:e,deletedDrawsDetail:n,auditData:r}){if(!1===t?.audit?.[eu])return;const{extension:i}=zc({name:eu,element:e}),a={...r,deletedDrawsDetail:n},o={value:Array.isArray(i?.value)?i?.value.concat(a):[a],name:eu};_c({element:e,extension:o})}({appliedPolicies:u,event:r,deletedDrawsDetail:l,auditData:o});if(m.length&&qd({tournamentId:a?.tournamentId,matchUpIds:m}),n.forEach((t=>function({tournamentId:t,eventId:e,drawId:n}){return Or({payload:{drawId:n,tournamentId:t,eventId:e},topic:Sd,key:n}),xr({key:n}),{...z}}({drawId:t}))),i&&S){const e=tT({...t.eventDataParams,drawIdsToRemove:n,policyDefinitions:d,tournamentRecord:a,event:r});if(e.error)return{...z,info:e.error}}return{...z}}function oT({autoPublish:t=!0,tournamentRecord:e,auditData:n,event:r,force:i}){if(!e)return{error:nt};if(!r)return{error:$t};const{flightProfile:a}=jm({event:r});if(a){const o=a.flights?.map((({drawId:t})=>t)).filter(Boolean),s=aT({eventId:r.eventId,tournamentRecord:e,autoPublish:t,auditData:n,drawIds:o,event:r,force:i});return s.error?s:$c({event:r,name:ru})}return{...z}}function sT(t){const{matchUpFormat:e,recoveryTimes:n,averageTimes:r,tournamentId:i,eventId:a}=t,o=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(o).length)return{error:et};const s=Object.keys(o).filter((t=>!i||i===t));if(i&&!s.includes(i))return{error:Jn};let c;for(const t of s){const i=o[t],{event:s}=Gm({tournamentRecord:i,eventId:a});a&&s&&(c=!0);const u=cT({tournamentRecord:i,event:s,matchUpFormat:e,averageTimes:r,recoveryTimes:n});if(u.error)return u}return!a||c?{...z}:{error:Wt}}function cT({tournamentRecord:t,recoveryTimes:e,matchUpFormat:n,averageTimes:r,event:i}){if(!t)return{error:nt};if(r&&!Array.isArray(r))return{error:Jn};if(e&&!Array.isArray(e))return{error:Jn};const a=mu;if(i){const{extension:t}=zc({element:i,name:a});_c({element:i,extension:{name:a,value:uT({...t?.value||{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})}})}else{const{extension:i}=zc({element:t,name:a});_c({extension:{name:a,value:uT({...i?.value||{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})},element:t})}return{...z}}function uT(t){const{matchUpRecoveryTimes:e=[],matchUpAverageTimes:n=[],matchUpFormat:r}=t;let{averageTimes:i,recoveryTimes:a}=t;i=(i||[]).filter((t=>t?.categoryNames?.length||t?.categoryTypes?.length));const o=i?.length&&n.map((t=>t?.matchUpFormatCodes.includes(r)?{...t,matchUpFormatCodes:t.matchUpFormatCodes?.filter((t=>t!==r))}:t)).filter((({matchUpFormatCodes:t})=>t?.length)).concat({matchUpFormatCodes:[r],averageTimes:i});a=(a||[]).filter((t=>t?.categoryNames?.length||t?.categoryTypes?.length));const s=a?.length&&e.map((t=>t?.matchUpFormatCodes.includes(r)?{...t,matchUpFormatCodes:t.matchUpFormatCodes?.filter((t=>t!==r))}:t)).filter((({matchUpFormatCodes:t,averageTimes:e})=>t?.length||e)).concat({matchUpFormatCodes:[r],recoveryTimes:a});return{matchUpAverageTimes:o?.length&&o||n,matchUpRecoveryTimes:s?.length&&s||e}}function dT(t){const{tournamentRecord:e,recoveryMinutes:r,averageMinutes:i,matchUpFormat:a,categoryType:o,eventId:s,event:c}=t;if(!e)return{error:nt};if(!Di({matchUpFormat:a}))return{error:Jn};if(!c)return{error:$t};const{averageTimes:u=[],recoveryTimes:p=[]}=rD({tournamentRecord:e,matchUpFormat:a,event:c}),l=c.category,m=l?.categoryName||l?.ageCategoryCode||c?.eventId;let f={categoryNames:[m],minutes:{}};const h={categoryNames:[m],minutes:{}},g=t=>{if(t.categoryTypes?.includes(o)&&console.log("encountered:",{categoryType:o}),!t.categoryNames?.includes(m)||(t.categoryNames=t.categoryNames.filter((t=>t!==m)),f={minutes:t.minutes,categoryNames:[m]},t.categoryNames.length))return t},I=i&&!isNaN(d(i)),U=r&&!isNaN(d(r)),y=u.map(g).filter((t=>t?.categoryNames?.length)),S=p.map(g).filter((t=>t?.categoryNames?.length));return I&&(Object.assign(f.minutes,{[c?.eventType||n]:i}),y.push(f)),U&&(Object.assign(h.minutes,{[c?.eventType||n]:r}),S.push(h)),I||U?sT({averageTimes:I&&y,recoveryTimes:U&&S,tournamentRecord:e,matchUpFormat:a,eventId:s}):{error:Jn}}function pT(t){if(t.event)return lT({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});const e=cc(t,[{[ms]:!0,[js]:!0}]);if(e.error)return e;const{tournamentRecords:n,eventId:r}=t;for(const t of Object.values(n??{})){const{event:e}=Gm({tournamentRecord:t,eventId:r});if(e)return lT({event:e})}}return{error:Wt}}function lT({event:t}){return $c({event:t,name:mu})}const mT={MON:"MON",TUE:"TUE",WED:"WED",THU:"THU",FRI:"FRI",SAT:"SAT",SUN:"SUN"};function fT(t){return!!Array.isArray(t)&&(w(t).length===t.length&&t.every((t=>Object.keys(mT).includes(t))))}function hT({tournamentRecord:t,event:e,startDate:n}){if(!t)return{error:nt};if(!e)return{error:$t};if(!Ri.test(n))return{error:Oe};const r=UT(t);if(r.error)return r;const{tournamentStartDate:i,tournamentEndDate:a}=r,o=new Date($i(n)).getTime();if(!i||!a||o<i||o>a)return{error:Oe};const s=e.endDate&&new Date($i(e.endDate)).getTime();return s&&o>s&&(e.endDate=n),e.startDate=n,{...z}}function gT(t){const{tournamentRecord:e,event:n,endDate:r}=t;if(!e)return{error:nt};if(!n)return{error:$t};if(!Ri.test(r))return{error:Oe};const i=UT(e);if(i.error)return i;const{tournamentStartDate:a,tournamentEndDate:o}=i,s=new Date($i(r)).getTime();if(!a||!o||s<a||s>o)return{error:Oe};const c=n.startDate&&new Date($i(n.startDate)).getTime();return c&&s<c&&(n.startDate=r),n.endDate=r,{...z}}function IT(t){const e=cc(t,[{tournamentRecord:!0,event:!0},{[Xs]:t=>Ri.test(t),[ec]:Oe,startDate:!1,endDate:!1},{[Xs]:t=>t.filter(Boolean).every((t=>Ri.test(t))),[ec]:Oe,activeDates:!1},{[Xs]:fT,weekdays:!1}]);if(e.error)return e;const{tournamentRecord:n,weekdays:r,event:i,startDate:a,endDate:o}=t,s=t.activeDates?.filter(Boolean);if(a&&o){if(new Date($i(a)).getTime()>new Date($i(o)).getTime())return{error:Jn}}if(s){const t=a||n.startDate,e=o||n.endDate,r=!t||s.every((e=>new Date(e)>=new Date(t))),i=!e||s.every((t=>new Date(t)<=new Date(e)));if(!r||!i)return{error:Oe}}if(a){const t=hT({tournamentRecord:n,event:i,startDate:a});if(t.error)return t}if(o){const t=gT({tournamentRecord:n,event:i,endDate:o});if(t.error)return t}return s&&(i.activeDates=s),r&&(i.weekdays=r),{...z}}function UT(t){const{startDate:e,endDate:n}=t;return Ri.test(e)&&Ri.test(n)?{tournamentStartDate:new Date($i(e)).getTime(),tournamentEndDate:new Date($i(n)).getTime()}:ti({result:{error:ke},context:{startDate:e,endDate:n}})}function yT({event:t,orderedDrawIdsMap:e}){if("object"!=typeof t)return{error:$t};if(!e)return{error:be,info:"Missing drawIdsOrderMap"};if("object"!=typeof e)return{error:Jn,info:"orderedDrawIdsMap must be an object"};const n=Object.values(e);if(!n.every((t=>!isNaN(t))))return{error:Jn,info:"drawOrder must be numeric"};if(w(n).length!==n.length)return{error:Jn,info:"drawOrder values must be unique"};if(t.drawDefinitions?.length){const n=(t.drawDefinitions||[]).map((({drawId:t})=>t)),r=Object.keys(e);if(r?.length&&O(n,r).length!==n.length)return{error:Jn,info:"Missing drawIds"};t.drawDefinitions.forEach((t=>{t.drawOrder=e[t.drawId]}))}const{flightProfile:r}=jm({event:t});return r?.flights?.forEach((t=>{t.flightNumber=e[t.drawId]})),{...z}}function ST({tournamentRecord:t,event:e}){if(!t)return{error:nt};if(!e)return{error:$t};const{flightProfile:n}=jm({event:e}),r=n?.flights&&Object.assign({},...n.flights.sort(((t,e)=>t.flightNumber-e.flightNumber)).map(((t,e)=>({[t.drawId]:e+1}))))||e.drawDefinitions?.length&&Object.assign({},...e.drawDefinitions.sort(((t,e)=>t.drawOrder-e.drawOrder)).map(((t,e)=>({[t.drawId]:e+1}))))||void 0;return r?yT({event:e,orderedDrawIdsMap:r}):{...z}}function vT({autoPublish:t=!0,tournamentRecord:e,auditData:n,drawId:r,event:i,force:a}){if(!e)return{error:nt};if(!r)return{error:Tt};if(!i)return{error:$t};const{flightProfile:o}=jm({event:i});if(o){const t=o.flights?.find((t=>t.drawId===r));if(t){const t=o.flights.filter((t=>t.drawId!==r));Vc({event:i,extension:{name:ru,value:{...o,flights:t}}})}}const s=i.drawDefinitions?.find((t=>t.drawId===r));if(s){const o=aT({drawIds:[r],eventId:i.eventId,tournamentRecord:e,autoPublish:t,auditData:n,event:i,force:a});if(o.error)return o}return ST({tournamentRecord:e,event:i})}function wT(t){const e=cc(t,[{[Ws]:!0,[hs]:!0,[zs]:!1},{replacementIndividualParticipantId:!0,[Xs]:t=>j(t),existingIndividualParticipantId:!0,[$s]:Xe,participantId:!0}]),{replacementIndividualParticipantId:n,existingIndividualParticipantId:r,tournamentRecord:i,drawDefinition:a,participantId:o,event:s,uuids:c}=t;if(e.error)return e;if(s?.eventType!==co)return{error:qt};const u=s?.entries?.filter((({entryStatus:t})=>[Zp,Xp].includes(t))).map((({participantId:t})=>t))||[];if(!u.includes(n))return{error:He};const d=(i.participants||[]).find((t=>t.participantId===o));if(d?.participantType!==sp)return{error:We,participant:d};const p=d.individualParticipantIds,l=[n,...p.filter((t=>t!==r))],{participant:m}=Wm({participantIds:l,tournamentRecord:i});let f;if(m)f=m.participantId;else{const t=WD({participant:{participantId:c?.pop(),participantRole:Ih,individualParticipantIds:l,participantType:sp},returnParticipant:!0,tournamentRecord:i});if(t.error)return t;f=t.participant.participantId}const{flightProfile:h}=jm({event:s});if(a){const t=h?.flights?.find((({drawId:t})=>t===a.drawId));t&&(t.drawEntries=t.drawEntries.map((t=>t.participantId===o?{...t,participantId:f}:t))),a.entries=a.entries.map((t=>t.participantId===o?{...t,participantId:f}:t));for(const t of a.structures||[])if(t.structures){t.positionAssignments=void 0;for(const e of t.structures)e.positionAssignments=e.positionAssignments.map((t=>t.participantId===o?{...t,participantId:f}:t))}else t.positionAssignments&&(t.positionAssignments=t.positionAssignments.map((t=>t.participantId===o?{...t,participantId:f}:t)))}s.entries=s.entries.map((t=>t.participantId===o&&{...t,participantId:f}||t.participantId===n&&{...t,participantId:r}||t));const g=i.events.some((({entries:t,eventId:e,drawDefinitions:n})=>s.eventId===e?n.some((({drawId:t,entries:e})=>t!==a?.drawId&&e?.find((t=>t.participantId===o)))):t?.find((t=>t.participantId===o))));if(!g){const t=Rh({addIndividualParticipantsToEvents:!1,participantIds:[o],tournamentRecord:i});if(t.error)return t}return{...z,participantOtherEntries:g,newPairParticipantId:f}}function PT(t){const{flight:e,suppressNotifications:n,modifyEventEntries:r,existingDrawCount:i,allowReplacement:a,checkEntryStatus:o,tournamentRecord:s,drawDefinition:c,event:u}=t;if(!c)return{error:ot};if(!u)return{error:$t};u.drawDefinitions||(u.drawDefinitions=[]);const{drawId:p,drawName:l,entries:m}=c,{entries:f}=u;let h=0;if(void 0!==i&&i!==u.drawDefinitions.length)return{error:Jn,info:"drawDefintions count mismatch"};const{flightProfile:g}=jm({event:u}),I=e&&g?.flights?.find((t=>t.flightNumber===e.flightNumber)),U=g?.links?.find((t=>t?.target?.drawId===p))?.source?.drawId,y=U&&!u.drawDefinitions.find((t=>t.drawId===U));if(y)return ti({result:{error:ot},info:{sourceDrawId:U}});if(I&&I.drawId!==c.drawId)return ti({result:{error:at},info:{relevantFlight:I}});const S=m?.every((({participantId:t,entryStatus:e})=>{const n=I?.drawEntries.find((e=>e.participantId===t));return!e||n?.entryStatus===e})),v=!o||f&&m?.every((({participantId:t,entryStatus:e,entryStage:n})=>{const r=f.find((e=>e.participantId===t&&(!e.entryStage||e.entryStage===n)));return r?.entryStatus===e}));if(I&&!S)return ti({result:{error:at},context:{drawEntriesPresentInFlight:S,matchingEventEntries:v,relevantFlight:I},info:"Draw entries are not present in flight or do not match entryStatuses"});if(r&&m?.filter(Boolean).forEach((t=>{if(t?.entryStatus&&al.includes(t?.entryStatus)){const e=f?.filter(Boolean).find((e=>e.participantId===t.participantId));e&&t.entryStatus&&e?.entryStatus!==t.entryStatus&&(e.entryStatus=t.entryStatus,h+=1)}})),f&&!v)return ti({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:v,eventEntries:f},error:at}});const w=g?.flights?.map((({flightNumber:t})=>!isNaN(t)&&d(t)))?.filter(Boolean)||[],P=u.drawDefinitions.map((({drawOrder:t})=>t&&d(t)))?.filter(Boolean)||[];let D=Math.max(0,...P,...w)+1;const T=g?.flights?.find((t=>t.drawId===p));let b;if(T){T.drawName=c.drawName,b={name:ru,value:{...g,flights:g.flights}};const t=T.flightNumber;t&&!P.includes(t)?D=t:T.flightNumber=D}else{const t=g?.flights||[];t.push({manuallyAdded:!0,flightNumber:D,drawEntries:m,drawName:l,drawId:p}),b={name:ru,value:{...g||{},flights:t}}}Vc({event:u,extension:b}),Object.assign(c,{drawOrder:D});const R=u.drawDefinitions.find((t=>t.drawId===p)),M=s?.tournamentId,N=u.eventId;if(R){if(!a)return{error:bt};const t=ff({drawDefinition:R})?.matchUps,e=t?.map(Nu)??[],r=ff({drawDefinition:c})?.matchUps;if(!n){e?.length&&qd({matchUpIds:e,action:"modifyDrawDefinition",tournamentId:M,eventId:N}),r?.length&&Gd({matchUps:r,tournamentId:M,eventId:N}),u.drawDefinitions=u.drawDefinitions.map((t=>t.drawId===p?c:t));const t=c.structures?.map((({structureId:t})=>t));Hd({drawDefinition:c,tournamentId:M,structureIds:t,eventId:N})}}else if(u.drawDefinitions.push(c),!n){const{matchUps:t}=ff({drawDefinition:c,event:u});t&&Gd({tournamentId:s?.tournamentId,matchUps:t}),Wd({drawDefinition:c,tournamentId:M,eventId:N})}return{...z,modifiedEventEntryStatusCount:h}}function DT(t){const{provisionalPositioning:e,useExistingSeedLimit:n,tournamentRecord:r,drawDefinition:i,seedingProfile:a,structureId:o,assignments:s,drawId:c,event:u}=t;let d=0;if(!s?.length)return{error:Kt};if(!r)return{error:nt};if(!c)return{error:Tt};const p=pl({provisionalPositioning:e,drawDefinition:i,structureId:o});if(p.error)return p;const{seedAssignments:l,seedLimit:m}=p,f=Object.assign({},...(l??[]).filter((t=>t.seedNumber)).map((t=>({[t.seedNumber]:t}))));s.forEach((t=>{const{seedNumber:e}=t;m&&e<=m&&(!n||f[e])&&(f[e]=t)}));const h=Object.values(f),g=h.map((t=>t?.participantId)).filter(Boolean);if(g.length!==M(g).length)return{error:Rt};for(const t of h){const n=tg({...t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:i,seedingProfile:a,structureId:o,event:u});if(n?.error)return n;n?.success&&d++}return d?{...z,modifications:d}:{error:qn}}function TT({deleteExisting:t,event:e,flightProfile:n}){const r="attachFlightProfile";if(!n)return ti({result:{error:be},stack:r});if(!e)return ti({result:{error:$t},stack:r});const{flightProfile:i}=jm({event:e});if(i&&!t)return ti({result:{error:or},stack:r});if(e.drawDefinitions?.length)return ti({result:{error:st},stack:r});return Vc({event:e,extension:{name:ru,value:n}}),{flightProfile:la(n,!1,!0),...z}}function bT({tournamentRecord:t,scaleAttributes:e,drawDefinition:n,entryStatuses:r,drawId:i,event:a,stage:o}){if(!a)return{error:$t};if(r&&!Array.isArray(r))return ti({result:{error:Jn},info:ug("entryStatus"),stack:"removeScaleValues"});let s=a.entries;if(i){const{flightProfile:t}=jm({event:a}),e=t?.flights?.find((t=>t.drawId===i));s=e?e.drawEntries:n?.entries}return function({tournamentRecord:t,scaleAttributes:e,participantIds:n}){if(!t)return{error:nt};if(!n)return{error:an};if(!e)return{error:be,info:"scaleAttributes required"};const{scaleType:r,eventType:i,scaleName:a}=e,o=[tm,r,i,a].join(".");return t.participants?.forEach((t=>{n.includes(t.participantId)&&t.timeItems&&(t.timeItems=t.timeItems.filter((t=>t&&t?.itemType!==o)))})),{...z}}({tournamentRecord:t,scaleAttributes:e,participantIds:(s||[]).filter((t=>(!o||!t.entryStage||t.entryStage===o)&&(!r||r.includes(t.entryStatus)))).map(Mu)})}function RT({removePriorValues:t,tournamentRecord:e,displaySettings:n,status:r=am,event:i}){if(!e)return ti({result:{error:nt}});if(!i)return ti({result:{error:$t}});if(!G(n))return ti({result:{error:be}});if(G(n.draws))for(const t of Object.keys(n.draws)){const e=n.draws[t].scheduleDetails??[];if(e.length){const r=[];for(const t of e){const e=r.find((e=>q(e.attributes,t.attributes)));e?.dates&&t.dates?e.dates.push(...t.dates):r.push(t)}n.draws[t].scheduleDetails=r}}const a=XD({statusObject:{displaySettings:n},removePriorValues:t,status:r,event:i});return a.error?a:{...z}}function MT({tournamentRecord:t,drawDefinition:e,entryStatuses:n,scaleName:r,drawId:i,event:a,stage:o}){if(!t)return{error:nt};if(!a)return{error:$t};r=r||a.category?.categoryName||a.category?.ageCategoryCode;return bT({tournamentRecord:t,scaleAttributes:{eventType:a.eventType,scaleType:fc,scaleName:r},drawDefinition:e,entryStatuses:n,drawId:i,event:a,stage:o})}function NT(t){const e=cc(t,[{[hs]:!0},{eventIds:!0,[nc]:Zs}]);if(e.error)return e;const{removePairParticipants:n,tournamentRecord:r,eventIds:i}=t,a=[],o=[],s=[],c=[];if(r.events=(r.events||[]).filter((t=>{if(i.includes(t.eventId)){const e={action:rT,payload:{events:[t]}};a.push(e),o.push({tournamentId:r.tournamentId,eventName:t.eventName,eventType:t.eventType,category:t.category,eventId:t.eventId,gender:t.gender})}const e=t.eventType===co?(t.entries||[]).map((({entryStatus:t,participantId:e})=>t!==Zp&&e)).filter(Boolean):[],n=i.includes(t.eventId);return n?c.push(...e):s.push(...e),!n})),n){const t=c.filter((t=>!s.includes(t)));r.participants=r.participants.filter((({participantId:e})=>!t.includes(e)))}if(LP({tournamentRecord:r}),a.length)if(Br(gd)){const t=r.tournamentId;Or({topic:gd,payload:{type:rT,tournamentId:t,detail:a}})}else{sy({tournamentRecord:r,timeItem:{itemValue:o,itemType:rT}})}return{...z}}function AT(t){const e=cc(t,[{tournamentRecord:!0,eventId:!0,event:!0},{eventUpdates:!0,_ofType:Js}]);if(e.error)return e;const{eventUpdates:n,event:r}=t,i="modifyEvent",a=function(t){const{tournamentRecord:e,event:n}=t,r=n?.entries?.filter((({entryStatus:t})=>{const e=t;return[...al,qp].includes(e)})).map((({participantId:t})=>t))??[];return r?ih({participantFilters:{participantIds:r},withIndividualParticipants:!0,tournamentRecord:e}).participants??[]:[]}(t),o=function({enteredParticipants:t}){const e=[],n=t.reduce(((t,n)=>{const r=n.person?.sex?[n.person.sex]:n.individualParticpants?.map((t=>t.person?.sex))||[];return e.push(...r),t.includes(n.participantType)?t:t.concat(n.participantType)}),[]),r=w(e);return{enteredParticipantTypes:n,enteredParticipantGenders:r}}({enteredParticipants:a}),{enteredParticipantGenders:s,enteredParticipantTypes:c}=o,u=jm({event:r})?.flightProfile?.flights,d=function({noFlightsNoDraws:t,enteredParticipantGenders:e,eventUpdates:n,stack:r}){const i=!e.length||!n.gender||n.gender===ei||1===e.length&&e[0]===n.gender||t&&n.gender===ri;return n.gender&&!i?ti({context:{gender:n.gender,validGender:i},result:{error:Kn},stack:r}):{...z}}({noFlightsNoDraws:!r.drawDefinitions?.length&&!u?.length,enteredParticipantGenders:s,eventUpdates:n,stack:i});if(d.error)return d;const p=function({enteredParticipantTypes:t,eventUpdates:e,stack:n}){const r=t.includes(po)&&[po]||t.includes(ap)&&[oo]||t.includes(sp)&&[co]||[co,oo,po],i=r.includes(e.eventType??"");return e.eventType&&!i?ti({context:{participantType:e.eventType,validEventType:i},result:{error:qt},stack:n}):{...z}}({enteredParticipantTypes:c,eventUpdates:n,stack:i});if(p.error)return p;const l=function(t){const e=t.eventUpdates?.category;if(!e)return{...z};const n=ia({category:e});if(n.error)return n;if(t.event.eventType===po){const e=t.event?.drawDefinitions?.map((t=>ll(t)))??[];if(![ll(t.event),...e,...(df(t)?.matchUps??[]).map((t=>ll(t)))??[]].filter(Boolean).every((e=>e.collectionDefinitions.every((e=>!e.category||aa({category:t.eventUpdates.category,childCategory:e.category}))))))return ti({result:{error:Qn},stack:t.stack})}if(t.enteredParticipants?.length){const n=t.eventUpdates.startDate||t.event.startDate||t.tournamentRecord.startDate,r=t.eventUpdates.endDate||t.event.endDate||t.tournamentRecord.endDate,i=t.enteredParticipants.map((t=>t.participantType===ap?t:t.individualParticpants??[])).flat(),a=ra({category:e,consideredDate:n}),o=ra({category:e,consideredDate:r});if(a?.ageMinDate||a?.ageMaxDate||o?.ageMinDate||o?.ageMaxDate)for(const e of i){const n=e.person?.birthDate;if(!n)return ti({result:{error:Re},stack:t.stack});const r=new Date(n).getTime();if(a.ageMinDate||a.ageMaxDate){const e=new Date(a.ageMinDate).getTime(),n=new Date(a.ageMaxDate).getTime();if(r<e||r>n)return ti({result:{error:qe},stack:t.stack})}if(o.ageMin||o.ageMax){const e=new Date(o.ageMinDate).getTime(),n=new Date(o.ageMaxDate).getTime();if(r<e||r>n)return ti({result:{error:qe},stack:t.stack})}}}return{...z}}({...t,...o,enteredParticipants:a,stack:i});if(l.error)return l;const m=function(t){const{tournamentRecord:e,eventUpdates:n,event:r,stack:i}=t;if(n.startDate||n.endDate){const t=IT({startDate:n.startDate,endDate:n.endDate,tournamentRecord:e,event:r});if(t.error)return ti({result:t,stack:i})}return{...z}}({...t,stack:i});return m.error?m:(n.eventType&&(r.eventType=n.eventType),n.eventName&&(r.eventName=n.eventName),n.gender&&(r.gender=n.gender),{...z})}function ET({qualifyingPositions:t,drawEntries:e=[],drawName:n,drawId:r,event:i,stage:a}){const o="addFlight";if(!i)return ti({result:{error:$t},stack:o});if(!n)return ti({result:{error:be},stack:o});if(e?.length){const t=(i.entries??[]).map(Mu),n=e.map(Mu);if(O(n,t).length!==n.length)return ti({result:{error:Jn},stack:o})}const s=jm({event:i})?.flightProfile,c=s?.flights?.map((({flightNumber:t})=>!isNaN(t)&&d(t)))?.filter(Boolean)||[],u=Math.max(0,...c)+1,p={drawId:r||ha(),flightNumber:u,drawEntries:e,drawName:n};a&&(p.stage=a),t&&(p.qualifyingPositions=t);const l=(s?.flights||[]).find((({drawId:t})=>t===p.drawId));if(l)return ti({result:{error:ar},stack:o});const m=(s?.flights||[]).concat(p);return Vc({event:i,extension:{name:ru,value:{...s||{},flights:m}}})}var CT={__proto__:null,addDrawDefinition:PT,addEvent:JD,addFlight:ET,assignSeedPositions:DT,attachFlightProfile:TT,categoryCanContain:aa,deleteDrawDefinitions:aT,deleteEvents:NT,deleteFlightAndFlightDraw:vT,deleteFlightProfileAndFlightDraws:oT,generate:{__proto__:null,generateEventsFromTieFormat:ZD},generateEventsFromTieFormat:ZD,getCategoryAgeDetails:ra,getEvent:CD,getEventProperties:AD,getEventStructures:Pg,getEventTimeItem:yp,getEvents:ED,getFlightProfile:jm,getScaledEntries:Ew,modifyEvent:AT,modifyEventMatchUpFormatTiming:dT,modifyPairAssignment:wT,mutate:{__proto__:null,addDrawDefinition:PT,addEvent:JD,addFlight:ET,assignSeedPositions:DT,attachFlightProfile:TT,deleteDrawDefinitions:aT,deleteEvents:NT,deleteFlightAndFlightDraw:vT,deleteFlightProfileAndFlightDraws:oT,modifyEvent:AT,modifyEventMatchUpFormatTiming:dT,modifyPairAssignment:wT,refreshEventDrawOrder:ST,removeEventMatchUpFormatTiming:pT,removeScaleValues:bT,removeSeeding:MT,setEventDates:IT,setEventDisplay:RT,setEventEndDate:gT,setEventStartDate:hT,updateDrawIdsOrder:yT,validateCategory:ia},query:{__proto__:null,categoryCanContain:aa,getCategoryAgeDetails:ra,getEvent:CD,getEventProperties:AD,getEventStructures:Pg,getEventTimeItem:yp,getEvents:ED,getFlightProfile:jm,getScaledEntries:Ew},refreshEventDrawOrder:ST,removeEventMatchUpFormatTiming:pT,removeScaleValues:bT,removeSeeding:MT,setEventDates:IT,setEventDisplay:RT,setEventEndDate:gT,setEventStartDate:hT,updateDrawIdsOrder:yT,validateCategory:ia};const OT="splitWaterfall",FT="splitShuttle",kT={SPLIT_LEVEL_BASED:"splitLevelBased",SPLIT_WATERFALL:OT,SPLIT_SHUTTLE:FT};function xT({json:t,tagName:e}){const n=Object.keys(t).filter((e=>Array.isArray(t[e]))).map((e=>({key:e,value:t[e].filter((t=>"object"==typeof t&&1===Object.keys(t).length))}))),r=Object.keys(t).filter((e=>"object"==typeof t[e]&&!Array.isArray(t[e]))).map((e=>({key:e,value:t[e]})));return _T({tagName:e,attributes:Object.keys(t).filter((e=>["string","number"].includes(typeof t[e]))).map((e=>({key:e,value:t[e]}))),childArrays:n,childObjects:r})}function _T(t){const{tagName:e,attributes:n=[],childArrays:r=[],childObjects:i}=t,a="\r\n",o=t=>{const e=Object.keys(t)[0];return{key:e,value:t[e]}},s=r?.map((({key:t,value:e})=>_T({tagName:t,childObjects:e.map(o)}))).join("\r\n"),c=i?.map((({key:t,value:e})=>xT({tagName:t,json:e??[]}))).join("\r\n"),u=n?.map((({key:t,value:e})=>`${t}="${e}"`)).join(" ");if("childArray"===e)return c;return`<${e}${u?` ${u}`:""}>${c?.length?`${a}${c}${a}`:""}${s?.length?`${a}${s}${a}`:""}</${e}>`}function LT({teamParticipants:t,mappedMatchUps:e,participantMap:n,tournamentName:r,tournamentId:i,teamMatchUp:a,tournament:o,startDate:s,doubles:c,singles:u}){const d=t?.find((t=>t.participantRoleResponsibilities?.includes("Home"))),p=t?.filter((t=>t.participantId!==d?.participantId)),l=Fi(s,"/","MDY"),m=d?.participantName||p?.[1]?.participantName,f=d?.participantId||p?.[1]?.participantId,h=p?.[0]?.participantName,g=p?.[0]?.participantId,I={},U=t.map((t=>({team:{...VT({teamParticipant:t,teamMatchUp:a,uniValues:I,participantMap:n,mappedMatchUps:e,homeid:f})}}))),y=Xr({venue:{tournamentname:o?r:void 0,neutralgame:d?"N":"Y",gameid:i,officials:{},tournament:o,rules:{},homename:m,visname:h,homeid:f,visid:g,date:l},childArray:U,singles_matches:u?.map((t=>jT({matchUp:t,homeid:f,uniValues:I}))),doubles_matches:c?.map((t=>jT({matchUp:t,homeid:f,uniValues:I})))});return{json:y,xml:xT({json:y,tagName:"tngame"})}}function BT({homeid:t,uniValues:e,participant:n}){if(!n)return{};const r=2===n.individualParticipants?.length,i=r?w(n.individualParticipants?.map((t=>t.teams?.[0]?.participantId))):[],a=r?w(n.individualParticipants?.map((t=>t.teams?.[0]?.teamId))):[],o=!r&&n.teams?.[0]?.participantId||1===i?.length&&i[0]||void 0,s=!r&&n.teams?.[0]?.teamId||1===a?.length&&a[0]||o,c=r?void 0:n.participantName,u=n.individualParticipants?.[0]?.participantName,d=n.individualParticipants?.[1]?.participantName;return Xr({vh:t&&(o===t?"H":"V")||"",uni:r?void 0:e[o][n.participantId],uni_1:e[o][n.individualParticipants?.[0]?.participantId],uni_2:e[o][n.individualParticipants?.[1]?.participantId],team:s,name:c,name_1:u,name_2:d})}function VT({teamParticipant:t,teamMatchUp:e,participantMap:r,mappedMatchUps:a,homeid:o,uniValues:s}){const{participantId:c,participantName:u}=t,d=o&&(c===o?"H":"V")||"",p=r?.[c]?.matchUps,l=p&&Object.keys(p),m=e?.sides?.find((({participant:t})=>t.participantId===c))?.sideNumber,f=e?.score?.sets?.[0]?.[`side${m}Score`]??0;s[c]={};const h={SINGLES:{w:0,l:0},DOUBLES:{w:0,l:0}},g=[],I=[];let U=0;for(const t of l??[]){const e=a?.[t],r=e.sides.find((({participant:t})=>t.participantId===c))?.sideNumber;U+=e.score?.sets?.[0]?.[`side${r}Score`]??0;for(const t of e.tieMatchUps??[]){const{matchUpType:e,winningSide:a}=t,o=a&&(a===r?"w":"l")||"";o&&(h[e][o]+=1);const s="w"===o?"1":"0",c="l"===o?"1":"0";if(e===n){const t=I.length+1;I.push({singles_pair:{pair:t,won:s,lost:c,tied:"0"}})}else if(e===i){const t=g.length+1;g.push({doubles_pair:{pair:t,won:s,lost:c,tied:"0"}})}}}const y=[{singles:{childArray:I,won:h.SINGLES.w,lost:h.SINGLES.l}},{doubles:{childArray:g,won:h.DOUBLES.w,lost:h.DOUBLES.l}}],S=[];let v=1;for(const e of t.individualParticipantIds){const t=r?.[e];if(t){const{participant:e,counters:n}=t,r={won:n?.DOUBLES?.wins||0,lost:n?.DOUBLES?.losses||0},i={won:n?.SINGLES?.wins||0,lost:n?.SINGLES?.losses||0},{participantName:a,participantId:o}=e;s[c][o]=v,S.push({player:{name:a,uni:v,singles:i,doubles:r}})}v+=1}return{vh:d,id:c,name:u,score:f||U,totals:y,childArray:S}}function jT({matchUp:t,homeid:e,uniValues:r}){const{collectionPosition:i,orderOfFinish:a,matchUpType:o,sides:s}=t??{},c=s?.map((i=>{const{sideNumber:a,participant:s}=i,c=function({sets:t,sideNumber:e}){return Object.assign({},...t?.map((t=>{const{setNumber:n,side1Score:r,side2Score:i,side1TiebreakScore:a,side2TiebreakScore:o}=t,s=`set_${n}`,c=`tie_${n}`,u=1===e?r:i,d=1===e?a:o;return{[s]:u,[c]:d}}))??[])}({sets:t.score?.sets,sideNumber:a}),u=o===n?"singles_score":"doubles_score";return{[u]:{...BT({homeid:e,uniValues:r,participant:s}),...c}}})),u=o===n?"singles_match":"doubles_match";return{[u]:{match:i,order:a,childArray:c}}}const GT="DESC",qT={ASC:"ASC",ASCENDING:"ASC",DESC:"DESC",DESCENDING:GT};function $T(t){let{tieFormat:n}=t;const{useDefaultEventRanking:i,tournamentRecord:a,drawDefinition:o,scaleAccessor:s,singlesOnly:c,attach:u,event:d}=t;if(d?.eventType!==lo)return{error:qt};if(!a)return{error:nt};if(!n&&!o)return{error:ct};if(n=n??fl({drawDefinition:o,event:d})?.tieFormat,sa({tieFormat:n}).error)return{error:ae};if("object"!=typeof s&&!i)return{error:Jn,context:{scaleAccessor:s}};const p={},l=(o?.entries??d?.entries??[]).filter((t=>t?.entryStatus===Wp)).map(Mu),{participants:m=[]}=ih({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:a}),f=m.filter((({participantId:t})=>l.includes(t))),g=d?.category?.categoryName??d?.category?.ageCategoryCode,{scaleName:I=g,scaleType:U=pc,sortOrder:y,accessor:S}=s||{},v=U===pc?"rankings":"ratings";const w=(t,n)=>{let r=t[v]?.[n];if(!r&&i&&(r=t[v]?.[e]),Array.isArray(r)){const t=r.find((t=>t.scaleName===I))?.scaleValue;if(h(t))return t;if(S&&"object"==typeof t)return t[S]}return 0},P=(t,e,n)=>{const r=y===GT?t:e;return w(y===GT?e:t,n)-w(r,n)},D=(t,n)=>P(t,n,e),T=(t,e)=>P(t,e,r),b=[],R=n?.collectionDefinitions??[];for(const t of f){const n=t.individualParticipants?.sort(D)??[],r=c?n:t.individualParticipants?.sort(T)??[],i={};for(const t of R){const a=[],{collectionId:o,matchUpCount:s,matchUpType:c,gender:u}=t,d=um(e)(c);E(0,s).forEach((t=>{const e=d?n:r??[],s=t+1,c=[];E(0,d?1:2).forEach((t=>{const n=e?.find((e=>{const n=u&&([ni,ai].includes(u)&&u||u===ri&&[ni,ai][t]);return!(n&&n!==e.person?.sex||a.includes(e.participantId))}))?.participantId;n&&(c.push(n),a.push(n),i[n]||(i[n]=[]),i[n].push({collectionPosition:s,collectionId:o}))})),d||b.push(c)}))}const a=Object.keys(i).map((t=>({collectionAssignments:i[t],participantId:t})));p[t.participantId]=a}const M=[];for(const t of b){const{participant:e}=Wm({tournamentParticipants:m,participantIds:t});if(!e){const e={individualParticipantIds:t,participantRole:Ih,participantType:sp};M.push(e)}}if(u){for(;M.length;)WD({participant:M.pop(),tournamentRecord:a});_c({element:o,extension:{name:au,value:p}})}return{...z,lineUps:p,participantsToAdd:M}}function WT(t){if(!t)return{error:be};const e=cc(t,[{dates:!1,[Xs]:t=>Array.isArray(t)&&t.every(Ci)},{uuids:!1,[Xs]:t=>Array.isArray(t)&&t.every(j)},{startTime:!1,endTime:!1,[Xs]:Vi},{idPrefix:!1,namePrefix:!1,[Xs]:j},{count:!0,[Xs]:h}]);if(e.error)return e;const{startDate:n,endDate:r}=t.tournamentRecord??{},i=t.dates||n&&r&&_i(n,r)||[],a=E(1,t.count+1).map((e=>Xr({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${e}`)??ha(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${e}`),dateAvailability:i.map((e=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:e})))})));return{...z,courts:a}}function HT({court:t,date:e}){const n=e&&t.dateAvailability.find((t=>ea(t.date,e))),r=t.dateAvailability.find((t=>!t.date));return n||r}function zT(t){const e=cc(t,[{courtDate:!0,_ofType:Js}]);if(e.error)return e;const{includeBookingTypes:n=[],courtDate:r}=t,i=[];let a=Qi(r.startTime);(r.bookings||[]).filter((t=>!t.bookingType||!n.includes(t.bookingType))).sort(((t,e)=>Gi(t.startTime).localeCompare(Gi(e.startTime)))).forEach((t=>{const e={startTime:qi(a.toISOString()),endTime:t.startTime};Qi(t.startTime)>a&&i.push(e),Qi(t.endTime)>a&&(a=Qi(t.endTime))}));const o={startTime:qi(a.toISOString()),endTime:r.endTime};return Qi(r.endTime)>a&&i.push(o),{timeSlots:i}}function YT(t){const e=cc(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:Zs}]);if(e.error)return e;const{averageMatchUpMinutes:n,includeBookingTypes:r,periodStart:i,date:a}=t,o=t.courts,s=Qi(i),c=Xi(s,n),{enoughTime:u}=function({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:n,periodEndTime:r}){function i(e){const i=Qi(e.startTime),a=Qi(e.endTime);return!(i>n)&&(!(a<r)&&Ji(n,a)>=t)}return{enoughTime:t=>{const{timeSlots:n}=zT({includeBookingTypes:e,courtDate:t}),r=n?.filter(i);return!!r?.length}}}({averageMatchUpMinutes:n,includeBookingTypes:r,periodStartTime:s,periodEndTime:c});return{availableToScheduleCount:(o?.filter((t=>{if(!Array.isArray(t.dateAvailability))return!1;const e=HT({date:a,court:t});return!(!e||!u(e))}))||[]).length,...z}}function KT(t){const{remainingScheduleTimes:e=[],clearScheduleDates:n,periodLength:r=30,scheduleDate:i,courts:a=[]}=t;let{bookings:o=[]}=t;if(!Array.isArray(a)||!a.length)return{error:Jn,courts:a};if(!Array.isArray(o))return{error:Ae};if(!Ci(i))return{error:Oe};n&&(Array.isArray(n)?n.includes(i)&&(o=[]):o=[]);const{courtBookings:s,unassignedBookings:c}=o.reduce(((t,e)=>{const{courtId:n}=e;return n?t.courtBookings[n]?t.courtBookings[n].push(e):t.courtBookings[n]=[e]:t.unassignedBookings.push(e),t}),{courtBookings:{},unassignedBookings:[]}),u=a.map(((t,n)=>{const{courtId:r,courtName:a}=t,o=s[r]||[],c=HT({date:i,court:t})||{},{bookings:u=[],startTime:d,endTime:p,date:l}=c;return{courtId:r,courtName:a,dateAvailability:{bookings:[e[n]&&{startTime:d,endTime:e[n]},...la(u,!1,!0),...o].filter(Boolean),startTime:d,endTime:p,date:l}}}));c.sort(((t,e)=>ji(t.startTime)-ji(e.startTime)));const d=[];for(const t of c){const{startTime:e,endTime:n,averageMinutes:i,recoveryMinutes:a,matchUpId:o}=t,s=ji(e),c=ji(n),p=u.map((t=>{const e=t.dateAvailability,{timeSlots:n=[]}=zT({courtDate:e});return{courtName:t.courtName,courtId:t.courtId,timeSlots:n}})).flat().reduce(((t,{courtId:e,courtName:n,timeSlots:i})=>{let a;const o=i.find((({startTime:e,endTime:n})=>{a=ji(e)-s;const i=s>=ji(e);return c<=ji(n)&&0!==t.startDifference&&((0===a||a+r>=0)&&(void 0===t.startDifference||a<t.startDifference)||i)}));return o?{courtName:n,courtId:e,startDifference:a}:t}),{});if(p.courtId){const t={averageMinutes:i,recoveryMinutes:a,matchUpId:o,startTime:e,endTime:n};d.push(t);const r=u.find((({courtId:t})=>t===p.courtId));r?.dateAvailability.bookings.push(t)}else console.log({unassignedBooking:t})}return{virtualCourts:u.map((({courtId:t,courtName:e,dateAvailability:n})=>({dateAvailability:[n],courtName:e,courtId:t}))),assignedBookings:d}}function QT({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:n}){const r=(t||90)+(n||0);return e>r?r:e||30}function JT(t){const{startTime:e="8:00",endTime:n="20:30",count:r=10,date:i}=t??{};return E(0,r).map((()=>({dateAvailability:[{date:i,startTime:e,endTime:n}]})))}function ZT({scheduleDate:t,startTime:e,endTime:n,courts:r}){const i=(e?"startTime":n&&"endTime")||void 0;return r.reduce(((r,a)=>{const o=HT({date:t,court:a}),s=i&&(o?.[i]||a[i]);return s&&(!r||e&&ji(s)<ji(r)||n&&ji(s)>ji(r))?s:r}),void 0)}function XT(t){const e=cc(t,[{courts:!0,_ofType:Zs}]);if(e.error)return e;let{date:n=Oi(),startTime:r="08:00",endTime:i="19:00",periodLength:a,courts:o}=t;const{calculateStartTimeFromCourts:s=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:p,courtsCount:l,bookings:m}=t;a=a||QT({averageMatchUpMinutes:u}),n=$i(n),r=qi(r),i=qi(i);let f=0,h=0,g=0,I=0,U=0;!o&&l&&(o=JT({startTime:r,endTime:i,count:l,date:n}));const{virtualCourts:y}=KT({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:n,periodLength:a,bookings:m,courts:o}),{firstTimeSlotStartTime:S}=function({averageMinutes:t,startTime:e,endTime:n,courts:r,date:i}){let a;if(e=e||ZT({courts:r,scheduleDate:i,startTime:!0}),n=n||ZT({courts:r,scheduleDate:i,endTime:!0}),e&&n){const o=Qi(e),s=Qi(n);for(const e of r||[]){if(!Array.isArray(e.dateAvailability))continue;const n=HT({court:e,date:i}),{timeSlots:r}=zT({courtDate:n});r?.forEach((e=>{const n=Qi(e.startTime),r=Qi(e.endTime);if(n>s||n<o)return!1;if(r<o)return!1;if(Ji(n,r)>=t){const t=qi(n.toISOString());(!a||t<a)&&(a=t)}}))}}return{firstTimeSlotStartTime:a}}({averageMinutes:u,courts:y,startTime:r,endTime:i,date:n});s&&S&&(r=S??r);const v=ji(r),w=ji(i)-v,P=E(0,Math.floor(w/a)+1).map((t=>{const e=function(t){let e=Math.floor(t/60);const n=t-60*e;return e>23&&(e%=24),[ta(e),ta(n)].join(":")}(v+t*a),r=YT({courts:y??[],averageMatchUpMinutes:u,periodStart:e,date:n});if(r.error)return{error:r.error};const{availableToScheduleCount:i=0}=r,o=i>h?i-h:0;U+=t?i:0;const s=t?U/t:i,c=t?a*s/u*(t-1)+s:s,p=i?h&&c-f||o:0;f=c,h=i,g+=p;const l=d(g)-I;return I+=l,{periodStart:e,add:l,availableToScheduleCount:i,newCourts:o,totalMatchUps:I}}));return{scheduleTimes:P.reduce(((t,e)=>{const n=E(0,e.add).map((()=>({scheduleTime:e.periodStart})));return t.concat(...n)}),[]).flat(),timingProfile:P,totalMatchUps:I}}const tb={getCourtsAvailableAtPeriodStart:YT,generateTimeSlots:zT,getScheduleTimes:XT,courtGenerator:JT};var eb={__proto__:null,drawMatic:Nw,garman:{__proto__:null,default:tb,garman:tb},generateAdHocMatchUps:kS,generateAdHocRounds:Rw,generateAndPopulatePlayoffStructures:ry,generateCourts:WT,generateDrawDefinition:xD,generateDrawMaticRound:$S,generateDrawStructuresAndLinks:DS,generateDrawTypeAndModifyDrawDefinition:TS,generateFlightProfile:function(t){const{drawNameRoot:e="Flight",attachFlightProfile:n,tournamentRecord:r,scaleAttributes:i,scaleSortMethod:a,deleteExisting:o,sortDescending:s,drawNames:c=[],flightsCount:u,splitMethod:d,uuids:p=[],event:l,stage:m}=t;if(!l)return{error:$t};const f=l.entries??[],{flightProfile:h}=jm({event:l});if(h&&n&&!o)return{error:or};const g=t.scaledEntries??Ew({tournamentRecord:r,scaleAttributes:i,scaleSortMethod:a,sortDescending:s,event:l,stage:m}).scaledEntries,I=g.map(Mu),U=P(f.filter((({participantId:t})=>!I.includes(t))).filter((t=>(!m||!t.entryStage||t.entryStage===m)&&(!t.entryStatus||il.includes(t.entryStatus))))),y=g.concat(...U),S=y.length;let v=x(y,Math.ceil(S/u));d===OT?v=B(y,u):d===FT&&(v=B(y,u,!0));const w=E(0,u).map((t=>{const n=t+1;return{flightNumber:n,drawId:p?.pop()??ha(),drawEntries:(r=v[t],(r||[]).map((({participantId:t,scaleValue:e})=>{const n=f.find((e=>e.participantId===t));return n?.scaleValue&&e&&(n.scaleValue=e),n})).sort(((t,e)=>t.scaleValue-e.scaleValue)).map(((t,e)=>(t.scaleValue&&(t.seedNumber=e+1),t)))),drawName:c?.length&&c[t]||`${e} ${n}`};var r})),D={scaleAttributes:i,splitMethod:d,flights:w};if(n){const t=TT({flightProfile:D,deleteExisting:o,event:l});return{splitEntries:Pr()&&v||void 0,...t}}return{flightProfile:D,...z}},generateLineUps:$T,generateQualifyingStructure:qI,generateSeedingScaleItems:_D,generateStatCrew:function(t){const e=cc(t,[{[hs]:!0}]);if(e.error)return e;const{tournamentRecord:r}=t,{startDate:a,tournamentId:o,tournamentName:s}=r,{participantMap:c,matchUps:u,mappedMatchUps:d}=ih({withMatchUps:!0,withEvents:!0,tournamentRecord:r}),p=r.participants.filter((t=>t.participantType===cp)),l=u?.filter((t=>t.matchUpType===cp))??[],m=l?.reduce(((t,e)=>{const n=e?.tieMatchUps??[];return n?[...t,...n]:n}),[])??[],f=u?.filter((t=>t.matchUpType===n))??[],h=u?.filter((t=>t.matchUpType===i))??[],g=m.length===f.length+h.length,I=1===l.length&&g,U={mappedMatchUps:d,participantMap:c,tournamentName:s,tournamentId:o,tournament:g?"N":"Y",startDate:a},y=[],S=[];if(I){const t=l[0],{json:e,xml:n}=LT({teamParticipants:p,teamMatchUp:t,...U,doubles:h,singles:f});S.push(e),y.push(n)}else for(const t of l){const e=t?.sides?.map((({participant:t})=>t?.participantId)).filter(Boolean);if(2!==e?.length)continue;const r=e.map((t=>t&&c?.[t]?.participant)),{xml:a,json:o}=LT({doubles:t.tieMatchUps?.filter((t=>t.matchUpType===i)),singles:t.tieMatchUps?.filter((t=>t.matchUpType===n)),teamParticipants:r,teamMatchUp:t,...U});S.push(o),y.push(a)}return{json:S,xml:y,...z}},generateVoluntaryConsolation:WS,roundRobinGroups:jh},nb={__proto__:null,isValid:Di,isValidMatchUpFormat:Di,parse:Ii,stringify:li};function rb({tournamentRecord:t,drawDefinition:e,participantId:n,sideNumber:r,matchUpId:i,event:a}){if(n&&"string"!=typeof n)return{error:He};if(!e)return{error:ot};if(!i)return{error:de};const o=void 0===r;if(o&&(r=1),![1,2].includes(r))return ti({result:{error:Jn,context:{sideNumber:r}}});const{matchUp:s,structure:c}=GU({drawDefinition:e,matchUpId:i,event:a});if(!s)return{error:le};if(!!(c?.structures||e.drawType&&e.drawType!==_o||c?.matchUps?.find((({roundPosition:t})=>!!t))))return{error:vt};if(!n&&(s?.score?.scoreStringSide1||Xu.includes(s?.matchUpstatus)||s?.matchUpStatus&&[Vu,Bu].includes(s.matchUpStatus)))return{error:Ge,info:"matchUp has completed status or score"};if(s){if(s.sides=[1,2].map((t=>{const e=s.sides?.find((e=>e.sideNumber===t))??{sideNumber:t};return r===t?{...e,participantId:n}:e})),o)for(const t of s.sides)t.sideNumber&&(t.sideNumber=3-t.sideNumber);$d({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:s})}return{...z,sidesSwapped:o}}function ib({removePriorValues:t,tournamentRecord:e,duplicateValues:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:o,event:s}){const{matchUp:c}=GU({drawDefinition:r,event:s,matchUpId:a});if(!c)return{error:le};const u=ay({removePriorValues:t,element:c,duplicateValues:n,timeItem:o});return i||$d({tournamentId:e?.tournamentId,eventId:s?.eventId,context:"addTimeItem",drawDefinition:r,matchUp:c}),u}function ab(t){const e=cc(t,[{[hs]:!0},{[Is]:!0},{[Ss]:!0},{[Cs]:!0}]);if(e.error)return e;const n=yD(t,[{[Hs]:Gs,attr:{[Fs]:!0}}]);if(n.error)return n;const{tournamentRecord:r,drawDefinition:i,participantId:a,matchUpId:o}=t,s=n?.matchUp?.matchUp,{matchUpStatus:c,score:u}=s??{};if(c&&td.includes(c)||c&&Xu.includes(c)||vf({score:u}))return{error:At};const d=cm({matchUp:s});if(d?.error)return d;const{checkedInParticipantIds:p,allRelevantParticipantIds:l}=d??{};if(!l?.includes(a))return{error:He};if(!p?.includes(a))return{error:sn};const m=Cl({matchUp:s});if(m?.error)return m;const{sideParticipantIds:f,nestedIndividualParticipantIds:h}=m??{},g=f?.indexOf(a);void 0!==g&&[0,1].includes(g)&&(h?.[g]??[]).forEach((t=>{ib({drawDefinition:i,matchUpId:o,timeItem:{itemType:Fl,itemValue:t}})}));return ib({tournamentRecord:r,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:Fl}}),{...z,checkedOut:!0}}function ob(t){const e=cc(t,[{[hs]:!0},{[Is]:!0},{[Ss]:!0},{[Cs]:!0}]);if(e[$s])return e;const n=yD(t,[{[Hs]:Gs,attr:{[Fs]:!0}}]);if(n[$s])return n;const{tournamentRecord:r,drawDefinition:i,participantId:a,matchUpId:o}=t,s=cm({matchUp:n?.matchUp?.matchUp});if(s?.error)return s;const{checkedInParticipantIds:c,allRelevantParticipantIds:u}=s??{};if(!u?.includes(a))return{[$s]:He};const d={...z,checkedIn:!0};if(c?.includes(a))return d;return ib({tournamentRecord:r,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:Ol}}),d}function sb(t){const e=cc(t,[{[Ss]:!0,[Is]:!0,[Cs]:!0}]);if(e.error)return e;const n=t.tournamentId??t.activeTournamentId,r=t.tournamentRecord??(n&&t.tournamentRecords?.[n]);if(!r)return{error:nt};const i=yD(t,[{[Hs]:Gs,attr:{[Fs]:!0},[$s]:le}]),a=i.matchUp?.matchUp;if(!a)return{error:le};const{checkedInParticipantIds:o=[]}=cm({matchUp:a}),{participantId:s,matchUpId:c,drawDefinition:u}=t;return s&&o.includes(s)?ab({tournamentRecord:r,drawDefinition:u,participantId:s,matchUpId:c,matchUp:a}):ob({tournamentRecord:r,drawDefinition:u,participantId:s,matchUpId:c,matchUp:a})}function cb({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:a}){if(!t)return{error:nt};if(!e)return{error:Tt};if(!a)return{error:Wt};const o=hl({drawDefinition:e}),{matchUp:s}=GU({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!s)return{error:le};const{matchUp:c,structure:u}=GU({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:a});if(!c)return{error:le};const{collectionPosition:d,drawPositions:p,collectionId:l,matchUpTieId:m,matchUpType:f}=c;if(f&&!H([n,i],f))return{error:he};const{positionAssignments:h}=cd({structure:u}),g=h?.filter((t=>p?.includes(t.drawPosition))),{matchUp:I}=GU({matchUpId:m,drawDefinition:e,matchUpsMap:o}),U=[...I?.sides?.map(Mu)??[],...g?.map(Mu)??[]],{participants:y}=ih({tournamentRecord:t,participantFilters:{participantTypes:[cp],participantIds:U}}),{matchUp:S}=GU({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),v=fl({matchUp:I,drawDefinition:e,structure:u,event:a})?.tieFormat;return{inContextDualMatchUp:S,inContextTieMatchUp:c,relevantAssignments:g,collectionPosition:d,teamParticipants:y,collectionId:l,matchUpType:f,dualMatchUp:I,tieMatchUp:s,tieFormat:v,structure:u,...z}}function ub(t){const e=cb(t);if(e.error)return e;const n="replaceTieMatchUpParticipantid",{existingParticipantId:r,tournamentRecord:a,newParticipantId:o,drawDefinition:s,substitution:c,event:u}=t;if(!r||!o)return ti({result:{error:Xe},stack:n});if(r===o)return{...z};const{inContextDualMatchUp:d,inContextTieMatchUp:p,collectionPosition:l,collectionId:m,dualMatchUp:f,tieMatchUp:h,tieFormat:g}=e,I=p?.matchUpType,U=p?.sides?.find((t=>t.participant?.participantId===r||t.participant?.individualParticipantIds?.includes(r)));if(!U)return{error:en};const y=ih({tournamentRecord:a,participantFilters:{participantIds:[r,o]}})?.participants??[];if(2!==y.length)return ti({result:{error:Xe},stack:n});if(y[0].participantType!==y[1].participantType)return ti({result:{error:Ke},stack:n});const{appliedPolicies:S}=Np({tournamentRecord:a,drawDefinition:s,event:u}),v=t.policyDefinitions?.[wc]??S?.[wc]??fh[wc],P=y.find((({participantId:t})=>t===o));if(!1!==(t.enforceGender??v?.participants?.enforceGender)&&[ni,ai].includes(p?.gender)&&p?.gender!==P?.person?.sex)return{error:We,info:"Gender mismatch"};const D=v?.processCodes?.substitution;JU({tournamentId:a.tournamentId,eventId:u.eventId,inContextDualMatchUp:d,drawDefinition:s,dualMatchUp:f});const T=f?.sides?.find((({sideNumber:t})=>t===U.sideNumber));if(!T)return ti({result:{sideNumber:U.sideNumber,existingParticipantId:r,error:rr},stack:n});const b=p?.sides?.flatMap((t=>t.participant?.individualParticipantIds||t.participant?.participantId||[]));if(b?.includes(o))return ti({result:{error:dn},stack:n});const R=d?.sides?.find((({sideNumber:t})=>t===U.sideNumber))?.participantId,M=T.lineUp,N=M?.find((({participantId:t})=>o===t)),A=M?.reduce(((t,e)=>e.substitutionOrder>t?e.substitutionOrder:t),0),E=M?.map((t=>{const e=la(t,!1,!0);if(![r,o].includes(e.participantId))return e;if(!c&&[r,o].includes(e.participantId)&&(e.collectionAssignments=e.collectionAssignments?.filter((t=>!(t.collectionPosition===l&&t.collectionId===m)))),c&&r===e.participantId&&(e.collectionAssignments=e.collectionAssignments.map((t=>t.collectionPosition===l&&t.collectionId===m&&void 0===t.substitutionOrder?{...t,substitutionOrder:A}:t))),e.participantId===o){e.collectionAssignments||(e.collectionAssignments=[]);const t={collectionId:m,collectionPosition:l};c&&(t.previousParticipantId=r,t.substitutionOrder=(A??0)+1),e.collectionAssignments.push(t)}return e}))??[];if(!N){const t={collectionId:m,collectionPosition:l};c&&(t.substitutionOrder=(A??0)+1,t.previousParticipantId=r);const e={collectionAssignments:[t],participantId:o};E.push(e)}const C=I===i,{assignedParticipantIds:O}=$m({lineUp:M,collectionPosition:l,collectionId:m}),{assignedParticipantIds:F}=$m({lineUp:E,collectionPosition:l,collectionId:m});if(T.lineUp=E,R&&g){const t=pg({participantId:R,lineUp:E,drawDefinition:s,tieFormat:g});if(t.error)return ti({result:t,stack:n})}else console.log("team participantId not found");let k,x;if(C){const{tournamentRecord:e}=t;let r=Wm({participantIds:F,tournamentRecord:e});if(!r.participant){const t=WD({returnParticipant:!0,pairOverride:!0,tournamentRecord:e,participant:{participantRole:Ih,individualParticipantIds:F,participantType:sp}});if(t.error)return ti({result:t,stack:n});k=t.participant?.participantId}r=Wm({participantIds:O,tournamentRecord:e});const i=r.participant?.participantId;if(i){Rh({participantIds:[i],tournamentRecord:e}).success&&(x=i)}}if(c||1===U.substitutions?.length){if(c)D&&h&&(h.processCodes=w([...h?.processCodes??[],...D]));else for(const t of D||[]){const e=h?.processCodes?.lastIndexOf(t);void 0!==e&&h?.processCodes?.splice(e,1)}h&&$d({tournamentId:a?.tournamentId,matchUp:h,context:n,drawDefinition:s})}return f&&$d({tournamentId:a?.tournamentId,matchUp:f,context:n,drawDefinition:s}),{...z,modifiedLineUp:E,participantRemoved:x,participantAdded:k}}function db({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:n,drawDefinition:r,participantIds:i,collectionId:a}){if(!a||!t||!Array.isArray(i))return{modifiedLineUp:n?.lineUp||[],error:Jn};const o=n?.lineUp||Hm({participantId:e,drawDefinition:r})?.lineUp,s=[],c=[];return{modifiedLineUp:o?.map((e=>{if(!i.includes(e.participantId))return e;const n=e.collectionAssignments?.filter((n=>{const r=n.collectionId===a&&n.collectionPosition===t;return r&&(n.previousParticipantId&&s.push(n.previousParticipantId),c.push({participantId:e.participantId,...n})),!r}));return{participantId:e.participantId,collectionAssignments:n}})).filter(Boolean)||[],assignmentsRemoved:c,previousParticipantIds:s}}function pb({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:n,tournamentRecord:r}){const i="addIndividualParticipantIds";if(!r)return ti({result:{error:nt},stack:i});if(!e||!t)return ti({result:{error:be},stack:i});const a=r.participants??[],o=a.find((t=>t.participantId===e));if(!o)return ti({result:{error:en},stack:i});if(o?.participantType&&![cp,op].includes(o.participantType))return ti({context:{participantType:o.participantType},result:{error:Ke},stack:i});const s=t.filter((t=>{const e=a.find((e=>e.participantId===t));return e?.participantType!==ap}));if(s.length)return ti({result:{error:ze,invalidParticipantIds:s},stack:i});o.individualParticipantIds||(o.individualParticipantIds=[]);const c=o.individualParticipantIds,u=t.filter((t=>!c.includes(t)));u.length&&(n&&bh({individualParticipantIds:u,tournamentRecord:r}),o.individualParticipantIds=o.individualParticipantIds.concat(...u));const{topics:d}=Lr();if(d.includes(bd)){const t=a.find((({participantId:t})=>t===e));Or({topic:bd,payload:{participants:[t]}})}return function({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r=(n.events||[]).filter((t=>t?.eventType===po&&t?.entries?.some((t=>t.participantId===e)))),i=e=>!t.includes(e.participantId);for(const t of r){t.entries=(t.entries||[]).filter(i);const{flightProfile:e}=jm({event:t});e?.flights?.forEach((t=>{t.drawEntries=(t.drawEntries||[]).filter(i)})),t?.drawDefinitions?.forEach((t=>{t.entries=(t.entries||[]).filter(i)}))}}({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}),{groupingParticipant:la(o,!1,!0),added:u.length,...z}}function lb(t){const{updateParticipantName:e=!0,groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i,pairOverride:a,participant:s}=t;if(!i)return{error:nt};if(!s)return{error:Je};if(!s.participantId)return WD({tournamentRecord:i,participant:s});const{participant:c}=hp({participantId:s.participantId,tournamentRecord:i});if(!c)return WD({tournamentRecord:i,participant:s});const{participantRoleResponsibilties:u,individualParticipantIds:d,participantOtherName:p,participantName:l,participantRole:m,participantType:f,onlineResources:h,contacts:g,person:I}=s;if(f&&c.participantType!==f)return{error:je};const U={};if(g&&(U.contacts=g),h&&(U.onlineResources=h),p&&j(p)&&(U.participantOtherName=p),l&&j(l)&&(U.participantName=l),Array.isArray(d)){const{participants:t}=ih({participantFilters:{participantTypes:[ap]},tournamentRecord:i}),n=t?.map(Mu);if(n){const r=d.filter((t=>j(t)&&n.includes(t)));([op,o].includes(f||c.participantType)||f===sp&&(2===r.length||a))&&(U.individualParticipantIds=r),c.participantType===up.PAIR&&e&&(U.participantName=function({individualParticipants:t,newValues:e}){const n=e.individualParticipantIds;let r=t.filter((({participantId:t})=>n.includes(t))).map((({person:t})=>t?.standardFamilyName)).filter(Boolean).sort().join("/");1===n.length&&(r+="/Unknown");return r}({individualParticipants:t,newValues:U}))}}return Object.keys(Ph).includes(m)&&(U.participantRole=m),Object.keys(up).includes(f)&&(U.participantType=f),Array.isArray(u)&&(U.participantRoleResponsibilties=u),c.participantType===up.INDIVIDUAL&&I&&function({updateParticipantName:t,existingParticipant:e,newValues:n,person:r}){const i={},{standardFamilyName:a,standardGivenName:o,nationalityCode:s,personId:c,birthdate:u,tennisId:d,sex:p}=r;p&&Object.keys(oi).includes(p)&&(i.sex=p);let l;j(c)&&(i.personId=c);s&&j(s)&&(m=s,mp.flatMap((({iso:t,ioc:e})=>[t,e])).filter(Boolean).includes(m)||""===s)&&(i.nationalityCode=s);var m;a&&(j(a),1)&&a.length>1&&(i.standardFamilyName=a,l=!0);o&&(j(o),1)&&o.length>1&&(i.standardGivenName=o,l=!0);if(l&&t){const t=`${i.standardGivenName} ${i.standardFamilyName}`;n.participantName=t}u&&Ci(u)&&(i.birthdate=u);d&&j(d)&&(i.tennisId=d);Object.assign(e.person,i)}({updateParticipantName:e,existingParticipant:c,newValues:U,person:I}),Object.assign(c,Xr(U)),n&&pb({individualParticipantIds:[c.participantId],groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i}),Or({topic:bd,payload:{tournamentId:i.tournamentId,participants:[c]}}),{participant:la(c),...z}}function mb(t){const e=cb(t);if(e.error)return e;const r="assignTieMatchUpParticipantId";let a=t.teamParticipantId;const{tournamentRecord:o,drawDefinition:s,participantId:c,event:u}=t;if(!c)return ti({result:{error:Xe},stack:r});if(t.sideNumber&&![1,2].includes(t.sideNumber))return ti({result:{error:Pe},stack:r});const{inContextDualMatchUp:d,inContextTieMatchUp:p,relevantAssignments:l,collectionPosition:m,teamParticipants:f,collectionId:h,matchUpType:g,dualMatchUp:I,tieFormat:U}=e,y=p?.sides?.flatMap((t=>t.participant?.individualParticipantIds||t.participant?.participantId||[]));if(y?.includes(c))return ti({result:{...z},stack:r});a=a??(t.sideNumber?d?.sides?.find((e=>e.sideNumber===t.sideNumber))?.participantId:void 0);const S=ih({participantFilters:{participantIds:[c]},tournamentRecord:o})?.participants?.[0];if(!S)return ti({result:{error:en},stack:r});const{appliedPolicies:v}=Np({tournamentRecord:o,drawDefinition:s,event:u}),w=t.policyDefinitions?.[wc]??v?.[wc]??fh[wc];if(!1!==(t.enforceGender??w?.participants?.enforceGender)&&[ni,ai].includes(p?.gender)&&p?.gender!==S.person?.sex)return{error:We,info:"Gender mismatch"};const{individualParticipantIds:P,participantType:D}=S;if(um(n)(g)&&D!==ap)return{error:Ke};const T=D===ap?[c]:P,b=a&&f?.find((({participantId:t})=>t===a))||f?.find((({individualParticipantIds:t})=>k(T,t)));if(!b)return{error:Xn};if(a||(a=b.participantId),!a)return{error:en};const R=l?.find((t=>t.participantId===b?.participantId)),M=R?.drawPosition,N=I?.sides?.find((t=>t.participantId===a))?.sideNumber,A=p?.sides?.find((t=>M&&t.drawPosition===M))?.sideNumber,E=N??A??t.sideNumber;if(!U)return{error:ue};const C=U.collectionDefinitions?.find((t=>t.collectionId===h));if(!C)return{error:ce};JU({tournamentId:o.tournamentId,eventId:u.eventId,inContextDualMatchUp:d,drawDefinition:s,dualMatchUp:I});const O=I?.sides?.find((t=>t.sideNumber===E)),F=p?.sides?.find((t=>t.sideNumber===E)),x=O?.lineUp??Hm({participantId:a,drawDefinition:s})?.lineUp,_=x?.filter((t=>t.collectionAssignments?.find((t=>t.collectionPosition===m&&t.collectionId===h&&!t.previousParticipantId)))),L=_?.map((t=>t?.participantId)),B=L?.length>1&&L||(D===sp?S.individualParticipantIds:[c]),V=db({collectionPosition:m,teamParticipantId:a,dualMatchUpSide:O,drawDefinition:s,participantIds:B,collectionId:h});if(V.error)return ti({result:V,stack:r});const{modifiedLineUp:j}=V;let G;if(g===i){if(D!==sp){let t=fb({collectionPosition:m,teamParticipantId:a,drawDefinition:s,modifiedLineUp:j,participantId:c,collectionId:h,tieFormat:U});if(t?.error)return ti({result:t,stack:r});if(t=function({side:t}){let e;if(t.participant){const n=t.participant.individualParticipantIds||[];if(1===n.filter(Boolean).length){const{participant:t}=Wm({participantIds:n,tournamentRecord:o});n.push(c);const{participant:r}=Wm({participantIds:n,tournamentRecord:o});if(!r&&t){t.individualParticipantIds=n;const e=lb({pairOverride:!0,tournamentRecord:o,participant:t});if(e.error)return e}else e=t?.participantId}}else{const t=WD({participant:{individualParticipantIds:[c],participantRole:Ih,participantType:sp},pairOverride:!0,tournamentRecord:o});if(t.error)return t}return{...z,deletedParticipantId:e}}({side:F}),t.error)return t;G=t.deletedParticipantId,O&&(O.lineUp=j),I&&$d({tournamentId:o?.tournamentId,matchUp:I,context:r,drawDefinition:s})}else if(D===sp)for(const t of B)fb({collectionPosition:m,teamParticipantId:a,drawDefinition:s,modifiedLineUp:j,participantId:t,collectionId:h,tieFormat:U})}else{const t=fb({collectionPosition:m,teamParticipantId:a,drawDefinition:s,modifiedLineUp:j,participantId:c,collectionId:h,tieFormat:U});if(t?.error)return t}if(O&&(O.lineUp=j),I&&$d({tournamentId:o?.tournamentId,matchUp:I,context:r,drawDefinition:s}),G){const{error:t}=Rh({participantIds:[G],tournamentRecord:o});t&&console.log("cleanup")}return{...z,modifiedLineUp:j}}function fb({collectionPosition:t,teamParticipantId:e,drawDefinition:n,modifiedLineUp:r,participantId:i,collectionId:a,tieFormat:o}){const s=Hm({participantId:e,drawDefinition:n})?.lineUp,c=(r||s)?.find((t=>t?.participantId===i)),u={collectionId:a,collectionPosition:t};if(c)c.collectionAssignments.push(u);else{const t={collectionAssignments:[u],participantId:i};r.push(t)}return pg({participantId:e,lineUp:r,drawDefinition:n,tieFormat:o})}function hb(t){const{tournamentRecord:e,drawDefinition:r,participantId:a,event:o}=t,s="removeTieMatchUpParticiapantId";if(!a)return ti({result:{error:Xe},stack:s});const c=cb(t);if(c.error)return c;const{appliedPolicies:u}=Np({tournamentRecord:e,drawDefinition:r,event:o}),d=t.policyDefinitions?.[wc]??u?.[wc]??fh[wc],p=d?.processCodes?.substitution,{inContextDualMatchUp:l,inContextTieMatchUp:m,relevantAssignments:f,collectionPosition:h,teamParticipants:g,collectionId:I,matchUpType:U,dualMatchUp:y,tieMatchUp:S,tieFormat:v}=c;if(!y)return ti({result:{error:fe},stack:s});const w=m?.sides?.find((t=>t.participant?.participantId===a||t.participant?.individualParticipantIds?.includes(a)));if(!w)return ti({result:{error:en},stack:s});const P=t.policyDefinitions?.[Nc]??u?.[Nc];if(!w.substitutions?.length&&(vf({score:m?.score})||m?.winningSide)&&!1!==P?.requireParticipantsForScoring)return ti({result:{error:sr},stack:s});const D=l?.sides?.find((({sideNumber:t})=>t===w.sideNumber))?.participantId;if(!D)return ti({result:{error:en},stack:s});const T=ih({participantFilters:{participantIds:[a]},tournamentRecord:e})?.participants?.[0];if(!T)return ti({result:{error:en},stack:s});if(U===n&&T.participantType===sp)return ti({result:{error:We},stack:s});const b=T.participantType===ap?[a]:T.individualParticipantIds;JU({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:l,drawDefinition:r,dualMatchUp:y});let R=y.sides?.find((({sideNumber:t})=>t===w.sideNumber));if(!R&&(y.sides?.filter((({lineUp:t})=>!t)).length||0)<2){const t=g?.map((({participantId:t})=>({drawPosition:f?.find((e=>e.participantId===t))?.drawPosition,teamParticipantId:t})));R=y.sides?.find((e=>t?.find((({drawPosition:t})=>t===e.drawPosition))?.teamParticipantId===D))}if(!R)return ti({result:{error:en,context:{participantId:a}}});const{modifiedLineUp:M,previousParticipantIds:N}=db({collectionPosition:h,teamParticipantId:D,dualMatchUpSide:R,participantIds:b,drawDefinition:r,collectionId:I});if(R.lineUp=M,D&&v&&pg({participantId:D,lineUp:M,drawDefinition:r,tieFormat:v}),U===i&&T.participantType===ap){const t=m?.sides?.find((t=>t.sideNumber===R?.sideNumber)),{participantId:n}=t??{},r=n&&ih({participantFilters:{participantIds:[n]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(!r)return ti({result:{error:en},stack:s});{const t=r?.individualParticipantIds?.filter((t=>t!==a))??[];if(N&&t.push(...N),t.length>2)return ti({result:{error:ze},stack:s});if(r.draws?.length){if(1===t.length){const{participant:n}=Wm({participantIds:t,tournamentRecord:e});if(!n){const n=WD({participant:{participantRole:Ih,individualParticipantIds:t,participantType:sp},pairOverride:!0,tournamentRecord:e});if(n.error)return ti({result:n,stack:s})}}}else if(t.length){r.individualParticipantIds=t;const n=lb({participant:r,pairOverride:!0,tournamentRecord:e});if(n.error)return ti({result:n,stack:s})}else{const t=Rh({participantIds:[n],tournamentRecord:e});t.error&&console.log("cleanup",{result:t})}}}if(1===w.substitutions?.length){const t=m?.sides?.find((t=>t.sideNumber!==w.sideNumber));if(!t?.substitutions?.length&&S?.processCodes?.length){for(const t of p||[]){const e=S.processCodes.lastIndexOf(t);S.processCodes.splice(e,1)}$d({tournamentId:e?.tournamentId,matchUp:S,context:s,drawDefinition:r})}}return $d({tournamentId:e?.tournamentId,matchUp:y,context:s,drawDefinition:r}),{...z,modifiedLineUp:M}}function gb(t){const e=cc(t,[{[hs]:!0,[Is]:!0,[Cs]:!0}]);if(e.error)return e;const{drawDefinition:n,sideNumber:r,matchUpId:i,event:a}=t;if(r&&![1,2].includes(r))return{error:Jn,sideNumber:r};const{matchUp:o,structure:s}=GU({drawDefinition:n,matchUpId:i,event:a});return o?Dl({structure:s})?(o.sides?.forEach((t=>{r&&t.sideNumber!==r||delete t.participantId})),$d({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:n,matchUp:o}),{...z}):{error:vt}:{error:le}}function Ib({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:n,targetDrawPosition:r,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:o,dualMatchUp:s,matchUpsMap:c,matchUp:u,event:d}){if(s){const e=t.find((({matchUpId:t})=>u.matchUpId===t)),n=e.sides?.find((t=>t.drawPosition===r))?.sideNumber,i=u.sides?.find((t=>t.sideNumber===n));i&&delete i.lineUp}u.drawPositions=(u.drawPositions||[]).map((t=>t===r?void 0:t)).filter(Boolean);const p=e.filter((({drawPosition:t})=>u.drawPositions?.includes(t))).filter((t=>t.bye)).length;return u.matchUpStatus=p&&Fu||[Lu,zu].includes(u.matchUpStatus)&&u.matchUpStatus||Hu,[zu,Lu].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&ig({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:a,matchUpsMap:c,matchUp:u}),$d({tournamentId:i?.tournamentId,eventId:d?.eventId,context:`removeSubsequentDrawPosition-${r}`,drawDefinition:o,matchUp:u}),{...z}}function Ub(t){const{dualWinningSideChange:e,inContextDrawMatchUps:n,tournamentRecord:r,drawDefinition:i,matchUpStatus:a,matchUpsMap:o,dualMatchUp:s,targetData:c,matchUpId:u,structure:d,event:p}=t,l=Boolean(t.matchUp.collectionId),m=Dl({structure:d}),{drawPositions:f,winningSide:h}=c.matchUp||{};if(!m&&!f)return{error:gt};const{targetLinks:{loserTargetLink:g,winnerTargetLink:I,byeTargetLink:U},targetMatchUps:{loserMatchUp:y,winnerMatchUp:S,byeMatchUp:v}}=c,w=HU({...t,matchUpStatus:a||Hu,removeWinningSide:!0});if(w.error)return w;let P;if(l){const{matchUpTieId:n,matchUpsMap:a}=t;if(P=ey({appliedPolicies:t.appliedPolicies,matchUpId:n,tournamentRecord:r,drawDefinition:i,matchUpsMap:a,event:p}),!e&&!P.removeWinningSide)return{...z}}if(m)return{...z};const{matchUps:D}=Jm({afterRecoveryTimes:!1,inContext:!0,drawDefinition:i,matchUpsMap:o,structure:d}),{positionAssignments:T}=ud({structure:d}),b=h-1,R=1-b,M=f[b],N=f[R],{winnerParticipantId:A,loserParticipantId:E}=T?.reduce(((t,e)=>(e.drawPosition===N&&(t.loserParticipantId=e.participantId),e.drawPosition===M&&(t.winnerParticipantId=e.participantId),t)),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},C=D.filter((t=>t.drawPositions?.includes(N)));if(S&&yb({sourceMatchUpStatus:a,sourceMatchUpId:u,inContextDrawMatchUps:n,winningDrawPosition:M,winnerParticipantId:A,tournamentRecord:r,winnerTargetLink:I,drawDefinition:i,winnerMatchUp:S,dualMatchUp:s,matchUpsMap:o}),y){const{winnerHadMatchUpStatus:t}=function({matchUpStatuses:t=[Fu,zu,Lu],drawPositionMatchUps:e,loserDrawPosition:n,sourceMatchUps:r}){const i=e?.reduce(((t,e)=>!t||e.roundNumber>t.roundNumber?e:t),void 0),a=i?.drawPositions?.find((t=>t!==n)),o=r.filter((t=>t?.drawPositions?.includes(a))).map((t=>t.matchUpStatus)),s=r.filter((t=>t?.drawPositions?.includes(n))).map((t=>t.matchUpStatus));return{sourceMatchUp:i,winnerHadMatchUpStatus:k(o||[],t),winnerMatchUpStatuses:o,loserHadMatchUpStatus:k(s||[],t),loserMatchUpStatuses:s}}({drawPositionMatchUps:C,loserDrawPosition:N,sourceMatchUps:D}),e=g.linkCondition;if(t&&e===xo){Sb({targetLink:g,inContextDrawMatchUps:n,drawDefinition:i,drawPosition:Math.min(...y.drawPositions),matchUpsMap:o,event:p})}const c=function({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:n,loserTargetLink:r,sourceMatchUpId:i,drawDefinition:a,loserMatchUp:o,matchUpsMap:s,dualMatchUp:c,event:u}){const d="removeDirectedLoser",p=r.target.structureId,{structure:l}=ad({drawDefinition:a,structureId:p});if(!l)return{error:Lt};const{positionAssignments:m}=ud({structure:l}),f=m?.find((t=>t.participantId===e))?.drawPosition;if(m?.forEach((t=>{t.participantId===e&&delete t.participantId})),l.seedAssignments=(l.seedAssignments??[]).filter((t=>t.participantId!==e)),c){const t=o?.sides.reduce(((t,e,n)=>e.drawPosition===f?n:t),void 0),e=s?.drawMatchUps?.find((({matchUpId:t})=>t===o.matchUpId)),r=e?.sides?.[t];r&&(delete r.lineUp,$d({tournamentId:n?.tournamentId,eventId:u?.eventId,matchUp:e,context:d,drawDefinition:a}))}return{...z}}({sourceMatchUpStatus:a,sourceMatchUpId:u,loserParticipantId:E,tournamentRecord:r,loserTargetLink:g,drawDefinition:i,loserMatchUp:y,dualMatchUp:s,matchUpsMap:o,event:p});if(c.error)return c}if(v){Sb({targetLink:U,inContextDrawMatchUps:n,drawDefinition:i,drawPosition:Math.min(...v.drawPositions),matchUpsMap:o,event:p})}const O=P&&{tieMatchUpResult:P};return{...z,...O}}function yb({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:n,winnerParticipantId:r,tournamentRecord:i,winnerTargetLink:a,sourceMatchUpId:o,drawDefinition:s,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:d,event:p}){const{structureId:l,roundNumber:m}=c;if(a){const t=a.target.structureId,{structure:e}=ad({drawDefinition:s,structureId:t});if(!e)return{error:Lt};const{positionAssignments:n}=ud({structure:e});e.seedAssignments=(e.seedAssignments??[]).filter((t=>t.participantId!==r));const o=n?.find((t=>t.participantId===r)),d=o?.drawPosition,{matchUps:l}=Jm({drawDefinition:s,structure:e,event:p}),m=T(l.map((t=>t.drawPositions)).flat(1/0).filter(Boolean));if(1===(d?m[d]:void 0))n?.forEach((t=>{t.participantId===r&&delete t.participantId}));else{const t=l.filter((({drawPositions:t})=>t.includes(d)));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:t,winnerTargetLink:a})}const f=u?.drawMatchUps?.find((({matchUpId:t})=>t===c.matchUpId));f&&$d({tournamentId:i?.tournamentId,eventId:p?.eventId,matchUp:f,context:"removeDirectedWinner",drawDefinition:s})}return m&&function({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:n,tournamentRecord:r,sourceMatchUpId:i,drawDefinition:a,structureId:o,dualMatchUp:s,roundNumber:c,matchUpsMap:u,event:d}){const{structure:p}=ad({drawDefinition:a,structureId:o});if(p?.structureType===Mo)return{...z};u=u??hl({drawDefinition:a});const l=(u?.mappedMatchUps||{})[o].matchUps,{initialRoundNumber:m}=bf({drawPosition:n,matchUps:l}),f=l?.filter((t=>t.roundNumber>=c&&t.roundNumber!==m&&t.drawPositions?.includes(n))),{positionAssignments:h}=cd({drawDefinition:a,structureId:o});for(const o of f??[])Ib({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:h,targetDrawPosition:n,tournamentRecord:r,sourceMatchUpId:i,drawDefinition:a,dualMatchUp:s,matchUpsMap:u,matchUp:o,event:d})}({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:o,drawDefinition:s,dualMatchUp:d,matchUpsMap:u,roundNumber:m,structureId:l}),{...z}}function Sb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:i,targetLink:a,event:o}){const s=a.target.structureId,c="removeDirectedBye";Nf({color:"brightyellow",method:c,drawPosition:r});return ti({result:_f({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:i,structureId:s,event:o}),stack:c})}function vb(t){const{tournamentRecord:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:i,targetData:a,structure:o,event:s}=t,c="doubleExitAdvancement";if(o.structureType===Mo)return ti({result:{...z},stack:c});const{matchUp:u,targetMatchUps:d,targetLinks:p}=a,{loserMatchUp:l,winnerMatchUp:m,loserTargetDrawPosition:f}=d,h=[zu,Lu].includes(l?.matchUpStatus)&&!l.sides?.map((t=>t.participantId??t.participant)).filter(Boolean).length;if(l&&l.matchUpStatus!==Fu){const{loserTargetLink:a}=p;if(n?.progression?.doubleExitPropagateBye){const t=Pb({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:a,drawDefinition:r,matchUpsMap:i,event:s});if(t.error)return ti({result:t,stack:c})}else if(!h){const{feedRound:n,drawPositions:r,matchUpId:i}=l,a=n?2:2-r.indexOf(f),o=wb({...t,targetMatchUp:l,walkoverWinningSide:a,tournamentRecord:e,sourceMatchUp:u,matchUpId:i});if(o.error)return ti({result:o,stack:c})}}if(m){const n=wb({...t,matchUpId:m.matchUpId,targetMatchUp:m,tournamentRecord:e,sourceMatchUp:u});if(n.error)return ti({result:n,stack:c})}return ti({result:{...z},stack:c})}function wb(t){const{inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,sourceMatchUp:i,targetMatchUp:a,matchUpsMap:o}=t,s=r.structures.find((({structureId:t})=>t===a.structureId)),c=t.matchUpStatus===Bu?Bu:Vu,u=t.matchUpStatus===Bu?Lu:zu,d="conditionallyAdvanceDrawPosition",p=o.drawMatchUps.find((t=>t.matchUpId===a.matchUpId));if(!p)return{error:fe};const l=i?.drawPositions||[];let m=p.drawPositions?.filter(Boolean);const f=i?.structureId===a.structureId;if(f&&k(l,m)&&(m=m.filter((t=>!l.includes(t)))),f&&m.length>1)return ti({result:{error:lt},stack:d});const{pairedPreviousMatchUpIsDoubleExit:h,pairedPreviousMatchUp:g}=ng(t),I=rf({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),{targetMatchUps:U,targetLinks:y}=I,{loserTargetDrawPosition:S,winnerMatchUp:v,loserMatchUp:w}=U;if(w){const{loserTargetLink:t}=y,e=Pb({loserTargetDrawPosition:S,tournamentRecord:n,loserTargetLink:t,drawDefinition:r,matchUpsMap:o});if(e.error)return ti({result:e,stack:d})}const P=p.drawPositions?.filter(Boolean)||[],D=1===P.length,T=t.walkoverWinningSide||D&&ag({drawPosition:P[0],matchUpId:a.matchUpId,inContextDrawMatchUps:e})||void 0,b=[zu,Lu].includes(p.matchUpStatus)&&!P.length,R=1===p.finishingRound,M=b&&!R?c:u,N=e.find((t=>t.matchUpId===g.matchUpId));let A,E=[];i&&(i?.structureId===N?.structureId?A=i.roundPosition<g?.roundPosition?1:2:a.feedRound?A=i.structureId===a.structureId?2:1:T&&(A=3-T));const C=t.matchUpStatus,O=g?.matchUpStatus;1===A?E=[{matchUpStatus:Db(C),previousMatchUpStatus:C,sideNumber:1},{matchUpStatus:Db(O),previousMatchUpStatus:O,sideNumber:2}]:2===A&&(E=[{matchUpStatus:Db(O),previousMatchUpStatus:O,sideNumber:1},{matchUpStatus:Db(C),previousMatchUpStatus:C,sideNumber:2}]),E.length&&(E=E.map((t=>Xr(t))));const F=HU({...t,winningSide:T,matchUp:p,matchUpStatusCodes:E,matchUpStatus:M});if(F.error)return ti({result:F,stack:d});if(b)return vb({...t,matchUpStatus:M,targetData:I});if(!v)return ti({result:{...z},stack:d});const x=2===m.length?m[T-1]:m[0],{positionAssignments:_}=cd({structure:s}),L=_?.find((t=>t.drawPosition===x)),B=o.drawMatchUps.find((t=>t.matchUpId===v.matchUpId)),V=B?.drawPositions?.filter(Boolean),j=1===V.length;if(x){if(L?.bye){const n=rf({matchUpId:B.matchUpId,inContextDrawMatchUps:e,drawDefinition:r});if(j){const n=V.filter(Boolean)[0],i=ag({drawPosition:n,matchUpId:B.matchUpId,inContextDrawMatchUps:e}),a=HU({appliedPolicies:t.appliedPolicies,matchUpId:B.matchUpId,matchUp:B,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,winningSide:i});return a.error?ti({result:a,stack:d}):Ff({drawPositionToAdvance:n,matchUpId:B.matchUpId,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}if([zu,Lu].includes(v.matchUpStatus)){const e=vb({...t,matchUpId:B.matchUpId,matchUpStatus:M,targetData:n});if(e.error)return ti({result:e,stack:d})}return ti({result:{...z},stack:d})}return og({matchUpId:v.matchUpId,drawPosition:x,inContextDrawMatchUps:e,drawDefinition:r})}if(h){if(!B)return{error:fe};if(j){const t=V[0],n=ag({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawPosition:t});console.log("existing drawPosition is winningSide",{walkoverWinningSide:n})}const n=[zu,Lu].includes(B.matchUpStatus)?u:c,i=HU({matchUpId:B.matchUpId,appliedPolicies:t.appliedPolicies,matchUp:B,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,matchUpStatus:n});if(i.error)return ti({result:i,stack:d});if(n===c){const e=vb({...t,matchUpId:a.matchUpId,matchUpStatus:n,targetData:I});if(e.error)return e}}return ti({result:{...z},stack:d})}function Pb(t){const{loserTargetDrawPosition:e,tournamentRecord:n,loserTargetLink:r,drawDefinition:i,matchUpsMap:a,event:o}=t,s=r?.target?.structureId,{structure:c}=ad({drawDefinition:i,structureId:s});return c?Ef({drawPosition:e,tournamentRecord:n,drawDefinition:i,structureId:s,matchUpsMap:a,event:o}):{error:Vt}}function Db(t){return t===Vu?zu:t===Bu?Lu:t}function Tb(t){const{tournamentRecord:e,drawDefinition:n,matchUpStatus:r,structure:i,matchUp:a}=t,o=!(!a.tieMatchUps||a.rondPosition||!t.inContextDrawMatchUps.find((t=>t.matchUpId===a.matchUpId)).containerStructureId),s=r===Fu,c=a.winningSide,u=[Vu,Bu].includes(r),d=wf({matchUpStatus:r}),p=Pf({matchUpStatus:r}),l=!d&&!p,m=t.matchUpTieId||c&&d&&!u,f=c&&u;return l&&{error:ee}||m&&bb(t)||f&&function(t){const e=Ub(t);return e.error?e:vb(t)}(t)||c&&Ub(t)||p&&HU({...t,removeScore:[ku,zu].includes(r),matchUpStatus:r||Hu})||s&&function({tournamentRecord:t,drawDefinition:e,structure:n,matchUp:r}){const i="attemptToSetMatchUpStatusBYE";if(r?.winningSide)return ti({result:{error:ie},context:{matchUpStatus:Fu},stack:i});const{positionAssignments:a}=ud({structure:n}),o=a?.filter((t=>t.bye)).map((t=>t.drawPosition)),s=r.drawPositions?.some((t=>o?.includes(t)));return s?(r.matchUpStatus=Fu,r.matchUpStatusCodes=[],$d({tournamentId:t?.tournamentId,context:i,drawDefinition:e,matchUp:r}),{...z}):ti({result:{error:te},info:"matchUp does not include BYE",stack:i})}({tournamentRecord:e,drawDefinition:n,structure:i,matchUp:a})||!d&&{error:ee}||u&&function(t){const e=bb({...t,removeScore:!0});return e.error?e:vb(t)}(t)||o&&bb(t)||ti({result:{error:ie},stack:"attemptToSetMatchUpStatus"})}function bb(t){const e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){const n=Ub(t);if(n.error)return ti({result:n,stack:e})}const n=Boolean(t.matchUp.collectionId),r=HU({...t});if(n){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:a}=t,o=ey({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:n,event:t.event,drawDefinition:i,matchUpsMap:a});if(o.error)return ti({result:o,stack:e});Object.assign(r,{tieMatchUpResult:o})}return ti({result:r,stack:e})}function Rb({drawDefinition:t,structure:e,matchUp:n}){const r=[];if(e.finishingPosition===us){if(Tg({drawDefinition:t,structure:e})){const{structureIds:i}=function({drawDefinition:t,structure:e,matchUp:n}){const{drawPositions:r}=n,{positionAssignments:i}=cd({drawDefinition:t,structure:e}),a=i?.filter((({drawPosition:t})=>r?.includes(t))),o=a?.map((t=>{const{extension:e}=zc({element:t,name:gu});return e?.value?.groupOrder})),{containerStructures:s}=Zd({drawDefinition:t}),c=s[e.structureId],u=ef({drawDefinition:t,structureId:c})?.links?.source,d=u?.filter((t=>k(o,t.source?.finishingPositions||[]))).map((t=>t.source.structureId));return{structureIds:d}}({drawDefinition:t,structure:e,matchUp:n});i?.length&&r.push(...i)}}return{connectedStructureIds:r}}function Mb(t){const e="attemptToSetWinningSide";let n;const{appliedPolicies:r,disableAutoCalc:i,drawDefinition:a,dualMatchUp:o,winningSide:s,structure:c,matchUp:u}=t;if(o?._disableAutoCalc&&!1!==i)return zU(t);if(u.winningSide&&u.winningSide!==s){const{connectedStructureIds:e}=Rb({drawDefinition:a,structure:c,matchUp:u});e.length&&(console.log({connectedStructureIds:e}),n=!0);const r=Ub(t);if(r.error)return r}const d=ny(t);if(d.error)return ti({result:d,stack:e});let p,l;return t.qualifierChanging&&r?.[bc]?.autoReplaceQualifiers&&(p=function(t){let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:i,winningSide:a}=t,o=t.targetData.targetLinks?.winnerTargetLink;if(o.target.feedProfile===No){const s=r.sides.find((({sideNumber:t})=>t!==a)).participantId,c=n.find((t=>t.structureId===o.target.structureId&&t.roundNumber===o.target.roundNumber&&t.sides.some((({participantId:t})=>t===s))));if(c?.matchUpStatus===Hu&&!Oy({inContextDrawMatchUps:n,drawDefinition:i,targetData:rf({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=ad({structureId:c.structureId,drawDefinition:i}),o=cd({structure:n}).positionAssignments;for(const c of o||[])if(c.participantId===s){const s=r.sides.find((({sideNumber:t})=>t===a)).participantId;if(c.participantId=s,n?.positionAssignments)n.positionAssignments=o;else if(n?.structures){const t=Object.assign({},...(o||[]).map((t=>({[t.drawPosition]:t.participantId}))));for(const e of n.structures)e.positionAssignments?.forEach((e=>e.participantId=t[e.drawPosition]))}Yd({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:n}),e=!0}}}return{...z,qualifierReplaced:e}}(t).qualifierReplaced),t.qualifierAdvancing&&r?.[bc]?.autoPlaceQualifiers&&(l=function(t){let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:i,winningSide:a}=t,o=t.targetData.targetLinks?.winnerTargetLink;if(o.target.feedProfile===No){const s=r.sides.find((({sideNumber:t})=>t===a))?.participantId,c=A(n.filter((t=>t.structureId===o.target.structureId&&t.roundNumber===o.target.roundNumber&&t.sides.some((({participantId:t,qualifier:e})=>e&&!t)))));if(c?.matchUpStatus===Hu&&!Oy({inContextDrawMatchUps:n,drawDefinition:i,targetData:rf({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const n=c.sides.find((t=>t.qualifier&&!t.participantId))?.drawPosition,{structure:r}=ad({structureId:c.structureId,drawDefinition:i});if(!r)return{error:Lt};const a=cd({structure:r}).positionAssignments;for(const o of a||[])if(o.drawPosition===n&&!o.participantId){if(o.participantId=s,r.positionAssignments)r.positionAssignments=a;else if(r.structures){const t=Object.assign({},...(a||[]).map((t=>({[t.drawPosition]:t.participantId}))));for(const e of r.structures)e.positionAssignments?.forEach((e=>e.participantId=t[e.drawPosition]))}Yd({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:r}),e=!0}}}return{...z,qualifierPlaced:e}}(t).qualifierPlaced),ti({result:Xr({...z,...d,connectedStructures:n,qualifierReplaced:p,qualifierPlaced:l}),stack:e})}const Nb={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function Ab(t){const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:i,targetData:a,matchUp:o}=t,{matchUpId:s}=o;let{iteration:c=0}=t;c+=1;const u="removeDoubleExit";Nf({color:"brightyellow",method:u,matchUpId:s,iteration:c,keyColors:Nb});const{targetMatchUps:{loserMatchUp:d,winnerMatchUp:p,loserTargetDrawPosition:l},targetLinks:{loserTargetLink:m}}=a;if(p&&p.matchUpStatus!==Fu){const{stage:e,roundNumber:n,roundPosition:r,structureName:i}=p;Nf({winner:"winner",roundPosition:r,structureName:i,roundNumber:n,keyColors:Nb,stage:e}),Eb({...t,targetMatchUp:p,sourceMatchUp:o,iteration:c})}const f=d?.matchUpStatus===Fu&&(d?.feedRound||1===d?.roundNumber);if(f&&a?.targetLinks?.loserTargetLink?.linkCondition===xo){const t=e.filter((({roundNumber:t,structureId:e})=>e===o.structureId&&1===t)),n=x(t.map((({roundPosition:t})=>t)).sort(),2).find((t=>t.includes(o.roundPosition))),r=t.filter((({roundPosition:t})=>n.includes(t)))?.map((({matchUpStatus:t})=>t));if(r.every((t=>[Bu,Vu].includes(t))))return ti({result:{...z},stack:u})}if(d&&(d.matchUpStatus!==Fu||f)){const a=e.find((({matchUpId:t})=>t===d.matchUpId)),{structure:o}=ad({drawDefinition:r,structureId:a.structureId}),{stage:s,roundNumber:p,roundPosition:h,feedRound:g,structureName:I}=d;if(Nf({loser:"loser",roundPosition:h,structureName:I,roundNumber:p,keyColors:Nb,feedRound:g,stage:s}),n?.progression?.doubleExitPropagateBye||f)Sb({drawPosition:l,targetLink:m,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:i});else{const e=Eb({...t,targetMatchUp:d,structure:o,iteration:c});if(e.error)return ti({result:e,stack:u})}}return ti({result:{...z},stack:u})}function Eb(t){const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,sourceMatchUp:i,targetMatchUp:a,matchUpsMap:o,structure:s,iteration:c}=t,u="conditionallyRemoveDrawPosition";Nf({method:u,structureName:s?.structureName,iteration:c});const d=rf({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),{targetMatchUps:{winnerMatchUp:p}}=d,l=o?.drawMatchUps.find((t=>t.matchUpId===a.matchUpId));let m,f,h,g=[];if(a.feedRound){const t=p?.drawPositions?.filter(Boolean);h=t?.find((t=>a.drawPositions.includes(t)))}else if(i){f=rg({structureId:s.structureId,matchUp:i,matchUpsMap:o})?.pairedPreviousMatchUp,m=[Vu,Bu].includes(f?.matchUpStatus),g=f?.drawPositions?.filter(Boolean)||[];if([...Xu,Fu].includes(f?.matchUpStatus)||f?.winningSide){const t=i.drawPositions||[];let e=a.drawPositions?.filter(Boolean);k(t,e)&&(e=e?.filter((e=>!t.includes(e))));h=t.concat(g).find((t=>e?.includes(t)))}}else h=O(a?.drawPositions||[],p?.drawPositions||[])?.[0];if(p&&h){const{stage:t,roundNumber:n,roundPosition:i,structureName:a}=p;Nf({method:"removeDirectedWinner",drawPositionToRemove:h,color:"brightgreen",roundPosition:i,structureName:a,roundNumber:n,keyColors:Nb,stage:t}),yb({winningDrawPosition:h,winnerMatchUp:p,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}let I=Ab({targetData:d,matchUp:a,inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:o,structure:s,iteration:c});if(I.error)return ti({result:I,stack:u});const U=function({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Fu?Fu:t?[Bu,Lu].includes(e?.matchUpStatus)?Lu:zu:Hu}({pairedPreviousDoubleExit:m,noContextTargetMatchUp:l}),y=!m;return I=HU({...t,matchUpId:a.matchUpId,matchUp:l,removeWinningSide:!0,matchUpStatusCodes:[],matchUpStatus:U,removeScore:y,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),I.error?ti({result:I,stack:u}):{...z}}function Cb(t){const{matchUp:e,matchUpStatus:n,score:r,winningSide:i}=t,a="noDownStreamDependencies";if([Vu,Bu].includes(e?.matchUpStatus)&&![Vu,Bu].includes(n)){const e=Ab(t);if(e.error)return ti({result:e,stack:a})}const o=n===Vu,s=vf({score:r})&&!o&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!i),c=t?.inContextMatchUp?.collectionId&&function(t){const{matchUpFormat:e,score:n}=t,r=n?.sets?.length,i=e&&Ii(e),{setFormat:a,finalSetFormat:o,bestOf:s}=i??{},c=s&&r===s&&o||a;return c?.timed||!1}(t.inContextMatchUp),u=t.removeScore||!c&&![Gu,Cu].includes(n||Gu),d=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!i&&!vf({score:r}),p=n&&n!==Hu,l=n=>{let r;const{structure:i,drawDefinition:a,dualMatchUp:o,disableAutoCalc:s}=t;if(o?._disableAutoCalc&&!1!==s)return zU({...t,removeWinningSide:d});const{connectedStructureIds:c}=Rb({drawDefinition:a,structure:i,matchUp:e});c.length&&(console.log({connectedStructureIds:c}),r=!0),Object.assign(t,{removeScore:n});const u=Ub(t);if(u.error)return u;if(t.removingQualifier&&t.appliedPolicies?.[bc]?.autoRemoveQualifiers){const e=function(t){let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:i}=t,a=t.targetData.targetLinks?.winnerTargetLink;if(a.target.feedProfile===No){const o=r.sides?.find((({sideNumber:t})=>t===r.winningSide))?.participantId,s=n.find((t=>t.structureId===a.target.structureId&&t.roundNumber===a.target.roundNumber&&t.sides?.some((({participantId:t})=>t===o))));if(s&&s.matchUpStatus===Hu&&!Oy({inContextDrawMatchUps:n,drawDefinition:i,targetData:rf({matchUpId:s.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=ad({structureId:s.structureId,drawDefinition:i}),r=cd({structure:n}).positionAssignments;for(const a of r||[])if(a.participantId===o){if(a.participantId=void 0,n?.positionAssignments)n.positionAssignments=r;else if(n?.structures){const t=Object.assign({},...(r||[]).map((t=>({[t.drawPosition]:t.participantId}))));for(const e of n?.structures||[])e.positionAssignments?.forEach((e=>e.participantId=t[e.drawPosition]))}Yd({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:n}),e=!0}}}return{qualifierRemoved:e}}(t);return{...z,connectedStructures:r,...e}}return{...z,connectedStructures:r}};if(d&&i&&t.isCollectionMatchUp)return Ob(t);const m=[ku,Cu].includes(n)&&t.dualWinningSideChange;return ti({result:(i||m)&&Mb(t)||s&&l(u)||p&&Tb(t)||d&&l(u)||e&&Ob({...t,removeScore:!0})||{...z},stack:a})}function Ob(t){if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide&&!t.autoCalcDisabled){const e=Ub(t);if(e.error)return e}const e=HU({...t});if(t.isCollectionMatchUp){const{matchUpTieId:e,drawDefinition:n,event:r,matchUpsMap:i}=t,{removeWinningSide:a}=ey({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:e,drawDefinition:n,matchUpsMap:i,event:r});a&&console.log("REMOVE WINNING SIDE")}return ti({result:e,stack:"ndd:scoreModification"})}function Fb(t){const e=cc(t,[{[hs]:!0,[Is]:!0,[Cs]:!0},{homeParticipantId:!0,[$s]:Xe}]);if(e.error)return e;const n=yD(t,[{[Hs]:Gs,attr:{[Fs]:!0}}]);if(n.error)return n;const r=n?.matchUp?.matchUp?.sides?.map((t=>t?.participantId));if(t.homeParticipantId&&!r?.includes(t.homeParticipantId))return{error:He};const{disableNotice:i,homeParticipantId:a,removePriorValues:o,tournamentRecord:s,drawDefinition:c,matchUpId:u}=t;return ib({duplicateValues:!1,removePriorValues:o,tournamentRecord:s,drawDefinition:c,disableNotice:i,matchUpId:u,timeItem:{itemType:Vl,itemValue:a}})}function kb({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=Mm({timeItems:n?.timeItems||[],itemType:zl});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{timeModifiers:r}:e}function xb(t){const e="addMatchUpScheduledTime";let n=t.matchUp;const{removePriorValues:r,tournamentRecord:i,drawDefinition:a,disableNotice:o,scheduledTime:s,matchUpId:c}=t;if(!c)return ti({result:{error:de},stack:e});if(!Ei(s))return ti({result:{error:Fe},stack:e});if(!n){const t=GU({drawDefinition:a,matchUpId:c});if(t.error)return ti({result:t,stack:e});n=t.matchUp}const u=$i(s),d=Am({matchUp:n}).scheduledDate,p=u&&!d,l=kb({matchUp:n}).timeModifiers||[];if(l?.length){const t=_b({disableNotice:!0,removePriorValues:r,tournamentRecord:i,timeModifiers:[],drawDefinition:a,matchUpId:c,matchUp:n});if(t?.error)return ti({result:t,stack:e})}const m=zi(s,!0,p);return ib({duplicateValues:!1,removePriorValues:r,tournamentRecord:i,drawDefinition:a,disableNotice:o,matchUpId:c,timeItem:{itemType:Gl,itemValue:m}})}function _b({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,timeModifiers:i,matchUpId:a,matchUp:o}){const s="addMatchUpTimeModifiers";if(!a)return ti({result:{error:de},stack:s});if(void 0!==i&&!Array.isArray(i))return ti({info:ug("timeModifiers"),result:{error:Jn},stack:s});if(!o){const t=GU({drawDefinition:n,matchUpId:a});if(t.error)return ti({result:t,stack:s});o=t.matchUp}let c=kb({matchUp:o}).timeModifiers||[];const u=i.filter((t=>!c.includes(t)));if(i.length&&!u.length)return{...z};if(u.some((t=>Xl.includes(t)))){c=c.filter((t=>!Xl.includes(t)));const r=xb({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:n,matchUpId:a});if(r.error)return ti({result:r,stack:s})}const d=i?.length?[...u,...c]:void 0;return ib({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemType:zl,itemValue:d}})}function Lb({scheduledDate:t,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a}){if(!a)return{error:de};const o=t&&Ri.test(t);if(t&&!o)return{error:Oe};return ib({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemValue:$i(t),itemType:Bl}})}function Bb({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtDayDate:o,matchUpId:s,courtIds:c}){if(!n&&!e)return{error:nt};if(!s)return{error:de};const u=GU({drawDefinition:r,matchUpId:s});if(u.error)return u;if(u?.matchUp?.matchUpType!==a)return{error:he};if(!(void 0===c||Array.isArray(c)&&c.length&&c.every((t=>"string"==typeof t))))return{error:Jn,context:{courtIds:c}};let d;if(c){const t=vP({tournamentRecords:e||n&&{[n.tournamentId]:n}});if(t.error)return t;const r=t.courts?.filter((t=>c.includes(t.courtId)));if(r?.length!==c.length)return{error:Jn,context:{courtIds:c}};d=r?.map((t=>({venueId:t.venueId,courtId:t.courtId})))}return ib({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:s,timeItem:{itemType:xl,itemDate:o,itemValue:d}})}function Vb({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,venueId:o}){if(!n)return{error:nt};if(!a)return{error:de};if(o){const t=km({tournamentRecords:e,tournamentRecord:n,venueId:o});if(t.error)return t}return ib({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemType:kl,itemValue:o}})}function jb({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtDayDate:a,matchUpId:o,courtId:s}){if(!n&&!e)return{error:nt};if(!o)return{error:de};if(s){const t=_m({tournamentRecords:e,tournamentRecord:n,courtId:s});if(t.error)return t;const a=t.venue?.venueId;Vb({tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,venueId:a})}return ib({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:_l,itemDate:a,itemValue:s}})}function Gb(t,e){const n=bi.test(t)?t:qi(t),r=$i(t)||$i(e)||Fi(new Date);return new Date(`${r}T${n}`).getTime()}function qb(t){const e="addMatchUpScheduleItems",n=cc(t,[{drawDefinition:!0,matchUpId:!0},{schedule:!0,[nc]:Js}],e);if(n.error)return n;let{matchUpDependencies:r,inContextMatchUps:i}=t;const{errorOnAnachronism:a=!1,checkChronology:o=!0,removePriorValues:s,tournamentRecords:c,tournamentRecord:u,drawDefinition:d,disableNotice:p,drawMatchUps:l,matchUpId:m,schedule:f,event:h}=t;let g,I;if(l)g=l.find((t=>t.matchUpId===m));else{const t=GU({drawDefinition:d,event:h,matchUpId:m});if(t.error)return t;g=t.matchUp}const{endTime:U,courtId:S,courtIds:v,courtOrder:w,resumeTime:P,homeParticipantId:D,scheduledDate:T,scheduledTime:b,startTime:R,stopTime:M,timeModifiers:N,venueId:A}=f;!o||r&&i||({matchUpDependencies:r,matchUps:i}=Sf({drawDefinition:d}));const E=r?.[m]?.matchUpIds;if(f.scheduledDate&&o&&E){const t=i?.filter((t=>(t.schedule?.scheduledDate||$i(t.schedule?.scheduledTime))&&E.includes(t.matchUpId))).map((({schedule:t})=>{const e=Ni(t);return new Date(e).getTime()}));if(t?.length){const n=Ni(f),r=new Date(n).getTime();if(Math.max(...t)>=r){if(a)return ti({result:{error:J},stack:e});I=J}}}if(void 0!==T){const t=Lb({disableNotice:!0,removePriorValues:s,tournamentRecord:u,drawDefinition:d,scheduledDate:T,matchUpId:m});if(t?.error)return ti({result:t,stack:e,context:{scheduledDate:T}})}if(void 0!==b){const t=xb({disableNotice:!0,removePriorValues:s,tournamentRecord:u,drawDefinition:d,scheduledTime:b,matchUpId:m,matchUp:g});if(t?.error)return ti({result:t,stack:e,context:{scheduledTime:b}})}if(void 0!==R){const t=Hb({disableNotice:!0,removePriorValues:s,tournamentRecord:u,drawDefinition:d,matchUpId:m,startTime:R,event:h});if(t?.error)return ti({result:t,stack:e,context:{startTime:R}})}if(void 0!==M){const t=Yb({disableNotice:!0,removePriorValues:s,tournamentRecord:u,drawDefinition:d,matchUpId:m,stopTime:M,event:h});if(t?.error)return ti({result:t,stack:e,context:{stopTime:M}})}if(void 0!==P){const t=Kb({disableNotice:!0,removePriorValues:s,tournamentRecord:u,drawDefinition:d,resumeTime:P,matchUpId:m,event:h});if(t?.error)return ti({result:t,stack:e,context:{resumeTime:P}})}if(void 0!==U){const t=zb({disableNotice:!0,removePriorValues:s,tournamentRecord:u,drawDefinition:d,matchUpId:m,endTime:U,event:h});if(t?.error)return ti({result:t,stack:e,context:{endTime:U}})}if(void 0!==v){const t=Bb({disableNotice:!0,removePriorValues:s,tournamentRecord:u,drawDefinition:d,matchUpId:m,courtIds:v});if(t?.error)return ti({result:t,stack:e,context:{courtIds:v}})}if(void 0!==S&&void 0!==T){const t=jb({courtDayDate:T,disableNotice:!0,removePriorValues:s,tournamentRecords:c,tournamentRecord:u,drawDefinition:d,matchUpId:m,courtId:S});if(t?.error)return ti({result:t,stack:e,context:{courtId:S}})}if(void 0!==A){const t=Vb({disableNotice:!0,removePriorValues:s,tournamentRecords:c,tournamentRecord:u,drawDefinition:d,matchUpId:m,venueId:A});if(t?.error)return ti({result:t,stack:e,context:{venueId:A}})}if(void 0!==w&&y(w)){const t=$b({disableNotice:!0,removePriorValues:s,tournamentRecord:u,drawDefinition:d,courtOrder:w,matchUpId:m});if(t?.error)return ti({result:t,stack:e,context:{courtOrder:w}})}if(void 0!==N){const t=_b({disableNotice:!0,removePriorValues:s,tournamentRecord:u,drawDefinition:d,timeModifiers:N,matchUpId:m,matchUp:g});if(t?.error)return ti({result:t,stack:e,context:{timeModifiers:N}})}return j(D)&&Fb({disableNotice:!0,homeParticipantId:D,removePriorValues:s,tournamentRecord:u,drawDefinition:d,matchUpId:m}),p||$d({tournamentId:u?.tournamentId,eventId:h?.eventId,context:e,drawDefinition:d,matchUp:g}),I?{...z,warnings:[I]}:{...z}}function $b({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,courtOrder:i,matchUpId:a}){if(!a)return{error:de};if(i&&!y(i))return{error:Jn,info:"courtOrder must be numeric"};const o=i&&d(i);return ib({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemType:Ll,itemValue:o}})}function Wb({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,participantId:i,officialType:a,matchUpId:o}){if(!o)return{error:de};if(!i)return{error:Xe};if(e){if(!Fc({tournamentParticipants:ih({tournamentRecord:e,participantFilters:{participantTypes:[ap],participantRoles:[Sh]}}).participants??[],participantId:i}))return{error:en}}const s={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:i};return a&&(s.itemSubTypes=[a]),ib({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:o,timeItem:s})}function Hb({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,startTime:a,event:o}){if(!i)return{error:de};if(!Ei(a))return{error:Fe};const{matchUp:s}=GU({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:c}=Am({matchUp:s}),u=(s?.timeItems??[]).filter((t=>[$l,Wl,Hl].includes(t?.itemType))).map((t=>Gb(t.itemValue,c))).reduce(((t,e)=>!t||e<t?e:t),void 0);if(!u||Gb(a,c)<u){s?.timeItems&&(s.timeItems=s.timeItems.filter((t=>t.itemType!==ql)));const o=zi(a,!0,!0);return ib({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemType:ql,itemValue:o}})}return{error:On}}function zb({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,endTime:o,event:s}){if(!a)return{error:de};if(!Ei(o))return{error:Fe};const{matchUp:c}=GU({drawDefinition:r,event:s,matchUpId:a}),{scheduledDate:u}=Am({matchUp:c}),d=(c?.timeItems??[]).filter((t=>[ql,Wl,$l].includes(t?.itemType))).map((t=>Gb(t.itemValue,u))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(!t||!d||Gb(o,u)>d){c?.timeItems&&(c.timeItems=c.timeItems.filter((t=>t.itemType!==Hl)));const t=zi(o,!0,!0);return ib({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemType:Hl,itemValue:t}})}return{error:An}}function Yb({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,stopTime:a,event:o}){if(!i)return{error:de};if(!Ei(a))return{error:Fe};const{matchUp:s}=GU({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:c}=Am({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((t,e)=>e.itemType===Hl||t),void 0))return{error:En};const d=u.filter((t=>[ql,Wl,$l].includes(t?.itemType))).sort(((t,e)=>Gb(t.itemValue,c)-Gb(e.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===$l,m=d.filter((t=>!l||t.createdAt!==p.createdAt)).map((t=>Gb(t.itemValue,c))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(Gb(a,c)>m){if(s?.timeItems&&l){const t=p.createdAt;s.timeItems=s.timeItems.filter((e=>e.createdAt!==t))}return ib({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemValue:zi(a,!0,!0),itemType:$l}})}return{error:Cn}}function Kb({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,resumeTime:i,matchUpId:a,event:o}){if(!a)return{error:de};if(!Ei(i))return{error:Fe};const{matchUp:s}=GU({drawDefinition:n,event:o,matchUpId:a}),{scheduledDate:c}=Am({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((t,e)=>e.itemType===Hl||t),void 0))return{error:En};const d=u.filter((t=>[ql,Wl,$l].includes(t?.itemType))).sort(((t,e)=>Gb(t.itemValue,c)-Gb(e.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===Wl,m=d.filter((t=>!l||t.createdAt!==p.createdAt)).map((t=>Gb(t.itemValue,c))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(Gb(i,c)>m){if(s?.timeItems&&l){const t=p.createdAt;s.timeItems=s.timeItems.filter((e=>e.createdAt!==t))}return ib({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemValue:zi(i,!0,!0),itemType:Wl}})}return{error:Fn}}function Qb(t){const e="setMatchUpStatus";t.matchUpStatus&&[zu,Vu].includes(t.matchUpStatus)&&(t.score=void 0);const{allowChangePropagation:n,disableScoreValidation:r,tournamentRecords:i,tournamentRecord:a,disableAutoCalc:s,enableAutoCalc:c,drawDefinition:u,matchUpStatus:d,winningSide:p,matchUpId:l,event:m,score:f}=t;if(!u)return{error:ot};if(d&&[ku,Gu,Cu,Hu].includes(d)&&p)return{error:Jn,winningSide:p,matchUpStatus:d};if(![void 0,...Qu].includes(d))return ti({result:{error:ie},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});const h=hl({drawDefinition:u}),{matchUps:g}=cf({nextMatchUps:!0,tournamentRecord:a,inContext:!0,drawDefinition:u,matchUpsMap:h,event:m}),I=h.drawMatchUps.find((t=>t.matchUpId===l)),U=g?.find((t=>t.matchUpId===l));if(!I||!g)return{error:le};if((I.winningSide||p)&&d===Fu)return{context:"Cannot have Bye with winningSide",error:re,matchUpStatus:d};const y=U?.structureId,{structure:S}=ad({drawDefinition:u,structureId:y}),v=um(o)(I.matchUpType),w=U?.drawPositions?.filter(Boolean),P=U?.matchUpTieId,D=rf({matchUpId:P||l,inContextDrawMatchUps:g,drawDefinition:u});Object.assign(t,{inContextDrawMatchUps:g,inContextMatchUp:U,matchUpTieId:P,matchUpsMap:h,targetData:D,structure:S,matchUp:I});const T=Oy(t);let b;if(v){if(s)_c({extension:{name:Zc,value:!0},element:I});else if(c){const e=I.winningSide,{winningSide:n,scoreStringSide1:r,scoreStringSide2:i,set:a}=QU({drawDefinition:u,matchUpsMap:h,structure:S,matchUp:I,event:m}),o={scoreStringSide1:r,scoreStringSide2:i,sets:a?[a]:[]};if(b=n!==e,T&&b)return ti({stack:"winningSideWithDownstreamDependencies",result:{error:$e},context:{winningSide:p,matchUp:I}});kc({name:Zc,element:I}),Object.assign(t,{winningSide:n,dualWinningSideChange:b,projectedWinningSide:n,score:o})}JU({tournamentId:a?.tournamentId,inContextDualMatchUp:U,eventId:m?.eventId,dualMatchUp:I,drawDefinition:u})}if(v&&d&&[Ou].includes(d))return{info:"Not supported for matchUpType: TEAM",error:Jn};if(f&&!v&&!r){const t=I.matchUpFormat??S?.matchUpFormat??u?.matchUpFormat??m?.matchUpFormat,e=yw({existingMatchUpStatus:I.matchUpStatus,matchUpFormat:t,matchUpStatus:d,winningSide:p,score:f});if(e.error)return e}const R=Np({policyTypes:[bc,Nc],tournamentRecord:a,drawDefinition:u,event:m})?.appliedPolicies??{};G(t.policyDefinitions)&&Object.assign(R,t.policyDefinitions);const M=function({assignedDrawPositions:t,inContextMatchUp:e,appliedPolicies:n,drawDefinition:r,matchUpStatus:i,structure:a,matchUp:o}){if(!1===n?.[Nc]?.requireParticipantsForScoring)return{...z};const s=e?.sides?.map((t=>t.participantId)).filter(Boolean).length,c=o?.sides?[]:cd({structureId:a?.structureId,drawDefinition:r}).positionAssignments,u=s&&2===s||o.collectionId&&Dl({structure:a})&&s&&s>=1||2===t?.length&&c?.filter((e=>t.includes(e.drawPosition))).every((t=>t.participantId));if(i&&Ku.includes(i)&&!u)return ti({info:"matchUpStatus requires assigned participants",context:{matchUpStatus:i,requiredParticipants:u},result:{error:ie}});return{...z}}({assignedDrawPositions:w,inContextMatchUp:U,appliedPolicies:R,drawDefinition:u,matchUpStatus:d,structure:S,matchUp:I});if(M?.error)return M;const N=U?.stage===ho&&1===U.finishingRound,A=N&&p,E=N&&I.winningSide&&!p&&(!t.matchUpStatus||t.matchUpStatus&&Pf({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!vf({outcome:t.outcome})),C=A&&p!==I.winningSide&&I.winningSide;if(Object.assign(t,{qualifierAdvancing:A,qualifierChanging:C,removingQualifier:E,appliedPolicies:R}),P){const{matchUp:e}=GU({matchUpId:P,inContext:!0,drawDefinition:u,matchUpsMap:h,event:m});if(e){const n=fl({matchUp:e,drawDefinition:u,structure:S,event:m})?.tieFormat,{projectedWinningSide:r}=function({drawDefinition:t,matchUpStatus:e,matchUpsMap:n,winningSide:r,dualMatchUp:i,tieFormat:a,structure:o,matchUp:s,event:c,score:u}){const d=la(i,void 0,!0);for(const t of d?.tieMatchUps||[])t.matchUpId===s.matchUpId&&(t.winningSide=r,t.score=u,vf({score:u})||e?e&&(t.matchUpStatus=e):Object.assign(t,{...WU}));a=a??fl({matchUp:s,structure:o,drawDefinition:t,event:c})?.tieFormat;const{winningSide:p}=QU({matchUp:d,drawDefinition:t,matchUpsMap:n,structure:o,tieFormat:a,event:c});return{projectedWinningSide:p}}({drawDefinition:u,matchUpStatus:d,dualMatchUp:e,matchUpsMap:h,winningSide:p,tieFormat:n,structure:S,matchUp:I,event:m,score:f});b=r!==e.winningSide;const i=e._disableAutoCalc;Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:b,projectedWinningSide:r,autoCalcDisabled:i,matchUpTieId:P,dualMatchUp:e,tieFormat:n})}}const O=wf({matchUpStatus:d});if(!P){if(T&&!p&&(d&&Pf({matchUpStatus:d})||d&&[Vu,Bu].includes(d)))return{error:re,activeDownstream:T,winningSide:p};if(p&&p===I.winningSide&&d&&!O)return{context:"winningSide must include directing matchUpStatus",error:re,directingMatchUpStatus:O,matchUpStatus:d}}const{schedule:F}=t;if(F){const t=qb({disableNotice:!0,tournamentRecords:i,tournamentRecord:a,drawDefinition:u,matchUpId:l,schedule:F});if(t.error)return t}const k=!v&&!b&&p&&I.winningSide&&I.winningSide!==p;if(n&&k&&I.roundPosition)return function(t){const{tournamentRecord:e,inContextMatchUp:n,structure:r,drawDefinition:i}=t,a=n.roundNumber,o=n.sides.find((t=>t.sideNumber===n.winningSide)),s=n.sides.find((t=>t.sideNumber!==n.winningSide)),{drawPosition:c,participantId:u}=o,{drawPosition:d,participantId:p}=s,{matchUps:l}=Jm(t),m=l.filter((({drawPositions:t,roundNumber:e})=>t?.includes(c)&&e>a));Pr({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:m}),m.forEach((n=>{n.drawPositions=n.drawPositions?.map((t=>t===c?d:t))||[],$d({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:"swapWinnerLoser",drawDefinition:i,matchUp:n})}));const{stage:f,stageSequence:h}=r,g=i.structures.filter((({stage:t,stageSequence:e})=>t===f&&e>h)).map((({structureId:t})=>t)),{targetLinks:{loserTargetLink:I,winnerTargetLink:U}}=t.targetData,y=[I?.target.structureId,U?.target?.structureId].filter(Boolean);return i.structures.filter((({stage:t,structureId:e})=>t!==f&&y.includes(e))).forEach((({stage:t,stageSequence:e,structureId:n})=>{g.includes(n)||g.push(n),i.structures.filter((({stage:n,stageSequence:r})=>n===t&&r>e)).forEach((({structureId:t})=>{g.includes(t)||g.push(t)}))})),i.structures.filter((({structureId:t})=>g.includes(t))).forEach((t=>{const{positionAssignments:e}=cd({structure:t}),n=e?.find((({participantId:t})=>t===u)),r=e?.find((({participantId:t})=>t===p));n&&(n.participantId=p),r&&(r.participantId=u)})),HU({...t})}(t);const x=p&&!P||t.projectedWinningSide;Nf({activeDownstream:T,matchUpWinner:x,method:e,winningSide:p});const _=!T&&Cb(t)||x&&function(t){const{matchUp:e,winningSide:n,matchUpTieId:r,dualWinningSideChange:i}=t;return n===e.winningSide||r&&!i?Jb(t):ti({stack:"winningSideWithDownstreamDependencies",result:{error:$e},context:{winningSide:n,matchUp:e}})}(t)||(O||t.autoCalcDisabled)&&Jb(t)||{error:tr};return ti({result:_,stack:e})}function Jb(t){const{tournamentRecord:e,matchUp:n,event:r}=t,i=t.isCollectionMatchUp&&n.winningSide&&!t.winningSide&&!vf({score:t.score}),a=t.isCollectionMatchUp?t.matchUpStatus||i&&Hu||t.winningSide&&xu||Gu:t.matchUpStatus||xu,o=t.removeScore||[ku,zu].includes(a)&&![Gu,Cu].includes(a),s=HU({...t,matchUpStatus:a,removeWinningSide:i,removeScore:o});if(s.error)return s;if(t.isCollectionMatchUp){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:a}=t,o=ey({appliedPolicies:t.appliedPolicies,matchUpId:n,tournamentRecord:e,drawDefinition:i,matchUpsMap:a,event:r});if(o.error)return o;Object.assign(s,{tieMatchUpResult:o})}return s}function Zb({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r}){if(!e)return{error:ot};const{matchUp:i}=GU({drawDefinition:e,matchUpId:n,event:r});return i?.matchUpType!==a?{error:he}:Qb({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r})}function Xb({drawDefinition:t,event:e,matchUpId:n}){if(!t)return{error:ot};if(!n)return{error:de};const{matchUp:r}=GU({drawDefinition:t,event:e,matchUpId:n});return r?kc({name:Qc,element:r}):{error:le}}function tR(t){return function({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:n,drawDefinition:r,sideNumber:i,matchUpId:a,event:o}){const s="substituteParticipant";if(!r)return{error:ot};if(!a)return{error:de};if(!e||!t)return ti({result:{error:Xe},stack:s});const{matchUp:c}=GU({drawDefinition:r,matchUpId:a,event:o});if(!c)return{error:le};if(!c.collectionId)return ti({result:{error:he},stack:s});const u=hl({drawDefinition:r}),{matchUps:d}=cf({tournamentParticipants:n?.participants,inContext:!0,drawDefinition:r,matchUpsMap:u}),p=d?.find((t=>t.matchUpId===a)),l=d?.find((t=>t.matchUpId===p?.matchUpTieId)),m=l?.sides?.find((t=>t.participant.individualParticipants.some((({participantId:t})=>t===e))));if(!m||i&&m.sideNumber!==i)return{error:He};const f=m.participant?.individualParticipants?.map(Mu).filter((t=>t!==e));return f?.includes(t)?ub({newParticipantId:t,tieMatchUpId:a,existingParticipantId:e,substitution:!0,tournamentRecord:n,drawDefinition:r,event:o}):ti({result:{error:He},stack:s})}(t)}function eR({drawDefinition:t,matchUpId:e,event:n}){if(!t)return{error:ot};const{matchUp:r}=GU({drawDefinition:t,matchUpId:e,event:n});return _c({extension:{name:Zc,value:!0},element:r})}function nR(t){const e="setMatchUpFormat",n=cc(t,[{tournamentRecord:!0},{[Xs]:t=>Di({matchUpFormat:t}),[ec]:ne,matchUpFormat:!0}]);if(n.error)return ti({result:n,stack:e});const{tournamentRecord:r,drawDefinition:i,scheduledDates:a,stageSequences:o,matchUpFormat:s,structureId:c,eventType:u,matchUpId:d,eventId:p,stages:l,drawId:m,event:f,force:h}=t;if(a&&!Array.isArray(a))return ti({result:{error:Jn,scheduledDates:a},stack:e});if(u&&!H([oo,co],u))return ti({result:{error:qt},stack:e});let g=0;const I=t.structureIds||c&&[c].filter(Boolean)||[],U=t.eventIds||p&&[p].filter(Boolean)||[],y=t.drawIds||m&&[m].filter(Boolean)||[];if((c||I?.length)&&!i)return ti({result:{error:ot},stack:e});if(m&&d&&i){const t=Fw({tournamentRecord:r,drawDefinition:i,matchUpFormat:s,structureIds:I,structureId:c,matchUpId:d});if(t.error)return t;g+=1}const S=t=>{const n=[];for(const i of t.structures||[]){if(Array.isArray(l)&&!l.includes(i.stage)||Array.isArray(o)&&!o.includes(i.stageSequence)||I?.length&&!I.includes(i.structureId))continue;I?.length&&i.matchUpFormat!==s&&(i.matchUpFormat=s,n.push(i.structureId),g+=1);const c=((h||a)&&Jm({matchUpFilters:{matchUpStatuses:[Hu]},structure:i}).matchUps)??[],u=(a&&Jm({matchUpFilters:{matchUpStatuses:[Hu]},contextFilters:{scheduledDates:a},afterRecoveryTimes:!1,inContext:!0,structure:i}).matchUps)??[];if(c?.length){const n=u?u.map(Nu):c.map(Nu);for(const i of c)n.includes(i.matchUpId)&&(i.matchUpFormat=a?.length?s:void 0,$d({tournamentId:r?.tournamentId,eventId:f?.eventId,context:e,drawDefinition:t,matchUp:i}))}}return n.length||t.matchUpFormat===s||(t.matchUpFormat=s,g+=1),n};for(const t of r?.events||[])if(!(U?.length&&!U.includes(t.eventId)||u&&u!==t.eventType||u===po))if(Array.isArray(o)||Array.isArray(l)||I?.length||y?.length)for(const e of t.drawDefinitions||[]){if(Array.isArray(y)&&!y.includes(e.drawId))continue;Hd({structureIds:S(e),drawDefinition:e})}else t.matchUpFormat!==s&&(t.matchUpFormat=s,g+=1);return g?{...z,modificationsCount:g}:{...z,info:qn}}function rR({inheritance:t=!0,tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i}){if(!n)return{error:ot};const a=GU({drawDefinition:n,matchUpId:r})?.matchUp;if(!a?.tieMatchUps)return{error:he};const o=GU({inContext:!0,drawDefinition:n,matchUpId:r,event:i})?.matchUp;let s=0;return(a?.sides||[]).forEach((t=>{t.lineUp&&delete t.lineUp})),(o?.sides||[]).forEach((r=>{if(s+=1,!1===t){const t=o?.tieFormat,e=r.participantId;t&&e&&pg({drawDefinition:n,participantId:e,lineUp:[],tieFormat:t})}$d({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:i?.eventId,drawDefinition:n,matchUp:a})})),{...z,modificationsCount:s}}function iR(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i,setTBlast:a}=t;if(!i)return{sets:[]};const o=i.sets||[];let s=HS({winnerFirst:!1,matchUpFormat:e,matchUpStatus:n,setTBlast:a,sets:o}),c=HS({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:n,setTBlast:a,sets:o});const u=HS({matchUpFormat:e,matchUpStatus:n,winningSide:r,setTBlast:a,sets:o}),d=s===u?c:s;return r&&(s=1===r?u:d,c=2===r?u:d),{score:{sets:o,scoreStringSide1:s,scoreStringSide2:c}}}function aR(t){const e=cc(t,[{[Cs]:!0,[Is]:!0}]);if(e.error)return e;const n=tp(t);if(!t.drawDefinition){const e=t.tournamentRecord??(t.tournamentId&&n[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=e);const r=Gm({eventId:t.eventId,drawId:t.drawId,tournamentRecord:e});if(r.error)return r;r.drawDefinition&&(t.drawDefinition=r.drawDefinition),t.event=r.event}const{disableScoreValidation:r,policyDefinitions:i,tournamentRecord:a,disableAutoCalc:o,enableAutoCalc:s,drawDefinition:c,matchUpId:u,schedule:d,event:p,notes:l}=t,m=t.matchUpFormat||t.outcome?.matchUpFormat,{policy:f}=Bp({policyType:Nc,tournamentRecord:a,event:p}),h=void 0!==t.allowChangePropagation&&t.allowChangePropagation||void 0!==f?.allowChangePropagation&&f.allowChangePropagation||void 0,{outcome:g,setTBlast:I}=t;if(g?.winningSide&&![1,2].includes(g.winningSide))return{error:Le};if(m){const t=Fw({tournamentRecord:a,drawDefinition:c,matchUpFormat:m,matchUpId:u,event:p});if(t.error)return t}if(g?.score?.sets&&!g.score.scoreStringSide1){const{score:t}=iR({...g,setTBlast:I});g.score=t,g.score.sets=g.score.sets.filter((t=>t.side1Score||t.side2Score||t.side1TiebreakScore||t.side2TiebreakScore))}return Qb({matchUpStatusCodes:g?.matchUpStatusCodes,matchUpStatus:g?.matchUpStatus,winningSide:g?.winningSide,allowChangePropagation:h,disableScoreValidation:r,score:g?.score,tournamentRecords:n,policyDefinitions:i,tournamentRecord:a,disableAutoCalc:o,enableAutoCalc:s,drawDefinition:c,matchUpFormat:m,matchUpId:u,schedule:d,event:p,notes:l})}function oR(t){if(!t?.outcomes)return{error:be};if(!Array.isArray(t.outcomes))return{error:be,info:{outcomes:t.outcomes}};const e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},n=t.outcomes??[],r=n.reduce(((t,e)=>t.includes(e.tournamentId)?t:t.concat(e.tournamentId)),[]);for(const t of r){const r=e[t];if(!r)return{error:nt};const i=n.filter((e=>e.tournamentId===t));if(i.length){const t=sR({outcomes:i,tournamentRecord:r});if(t.error)return t}}return{...z}}function sR(t){const{tournamentRecords:e,tournamentRecord:n,outcomes:r,policyDefinitions:i}=t,a={};r.forEach((t=>{const{eventId:e}=t;a[e]||(a[e]=[]),a[e].push(t)}));for(const t of Object.keys(a)){const{event:r}=Gm({tournamentRecord:n,eventId:t});for(const o of a[t]){const{drawId:t}=o,a=r?.drawDefinitions?.find((e=>e.drawId===t));if(a&&t){const{matchUpFormat:s,matchUpId:c}=o,u=aR({schedule:o?.schedule,tournamentRecords:e,policyDefinitions:i,tournamentRecord:n,drawDefinition:a,matchUpFormat:s,matchUpId:c,outcome:o,drawId:t,event:r});if(u.error)return u}}}return{...z}}function cR(t){return function({drawDefinition:t,matchUpId:e,outcome:n,matchUp:r}){if(!r&&!t)return{error:ot};if(!n)return{error:be,info:"missing outcome"};if(!r&&!e)return{error:fe};if(!r){const n=GU({drawDefinition:t,matchUpId:e});if(n.error)return n;r=n.matchUp}return"object"==typeof n&&n.score?.scoreStringSide1&&n.score?.scoreStringSide2?_c({element:r,extension:{name:Qc,value:n}}):{error:Jn}}(t)}function uR(t){const e="resetTieFormat",{drawDefinition:n,event:r,uuids:i}=t,a=cc(t,[{[hs]:!0,[Cs]:!0}],e);if(a.error)return a;const o=yD(t,[{[Hs]:Gs}]);if(o[$s])return o;const s=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=o?.matchUp??{};if(!c?.tieMatchUps)return ti({result:{error:he},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...z};const d=fl({structure:u,drawDefinition:n,event:r})?.tieFormat;if(!d)return ti({result:{error:rr},info:"No inherited tieFormat",stack:e});const p=[],l=[],m=[],f=[];for(const t of d.collectionDefinitions){const{matchUpCount:e,collectionId:n}=t;l.push(n);const r=(c.tieMatchUps||[]).filter((t=>t.collectionId===n));if(r.length>e)r.sort(((t,e)=>(t.matchUpStatus===Hu?1:0)-(e.matchUpStatus===Hu?1:0))),m.push(...r.slice(0,e)),p.push(...r.slice(3).map(Nu));else if(m.push(...r),r.length<e){const n=BI({collectionDefinition:t,matchUpsLimit:e-r.length,matchUp:c,uuids:i});f.push(...n)}}for(const t of c?.tieMatchUps||[])t.collectionId&&!l.includes(t.collectionId)&&p.push(t.matchUpId);return f.length&&(m.push(...f),Gd({eventId:r?.eventId,matchUps:f,drawDefinition:n,tournamentId:s})),p.length&&qd({matchUpIds:p,eventId:r?.eventId,drawDefinition:n,tournamentId:s}),c&&(c.tieMatchUps=m,c.tieFormatId=void 0,c.tieFormat=void 0,$d({structureId:u?.structureId,eventId:r?.eventId,context:e,drawDefinition:n,tournamentId:s,matchUp:c})),{...z,newMatchUps:f,deletedMatchUpIds:p}}function dR(t){const{tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i}=t,a="resetScorecard";if(!n)return ti({result:{error:ot},stack:a});if(!r)return ti({result:{error:de},stack:a});if(!j(r))return ti({result:{error:Jn,matchUpId:r},stack:a});const o=hl({drawDefinition:n}),{matchUps:s}=cf({nextMatchUps:!0,inContext:!0,drawDefinition:n,matchUpsMap:o}),c=o.drawMatchUps.find((t=>t.matchUpId===r)),u=s?.find((t=>t.matchUpId===r));if(!c||!s)return{error:le};if(c.matchUpType!==lo)return{error:he};const d=rf({inContextDrawMatchUps:s,drawDefinition:n,matchUpId:r}),p=u?.structureId,{structure:l}=ad({drawDefinition:n,structureId:p});Object.assign(t,{inContextDrawMatchUps:s,inContextMatchUp:u,matchUpsMap:o,targetData:d,structure:l,matchUp:c});if(Oy(t))return{error:$e};if(c.tieMatchUps?.length)for(const t of c.tieMatchUps){const o=Qb({matchUpId:t.matchUpId,matchUpTieId:r,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:n,event:i});if(o.error)return ti({result:o,stack:a})}const m=Np({tournamentRecord:e,drawDefinition:n,event:i})?.appliedPolicies,f=ey({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:m,drawDefinition:n,matchUpsMap:o,matchUpId:r});if(f.error)return ti({result:f,stack:a});if(t.tiebreakReset&&!f.tieFormatRemoved){const t=fl({drawDefinition:n,structure:l,event:i})?.tieFormat;if(c.tieFormat&&t){const{matchUpCountDifference:a,descendantDifferences:o,ancestorDifferences:s,valueDifference:u}=lP({descendant:c.tieFormat,ancestor:t});if(1===o.collectionIds.length&&!s.collectionIds.length&&!s.groupsCount&&1===a&&1===u){const t=uR({tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i});if(t.error)return t}}}return{...z}}function pR(t){const e=cc(t,[{[Is]:!0,[Ws]:!0},{[ic]:{[Rs]:!1,roundNumbers:!1},[tc]:"At least one must be provided",[nc]:Zs}]);if(e.error)return e;const n=vy(t);if(n.error)return n;const{matchUpIds:r}=n,i=um(lo)(t.event.eventType),{tournamentRecord:a,drawDefinition:o,event:s}=t;for(const e of r){if(i){const n=dR({tiebreakReset:!0,tournamentRecord:a,drawDefinition:o,matchUpId:e,event:s});if(n.error)return n;if(t.removeAssignments){if(rR({inheritance:!1,drawDefinition:o,matchUpId:e}).error)return n}}const n=Qb({winningSide:void 0,removeScore:!0,tournamentRecord:a,drawDefinition:o,matchUpId:e,event:s});if(n.error)return n;if(t.removeAssignments){const n=gb({...t,matchUpId:e});if(n.error)return n}}return{...z}}function lR(t){return function({tournamentRecord:t,drawDefinition:e,finishingOrder:n}){if(!e)return{error:ot};const r="setOrderOfFinish";if(!Array.isArray(n))return ti({info:ug("finishingOrder"),result:{error:Jn},stack:r});const{completedMatchUps:i,matchUpsMap:a}=uf({inContext:!0,drawDefinition:e}),o=i?.map(Nu)??[],s=n.map(Nu),{matchUpTypes:c,roundNumbers:u,structureIds:d,matchUpTieIds:p}=(i??[]).filter((({matchUpId:t})=>s.includes(t))).reduce(((t,e)=>{const{matchUpTieId:n,matchUpType:r,roundNumber:i,structureId:a}=e;return t.matchUpTypes.includes(r)||t.matchUpTypes.push(r),t.roundNumbers.includes(i)||t.roundNumbers.push(i),t.structureIds.includes(a)||t.structureIds.push(a),t.matchUpTieIds.includes(n)||t.matchUpTieIds.push(n),t}),{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||p.length>1||u.length>1||d.length>1)return ti({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:Jn},stack:r});let l,m;const f={},h=[],g=[],I=n.every((({orderOfFinish:t,matchUpId:e})=>(h.push(e),t&&g.push(t),f[e]=t,l=o.includes(e),m=void 0===t||y(t)&&Math.floor(t)>0,l&&m)));if(!I)return ti({result:{error:l?Jn:ie},info:(l?!m&&"orderOfFinish must be integer > 0 or undefined":"matchUps must be completed")||void 0,stack:r});const U=i?.filter((t=>t.structureId===d[0]&&t.roundNumber===u[0]&&t.matchUpType===c[0]&&t.matchUpTieId===p[0]&&!h.includes(t.matchUpId)));for(const t of U??[]){const{orderOfFinish:e}=t||{};if(e){if(!y(e))return ti({context:{orderOfFinish:e,matchUp:t},result:{error:Jn},stack:r});g.push(e)}}if(M(g).length!==g.length||Math.max(...g)>g.length)return ti({info:"Values not unique or greater than expected number of values",result:{error:Jn},stack:r});if(d.length){const n=Xm({matchUpFilters:{matchUpIds:s},structureId:d[0],drawDefinition:e,matchUpsMap:a});if(n.error)return ti({result:n,stack:r});n.completedMatchUps?.forEach((n=>{n.orderOfFinish=f[n.matchUpId],$d({tournamentId:t.tournamentId,context:"setOrderOfFinish",drawDefinition:e,matchUp:n})}))}return{...z}}(t)}function mR(t){const{tournamentRecord:e,drawDefinition:r,matchUpId:a,lineUps:s,event:c}=t,u="applyLineUps",d=cc(t,[{[hs]:!0,[Is]:!0,[Cs]:!0},{lineUps:!0,[nc]:Zs}],u);if(d.error)return d;const p=e.participants||[];let l=GU({tournamentParticipants:p,inContext:!0,drawDefinition:r,matchUpId:a});if(l.error)return l;if(!l.matchUp)return{error:le};const{matchUp:m,structure:f}=l,{drawPositions:h,matchUpType:g}=m;if(g!==o)return{error:he};if(!h?.length)return{error:gt};const I=fl({matchUp:m,drawDefinition:r,structure:f,event:c})?.tieFormat,U={};for(const t of s){if(!Array.isArray(t))return{error:Jn,lineUp:t};const r={},a=[];for(const e of t){if("object"!=typeof e)return{error:Jn,lineUpAssignment:e};const{participantId:t,collectionAssignments:o=[]}=e;if(!Array.isArray(o))return{error:Jn,collectionAssignments:o};const s=p.find((e=>e.participantId===t));if(!s)return{error:en};if(s.participantType!==ap)return{error:Ke};const c=m.sides?.find((e=>e.participant?.individualParticipantIds?.includes(t)))?.sideNumber;c&&a.push(c);for(const e of o){if("object"!=typeof e)return{error:Jn,collectionAssignment:e};const{collectionId:a,collectionPosition:o}=e,s=I?.collectionDefinitions?.find((t=>t.collectionId===a));if(!s)return{error:Jn,collectionId:a};const c=`${a}-${o}`;r[c]||(r[c]=[]);const u=r[c].length;if(um(n)(s.matchUpType)&&u||s.matchUpType===i&&u>1)return{info:"Excessive collectionPosition assignments",error:Jn};r[c].push(t)}}const o=Object.values(r);for(const t of o)if(2===t.length){const{participant:n}=Wm({tournamentParticipants:p,participantIds:t});if(!n){const n=WD({participant:{participantType:sp,participantRole:Ih,individualParticipantIds:t},pairOverride:!0,tournamentRecord:e});if(n.error)return n}}const s=T(a),c=((s[1]||0)>(s[2]||0)?1:(s[2]||0)>(s[1]||0)&&2)||void 0,u=Object.keys(U).map((t=>parseInt(t)));c&&!u.includes(c)&&(U[c]=t)}if(!Object.keys(U).length)return{error:nr};if(l=GU({drawDefinition:r,matchUpId:a}),l.error)return l;if(!l.matchUp)return{error:le};const{matchUp:y}=l;y.sides||(y.sides=[]);for(const t of[1,2]){const e=y.sides.find((e=>e.sideNumber===t)),n=U[t];n&&(e?e.lineUp=n:y.sides.push({lineUp:n,sideNumber:t}))}return $d({tournamentId:e?.tournamentId,context:u,drawDefinition:r,matchUp:y}),{...z}}var fR={__proto__:null,allCompetitionMatchUps:lf,allDrawMatchUps:ff,allEventMatchUps:df,allTournamentMatchUps:pf,analyzeMatchUp:bD,applyLineUps:mR,assignMatchUpSideParticipant:rb,assignTieMatchUpParticipantId:mb,bulkMatchUpStatusUpdate:oR,calculateWinCriteria:gD,checkInParticipant:ob,checkMatchUpIsComplete:Zm,checkOutParticipant:ab,competitionScheduleMatchUps:pD,disableTieAutoCalc:eR,drawMatchUps:RD,enableTieAutoCalc:Zb,eventMatchUps:cD,filterMatchUps:Qm,findMatchUp:fP,getAllDrawMatchUps:cf,getAllStructureMatchUps:Jm,getCheckedInParticipantIds:cm,getCompetitionMatchUps:dD,getEventMatchUpFormatTiming:nD,getHomeParticipantId:ID,getMatchUpCompetitiveProfile:El,getMatchUpContextIds:UD,getMatchUpDailyLimits:lD,getMatchUpDailyLimitsUpdate:iD,getMatchUpDependencies:Sf,getMatchUpFormat:vD,getMatchUpFormatTiming:Tm,getMatchUpFormatTimingUpdate:JP,getMatchUpScheduleDetails:qm,getMatchUpType:zm,getMatchUpsStats:wD,getModifiedMatchUpFormatTiming:rD,getParticipantResults:DU,getPredictiveAccuracy:mD,getRoundMatchUps:Sl,getRounds:TD,isValidMatchUpFormat:Di,matchUpActions:oS,mutate:{__proto__:null,applyLineUps:mR,assignMatchUpSideParticipant:rb,assignTieMatchUpParticipantId:mb,bulkMatchUpStatusUpdate:oR,checkInParticipant:ob,checkOutParticipant:ab,disableTieAutoCalc:eR,enableTieAutoCalc:Zb,findMatchUp:fP,removeDelegatedOutcome:Xb,removeMatchUpSideParticipant:gb,removeTieMatchUpParticipantId:hb,replaceTieMatchUpParticipantId:ub,resetAdHocMatchUps:pR,resetMatchUpLineUps:rR,resetScorecard:dR,resetTieFormat:uR,setDelegatedOutcome:cR,setMatchUpFormat:nR,setMatchUpStatus:aR,setOrderOfFinish:lR,substituteParticipant:tR,toggleParticipantCheckInState:sb,updateTieMatchUpScore:ey},participantScheduledMatchUps:oD,query:{__proto__:null,allCompetitionMatchUps:lf,allDrawMatchUps:ff,allEventMatchUps:df,allTournamentMatchUps:pf,analyzeMatchUp:bD,calculateWinCriteria:gD,checkMatchUpIsComplete:Zm,competitionScheduleMatchUps:pD,drawMatchUps:RD,eventMatchUps:cD,filterMatchUps:Qm,getAllDrawMatchUps:cf,getAllStructureMatchUps:Jm,getCheckedInParticipantIds:cm,getCompetitionMatchUps:dD,getEventMatchUpFormatTiming:nD,getHomeParticipantId:ID,getMatchUpCompetitiveProfile:El,getMatchUpContextIds:UD,getMatchUpDailyLimits:lD,getMatchUpDailyLimitsUpdate:iD,getMatchUpDependencies:Sf,getMatchUpFormat:vD,getMatchUpFormatTiming:Tm,getMatchUpFormatTimingUpdate:JP,getMatchUpScheduleDetails:qm,getMatchUpType:zm,getMatchUpsStats:wD,getModifiedMatchUpFormatTiming:rD,getParticipantResults:DU,getPredictiveAccuracy:mD,getRoundMatchUps:Sl,getRounds:TD,isValidMatchUpFormat:Di,matchUpActions:oS,participantScheduledMatchUps:oD,tallyParticipantResults:LU,tournamentMatchUps:uD,validMatchUp:Ul,validMatchUps:yl},removeDelegatedOutcome:Xb,removeMatchUpSideParticipant:gb,removeTieMatchUpParticipantId:hb,replaceTieMatchUpParticipantId:ub,resetAdHocMatchUps:pR,resetMatchUpLineUps:rR,resetScorecard:dR,resetTieFormat:uR,setDelegatedOutcome:cR,setMatchUpFormat:nR,setMatchUpStatus:aR,setOrderOfFinish:lR,substituteParticipant:tR,tallyParticipantResults:LU,toggleParticipantCheckInState:sb,tournamentMatchUps:uD,updateTieMatchUpScore:ey,validMatchUp:Ul,validMatchUps:yl};function hR(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,scoreString:i,setTBlast:a}=t;if(!i)return{outcome:{...WU,winningSide:r,matchUpStatus:n}};if(r&&![1,2,void 0].includes(r))return{error:Jn,winningSide:r};const o=i&&ww({scoreString:i}),s={},c=HS({sets:o,matchUpFormat:e,setTBlast:a}),u=HS({sets:o,reversed:!0,matchUpFormat:e,setTBlast:a});return 2===r?(s.scoreStringSide1=u,s.scoreStringSide2=c):(s.scoreStringSide1=c,s.scoreStringSide2=u),s.sets=ww({scoreString:s.scoreStringSide1}),Xr({outcome:{matchUpStatus:n,winningSide:r,score:s}})}function gR({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:n,matchUp:r}){const i=(e?.[r.matchUpId]?.matchUpIds||[]).filter((t=>n.includes(t))),a=i.filter((e=>!t[e]));return{dependenciesScheduled:!a?.length,remainingDependencies:a}}function IR({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function UR({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:n,averageMatchUpMinutes:r=0,matchUpNotBeforeTimes:i,matchUpDependencies:a,recoveryMinutes:o=0,scheduleTime:s,matchUp:c}){const u=qi(c?.schedule?.endTime),p=u?Zi(u,d(o)):Zi(s,d(r)+d(o)),l=n&&(u?Zi(qi(u),n):Zi(s,d(r)+d(n))),m=a?.[c.matchUpId]?.participantIds||[],f=(c.roundPosition&&t[c.matchUpId]||[]).flat();m.forEach((t=>{IR({individualParticipantProfiles:e,participantId:t});const n=e[t].priorMatchUpType!==c.matchUpType&&l||p;f.includes(t)?function({individualParticipantProfiles:t,recoveryValue:e,participantId:n,scheduleTime:r,drawId:i}){t[n].potentialRecovery[i]||(t[n].potentialRecovery[i]=[]),t[n].potentialRecovery[i].push(e),t[n].potentialBookings[i]||(t[n].potentialBookings[i]=[]),t[n].potentialBookings[i].push({timeAfterRecovery:e,scheduleTime:r})}({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:n,participantId:t,scheduleTime:s}):(e[t].timeAfterRecovery=n,e[t].bookings.push({scheduleTime:s,timeAfterRecovery:n}))})),AP({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,timeAfterRecovery:p,matchUp:c})}function yR({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:n,matchUpId:r,details:i}){let a;const o=i.minutesMap?.[r]?.recoveryMinutes,s=i.minutesMap?.[r]?.averageMinutes,c=Zi(n,(s||0)+(o||0)),u=e?.[r]?.dependentMatchUpIds||[];if(u.length){const e=u.reduce(((e,n)=>{const r=t[n];if(!r)return e;const i={scheduleTime:r,matchUpId:n};return r&&!e.matchUpId||ji(r)<ji(e.scheduleTime)?i:e}),{});e.scheduleTime&&ji(c)>ji(e.scheduleTime)&&(a=e)}return{scheduledDependent:a}}const SR="DO_NOT_SCHEDULE",vR={DO_NOT_SCHEDULE:SR};function wR({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:n=!0,personRequests:r,scheduleTime:a,scheduleDate:o,matchUp:s}){const c=function(t){const{sides:e,matchUpType:n}=t||{};return(e||[]).map((t=>n===i&&(t?.participant?.individualParticipants||[])||t?.participant&&[t.participant]||[])).flat()}(s).map((({person:t})=>t?.personId));if(n){const t=(s?.potentialParticipants||[]).flat().map((({person:t})=>t?.personId));c.push(...t)}const u=c.map((t=>r[t]?.map((e=>({...e,personId:t}))))).filter(Boolean).flat().filter((t=>t.requestType===SR&&ea(o,t.date))),d=[],p=s?.matchUpId,l=Qi(qi(a),$i(o)),m=qi(Xi(l,t).toISOString());for(const t of u){const{requestId:n,startTime:r,endTime:i}=t;(a>r&&a<i||m>r&&m<i)&&(d.push({matchUpId:p,request:t,scheduleTime:a}),e[n]?(e[n].scheduleTimes.includes(a)||e[n].scheduleTimes.push(a),e[n].matchUpIds.includes(p)||e[n].matchUpIds.push(p)):e[n]={request:t,scheduleTimes:[a],matchUpIds:[p]})}return{conflicts:d}}function PR({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:n,value:r}){const{matchUpType:i}=n,{individualParticipantIds:a}=Xd(n),o=(t[n.matchUpId]||[]).filter((t=>!k(t,a))).flat();[...a,...o].forEach((t=>{if(IR({individualParticipantProfiles:e,participantId:t}),!e[t].potentialCounted[n.drawId]){const a=e[t].counters;a[i]?a[i]+=r:r>0&&(a[i]=r),a[hm]?a[hm]+=r:r>0&&(a[hm]=r),o.includes(t)&&(e[t].potentialCounted[n.drawId]=!0)}}))}function DR({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:n,greatestAverageMinutes:r,dateScheduledMatchUps:i,matchUpNotBeforeTimes:a,matchUpScheduleTimes:o,matchUpDependencies:s,clearScheduleDates:c,scheduleDate:u,minutesMap:d,matchUps:p}){const l=[];n||(i=p?.filter((t=>{const e=t.schedule||{},n=t.matchUpStatus===Fu;return n&&l.push({tournamentId:t.tournamentId,matchUpId:t.matchUpId}),!n&&aD({schedule:e})&&(!u||t.schedule.scheduledDate===u)})),n=i.map(Nu));const m=Array.isArray(c)?c.includes(u):c,f=m?[]:p.filter((({matchUpId:t})=>n.includes(t)));for(const n of f){PR({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:n});const i=n.schedule?.scheduledTime;if(i){o[n.matchUpId]=i;const c=d?.[n.matchUpId]?.recoveryMinutes;UR({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:a,matchUpDependencies:s,averageMatchUpMinutes:r,recoveryMinutes:c,scheduleTime:i,matchUp:n})}}return{dateScheduledMatchUpIds:n,byeScheduledMatchUpDetails:l,dateScheduledMatchUps:i,clearDate:m}}function TR({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:n,tournamentRecords:r,venueIds:i=[],periodLength:a,scheduleDate:o,matchUps:s}){if("object"!=typeof r)return{error:et};if(!yl(s)&&!Array.isArray(n))return{error:me};a=a??QT({recoveryMinutes:t,averageMatchUpMinutes:e});const c=Object.assign({},...Object.values(r).map((t=>(t.events??[]).map((e=>{const{scheduleTiming:n}=Vp({tournamentRecord:t,event:e});return{[e.eventId]:{event:e,scheduleTiming:n}}})))).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};n||(n=s?.filter((t=>{const e=t.schedule;return aD({schedule:e})&&(!o||t.schedule.scheduledDate===o)})));const d=n?.filter((t=>(!i.length||i.includes(t.schedule.venueId))&&t.matchUpStatus!==Fu)),p=d?.map((({eventId:t,schedule:e,matchUpFormat:n})=>{const{event:r,scheduleTiming:i}=c[t],o=r?.eventType,s={...i,defaultTiming:u,matchUpFormat:n},{averageMinutes:d,recoveryMinutes:p}=bm({timingDetails:s,eventType:o}),{courtId:l,venueId:m}=e,f=qi(e.scheduledTime),h=Zi(f,d);return{recoveryMinutes:p,averageMinutes:d,periodLength:a,startTime:f,courtId:l,endTime:h,venueId:m}})).filter(Boolean);return{bookings:p,relevantMatchUps:d,dateScheduledMatchUps:n}}function bR({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:n,averageMatchUpMinutes:r,clearScheduleDates:i,tournamentRecords:a,tournamentRecord:o,periodLength:s,scheduleDate:c,startTime:u,venueIds:d,matchUps:p,endTime:l}){if(o&&!a&&(a={[o.tournamentId]:o}),"object"!=typeof a||!Object.keys(a).length)return{error:et};s=s??QT({recoveryMinutes:n,averageMatchUpMinutes:r});const{courts:m,venues:f}=vP({dates:[c],ignoreDisabled:!0,tournamentRecords:a}),h=m?.filter((t=>!d||d.includes(t.venueId)))??[];u=u??ZT({courts:h,scheduleDate:c,startTime:!0}),l=l??ZT({courts:h,scheduleDate:c,endTime:!0});const{bookings:g,dateScheduledMatchUps:I}=TR({defaultRecoveryMinutes:n,averageMatchUpMinutes:r,tournamentRecords:a,scheduleDate:c,periodLength:s,venueIds:d,matchUps:p}),U={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:r,clearScheduleDates:i,date:c,periodLength:s,startTime:u,bookings:g,endTime:l,courts:h},{scheduleTimes:y}=XT(U),S=1===d?.length&&d[0]||1===f?.length&&f[0].venueId||void 0,v=I?.map(If("matchUpId"));return{dateScheduledMatchUpIds:v,dateScheduledMatchUps:I,scheduleTimes:y,venueId:S}}function RR({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:n}){const r=[];let i,a,o,s,c=[];for(const r of t.filter(Boolean))s||(s=r.hash),(r.hash===s||n)&&(c=c.concat(r.matchUpIds)),r.hash,o=e,a=r.recoveryMinutes,i=r.roundPeriodLength;return c.length&&r.push({matchUpIds:c,roundPeriodLength:i,recoveryMinutes:a,averageMinutes:o}),{groupedRounds:r}}function MR({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:n,containedStructureIds:r,matchUpNotBeforeTimes:i,matchUpScheduleTimes:a,matchUpDependencies:o,clearScheduleDates:s,tournamentRecords:c,periodLength:u,scheduleDate:d,useGarman:p,matchUps:l,courts:m,venues:f}){const h={},g=[],I=[],U=[];for(const y of f){const{rounds:f=[],venueId:S}=y,{scheduledRoundsDetails:v,greatestAverageMinutes:w,orderedMatchUpIds:P,minutesMap:D}=OP({scheduleCompletedMatchUps:n,containedStructureIds:r,tournamentRecords:c,periodLength:u,matchUps:l,rounds:f});U.push(...P??[]);const{groupedRounds:T}=RR({scheduledRoundsDetails:v,greatestAverageMinutes:w,garmanSinglePass:!0});let b,R=[];p&&({scheduleTimes:R,dateScheduledMatchUpIds:b}=bR({averageMatchUpMinutes:T[0]?.averageMinutes,scheduleDate:$i(d),venueIds:[y.venueId],clearScheduleDates:s,tournamentRecords:c,periodLength:u,matchUps:l}));const M=DR({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:b,greatestAverageMinutes:w,matchUpNotBeforeTimes:i,matchUpScheduleTimes:a,matchUpDependencies:o,clearScheduleDates:s,scheduleDate:d,minutesMap:D,matchUps:l});({dateScheduledMatchUpIds:b}=M);const N=M,{byeScheduledMatchUpDetails:A,clearDate:E}=M;A?.length&&I.push(...A);const{matchUpsToSchedule:C,matchUpMap:O}=EP({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:n,dateScheduledMatchUpIds:b,matchUpNotBeforeTimes:i,matchUpScheduleTimes:a,orderedMatchUpIds:P,clearDate:E,matchUps:l}),F=m.filter((t=>t.venueId===S));h[S]={previousRemainingScheduleTimes:[],courtsCount:F.length,greatestAverageMinutes:w,scheduledRoundsDetails:v,dateScheduledMatchUps:N,matchUpsToSchedule:C,scheduleTimes:R,groupedRounds:T,venueCourts:F,minutesMap:D,matchUpMap:O},s||g.push(...b)}return{allDateScheduledByeMatchUpDetails:I,allDateScheduledMatchUpIds:g,venueScheduledRoundDetails:h,allDateMatchUpIds:U}}function NR({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:n,scheduleTime:r,matchUp:i,details:a}){const o=(n?.[i.matchUpId]?.participantIds||[]).flat(),s=a?.minutesMap?.[i.matchUpId]?.averageMinutes||0,c=a?.minutesMap?.[i.matchUpId]?.recoveryMinutes||0,u=o.every((e=>{IR({individualParticipantProfiles:t,participantId:e});const n=t[e];if(!n.timeAfterRecovery)return!0;const a=qi(i?.schedule?.endTime),o=a?Zi(a,d(c)):Zi(r,d(s)+d(c));return!!![...Object.keys(n.potentialBookings).filter((t=>t!==i.drawId)).map((t=>n.potentialBookings[t])).flat(),...n.bookings].find((t=>function(t,e){const n=ji(t.scheduleTime),r=ji(t.timeAfterRecovery),i=ji(e.scheduleTime),a=ji(e.timeAfterRecovery),o=n>i&&n<a,s=i>n&&i<r,c=r>i&&r<a,u=a>n&&a<r;return Xr({hasOverlap:n===i||r===a||o||c||s||u,startAisContained:o,endAisContained:c,startBisContained:s,endBisContained:u},!0)}({scheduleTime:r,timeAfterRecovery:o},t).hasOverlap))})),p=e[i.matchUpId],l=p?Ji(Qi(p),Qi(r),!1):0;return{enoughTime:u&&l>=0}}function AR({autoSchedulingAudit:t,tournamentRecords:e}){Or({topic:gd,payload:t});const n=t=>{if(!t)return 0;return Object.values(t).reduce(((t,e)=>t+e.length||0),0)},r=(t?.schedulingProfile||[]).reduce(((t,e)=>t+e.venues.reduce(((t,e)=>t+e.rounds.length),0)),0),i={scheduledDatesCount:t.scheduledDates?.length,noTimeMatchUpIdsCount:n(t?.noTimeMatchUpIds),scheduledMatchUpIdsCount:n(t?.scheduledMatchUpIds),overLimitMatchUpIdsCount:n(t?.overLimitMatchUpIds),requestConflictsCount:n(t?.requestConflicts),profileRoundsCount:r},a={itemType:nT,itemValue:i};for(const t of Object.values(e)){const e=t.tournamentId;Br(gd)?Or({payload:{type:nT,tournamentId:e,detail:i},topic:gd}):sy({tournamentRecord:t,timeItem:a})}}function ER({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUpDailyLimits:n={},matchUp:r}){const{enteredIndividualParticipantIds:i}=Xd(r),{matchUpId:a,matchUpType:o}=r,s=(r.roundPosition&&t[a]||[]).flat(),c=w(i.concat(...s));c.forEach((t=>{IR({individualParticipantProfiles:e,participantId:t})}));return{participantIdsAtLimit:c.filter((t=>{const r=e[t];if(r)return[o,hm].find((t=>{const e=r.counters?.[t]||0,i=n[t]||0;return e&&i&&e>=i}))})),relevantParticipantIds:c}}function CR({scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:e=!1,errorOnAnachronism:n=!1,checkChronology:r=!0,matchUpDependencies:i,removePriorValues:a,tournamentRecords:o,tournamentRecord:s,matchUpDetails:c,matchUpIds:u,schedule:d}){if(!s)return{error:nt};if(!(c||u&&Array.isArray(u)))return{error:pe};if(!(c||d&&"object"==typeof d))return{error:Vn};let p;const l=[];let m=0;if(r&&!i){const t=Sf({tournamentRecords:o,tournamentRecord:s});i=t.matchUpDependencies,p=t.matchUps}p||(p=pf({tournamentRecord:s})?.matchUps??[]);const f=p.reduce(((n,r)=>{const{matchUpId:i,drawId:a,matchUpStatus:o}=r;return!e&&o===Fu||!t&&Xu.includes(o)||(n[a]?n[a].push(i):n[a]=[i]),n}),{}),h=c?.map((t=>t.matchUpId));for(const t of Object.keys(f)){const{drawDefinition:e}=Ey({tournamentRecord:s,drawId:t});if(!e)continue;const g=f[t].filter((t=>u?.includes(t)??h?.includes(t))),I=ff({inContext:!1,drawDefinition:e}).matchUps;for(const t of g){const u=qb({schedule:c?.find((e=>e.matchUpId===t))?.schedule||d,matchUpDependencies:i,errorOnAnachronism:n,removePriorValues:a,inContextMatchUps:p,tournamentRecords:o,tournamentRecord:s,checkChronology:r,drawDefinition:e,drawMatchUps:I,matchUpId:t});if(u?.warnings?.length&&l.push(...u.warnings),u?.success&&(m+=1),u.error)return u}}return l.length?{...z,scheduled:m,warnings:l}:{...z,scheduled:m}}function OR(t){const{scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:n=!1,errorOnAnachronism:r,matchUpContextIds:i,removePriorValues:a,tournamentRecords:o,checkChronology:s,matchUpDetails:c,schedule:u}=t;if(t.matchUpIds&&!i)return CR(t);const d=cc(t,[{[ms]:!0},{[ic]:{matchUpContextIds:!1,matchUpDetails:!1},[ec]:Jn,[nc]:Zs}]);if(d.error)return d;if((!c||i)&&!u)return{error:be,info:"schedule is required"};const p=[];let l=0;const{matchUpDependencies:m}=Sf({tournamentRecords:o});for(const t of Object.values(o)){const{tournamentId:d}=t,f=i?.filter((t=>t.tournamentId===d)).map(Nu),h=c?.filter((t=>t?.tournamentId===d));if(f?.length||h?.length){const i=CR({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:n,matchUpDependencies:m,errorOnAnachronism:r,removePriorValues:a,tournamentRecords:o,tournamentRecord:t,checkChronology:s,matchUpIds:f,schedule:u});if(i.warnings?.length&&p.push(...i.warnings),i.scheduled&&(l+=i.scheduled),i.error)return i}}return p.length?{...z,scheduled:l,warnings:p}:{...z,scheduled:l}}function FR({averageMinutes:t,startTime:e,endTime:n,court:r,date:i}){if(!Array.isArray(r.dateAvailability))return{error:be,stack:"getEarliestCourtTime"};const a=ZT({scheduleDate:i,courts:[r],startTime:!0}),o=ZT({scheduleDate:i,courts:[r],endTime:!0});e=e||a,n=n||o;const s=HT({court:r,date:i}),{timeSlots:c}=zT({courtDate:s}),u=Qi(e),d=Qi(n),p=c?.reduce(((e,n)=>{const r=Qi(n.startTime),i=Qi(n.endTime);if(r>d||i<u)return e;const a=u>r?u:r;if(Ji(a,i)>=t){const t=qi(a.toISOString());(!e||t<e)&&(e=t)}return e}),void 0);return{earliestCourtTime:p,courtStartTime:a,courtEndTime:o}}function kR(t){const{scheduleAttributes:e=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:n=Xu,scheduledDates:r,venueIds:i}=t,a=tp(t),o=G(a)?Object.values(a).map((({tournamentId:t})=>t)).filter(Boolean):[];if(!o?.length)return{error:et};let s=0;for(const t of o){const o=xR({ignoreMatchUpStatuses:n,scheduleAttributes:e,tournamentRecord:a[t],scheduledDates:r,venueIds:i});if(o.error)return o;s+=o.clearedScheduleCount??0}return{...z,clearedScheduleCount:s}}function xR({scheduleAttributes:t=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:e=Xu,tournamentRecord:n,scheduledDates:r,venueIds:i=[]}){if("object"!=typeof n)return{error:nt};if(!Array.isArray(e)||!Array.isArray(i))return{error:Jn};i.length&&t.push("venueId");const a=pf({matchUpFilters:{scheduledDates:r},tournamentRecord:n}).matchUps??[],o={};a.forEach((({matchUpStatus:n,schedule:r,drawId:a,matchUpId:s})=>{n&&e.includes(n)||!aD({schedule:r,scheduleAttributes:t})||i?.length&&!i.includes(r.venueId)||(o[a]||(o[a]=[]),o[a].push(s))}));const s=n.tournamentId;let c=0;for(const t in o){const{event:e,drawDefinition:r}=Gm({tournamentRecord:n,drawId:t}),i=ff({drawDefinition:r,matchUpFilters:{matchUpIds:o[t]}}).matchUps??[];for(const t of i){let n=!1;t.timeItems=(t.timeItems??[]).filter((t=>{const e=t?.itemType&&![xl,_l,kl,Ll,Bl,Gl].includes(t?.itemType);return e||(n=!0),e})),n&&($d({context:"clear schedules",eventId:e?.eventId,drawDefinition:r,tournamentId:s,matchUp:t}),c+=1)}}return{...z,clearedScheduleCount:c}}function _R(t){const{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:a,scheduleDates:o=[],tournamentRecords:s,periodLength:c,useGarman:u,dryRun:d,pro:p}=t,l=cc(t,[{[ms]:!0},{[Xs]:t=>!t||Array.isArray(t)&&t.every(Ci),[vs]:!1,[nc]:Zs}]);if(l.error)return l;const m=xP({tournamentRecords:s});if(m.error)return m;if(!m.schedulingProfile.length)return{...z};const{modifications:f,issues:h=[],schedulingProfile:g=[]}=m,I=Object.assign({},...Object.values(s).map((t=>Zd({tournamentRecord:t}).containedStructures))),U=o.map((t=>{if(Ci(t))return $i(t)})).filter(Boolean),y=g.map((t=>t.scheduleDate)).map((t=>Ci(t)&&$i(t))).filter((t=>t&&(!o.length||U.includes(t))));if(!y.length)return{error:Ne};if(a&&!d){kR({tournamentRecords:s,scheduledDates:Array.isArray(a)?a:[]})}const S=vP({ignoreDisabled:!1,tournamentRecords:s}).courts,{matchUps:v}=lf({matchUpFilters:{matchUpTypes:[n,i]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:s}),{matchUpDependencies:w}=Sf({includeParticipantDependencies:!0,tournamentRecords:s,matchUps:v}),{matchUpDailyLimits:P}=lD({tournamentRecords:s}),{personRequests:D}=VP({requestType:SR,tournamentRecords:s}),T={schedulingProfileModifications:f,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:h,dateSchedulingProfiles:g.filter((t=>{const e=$i(t?.scheduleDate);return y.includes(e)})).sort(((t,e)=>new Date(t.scheduleDate).getTime()-new Date(e.scheduleDate).getTime())),containedStructureIds:I,matchUpDependencies:w,matchUpDailyLimits:P,clearScheduleDates:a,tournamentRecords:s,schedulingProfile:g,personRequests:D,periodLength:c,matchUps:v,dryRun:d,courts:S};return p?function({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:n,schedulingProfileIssues:r,dateSchedulingProfiles:i,containedStructureIds:a,matchUpDependencies:o,matchUpDailyLimits:s,clearScheduleDates:c,tournamentRecords:u,periodLength:d=30,schedulingProfile:p,personRequests:l,matchUps:m=[],courts:f,dryRun:h}){const g={},I={},U={},y={},S={},v={},w={},P={},D={};for(const t of i??[]){const r=$i(t?.scheduleDate),i=t?.venues||[],p={},T={},b=(t,e)=>{t.forEach((t=>{const n=T[t].counters;n[e]?n[e]+=1:n[e]=1,n[hm]?n[hm]+=1:n[hm]=1}))};g[r]={},I[r]={},v[r]=[],w[r]=[],P[r]=[],D[r]=[];const R={};m?.forEach((t=>{t.schedule?.scheduledDate&&ea(r,$i(t.schedule.scheduledDate))&&AP({matchUpPotentialParticipantIds:p,matchUpNotBeforeTimes:R,matchUp:t})}));const{allDateScheduledByeMatchUpDetails:M,allDateScheduledMatchUpIds:N,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=MR({matchUpPotentialParticipantIds:p,individualParticipantProfiles:T,scheduleCompletedMatchUps:n,containedStructureIds:a,matchUpNotBeforeTimes:R,matchUpScheduleTimes:S,matchUpDependencies:o,clearScheduleDates:c,tournamentRecords:u,periodLength:d,scheduleDate:r,matchUps:m,courts:f,venues:i}),C=m?.filter((({matchUpId:t})=>N.includes(t))),{bookings:O}=TR({dateScheduledMatchUps:C,tournamentRecords:u,scheduleDate:r,periodLength:d}),{virtualCourts:F}=KT({scheduleDate:r,periodLength:d,bookings:O,courts:f}),k=F?.reduce(((t,e)=>{const{earliestCourtTime:n,courtEndTime:i}=FR({date:r,averageMinutes:0,court:e});return(!t.startTime||Qi(n)<Qi(t.startTime))&&(t.startTime=n),(!t.endTime||Qi(i)>Qi(t.endTime))&&(t.endTime=i),t}),{});let x=k.startTime;const _=({courtId:t,booking:e})=>F?.find((e=>e.courtId===t))?.dateAvailability[0].bookings.push(e),L=10;let B,V=0;for(;!B;){for(const{venueId:t}of i){const n=A[t],i=n.matchUpsToSchedule.length,a=[],c=[];let u,m=0;for(;!u;){for(const i of n.matchUpsToSchedule){if(c.length===n.courtsCount||a.length===n.courtsCount){u=!0;break}const{matchUpId:m,matchUpType:f}=i,{participantIdsAtLimit:h,relevantParticipantIds:v}=ER({matchUpPotentialParticipantIds:p,individualParticipantProfiles:T,matchUpDailyLimits:s,matchUp:i});if(h.length){w[r].includes(m)||w[r].push(m);continue}const{dependenciesScheduled:P,remainingDependencies:M}=gR({matchUpScheduleTimes:S,matchUpDependencies:o,allDateMatchUpIds:E,matchUp:i});if(!P){I[r][m]||(I[r][m]=[]),I[r][m].push({remainingDependencies:M});continue}const N=[],A=F?.reduce(((t,a)=>{if(c.includes(a.courtId))return t;const{earliestCourtTime:s}=FR({averageMinutes:n.greatestAverageMinutes,startTime:x,date:r,court:a});if(t.scheduleTime&&ji(s)>=ji(t.scheduleTime))return t;const{scheduledDependent:u}=yR({matchUpScheduleTimes:S,matchUpDependencies:o,scheduleTime:s,matchUpId:m,details:n});if(u)return t;const{enoughTime:d}=NR({individualParticipantProfiles:T,matchUpNotBeforeTimes:R,matchUpDependencies:o,scheduleTime:s,details:n,matchUp:i});if(!d)return g[r][m]||(g[r][m]=[]),g[r][m].includes(s)||g[r][m].push(s),t;const h=n.minutesMap?.[m]?.averageMinutes||n.greatestAverageMinutes,{conflicts:I}=wR({potentials:e,averageMatchUpMinutes:h,requestConflicts:D,personRequests:l,scheduleTime:s,scheduleDate:r,matchUp:i});if(I?.length)return N.push(...I),!1;b(v,f);const U=n.minutesMap?.[m]?.recoveryMinutes;return UR({matchUpPotentialParticipantIds:p,individualParticipantProfiles:T,matchUpNotBeforeTimes:R,averageMatchUpMinutes:h,matchUpDependencies:o,recoveryMinutes:U,scheduleTime:s,matchUp:i}),(!t.scheduleTime||ji(s)<ji(t.scheduleTime))&&(t.averageMatchUpMinutes=h,t.recoveryMinutes=U,t.scheduleTime=s,t.courtName=a.courtName,t.courtId=a.courtId),t}),{});if(A.scheduleTime){const{averageMatchUpMinutes:e,recoveryMinutes:r,scheduleTime:i,courtId:o}=A;S[m]=i,y[m]=o,a.push(m),c.push(o);const s=i,u=Zi(s,e);_({courtId:o,booking:{averageMatchUpMinutes:e,recoveryMinutes:r,periodLength:d,matchUpId:m,startTime:s,courtId:o,endTime:u,venueId:t}}),n.matchUpsToSchedule=n.matchUpsToSchedule.filter((t=>t.matchUpId!==m))}else N?.length&&(U[r]||(U[r]=[]),U[r].push(...N))}c.length!==n.courtsCount&&a.length!==n.courtsCount&&n.matchUpsToSchedule.length||(u=!0),n.matchUpsToSchedule.length&&a<n.courtsCount&&(Qi(x)<Qi(k.endTime)?x=Zi(x,d):(u=!0,n.complete=!0)),m+=1,!u&&m>=i&&(u=!0)}n.matchUpsToSchedule?.length||(n.complete=!0)}V+=1,B=i.every((({venueId:t})=>A[t].complete))||V===L}for(const{venueId:t}of i){const e=A[t].matchUpMap;Object.keys(e).forEach((t=>{const n=u[t];n&&Object.keys(e[t]).forEach((i=>{const{drawDefinition:a}=Ey({tournamentRecord:n,drawId:i});a&&e[t][i].forEach((({matchUpId:t})=>{const e=S[t],i=y[t];if(e){const o=e.split(":").map(ta).join(":"),s=`${$i(r)}T${o}`;h||(xb({drawDefinition:a,scheduledTime:s,matchUpId:t}),jb({courtDayDate:r,tournamentRecords:u,tournamentRecord:n,drawDefinition:a,matchUpId:t,courtId:i})),v[r].push(t)}}))}))})),P[r]=A[t].matchUpsToSchedule.map(Nu)}!h&&M?.length&&OR({matchUpDetails:M,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(const e of t.venues)for(const t of e.rounds){const e=(t.matchUps??[]).map((({matchUpId:t})=>t)),n=e?.filter((t=>v[r].includes(t)));t.canScheduledMatchUpIds=n;let i=Math.round((n?.length||0)/t.matchUpsCount*1e4)/100;(i===1/0||isNaN(i))&&(i=void 0),t.possibleToSchedulePct=i,t.matchUpsCount===n?.length&&(t.possibleToSchedule=!0)}}const T=(i??[]).map((({scheduleDate:t})=>t)),b={timeStamp:Date.now(),overLimitMatchUpIds:w,scheduledMatchUpIds:v,schedulingProfile:p,noTimeMatchUpIds:P,requestConflicts:D,scheduledDates:T};return AR({tournamentRecords:u,autoSchedulingAudit:b}),{...z,schedulingProfileModifications:t,schedulingProfileIssues:r,dateSchedulingProfiles:i,recoveryTimeDeferredMatchUpIds:g,dependencyDeferredMatchUpIds:I,matchUpScheduleTimes:S,overLimitMatchUpIds:w,scheduledMatchUpIds:v,noTimeMatchUpIds:P,requestConflicts:D,scheduledDates:T}}(T):function({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:n,schedulingProfileIssues:r,dateSchedulingProfiles:i,containedStructureIds:a,matchUpDependencies:o,matchUpDailyLimits:s,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:d,personRequests:p,periodLength:l,matchUps:m,courts:f,dryRun:h}){const g={},I={},U={},y={},S={},v={},w={},P={},D={},T={};for(const t of i){const r=$i(t?.scheduleDate),i=t?.venues||[],d={},b={},R=(t,e)=>{t.forEach((t=>{const n=b[t].counters;n[e]?n[e]+=1:n[e]=1,n[hm]?n[hm]+=1:n[hm]=1}))};U[r]={},y[r]={},g[r]={},I[r]={},w[r]=[],P[r]=[],D[r]=[],T[r]=[];const M={};m.forEach((t=>{t.schedule?.scheduledDate&&ea(r,$i(t.schedule.scheduledDate))&&AP({matchUpPotentialParticipantIds:d,matchUpNotBeforeTimes:M,matchUp:t})}));const{allDateScheduledByeMatchUpDetails:N,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=MR({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,scheduleCompletedMatchUps:n,containedStructureIds:a,matchUpNotBeforeTimes:M,matchUpScheduleTimes:v,matchUpDependencies:o,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:l,scheduleDate:r,matchUps:m,courts:f,venues:i}),C=10;let O,F=0;const k=10;for(;!O;){for(const{venueId:t}of i){let n=0;const i=A[t];for(;i.courtsCount&&i.scheduleTimes?.length&&i.matchUpsToSchedule?.length&&n<=i.courtsCount;){const{scheduleTime:a,attempts:c=0}=i.scheduleTimes.shift(),u=i.matchUpsToSchedule.find((t=>{const{matchUpId:n,matchUpType:c}=t,{participantIdsAtLimit:u,relevantParticipantIds:l}=ER({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpDailyLimits:s,matchUp:t});if(u.length)return P[r].includes(n)||P[r].push(n),!1;const{scheduledDependent:m}=yR({matchUpScheduleTimes:v,matchUpDependencies:o,scheduleTime:a,matchUpId:n,details:i});if(m)return!1;const{dependenciesScheduled:f,remainingDependencies:h}=gR({matchUpScheduleTimes:v,matchUpDependencies:o,allDateMatchUpIds:E,matchUp:t});if(!f)return y[r][n]||(y[r][n]=[]),y[r][n].push({scheduleTime:a,remainingDependencies:h}),!1;const{enoughTime:g}=NR({individualParticipantProfiles:b,matchUpNotBeforeTimes:M,matchUpDependencies:o,scheduleTime:a,details:i,matchUp:t});if(!g)return U[r][n]||(U[r][n]=[]),U[r][n].push({scheduleTime:a}),!1;const I=i.greatestAverageMinutes,{conflicts:w}=wR({potentials:e,averageMatchUpMinutes:I,requestConflicts:T,personRequests:p,scheduleTime:a,scheduleDate:r,matchUp:t});if(w?.length)return S[r]||(S[r]=[]),S[r].push(...w),!1;R(l,c);const D=i.minutesMap?.[n]?.recoveryMinutes;return UR({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpNotBeforeTimes:M,averageMatchUpMinutes:I,matchUpDependencies:o,recoveryMinutes:D,scheduleTime:a,matchUp:t}),v[n]=a,!0}));i.matchUpsToSchedule=i.matchUpsToSchedule.filter((({matchUpId:t})=>t!==u?.matchUpId)),u?n+=1:(I[r][t]||(I[r][t]=[]),I[r][t].push({scheduleTime:a,attempts:c+1}))}i.matchUpsToSchedule?.length&&(I[r][t]=I[r][t]?.filter((t=>{const e=t.attempts<C;return e&&i.scheduleTimes.push(t),!e}))),i.scheduleTimes?.length&&i.matchUpsToSchedule?.length||(i.complete=!0)}F+=1,O=i.every((({venueId:t})=>A[t].complete))||F===k}for(const{venueId:t}of i){const e=A[t].matchUpMap;Object.keys(e).forEach((n=>{const i=u[n];i&&Object.keys(e[n]).forEach((a=>{const{drawDefinition:o}=Ey({tournamentRecord:i,drawId:a});o&&e[n][a].forEach((({matchUpId:e})=>{const n=v[e];if(n){const a=n.split(":").map(ta).join(":"),s=`${$i(r)}T${a}`;h?w[r].push(e):(xb({drawDefinition:o,scheduledTime:s,matchUpId:e}).success&&w[r].push(e),t&&Vb({tournamentRecord:i,drawDefinition:o,matchUpId:e,venueId:t}))}}))}))})),D[r]=A[t].matchUpsToSchedule.map(Nu),g[r][t]=A[t].scheduleTimes.sort(((t,e)=>ji(t.scheduleTime)-ji(e.scheduleTime)))}!h&&N?.length&&OR({matchUpDetails:N,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(const e of t.venues)for(const t of e.rounds){const e=t.matchUps?.map((({matchUpId:t})=>t))||[],n=e.filter((t=>w[r].includes(t)));t.canScheduledMatchUpIds=n;let i=Math.round(n.length/t.matchUpsCount*1e4)/100;(i===1/0||isNaN(i))&&(i=0),t.possibleToSchedulePct=i,t.matchUpsCount===n.length&&(t.possibleToSchedule=!0)}}const b=i.map((({scheduleDate:t})=>t)),R={timeStamp:Date.now(),overLimitMatchUpIds:P,scheduledMatchUpIds:w,schedulingProfile:d,noTimeMatchUpIds:D,requestConflicts:T,scheduledDates:b};return AR({tournamentRecords:u,autoSchedulingAudit:R}),{...z,schedulingProfileModifications:t,schedulingProfileIssues:r,scheduleTimesRemaining:g,dateSchedulingProfiles:i,skippedScheduleTimes:I,recoveryTimeDeferredMatchUpIds:U,dependencyDeferredMatchUpIds:y,matchUpScheduleTimes:v,overLimitMatchUpIds:P,scheduledMatchUpIds:w,noTimeMatchUpIds:D,requestConflicts:T,scheduledDates:b}}(T)}function LR(t){const{tournamentRecord:e,tournamentRecords:n,activeTournamentId:r,...i}=t||{};return i.tournamentId||(i.tournamentId=ha()),(!i.startDate||Bi(i.startDate)||Ti.test(i.startDate))&&(!i.endDate||Bi(i.endDate)||Ti.test(i.endDate))?(i.extensions&&(i.extensions=i.extensions.filter(xc)),{...i}):{error:Oe}}function BR({addParticipants:t=!0,participantAttribute:e,tournamentRecord:n,personAttribute:r,teamNames:i,accessor:a,uuids:o}){if(!n)return{error:nt};const s={},c=(n.participants??[]).filter((({participantType:t,participantRole:e})=>t===ap&&e===Ih));let u=0;for(const t of c){const n=a&&hf({element:t,accessor:a})?.value||r&&t.person?.[r]||e&&t[e];if(n){if(!Object.keys(s).includes(n)){s[n]={participantName:i?.[u]??n,participantId:o?.pop()??ha(),individualParticipantIds:[],participantRole:Ih,participantType:cp};const t={value:r??e,name:iu};_c({element:s[n],extension:t}),u+=1}s[n].individualParticipantIds.push(t.participantId)}}const d=Object.keys(s),p=(n.participants??[]).map((t=>{if(t.participantType!==cp)return;if(t.participantRole!==Ih)return;const{extension:e}=zc({name:iu,element:t}),n=e?.value;return d.includes(n)?t.participantId:void 0})).filter(Boolean);let l=0;const m=[];return Object.keys(s).forEach((e=>{const r=s[e],{participantId:i}=r;p.includes(i)||(n.participants||(n.participants=[]),t&&n.participants.push(r),m.push(r),l++)})),t&&l?(Or({payload:{tournamentId:n.tournamentId,participants:m},topic:ld}),{...z,participantsAdded:l}):m.length?{...z,newParticipants:m}:{error:Be}}var VR=[{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"}],jR=["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 GR({count:t=1,participantsCount:e=32}={}){const n=P(jR),r=n.slice(0,t);return{cities:E(0,e).map((e=>e<Math.min(t,n.length)?r[e]:A(r)))}}function qR({count:t=1,participantsCount:e=32}={}){const n=P(VR),r=n.slice(0,t).map((t=>Object.keys(t))).flat();return{states:E(0,e).map((e=>e<Math.min(t,n.length)?r[e]:A(r)))}}function $R({count:t=1,participantsCount:e=32}={}){const n=E(0,t).map((()=>E(0,5).map((()=>U(0,9))).join("")));return{postalCodes:E(0,e).map((e=>e<t?n[e]:A(n)))}}function WR({idPrefix:t,participantType:e,index:n,uuids:r}){const i=j(e)?e[0]:"X";return t?`${t}-${i}-${n}`:r?.pop()||ha()}function HR(t){const{cities:e,states:n,postalCodes:r,nationalityCode:i,participantIndex:a}=t;return{postalCode:r?.[a],state:n?.[a],city:e?.[a],countryCode:i}}var zR={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 YR(t){const{count:e=100,sex:n}=t||{};if(!e||n&&![ni,ai].includes(n))return{personData:[],error:Jn};const r=Math.ceil(1.3*e),{lastNames:i,firstFemale:a,firstMale:o}=zR,s=mp.map((({iso:t})=>t)).filter(Boolean),c=Math.ceil(r/i.length),u=Math.ceil(r/a.length),d=Math.ceil(r/o.length),p=E(0,c).flatMap((()=>{const t=la(i,!1,!0);return E(0,i.length).map((()=>N(t)))})),l=E(0,u).flatMap((()=>{const t=la(a,!1,!0);return E(0,a.length).map((()=>N(t)))})),m=E(0,d).flatMap((()=>{const t=la(o,!1,!0);return E(0,o.length).map((()=>N(t)))})),f={};for(let t=0;t<r;t++){const t=p.pop(),e=n||A([ni,ai]),r=e===ni?m.pop():l.pop(),i=A(s);f[`${r}${t}`]={nationalityCode:i,sex:e,firstName:r,lastName:t}}return{personData:Object.values(f).slice(0,e)}}function KR(t){let e=t?.count||1;const{personExtensions:n,consideredDate:r,isMock:i=!0,gendersCount:a,personData:o,category:s,sex:c}=t||{};if(isNaN(e))return{error:Jn};const u=a?.[ni]||c===ni&&e||0,p=a?.[ai]||c===ai&&e||0;e=Math.max(e,u+p);const l=e-(u+p),m=[...u&&YR({count:u,sex:ni}).personData||[],...p&&YR({count:p,sex:ai}).personData||[],...l&&YR({count:l}).personData||[]];let f=m.filter((t=>!c||u&&p||t.sex===c));const h=[];if(Array.isArray(o)){const t=o.filter((t=>"string"==typeof t.firstName&&("string"==typeof t.lastName&&(!(t.sex&&![ni,ai].includes(t.sex))&&(!(t.nationalityCode&&("string"!=typeof t.nationalityCode||t.nationalityCode.length>3||!mp.find((({iso:e,ioc:n})=>[e,n].includes(t.nationalityCode)))))&&(t.nationalityCode&&h.push(t.nationalityCode),!0))))));if(!t.length)return{error:Jn};f=t}const g=o?f:P(f);if(g.length<e){const{maleFirstNames:t,maleLastNames:n,femaleFirstNames:r,femaleLastNames:i,nationalityCodes:a}=m.reduce(((t,e)=>{const{firstName:n,lastName:r,nationalityCode:i}=e;return e.sex===ni?(t.maleFirstNames.includes(n)||t.maleFirstNames.push(n),t.maleLastNames.includes(r)||t.maleLastNames.push(r)):(t.femaleFirstNames.includes(n)||t.femaleFirstNames.push(n),t.femaleLastNames.includes(r)||t.femaleLastNames.push(r)),t.nationalityCodes.includes(i)||t.nationalityCodes.push(i),t}),{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});E(0,e-g.length).forEach((()=>{const e=c||A([ni,ai]),o=A(a),s={firstName:A(e===ni?t:r),lastName:A(e===ni?n:i),sex:e,nationalityCode:o};g.push(s)}))}const{ageMinDate:I,ageMaxDate:U}=ra({consideredDate:r,category:s}),y=d(I?.slice(0,4)||0)||d(U?.slice(0,4)||0)-3,S=d(U?.slice(0,4)||0)||d(I?.slice(0,4)||0)+3,v=(I||U)&&[y,S],w=g.slice(0,e).map(((t,e)=>{const[r,a]=v||[],o=v&&N(E(r,a)),s=N(E(0,365)),c=o&&function(t,e,n){const r=new Date(t,0);return Fi(new Date(r.setDate(e)),n)}(o,s);return Object.assign(Xr({extensions:n||[{name:"regionCode",value:e+1}],birthDate:c,isMock:i}),t)}));return{persons:w.length&&w||g[0],nationalityCodes:h}}var QR=["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 JR({nameRoot:t="TEAM",count:e=1}={}){const n=P(QR).slice(0,e);return n.length<e&&E(0,e-n.length).forEach((e=>n.push(`${t} ${e+1}`))),{names:n}}function ZR(t){let{scaledParticipantsCount:e,rankingRange:n}=t;const{ratingsParameters:i=hU,valuesInstanceLimit:a,ratingsValues:o=[],consideredDate:s,categories:c,category:u,nationalityCodesCount:d,nationalityCodeType:p,nationalityCodes:l,participantsCount:m=32,participantType:f,teamSize:g=8,personIds:I,idPrefix:U,uuids:y,personExtensions:S,addressProps:v,gendersCount:w,matchUpType:D,personData:T,sex:b,inContext:R,withISO2:M,withIOC:N,scaleAllParticipants:A}=t,C=f===sp||D===r,O=f===cp||D===cp;!n||Array.isArray(n)&&n.every((t=>h(t)))&&2===n.length||(n=void 0),e=A?m:e;n=n||[1,e&&e>1e3?e:1e3],n[1]+=1;const F=m*((C?2:O&&(g??8))||1),k=KR({count:F,personExtensions:S,consideredDate:s,gendersCount:w,personData:T,category:u,sex:b});if(k.error)return k;const{nationalityCodes:x,persons:_}=k,L={},B={},V={},j={},q=t=>{Object.assign(L,t.doublesRankings),Object.assign(B,t.singlesRankings),Object.assign(j,t.doublesRatings),Object.assign(V,t.singlesRatings)};if(G(u)){const t=tM({scaledParticipantsCount:e,ratingsParameters:i,participantType:f,ratingsValues:o,rankingRange:n,category:u});q(t)}Array.isArray(c)&&c.forEach((t=>{const r=tM({scaledParticipantsCount:e,ratingsParameters:i,participantType:f,ratingsValues:o,rankingRange:n,category:t});q(r)}));const $=mp.filter((t=>"IOC"===p&&t.ioc||t.iso));const{postalCodesProfile:W,postalCodesCount:H,statesProfile:Y,citiesProfile:K,citiesCount:Q,statesCount:J}=v||{},Z=t=>Object.keys(t).map((t=>E(0,Y[t]).map((()=>t)))).flat(),X={cities:K&&Z(K)||v?.cities||GR({count:Q||F,participantsCount:F}).cities,states:Y&&Z(Y)||v?.states||qR({count:J||F,participantsCount:F}).states,postalCodes:W&&Z(W)||v?.postalCodes||$R({count:H||F,participantsCount:F}).postalCodes},tt=function(t){const e=Math.ceil(F/t);return a&&e>a?Math.ceil(F/a):t}(d),et=tt?P($).slice(0,d):l&&$.filter((t=>l.includes(t.iso)))||$,nt=P(E(0,Math.ceil(F/(tt||1))).map((()=>et)).flat(1/0)),rt=JR({count:m}).names,it=E(0,m).map((t=>{const e=(C?2:O&&(g??8))||1,n=E(0,e).map((n=>function(t){const e=_[t],{nationalityCode:n,participantExtensions:r,participantTimeItems:i,extensions:a,firstName:o,birthDate:s,lastName:d,personId:l,sex:m}=e||{},f=o||"GivenName",h=d||"FamilyName",g=`${f} ${h}`,S=nt[t],v=x?.length&&n||S&&("IOC"===p?S.ioc||S.iso:S.iso||S.ioc)||n;!nt?.length||v||n||console.log("%c Invalid Nationality Code",{participantIndex:t,country:S});const w=HR({...X,participantIndex:t,nationalityCode:v}),P=Xr({participantId:WR({participantType:ap,index:t,idPrefix:U,uuids:y}),extensions:r,timeItems:i,participantRole:Ih,participantType:ap,participantName:g,person:{personId:l||I?.length&&I[t]||ha(),birthDate:Ci(s)?s:void 0,addresses:[w],standardFamilyName:h,standardGivenName:f,nationalityCode:v,extensions:a,sex:m}});if(N&&v){const t=mp.find((({iso:t})=>t===v));t?.ioc&&(P.person.iocNationalityCode=t.ioc),t?.label&&(P.person.countryName=t.label)}if(M&&v){const t=mp.find((({iso:t})=>t===v));t?.iso2&&(P.person.iso2NationalityCode=t.iso2),t?.label&&(P.person.countryName=t.label)}const D=e=>{const n=e.categoryName||e.ratingType||e.ageCategoryCode,r=B[n]?.[t],i=L[n]?.[t];XR({scaleValue:r,eventType:so,scaleType:pc,participant:P,category:e}),XR({scaleValue:i,eventType:uo,scaleType:pc,participant:P,category:e});const a=V[n]?.[t],o=j[n]?.[t];XR({scaleValue:a,eventType:so,scaleType:lc,participant:P,category:e}),XR({scaleValue:o,eventType:uo,scaleType:lc,participant:P,category:e})};Array.isArray(c)?c.forEach((t=>D(t))):u&&D(u);return P}(t*e+n))),r=n.map((t=>t.participantId)),i=n.map((t=>t.person.standardFamilyName)).join("/"),a=C?sp:cp,o={participantId:WR({participantType:a,index:t,idPrefix:U,uuids:y}),participantName:C?i:rt[t],participantRole:Ih,individualParticipantIds:r,participantType:a};return R&&(o.individualParticipants=n),C||O?[o,...n]:n})).flat();return{participants:it,...z}}function XR({scaleValue:t,participant:e,eventType:n,scaleType:r,category:i}){const a=i.categoryName||i.ratingType||i.ageCategoryCode,o={itemValue:t,itemType:[mc,r,n,a].join(".")};a&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(o))}function tM(t){const{category:e,scaledParticipantsCount:n,ratingsParameters:r,participantType:i,ratingsValues:a=[]}=t,o=e.rankingRange||t.rankingRange||[1,1e3],s={},c={},u={},d={},{categoryName:p,ageCategoryCode:l,ratingType:m}=e,f=e.categoryName||e.ratingType||e.ageCategoryCode;if((p||l)&&!m){const[t,e]=o||[];if(c[f]=P(E(t,e)).slice(0,n||U(20,30)),[sp,cp].includes(i)){const[t,e]=o||[];s[f]=P(E(t,e)).slice(0,n||U(20,30))}}if(m&&r[m]){const{ratingMax:t,ratingMin:o,ratingAttributes:s}=e,c={...r[m],...s||{}},{attributes:p={},decimalsCount:l,accessors:h,range:g,step:I}=c,y=t=>{const e={},n=Object.keys(t||{});for(const r of n){const n=t[r];if("object"==typeof n&&n.generator){const{range:t}=n,[i,a]=t.slice().sort();e[r]=U(i,a)}else e[r]=n}return e},v=g[0]>g[1]?2:.7,[w,P]=g.slice().sort(),D=(()=>E(0,2e3).map((()=>S(w,P,v,I,l))).filter((e=>(!t||e<=t)&&(!o||e>=o))).slice(0,n||U(20,30)).map((t=>h?Object.assign({},...h.map((e=>({[e]:t}))),y(p)):t)))();u[f]=[...a,...D],[sp,cp].includes(i)&&(d[f]=[...a,...D])}return{singlesRankings:c,doublesRankings:s,singlesRatings:u,doublesRatings:d}}function eM(t){const{alternatesCount:e=0,tieFormatName:r,drawSize:a}=t;let o=0,s=0,c=0,u=0;const d={},p={[ni]:0,[ai]:0,[ri]:0,[ii]:0,[ei]:0},l=G(t.tieFormat)?t.tieFormat:ao({namedFormat:r});l?.collectionDefinitions?.filter(Boolean).forEach((t=>{const{category:e,collectionId:r,matchUpType:a,matchUpCount:l,gender:m}=t;if([ni,ai].includes(m)){const t=l*(a===i?2:1);p[m]<t&&(p[m]=t)}else m===ri&&(p[ni]<l&&(p[ni]=l),p[ai]<l&&(p[ai]=l));if(e){const t=JSON.stringify(e);d[t]=e}if(r||(t.collectionId=ha()),um(i)(a)){const t=l;u+=l,o=Math.max(o,t)}if(um(n)(a)){const t=l;c+=l,s=Math.max(s,t)}}));const m=Object.keys(d).length?Math.max(c,2*u):Math.max(s,2*o);return{maxDoublesDraw:o*(a+e),maxSinglesDraw:s*(a+e),teamSize:m,genders:p}}function nM({participantsProfile:t,tournamentRecord:e,eventProfiles:n,drawProfiles:r,startDate:i,uuids:a}){if(0===t?.participantsCount)return{addedCount:0,...z};const{participantsCount:o,participantType:s,largestTeamDraw:c,largestTeamSize:u,gendersCount:d}=function({participantsProfile:t,eventProfiles:e,drawProfiles:n}){let{participantsCount:r,participantType:i=ap}=t||{};const a=r||0,o={[ai]:0,[ri]:0,[ii]:0,[ni]:0,[ei]:0};let s=0,c=0,u=0,d=0,p=0;const l=({alternatesCount:t=0,uniqueParticipants:e,tieFormatName:n,drawSize:r=0,eventType:i,tieFormat:a,category:l,gender:m,stage:f})=>{const h=i===co,g=i===po,I=Boolean(e||f===ho||l||m);if(g){d=Math.max(d,r+t),a="object"==typeof a?a:ao({namedFormat:n});const{teamSize:e,maxDoublesDraw:i,maxSinglesDraw:p,genders:l}=eM({alternatesCount:t,tieFormatName:n,tieFormat:a,drawSize:r});u=Math.max(u,e),c=Math.max(c,p),I||(s=Math.max(s,i)),Object.keys(l).forEach((t=>o[t]+=l[t]))}else if(h)if(I){const e=2*(r+t);p+=e,m&&(o[m]+=e)}else r+t&&r+t>s&&(s=r+t);else if(I){const e=r+t;m&&(o[m]+=e),p+=e}else r&&r>c&&(c=r+t)};if(e?.forEach((t=>{const{tieFormatName:e,tieFormat:n,drawProfiles:r,eventType:i,category:a,gender:o}=t;if(r)for(const t of r){const{tieFormatName:r,tieFormat:s}=t;l({...t,tieFormatName:r||e,tieFormat:s||n,eventType:i,category:a,gender:o})}})),Array.isArray(n))for(const t of n)l(t);const m=Math.max(d*u,2*s,c);return s&&(i=sp),(r||a)<m&&(r=m),r&&s&&[sp,po].includes(i)&&(c&&Math.floor(c/2)>s?r=Math.floor(c/2):(!c||2*s>=c)&&(r=Math.ceil(r/2))),void 0===r&&(r=e?.length||n?.length?0:32),r<a&&(r=a),{uniqueParticipantsCount:p,participantsCount:r,largestTeamDraw:d,largestTeamSize:u,participantType:i,gendersCount:o}}({participantsProfile:t,eventProfiles:n,drawProfiles:r}),p=t?.teamKey,l=ZR({consideredDate:i,...t,participantsCount:o,participantType:s,gendersCount:d,uuids:a}).participants;let m=0,f=HD({tournamentRecord:e,participants:l});if(f.error)return f;if(m+=f.addedCount,p){const t=BR({tournamentRecord:e,...p});if(t.error)return t}const h=l.filter((({participantType:t})=>t===ap)).map(Mu),g=t?.idPrefix?`${cp}-${t.idPrefix}`:void 0;return f=HD({participants:E(0,c).map((t=>{const e=h.slice(t*u,(t+1)*u),n=WR({index:t,participantType:s,idPrefix:g,uuids:a});return{participantName:`Team ${t+1}`,participantRole:Ih,individualParticipantIds:e,participantType:cp,participantId:n}})),tournamentRecord:e}),f.error?f:(m+=f.addedCount,{addedCount:m,...z})}function rM({drawProfiles:t,category:e,gender:n}){const r={},i=t?.reduce(((t,i)=>{const{qualifyingPositions:a=0,participantsCount:o=0,uniqueParticipants:s,stage:c=fo,drawSize:u=0}=i||{};Object.keys(t).includes(c)||(t[c]=0);const d=(o||u)-a;return s||n||e||c===ho?(Object.keys(r).includes(c)||(r[c]=0),r[c]+=d):t[c]=Math.max(t[c],d),t}),{}),a=Object.keys(r);return a.forEach((t=>i[t]+=r[t])),{stageParticipantsCount:i,uniqueParticipantsCount:r,uniqueParticipantStages:a}}function iM({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:n,targetParticipants:r}){const i=e[fo]||0,a=e[ho]||0;return{stageParticipants:{QUALIFYING:r?.filter((({participantType:t})=>t===n)).filter((({participantId:e})=>!t.includes(e))).slice(0,a),MAIN:r?.filter((({participantType:t})=>t===n)).filter((({participantId:e})=>!t.includes(e))).slice(a,a+i)}}}const aM={[zu]:2,[Vu]:1,[Bu]:1,[$u]:1,[Lu]:4};function oM(t){let{defaultWithScorePercent:e=2,winningSide:n}=t;const{matchUpStatusProfile:r=aM,matchUpFormat:i=ba,pointsPerMinute:a=1,sideWeight:o=4}=t;if(!Di({matchUpFormat:i}))return{error:oe};if("object"!=typeof r)return{error:Jn};if(e>100&&(e=100),isNaN(e)||isNaN(a)||isNaN(o))return{error:Jn};const s=Object.keys(r).filter((t=>Object.keys(nd).includes(t)&&t!==xu));if(Object.keys(s).reduce(((t,e)=>t+r[e]),0)>100)return{error:Jn,matchUpStatusProfile:r};const c=s.reduce(((t,e)=>(t.pointer=t.pointer+r[e],t.valueMap.push([t.pointer,e]),t)),{pointer:0,valueMap:[]}),u=U(1,100),d=(c.valueMap.find((t=>u<=t[0]))??[100,xu])[1],p={sets:[],scoreStringSide1:"",side2ScoreString:""};if([zu,Lu].includes(d)){n=n||U(1,2);const t={score:p,matchUpStatus:d,winningSide:n};if(!(d===Lu&&U(1,100)>100-e))return{outcome:t}}else if([Vu,Bu].includes(d))return{outcome:{score:p,matchUpStatus:d}};const l=Ii(i),{bestOf:m=1,exactly:f,setFormat:h,finalSetFormat:g}=l??{},I=[],y=U(0,1),S=n?[n-1]:[...E(0,o).map((()=>y)),1-y],v=[$u,Lu,Gu,Wu].includes(d)&&(N(E(1,f||m))||1);let w;const P=E(1,(f??m)+1);for(const t of P){const e=t===(f??m),{set:n,incomplete:r,winningSideNumber:o}=sM({setFormat:e&&g||h,incomplete:v===t,pointsPerMinute:a,matchUpStatus:d,weightedRange:S,setNumber:t});if(I.push(n),r){w=o;break}if(bD({matchUp:{score:{sets:I},matchUpFormat:i}}).calculatedWinningSide)break}const D=bD({matchUp:{score:{sets:I},matchUpFormat:i,winningSide:n}}),T=w?n||w:D.calculatedWinningSide,{score:b}=iR({winningSide:T,score:{sets:I},matchUpStatus:d});return{outcome:{winningSide:T,matchUpStatus:d,score:b}}}function sM({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:n,incomplete:r,setFormat:i,setNumber:a}){const o={setNumber:a},{setTo:s,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:d,timed:p,minutes:l}=i,m=U(0,t.length-1),f=t[m];let h;if(p){const i=l*e,a=Math.round(.2*i),s=i+N([1,-1])*a,c=function(t=1,e=3,n=!0){let r=0;for(let n=0;n<e;n++)r+=Math.random()*(t/e);return n&&t>1?Math.round(r):r}(s,2),u=[c,s-c];f&&u.reverse(),h=t[m]+1;let d=(u[0]>u[1]?1:u[1]>u[0]&&2)||0;if(r){const[t,e]=u;return Object.assign(o,{side1Score:t,side2Score:e}),Xu.includes(n)?{set:o,incomplete:r,winningSideNumber:h}:{set:o,incomplete:r}}d||(u[U(0,1)]+=1),d=u[0]>u[1]?1:2,d!==h&&u.reverse();const[p,g]=u;return Object.assign(o,{side1Score:p,side2Score:g,winningSide:h}),{set:o}}if(r)return o.side1Score=U(0,u),o.side2Score=U(0,u),Xu.includes(n)&&(h=t[m]+1),{set:o,incomplete:r,winningSideNumber:h};{const e=E(1,s+1).map((t=>E(0,s+2-t).map((()=>t)))).flat(),n=e[U(0,e.length-1)],r=s&&Sw({isSide1:!0,tiebreakAt:u,lowValue:n,setTo:s}),a=!r,p=1===t.length&&t[m]+1;if(!a){if(p){(r[0]>r[1]?1:2)!==p&&r.reverse()}else f&&r.reverse();const[t,e]=r;Object.assign(o,{side1Score:t,side2Score:e})}const l=Pw({matchUpScoringFormat:{setFormat:i},setObject:o});let h;if(l.hasTiebreakCondition||a){const{NoAD:t,tiebreakTo:e}=c||d||{},n=E(1,e+1).map((t=>E(0,e+2-t).map((()=>t)))).flat(),r=n[U(0,n.length-1)],i=vw({isSide1:!0,tiebreakNoAd:t,tiebreakTo:e,lowValue:r});if(i)if(a){const t=i[0]>i[1]?1:2;p?t!==p&&i.reverse():f&&i.reverse(),[o.side1TiebreakScore,o.side2TiebreakScore]=i,h=(i[0]>i[1]?1:i[1]>i[0]&&2)||void 0}else 2===l.leadingSide?[o.side1TiebreakScore,o.side2TiebreakScore]=i:[o.side2TiebreakScore,o.side1TiebreakScore]=i}o.winningSide=l.winningSide||l.leadingSide||p||h}return{set:o}}function cM(t){const{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:a,tournamentRecord:s,completionGoal:c,drawDefinition:u,event:d}=t;if(!u)return{error:ot};const p=t.matchUpFormat||u.matchUpFormat||d?.matchUpFormat,l=u.structures.slice().sort(rd);let m=0;const{matchUps:f,matchUpsMap:h}=cf({matchUpFilters:{matchUpTypes:[o],roundNumbers:[1]},contextFilters:{stages:[fo,ho]},inContext:!0,drawDefinition:u});if(f?.length){const t=d?.category?.ageCategoryCode||d?.category?.categoryName;if(t){const e=$T({singlesOnly:!0,tournamentRecord:s,drawDefinition:u,scaleAccessor:{scaleName:t,sortOrder:"ASC",scaleType:pc},event:d});if(e.error)return e;const{lineUps:n,participantsToAdd:r}=e;HD({tournamentRecord:s,participants:r});_c({element:u,extension:{name:au,value:n}})}else{const t=f[0]?.structureId,{positionAssignments:e}=cd({drawDefinition:u,structureId:t});if(e?.length){const{participants:t}=ih({participantFilters:{participantTypes:[o]},tournamentRecord:s}),r=r=>{const a=r.tieMatchUps.filter(um(n)),o=r.tieMatchUps.filter(um(i));a.forEach(((n,r)=>{const i=n.matchUpId;n.sides.forEach((n=>{const{drawPosition:a}=n,o=t?.find((t=>{const{participantId:n}=t,r=e.find((t=>t.participantId===n));return r?.drawPosition===a}));if(o){const t=o.individualParticipantIds?.[r];t&&mb({teamParticipantId:o.participantId,participantId:t,tournamentRecord:s,drawDefinition:u,tieMatchUpId:i,event:d})}}))})),o.forEach(((n,r)=>{const i=n.matchUpId;n.sides.forEach((n=>{const{drawPosition:a}=n,o=t?.find((t=>{const{participantId:n}=t,r=e.find((t=>t.participantId===n));return r?.drawPosition===a}));if(o){const t=o.individualParticipantIds?.slice(2*r,2*r+2);t?.forEach((t=>{mb({teamParticipantId:o.participantId,participantId:t,tournamentRecord:s,drawDefinition:u,tieMatchUpId:i,event:d})}))}}))}))};f.forEach(r)}}}const g="string"==typeof r&&r,I=g&&xu,U=2===l.length&&l[0].finishingPosition===us&&2===O(l.map((({stage:t})=>t)),[fo,Uo]).length,y=l.map((({structureId:t})=>t));for(const r of y){if(m>=c)break;const o=u.structures.find((t=>t.structureId===r)),l=Jm({contextFilters:{matchUpTypes:[i,n]},afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,drawDefinition:u,matchUpsMap:h,structure:o,event:d}).matchUps;l.length;const f=l.filter((({winningSide:t})=>!t)).sort(mf).map(Nu);for(const t of f){if(!isNaN(c)&&m>=c)break;const{matchUps:r}=Jm({matchUpFilters:{matchUpTypes:[i,n]},afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,drawDefinition:u,matchUpsMap:h,structure:o,event:d}),l=r.find((e=>e.matchUpId===t)),f=[Vu,Bu].includes(l.matchUpStatus);if(l?.readyToScore&&!f){const t=dM({matchUpStatusProfile:e,tournamentRecord:s,drawDefinition:u,targetMatchUp:l,matchUpFormat:p,matchUpStatus:I,scoreString:g,winningSide:!a&&1,event:d});if(t?.error)return t;m+=1}}U&&o.finishingPosition===us&&t.completeRoundRobinPlayoffs&&Jg({structureId:o.structureId,applyPositioning:!0,drawDefinition:u})}return{...z,completedCount:m}}function uM(t){const{matchUpStatusCodes:e,policyDefinitions:n,tournamentRecord:r,drawDefinition:i,targetMatchUp:a,matchUpStatus:o,matchUpFormat:s,scoreString:c,winningSide:u,event:d}=t;if(!a||a.matchUpStatus===Fu)return;const{matchUpId:p}=a||{},{outcome:l}=hR({matchUpFormat:s,matchUpStatus:o,scoreString:c,winningSide:u});return e&&(l.matchUpStatusCodes=e),aR({tournamentRecord:r,policyDefinitions:n,drawDefinition:i,matchUpFormat:s,matchUpId:p,outcome:l,event:d})}function dM(t){const{matchUpStatusProfile:e={},tournamentRecord:n,policyDefinitions:r,drawDefinition:i,matchUpStatus:a,matchUpFormat:o,targetMatchUp:s,scoreString:c,winningSide:u,event:d}=t;if(c||a)return uM(t);const{matchUpId:p}=s||{},{outcome:l}=oM({matchUpStatusProfile:e,matchUpFormat:o,winningSide:u});return aR({policyDefinitions:r,tournamentRecord:n,drawDefinition:i,matchUpFormat:o,matchUpId:p,outcome:l,event:d})}function pM({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawProfiles:i,isMock:a,event:o}){const s=jm({event:o}).flightProfile,{eventName:c,eventType:u,category:d}=o,{startDate:p}=r,l=[],m=d?.categoryName||d?.ageCategoryCode||d?.ratingType,f=o.drawDefinitions?.map((({drawId:t})=>t));if(Array.isArray(s?.flights))for(const[d,h]of s.flights.entries()){const{drawId:s,stage:g,drawName:I,drawEntries:U}=h;l.push(h.drawId);const y=i[d],{seedsCount:S,generate:v=!0}=y||{};if(v){const l=U.filter(If(Ss)).map(If(Ss)),h=m||c;if(r&&S&&S<=l.length){E(1,S+1).forEach(((t,e)=>{const n={scaleValue:t,scaleName:h,scaleType:fc,eventType:u,scaleDate:p},i=l[e];bS({tournamentRecord:r,participantId:i,scaleItem:n})}))}if(f?.includes(s))break;let v=xD({...y,matchUpType:u,seedingScaleName:h,tournamentRecord:r,drawEntries:U,drawName:I,drawId:s,isMock:a,event:o,stage:g});if(v.error)return{error:v.error,drawIds:[]};const{drawDefinition:w}=v;if(!w)return{error:ct};const P=i[d]?.drawExtensions;if(Array.isArray(P)&&P.filter(xc).forEach((t=>_c({element:w,extension:t}))),v=PT({suppressNotifications:!0,tournamentRecord:r,drawDefinition:w,event:o}),v.error)return{error:v.error,drawIds:[]};if(y?.withPlayoffs){const t=w.structures?.[0].structureId,e=ly({idPrefix:y.idPrefix,...y.withPlayoffs,tournamentRecord:r,drawDefinition:w,structureId:t,isMock:a,event:o});if(e?.error)return e}const D=y?.completionGoal;if(!(!1===y?.automated)&&(e||D)){const i=y?.matchUpFormat,a=cM({completeAllMatchUps:!D&&e,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,completionGoal:D,drawDefinition:w,matchUpFormat:i,event:o});if(a.error)return{error:a.error,drawIds:[]};const s=a.completedCount;if(y?.drawType===is){const a=w.structures?.find((t=>t.stage===fo));if(!a)return{error:Lt};let c=Jg({structureId:a.structureId,tournamentRecord:r,drawDefinition:w});if(c.error)return{error:c.error,drawIds:[]};if(c=cM({completeAllMatchUps:!D&&e,completionGoal:D?D?D-(s??0):void 0:void 0,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,drawDefinition:w,matchUpFormat:i,event:o}),c.error)return{error:c.error,drawIds:[]}}}}}return{...z,drawIds:l}}function lM(t){const{participantsProfile:e={},uniqueParticipantsCount:n,ratingsParameters:r,tournamentRecord:i,eventProfile:a,eventIndex:o,event:s,uuids:c}=t,{category:u,gender:d,eventType:p}=s,l=um(oo)(p)&&ap||um(co)(p)&&sp||p,m=n[fo]||0,f=n[ho]||0,h=a.drawProfiles?.length?m+f:a.participantsProfile?.participantsCount??0,g=[ni,ai].includes(d)?d:void 0,I=e?.idPrefix?`E-${o}-${e?.idPrefix}`:void 0,{participants:U}=ZR({uuids:a.uuids||c,...e,scaledParticipantsCount:a.scaledParticipantsCount,consideredDate:i?.startDate,rankingRange:a.rankingRange,participantType:l,participantsCount:h,ratingsParameters:r,category:u,idPrefix:I,sex:g}),y=HD({tournamentRecord:i,participants:U});if(y.error)return y;const S=U?.filter((({participantType:t})=>t===l)),v=U?.map(Mu);return{uniqueDrawParticipants:S,uniqueParticipantIds:v}}function mM({autoEntryPositions:t,tournamentRecord:e,drawParticipants:n,drawProfile:r,event:i}){const{drawType:a=jo,qualifyingPositions:o=0,stage:s=fo,drawSize:c=0,drawName:u,drawId:d}=r,p=c-o,l=n.slice(0,p).map(Mu);if(l.length){const n=hh({participantIds:l,autoEntryPositions:t,entryStage:s,tournamentRecord:e,event:i});if(n.error)return n}const m=ET({drawName:u||a,qualifyingPositions:o,drawEntries:l.map((t=>({entryStatus:Wp,entryStage:s,participantId:t}))),drawId:d,event:i,stage:s});return m.error?m:{...z}}function fM({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:n,tournamentRecord:r,drawProfiles:i,category:a,gender:o,event:s}){let c=0;for(const u of i){const{qualifyingPositions:i=0,uniqueParticipants:d,stage:p=fo,drawSize:l=0}=u,m=l-i,f=d||o||a||p===ho,h=f?t.slice(c,c+m):n[p||fo]||[];f&&(c+=m);const g=mM({autoEntryPositions:e,drawParticipants:h,tournamentRecord:r,drawProfile:u,event:s});if(g.error)return g}return{...z}}function hM(t){const{allUniqueParticipantIds:e,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,ratingsParameters:c,tournamentRecord:u,eventProfile:d,eventIndex:p,publish:l,isMock:m,uuids:f}=t;let h=d.gender,g=d.eventName;const{eventType:I=oo,policyDefinitions:U,drawProfiles:y=[],eventExtensions:S,surfaceCategory:v,tieFormatName:w,processCodes:P,discipline:D,eventLevel:T,timeItems:b,ballType:R,category:M}=d,N=d.eventId||ha(),A=d.tieFormat||(I===po?ao({namedFormat:w,event:{eventId:N,category:M,gender:h},hydrateCollections:o,isMock:m}):void 0),E=u.participants;for(const t of y)!h&&t.gender&&(h=t?.gender);const{stageParticipantsCount:C,uniqueParticipantsCount:O,uniqueParticipantStages:F}=rM({drawProfiles:y,category:M,gender:h}),k=um(oo)(I)&&ap||um(co)(I)&&sp||I,{uniqueDrawParticipants:x=[],uniqueParticipantIds:_=[]}=F?lM({event:{eventType:I,category:M,gender:h},uniqueParticipantsCount:O,participantsProfile:r,ratingsParameters:c,tournamentRecord:u,eventProfile:d,eventIndex:p,uuids:f}):{};let{eventAttributes:L}=d;"object"!=typeof L&&(L={});const B=M?.categoryName||M?.ageCategoryCode||M?.ratingType;g=g||B||"Generated Event";const V={...L,surfaceCategory:v,processCodes:P,discipline:D,eventLevel:T,eventName:g,eventType:I,tieFormat:A,ballType:R,category:M,eventId:N,gender:h};if(S?.length&&Array.isArray(S)){const t=S.filter(xc);t?.length&&Object.assign(V,{extensions:t})}if(Array.isArray(b)&&b.forEach((t=>cy({event:q,timeItem:t}))),"object"==typeof U)for(const t of Object.keys(U))my({policyDefinitions:{[t]:U[t]},event:V});let j;V.category&&(V.category.categoryName=B);const G=JD({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:V});if(G.error)return G;const q=G?.event,{stageParticipants:$}=iM({allUniqueParticipantIds:e,stageParticipantsCount:C,eventParticipantType:k,targetParticipants:E});if(y?.length){const t=fM({uniqueDrawParticipants:x,autoEntryPositions:a,stageParticipants:$,tournamentRecord:u,drawProfiles:y,category:M,gender:h,event:q});if(t.error)return t;const e=pM({matchUpStatusProfile:n,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:y,isMock:m,event:q});if(e.error)return e;j=e.drawIds}else if(d?.participantsProfile?.participantsCount){const t=x.map(Mu);if(t.length){const e=hh({participantIds:t,autoEntryPositions:a,tournamentRecord:u,entryStage:fo,event:q});if(e.error)return e}}return l&&tT({tournamentRecord:u,event:q}),{drawIds:j,eventId:N,uniqueParticipantIds:_}}function gM({tournamentRecords:t,scheduleDate:e,venueId:n,round:r}){if(!Ci(e))return{error:Oe};const{extension:i}=zc({name:fu,tournamentRecords:t,discover:!0}),a=i?.value||[];let o=a.find((t=>ea(e,t.scheduleDate)));if(!o){const{startDate:n,endDate:r}=eP({tournamentRecords:t}),i=new Date(e);if(n&&i<new Date(n)||r&&i>new Date(r))return{error:Oe};o={scheduleDate:e,venues:[]},a.push(o)}let s=o.venues.find((t=>t.venueId===n));s||(s={venueId:n,rounds:[]},o.venues.push(s));const c=["notBeforeTime"],u=t=>Object.keys(t).filter((t=>!c.includes(t))).sort().map((e=>G(t[e])?u(t[e]):t[e])).flat().join("|");if(s.rounds.find((t=>u(t)===u(r))))return ti({result:{error:xt},stack:"addSchedulingProfileRound"});s.rounds.push(r);const d=_P({tournamentRecords:t,schedulingProfile:a});return d.error?d:{...z}}function IM(t){const e=cc(t,[{drawProfile:!0,_ofType:Js}]);if(e.error)return e;const{allUniqueParticipantIds:n=[],participantsProfile:r={},matchUpStatusProfile:i,completeAllMatchUps:a,autoEntryPositions:o,hydrateCollections:s,randomWinningSide:c,ratingsParameters:u,tournamentRecord:d,isMock:p=!0,drawProfile:l,startDate:f,drawIndex:h,uuids:g}=t,I=la(l,!1,!0),{excessParticipantAlternates:U=!0,matchUpFormat:y=ba,drawType:S=jo,tournamentAlternates:v=0,alternatesCount:w=0,qualifyingPositions:P,qualifyingProfiles:D,generate:T=!0,eventExtensions:b,drawExtensions:R,completionGoal:M,tieFormatName:N,buildTeams:A,seedsCount:C,timeItems:F,drawName:k,category:x,idPrefix:_,publish:L,gender:B,stage:V}=I,j=I.drawSize||(I.ignoreDefaults?void 0:32),q=I.eventId||ha(),$=l.eventType||l.matchUpType||oo,W=$===co?sp:ap,H=G(l.tieFormat)&&l.tieFormat||$===cp&&ao({event:{eventId:q,category:x,gender:B},namedFormat:N,hydrateCollections:s,isMock:p})||void 0,Y=x?.categoryName||x?.ageCategoryCode||x?.ratingType,K=l.eventName||Y||`Generated ${$}`;let Q=d?.participants||[];const J=(D?.map((t=>t.structureProfiles||[])).flat().reduce(((t,e)=>t+(!e.participantsCount||e.participantsCount>e.drawSize?e.drawSize:e.participantsCount||0)),0)||0)*(W===sp?2:1),Z=(!l.participantsCount||l.participantsCount>j?j:l.participantsCount)||0,X={eventName:K,eventType:$,tieFormat:H,category:x,eventId:q,gender:B};Array.isArray(F)&&F.forEach((t=>cy({event:X,timeItem:t})));let{eventAttributes:tt}=l;if("object"!=typeof tt&&(tt={}),Object.assign(X,tt),b?.length&&Array.isArray(b)){const t=b.filter(xc);t?.length&&Object.assign(X,{extensions:t})}const et=[];if(0===r?.participantsCount||l.uniqueParticipants||J||!d||B||x){const t=(Z||0)+w+J;let e=t;const n={[ni]:0,[ai]:0};let i,a;$===cp&&(({teamSize:i,genders:a}=eM({alternatesCount:w,tieFormatName:N,tieFormat:H,drawSize:j})),Object.keys(a).forEach((t=>{[ni,ai].includes(t)&&a[t]&&(n[t]=j*a[t])})),e=i*((j||0)+J));const o=r?.idPrefix?`D-${h}-${r?.idPrefix}`:void 0,s=ZR({...r,scaledParticipantsCount:l.scaledParticipantsCount||r.scaledParticipantsCount,participantsCount:e,consideredDate:d?.startDate,sex:B||r?.sex,rankingRange:l.rankingRange,uuids:l.uuids||g,ratingsParameters:u,participantType:W,gendersCount:n,idPrefix:o,category:x}).participants;if(X.category&&(X.category.categoryName=Y),d){const t=HD({participants:s,tournamentRecord:d});if(t.error)return t}if(s.forEach((({participantId:t})=>et.push(t))),Q=s,$===cp){const e=a[ni]?s.filter((({participantType:t,person:e})=>t===ap&&e?.sex===ni)).map(Mu):[],n=a[ai]?s.filter((({participantType:t,person:e})=>t===ap&&e?.sex===ai)).map(Mu):[],r=s.filter((({participantType:t})=>t===ap)).map(Mu).filter((t=>!e.includes(t)&&!n.includes(t))),o=[...I.teamNames??[],...JR({count:t}).names],c=i-(a[ni]+a[ai]);let u=0,p=0,l=0;const m=E(0,t).map((t=>{const i=n.slice(u,u+a[ai]),s=e.slice(p,p+a[ni]),d=r.slice(l,l+c);u+=a[ai],p+=a[ni],l+=c;const m=!1!==A?[...i,...s,...d]:[];return{participantName:o[t]||`Team ${t+1}`,participantOtherName:`TM${t+1}`,participantRole:Ih,individualParticipantIds:m,participantType:cp,participantId:ha()}})),f=HD({participants:m,tournamentRecord:d});if(!f.success)return f;Q=m}}const nt=t=>{const{participantType:e}=t;return!(!um(oo)($)||e!==ap)||(!(!um(co)($)||e!==sp)||$===cp&&e===cp)},rt=t=>!l.gender||(t.person?.sex===l.gender||t.individualParticipantIds?.some((t=>{const e=Q.find((e=>e.participantId===t));return e&&rt(e)}))),it=Q.filter(nt).filter(rt).filter((({participantId:t})=>!n.includes(t))),at=it.slice(0,Z).map((t=>t.participantId));if(p&&at?.length){const t=hh({autoEntryPositions:o,entryStage:V,tournamentRecord:d,participantIds:at,event:X});if(t.error)return t}const ot=J?it.slice(Z,Z+J).map((t=>t.participantId)):0;if(p&&ot?.length){let t=0,e=1;const n=(t,e)=>t.stageSequence-e.stageSequence,r=(t,e)=>t.roundTarget-e.roundTarget;for(const i of D.sort(r)){e=i.roundTarget||e;let r,a=1;for(const s of i.structureProfiles.sort(n)){const n=(s.drawSize||m(s.participantsCount))-(r||0),i=ot.slice(t,t+n),c=hh({entryStage:ho,entryStageSequence:a,autoEntryPositions:o,tournamentRecord:d,participantIds:i,roundTarget:e,event:X});if(c.error)return c;r=s.qualifyingPositions,t+=n,a+=1}e+=1}}const st=U&&d?.participants?.filter((({participantId:t})=>!at.includes(t))).filter(nt).filter(rt).slice(0,w||j-Z||v).map((t=>t.participantId));if(p&&st?.length){const t=hh({participantIds:st,autoEntryPositions:!1,entryStatus:qp,tournamentRecord:d,event:X});if(t.error)return t.error}const ut=Y||K;if(d&&C&&C<=at.length){E(1,C+1).forEach(((t,e)=>{const n={scaleName:ut,scaleDate:f,scaleType:rm,scaleValue:t,eventType:$},r=at[e];bS({tournamentRecord:d,participantId:r,scaleItem:n})}))}const dt=xD({...la(l,!1,!0),tournamentRecord:d,seedingScaleName:ut,matchUpFormat:y,eventId:q,isMock:p,event:X});if(dt.error)return dt;if(!dt.drawDefinition)return{error:ct};const{drawDefinition:pt}=dt,lt=pt.drawId;if(Array.isArray(R)&&R.filter(xc).forEach((t=>_c({element:pt,extension:t}))),T){if(PT({drawDefinition:pt,event:X,suppressNotifications:!0}),l.withPlayoffs){const t=pt.structures?.[0].structureId,e=ly({...l.withPlayoffs,tournamentRecord:d,drawDefinition:pt,structureId:t,idPrefix:_,isMock:p,event:X});if(e?.error)return e}const t=!1===l.automated;if(p&&!t){const t=t=>{const e=cM({completeAllMatchUps:t.completeAllMatchUps,completionGoal:t.completionGoal,matchUpStatusProfile:i,randomWinningSide:c,tournamentRecord:d,drawDefinition:pt,matchUpFormat:y,event:X});if(e.error)return e;const n=e.completedCount;if(S===is){const t=pt.structures?.find((t=>t.stage===fo));if(!t)return{error:Lt};Jg({structureId:t.structureId,tournamentRecord:d,drawDefinition:pt});const e=cM({completionGoal:M?M?M-(n??0):void 0:void 0,matchUpStatusProfile:i,completeAllMatchUps:a,randomWinningSide:c,tournamentRecord:d,drawDefinition:pt,matchUpFormat:y,event:X});if(e.error)return e}};if(M&&t({completionGoal:M}),l.outcomes){const{matchUps:t}=ff({inContext:!0,drawDefinition:pt,event:X});for(const e of l.outcomes){const{matchUpStatus:n=xu,matchUpStatusCodes:r,stageSequence:i=1,matchUpIndex:a=0,structureOrder:o,matchUpFormat:s,drawPositions:c,roundPosition:u,stage:p=fo,roundNumber:l,winningSide:m,scoreString:f}=e,h=t?.reduce(((t,e)=>{const{structureId:n,matchUpId:r}=e;return t[n]?t[n].push(r):t[n]=[r],t}),{})??[],g=Object.assign({},...Object.keys(h).map(((t,e)=>({[t]:e+1})))),I=t?.filter((t=>!(p&&t.stage!==p||i&&t.stageSequence!==i||l&&t.roundNumber!==l||u&&t.roundPosition!==u||o&&g[t.structureId]!==o||c&&2!==O(c,t.drawPositions).length))),U=I?.[a],y=uM({matchUpStatusCodes:r,tournamentRecord:d,drawDefinition:pt,targetMatchUp:U,matchUpFormat:s,matchUpStatus:n,scoreString:f,winningSide:m});if(y?.error)return y}}a&&t({completeAllMatchUps:a})}L&&tT({tournamentRecord:d,event:X})}else{const t=ET({drawEntries:pt.entries,drawName:k||S,qualifyingPositions:P,drawId:lt,event:X,stage:V});if(t.error)return t}return{...z,event:Xr(X),uniqueParticipantIds:et,targetParticipants:Q,drawDefinition:pt,eventId:q,drawId:lt}}function UM(t){return parseInt(t)}function yM({startTime:t="",endTime:e=""}={}){if(!(t&&e&&Mi.test(t)&&Mi.test(e)))return!1;const[n,r]=t.split(":").map(UM),[i,a]=e.split(":").map(UM);return!(i<n)&&!(n===i&&a<r)}function SM(t,e){const[n,r]=t.startTime.split(":").map(UM),[i,a]=e.startTime.split(":").map(UM);return n<i?-1:n>i?1:r<a?-1:r>a?1:0}function vM({dateAvailability:t}){if(!t)return{error:Ce};if(!Array.isArray(t))return{error:Ee};const e="Times must be 24 hour => 00:00";for(const n of t){if("object"!=typeof n)return{error:Ee};const{date:t,startTime:r,endTime:i,bookings:a=[]}=n;if(!r||!i)return{error:Ee};if(t&&!Ri.test(t))return{error:Oe,dateAvailability:{date:t},info:"Dates must be formated => YYYY-MM-DD"};if(!Mi.test(r))return{error:Fe,dateAvailability:{startTime:r},info:e};if(!Mi.test(i))return{error:Fe,dateAvailability:{endTime:i},info:e};if(r===i)return{error:Fe,dateAvailability:{startTime:r,endTime:i},info:"startTime and endTime are equivalent"};if(!yM({startTime:r,endTime:i}))return{error:Fe,dateAvailability:{startTime:r,endTime:i},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:Ae};for(const t of a){if("object"!=typeof t)return{error:Ae};const{startTime:n,endTime:r}=t;if(!Mi.test(n))return{error:Fe,booking:{startTime:n},info:e};if(!Mi.test(r))return{error:Fe,booking:{endTime:r},info:e};if(n===r)return{error:Fe,dateAvailability:{startTime:n,endTime:r},info:"startTime and endTime are equivalent"};if(!yM({startTime:n,endTime:r}))return{error:Fe,dateAvailability:{startTime:n,endTime:r},info:"endTime must be after startTime"}}}}return{valid:!0}}function wM({tournamentRecord:t,disableNotice:e,venueId:n,courtId:r,court:i}){const{venue:a}=km({tournamentRecord:t,venueId:n});if(!a)return{error:Mn};a.courts||(a.courts=[]);const o={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,venueId:n,courtId:r};o.courtId||(o.courtId=ha());if(a.courts.some((t=>t.courtId===o.courtId)))return{error:bn};{const r=(i?.dateAvailability||[]).map((t=>({...t,date:$i(t.date),startTime:qi(t.startTime),endTime:qi(t.endTime),bookings:t.bookings?.map((({startTime:t,endTime:e,bookingType:n})=>({startTime:qi(t),endTime:qi(e),bookingType:n})))}))),s=Object.keys(o);for(const t of s)if(i?.[t])if("dateAvailability"===t){const t=vM({dateAvailability:r});if(!t.valid&&t.error)return t;o.dateAvailability=r}else o[t]=i[t];const c=o;return a.courts.push(c),e||Or({payload:{venue:a,tournamentId:t.tournamentId},topic:Ad,key:a.venueId}),{...z,court:la(o),venueId:n}}}function PM(t){const{tournamentRecord:e,venueId:n}=t;if("string"!=typeof n||!n)return{error:Nn};const r=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},i=[];let a;for(const e of Object.values(r)){const{venue:r}=km({tournamentRecord:e,venueId:n});if(r){const n=DM({...t,tournamentRecord:e});for(const t of n?.courts??[])i.push(t?.courtId);if(n.error)return n;a=!0}}return a?{...z,courtIds:i}:{error:Mn}}function DM({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:n,tournamentRecord:r,courtNames:i=[],courtTimings:a,courtsCount:o,startTime:s,courtIds:c,endTime:u,idPrefix:d,venueId:p,dates:l}){if(!p)return{error:Nn};const m=km({tournamentRecord:r,venueId:p});if(m.error)return m;const{venue:f}=m;if(!h(o)||!i)return{error:Dn};const g=E(0,o=o??i.length).map((r=>{const o=a?.[r],c=o?l.map((t=>({date:Fi(t),startTime:s,endTime:u,...o}))):e;return o&&s&&u&&c.push({startTime:s,endTime:u}),{courtName:i[r]||n&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${r+1}`||`${t} ${r+1}`,dateAvailability:c}})).map(((t,e)=>{const n=c?.pop()||d&&`${d}-${e+1}`;return wM({disableNotice:!0,tournamentRecord:r,courtId:n,venueId:p,court:t})})).map((t=>t.court)).filter(Boolean);return g.length!==o?ti({info:"not all courts could be generated",result:{error:Jn}}):(f&&Or({payload:{venue:f,tournamentId:r.tournamentId},topic:Ad,key:f.venueId}),{...z,courts:la(g)})}function TM({tournamentRecord:t,ignoreExistingVenues:e,venueProfiles:n,uuids:r}){const{startDate:i,endDate:a}=t,o=[];for(const[s,c]of n.entries()){const{venueAbbreviation:n,venueId:u=r?.pop()??ha(),dateAvailability:d,startTime:p="07:00",endTime:l="19:00",courtTimings:m,courtsCount:f,courtNames:h,venueName:g,idPrefix:I,courtIds:U}=c,y=Om({tournamentRecord:t,venue:{venueName:g||`Venue ${s+1}`,venueAbbreviation:n,venueId:u}});if(y.error){if(e)continue;return y}o.push(u);const S=_i(i,a),v=!Array.isArray(d)&&[{startTime:p,endTime:l}].concat(S.map((t=>({date:Fi(t),startTime:p,endTime:l}))));if(f||h){const e=PM({dateAvailability:d||v,tournamentRecord:t,courtTimings:m,courtsCount:f,courtNames:h,startTime:p,idPrefix:I,courtIds:U,endTime:l,venueId:u,dates:S});if(e.error)return e}}return o}const bM=["Generated Tournament","CourtHive Challenge","Replication Crisis","Open Competition","Factory Follies","Mock Tournament","Atomic Culture","Racket Rally","Stats Fail"];function RM(t){let{startDate:e,endDate:n}=t??{};const{tournamentName:r=N(bM),ratingsParameters:i=hU,tournamentExtensions:a,policyDefinitions:o,schedulingProfile:s,venueProfiles:c,uuids:u}=t??{},d=!1!==t?.isMock||void 0;if(e&&!Ci(e)||n&&!Ci(n))return{error:Oe};if(t.leagueProfiles&&!Array.isArray(t.leagueProfiles)||t.eventProfiles&&!Array.isArray(t.eventProfiles)||t.drawProfiles&&!Array.isArray(t.drawProfiles))return{error:Jn};if(!e){const t=new Date;e=Fi(n??t),n=Fi(t.setDate(t.getDate()+7))}if(!n){const t=new Date(e);n=Fi(t.setDate(t.getDate()+7))}const p=LR({...t.tournamentAttributes??{},tournamentName:r,startDate:e,endDate:n,isMock:d}),l=c?.length?TM({tournamentRecord:p,venueProfiles:c,uuids:u}):[];if(a?.length&&Array.isArray(a)){const t=a.filter((t=>xc({extension:t})));t?.length&&Object.assign(p,{extensions:t,isMock:d})}if("object"==typeof o)for(const t of Object.keys(o))my({policyDefinitions:{[t]:o[t]},tournamentRecord:p});if(!t?.leagueProfiles?.length||t.eventProfiles?.length||t.drawProfiles?.length||t.participantsProfile){const e=nM({tournamentRecord:p,...t});if(!e.success)return e}const m=[],f=[],g=[];if(t.leagueProfiles){const e=function(t){const{tournamentRecord:e,leagueProfiles:n,eventIds:r,venueIds:i,drawIds:a,allUniqueParticipantIds:o,uuids:s}=t;let c=0;for(const u of n){const n=[],{tieFormatName:d=xa,teamProfiles:p=[],teamsCount:l=0,category:m,idPrefix:f,gender:g}=u,I=u.leagueName??u.eventName??`League ${c+1}`,U=u.leagueId??u.eventId??s?.pop()??ha();r.push(U);const y=G(u.tieFormat)&&u.tieFormat||ao({event:{eventId:U,category:m,gender:g},namedFormat:d,isMock:t.isMock})||void 0;if(!y)return{error:ue};const S=Math.max(l,p.length),v=E(0,S),{genders:w,teamSize:P}=eM({tieFormat:y,drawSize:S}),D={[ai]:0,[ri]:0,[ii]:0,[ni]:0,[ei]:0};Object.keys(w).forEach((t=>D[t]+=w[t]));for(const r of v){const a=p?.[r]?.teamName??`Team ${r+1}`,c=p?.[r]?.teamId||s?.pop()||ha(),d=u.startDate??t.startDate,l=ZR({...u?.participantsProfile,participantsCount:P,consideredDate:d,gendersCount:D,category:m,uuids:s}).participants,h=l.map((t=>t.participantId)),g=cp,I=c??WR({participantType:g,idPrefix:f,index:r,uuids:s});n.push({participantId:I,entryStatus:Wp,entryStage:fo});const U=p?.[r]?.venueIds??[],y={participantId:I,participantRole:Ih,participantName:a,individualParticipantIds:h,participantType:g,homeVenueIds:U};U.forEach((t=>!i.includes(t)&&i.push(t))),o.push(...h),o.push(I);const S=HD({participants:[y,...l],tournamentRecord:e});if(S.error)return S}const T={eventName:I,entries:n,eventType:cp,tieFormat:y,category:m,eventId:U,gender:g};if(e.events||(e.events=[]),e.events.push(T),n.length){const t=(h(u.roundsCount)&&u.roundsCount)??"DOUBLE_ROUND_ROBIN"===u.roundsCount?2*(S-1):S-1,n=xD({automated:u.automated,tournamentRecord:e,drawType:_o,roundsCount:t,drawSize:S,event:T});if(n.error)return n;const{drawDefinition:r}=n;if(r){const t=r?.drawId;PT({drawDefinition:r,event:T,suppressNotifications:!0}),a.push(t)}}c++}TM({tournamentRecord:e,ignoreExistingVenues:!0,venueProfiles:i.map((t=>({venueId:t}))),uuids:s})}({allUniqueParticipantIds:m,tournamentRecord:p,...t,eventIds:f,venueIds:l,drawIds:g});if(e?.error)return e}if(t.drawProfiles){const e=function(t){const{tournamentRecord:e,drawProfiles:n,allUniqueParticipantIds:r,eventIds:i,drawIds:a}=t;let o=0;for(const s of n){let n=IM({allUniqueParticipantIds:r,tournamentRecord:e,drawProfile:s,drawIndex:o,...t});if(n.error)return n;const{drawId:c,eventId:u,event:d,uniqueParticipantIds:p}=n;if(!1!==s?.addEvent){if(n=JD({suppressNotifications:!1,internalUse:!0,tournamentRecord:e,event:d}),n.error)return n;c&&a.push(c),i.push(u)}p?.length&&r.push(...p),o+=1}}({allUniqueParticipantIds:m,ratingsParameters:i,tournamentRecord:p,...t,eventIds:f,drawIds:g});if(e?.error)return e}if(t.eventProfiles){const e=function(t){const{eventProfiles:e,allUniqueParticipantIds:n,eventIds:r,drawIds:i}=t;let a=0;for(const o of e){const e=hM({...t,eventIndex:a,eventProfile:o});if(e.error)return e;const{eventId:s,drawIds:c,uniqueParticipantIds:u}=e;c&&i.push(...c),r.push(s),u?.length&&n.push(...u),a+=1}}({allUniqueParticipantIds:m,ratingsParameters:i,tournamentRecord:p,...t,eventIds:f,drawIds:g});if(e?.error)return e}const{scheduledRounds:I,schedulerResult:U={}}=s?function(t){const{schedulingProfile:e,tournamentRecord:n,autoSchedule:r,periodLength:i,scheduleCompletedMatchUps:a}=t,o=function({schedulingProfile:t,tournamentRecord:e}){if("object"!=typeof t)return{error:Jn};const n=Zd({tournamentRecord:e}).containedStructures,r=pf({tournamentRecord:e}).matchUps??[],{tournamentId:i}=e,a=[];for(const o of t){const{scheduleDate:t,venues:s=[]}=o;for(const o of s){const{rounds:s,venueId:c}=o;for(const o of s){const{drawId:s,winnerFinishingPositionRange:u,roundSegment:d}=o,p=r.filter((t=>{const e=u?.indexOf("-")>0&&u.split("-").map((t=>+t)),n=t.finishingPositionRange?.winner;return!(t.drawId!==s||o.roundNumber&&t.roundNumber!==o.roundNumber||n&&e&&2!==O(n,e).length&&(w(n).length!==w(e).length||O(n,e).length!==w(n).length))}))[0];if(p){const{eventId:r,roundNumber:o,drawName:l,structureName:m,roundName:f}=p;let h=p.structureId;o&&!u&&(h=Object.keys(n).find((t=>n[t].includes(h)))??h);const g={tournamentId:i,structureId:h,roundNumber:o,roundSegment:d,eventId:r,drawId:s},I=gM({tournamentRecords:{[i]:e},round:g,scheduleDate:t,venueId:c});if(I.error)return I;a.push({structureName:m,roundName:f,drawName:l,...g})}}}}return{scheduledRounds:a}}({schedulingProfile:e,tournamentRecord:n});if(o.error)return o;const s=o.scheduledRounds;if(r){const{tournamentId:t}=n;return{schedulerResult:_R({scheduleCompletedMatchUps:a,tournamentRecords:{[t]:n},periodLength:i}),scheduledRounds:s}}return{scheduledRounds:s}}({...t,tournamentRecord:p}):{};return Cr(),Xr({...z,tournamentRecord:p,scheduledRounds:I,schedulerResult:U,eventIds:f,venueIds:l,drawIds:g})}function MM({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:n,tournamentName:r,personIds:i=[],tournamentId:a}){if(!n)return{error:nt};const o=Array.isArray(t)?yu.concat(...t):yu,s=e=>Array.isArray(t)?e?.extensions?.filter((t=>o.includes(t.name))):e?.extensions,c={};n.extensions=s(n);const u=a||ha();c[n.tournamentId]=u,n.tournamentId=u,n.createdAt=(new Date).toISOString(),n.tournamentName=r||`Anonymized: ${Fi(new Date)}`,n.isMock=!0,delete n.parentOrganisation;for(const t of n.participants||[]){t.extensions=s(t),t.onlineResources=[];const e=ha();c[t.participantId]=e,t.participantId=e}for(const t of n.participants||[])Array.isArray(t.individualParticipantIds)&&(t.individualParticipantIds=t.individualParticipantIds.map((t=>c[t])));let d=0;for(const t of n.venues||[]){t.venueAbbreviation=`V${d}`,t.extensions=s(t),t.venueName=`Venue #${d}`,t.onlineResources=[],t.addresses=[];const e=ha();c[t.venueId]=e,t.isMock=!0,d+=1;let n=0;for(const e of t.courts||[])e.courtName=`V${d}C${n}`,e.extensions=s(e),e.onlineResources=[],e.isMock=!0,n+=1}let p=1;for(const t of n.events||[]){t.extensions=s(t),t.onlineResources=[],t.isMock=!0;const e=ha();c[t.eventId]=e,t.eventId=e;const n=t.category?.categoryName||t.category?.ageCategoryCode||t.category?.ratingType||t.gender;if(t.eventName=`Event ${p} ${n}`,Array.isArray(t.entries))for(const e of t.entries)e.participantId=c[e.participantId];for(const e of t.drawDefinitions||[]){e.extensions=s(e);const t=ha();if(c[e.drawId]=t,e.drawId=t,e.isMock=!0,Array.isArray(e.entries))for(const t of e.entries)t.participantId=c[t.participantId];const n=t=>{t.extensions=s(t);const e=ha();c[t.structureId]=e,t.structureId=e;for(const e of t.positionAssignments||[])e.participantId&&(e.participantId=c[e.participantId]);for(const e of t.seedAssignments||[])e.participantId&&(e.participantId=c[e.participantId]);for(const e of t.matchUps||[]){e.isMock=!0;for(const t of e.sides||[])t.lineUp&&(t.lineUp=t.lineUp.map((({participantId:t,collectionAssignments:e})=>({participantId:c[t],collectionAssignments:e}))))}};for(const t of e.structures||[])if(n(t),Array.isArray(t.structures))for(const e of t.structures)n(e);for(const t of e.links||[])t.source.structureId=c[t.source.structureId],t.target.structureId=c[t.target.structureId]}const{extension:r}=zc({name:ru,element:t});Array.isArray(r?.value?.flights)&&r?.value.flights?.forEach((t=>{if(t.drawId=c[t.drawId],Array.isArray(t.drawEntries))for(const e of t.drawEntries)e.participantId=c[e.participantId]})),p+=1}const l=n.startDate||Fi(new Date),m=(n.participants||[]).filter((({participantType:t})=>t===ap)),f=m.reduce(((t,e)=>{const n=e.person?.sex;return[ni,ai].includes(n)?t[n]+=1:t[ii]+=1,t}),{[ni]:0,[ai]:0,[ii]:0}),h=Object.assign({},...Object.keys(f).map((t=>({[t]:KR({category:{ageCategoryCode:"O18"},count:f[t],personExtensions:[],consideredDate:l,sex:t})?.persons||[]})))),g={[ni]:0,[ai]:0,[ii]:0},I=m.length,U=m.reduce(((t,e)=>{const n=e.person?.addresses?.[0]||{},{city:r,state:i,postalCode:a}=n;return t.cities.includes(r)||t.cities.push(r),t.states.includes(i)||t.states.push(i),t.postalCodes.includes(a)||t.postalCodes.push(a),t}),{cities:[],postalCodes:[],states:[]}),y=U.postalCodes.length,S=U.cities.length,v=U.states.length,{cities:w}=GR({count:S||I,participantsCount:I}),{states:P}=qR({count:v||I,participantsCount:I}),{postalCodes:D}=$R({count:y||I,participantsCount:I}),T={cities:w,states:P,postalCodes:D};m.forEach(((t,n)=>{const r=t?.person,a=r?.sex||ii,o=$i(r?.birthDate)?.split("-")[0],u=g[a],d=h[a][u];if(g[a]+=1,o){const[,t,e]=d?.birthDate?.split("-")||[],n=[o,t,e].join("-");d.birthDate=n}if(r?.addresses){const t=HR({...T,participantIndex:n,nationalityCode:d.nationalityCode});d.addresses=[t]}d.personId=i?.[n]||ha(),e?(d.standardFamilyName=d.lastName,d.standardGivenName=d.firstName,t.participantName=`${d.standardGivenName} ${d.standardFamilyName}`):(d.standardFamilyName=r?.standardFamilyName,d.standardGivenName=r?.standardGivenName),delete d.firstName,delete d.lastName,d.extensions=s(r),t.person=d,c[r?.personId]=d.personId}));(n.participants||[]).filter((({participantType:t})=>t===sp)).forEach((t=>{const{individualParticipantIds:e}=t;t.participantName=function({individualParticipantIds:t,individualParticipants:e}){let n=e.filter((({participantId:e})=>t.includes(e))).map((({person:t})=>t?.standardFamilyName)).filter(Boolean).sort().join("/");1===t.length&&(n+="/Unknown");return n}({individualParticipantIds:e,individualParticipants:m})}));const b=(n.participants||[]).filter((({participantType:t})=>t===cp)),R=JR({count:b.length}).names;b.forEach(((t,e)=>{t.participantName=R[e]}));const M=(n.participants||[]).filter((({participantType:t})=>t===op)),N=JR({count:M.length,nameRoot:"Group"}).names;M.forEach(((t,e)=>{t.participantName=N[e]}));const{extension:A}=zc({element:n,name:fu});Array.isArray(A?.value)&&A?.value.forEach((t=>{t.tournamentId=c[t.tournamentId],t.structureId=c[t.structureId],t.eventId=c[t.eventId],t.drawId=c[t.drawId]}));const{extension:E}=zc({element:n,name:uu});return Array.isArray(E?.value)&&E?.value.forEach((t=>{t.personId=c[t.personId]})),{...z}}function NM(t){const{ratingsParameters:e=hU,participantsProfile:n={},matchUpStatusProfile:r,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,schedulingProfile:c,tournamentRecord:u,autoSchedule:d,eventProfiles:p,periodLength:l,venueProfiles:m,drawProfiles:f,isMock:h,uuids:g}=t;if(!u)return{error:nt};const I=[],U=[],y=[];p?.forEach((t=>{const e=u.events?.find(((e,n)=>void 0!==t.eventIndex&&n===t.eventIndex||t.eventName&&e.eventName===t.eventName||t.eventId&&e.eventId===t.eventId));e?.gender&&(t.gender=e.gender)}));const S=u.participants?.length||void 0;S&&n?.idPrefix&&(n.idPrefix=`${n.idPrefix}-${S}`);const v=nM({startDate:u.startDate,participantsProfile:n,tournamentRecord:u,eventProfiles:p,drawProfiles:f,uuids:g});if(!v.success)return v;if(p){let t=u.events?.length||0;for(const e of p){const{ratingsParameters:o}=e,c=u.events?.find(((t,n)=>void 0!==e.eventIndex&&n===e.eventIndex||e.eventName&&t.eventName===e.eventName||e.eventId&&t.eventId===e.eventId));if(c){const{gender:t,category:d,eventType:p}=c,{drawProfiles:l,publish:m}=e,f=um(oo)(p)&&ap||um(co)(p)&&sp||p;if(l){const{stageParticipantsCount:m,uniqueParticipantsCount:U,uniqueParticipantStages:S}=rM({drawProfiles:l,category:d,gender:t}),{uniqueDrawParticipants:v=[],uniqueParticipantIds:w=[]}=S?lM({event:{eventType:p,category:d,gender:t},uniqueParticipantsCount:U,participantsProfile:n,ratingsParameters:o,tournamentRecord:u,eventProfile:e,uuids:g}):{};I.push(...w);const{stageParticipants:P}=iM({targetParticipants:u.participants||[],allUniqueParticipantIds:I,stageParticipantsCount:m,eventParticipantType:f});let D=fM({uniqueDrawParticipants:v,autoEntryPositions:a,stageParticipants:P,tournamentRecord:u,drawProfiles:l,category:d,gender:t,event:c});if(D.error)return D;if(D=pM({matchUpStatusProfile:r,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:l,isMock:h,event:c}),D.error)return D;y.push(...D.drawIds)}m&&tT({tournamentRecord:u,event:c})}else{const c=hM({startDate:u.startDate,allUniqueParticipantIds:I,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:i,autoEntryPositions:a,randomWinningSide:s,ratingsParameters:o,tournamentRecord:u,eventProfile:e,eventIndex:t,uuids:g});if(c.error)return c;const{eventId:d,drawIds:p,uniqueParticipantIds:l}=c;p&&y.push(...p),U.push(d),l?.length&&I.push(...l),t+=1}}}if(f){let t=(u.events||[]).map((t=>t.drawDefinitions?.map((()=>1))||[])).flat().reduce(((t,e)=>t+e),0);for(const c of f){let d=IM({startDate:u.startDate,allUniqueParticipantIds:I,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,ratingsParameters:e,tournamentRecord:u,drawProfile:c,drawIndex:t,uuids:g});if(d.error)return d;const{drawId:p,eventId:l,event:m,uniqueParticipantIds:f}=d;if(d=JD({tournamentRecord:u,event:m,internalUse:!0}),d.error)return d;p&&y.push(p),U.push(l),f?.length&&I.push(...f),t+=1}}const w=m?.length?TM({tournamentRecord:u,venueProfiles:m}):[];let P={};if(c?.length){const t=_P({tournamentRecords:{[u.tournamentId]:u},schedulingProfile:c});if(t.error)return t;if(d){const{tournamentId:t}=u;P=_R({tournamentRecords:{[t]:u},periodLength:l})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:undefined,schedulerResult:P,...z,eventIds:U,venueIds:w,drawIds:y}}var AM={__proto__:null,anonymizeTournamentRecord:MM,generate:{__proto__:null,generateEventWithDraw:IM,generateOutcome:oM,generateOutcomeFromScoreString:hR,generateParticipants:ZR,generateTournamentRecord:RM},generateEventWithDraw:IM,generateOutcome:oM,generateOutcomeFromScoreString:hR,generateParticipants:ZR,generateTournamentRecord:RM,modifyTournamentRecord:NM,mutate:{__proto__:null,anonymizeTournamentRecord:MM,modifyTournamentRecord:NM}};function EM(t=0){("number"!=typeof t||isNaN(t))&&(t=0);const e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function CM({personRequests:t,personId:e,requests:n}){t[e]||(t[e]=[]);const r=n.filter((({requestType:t})=>t)).map((t=>{let{date:e,startTime:n,endTime:r}=t;return t.requestType===SR&&(e=$i(e),n=qi(n),r=qi(r),e&&n&&r)?{date:e,startTime:n,endTime:r,requestType:t.requestType}:t})).filter(Boolean);for(const n of r)n.requestId=EM(),t[e].push(n);return{mergeCount:r.length}}function OM(t){const{tournamentRecords:e,personRequests:n}=t,r=cc(t,[{[ms]:!0}]);if(r.error)return r;if(!n)return{...z};const i=Object.values(e);for(const t of i){const e=t.participants??[],r=[];for(const t of Object.keys(n))if(Fc({tournamentParticipants:e,personId:t})){const e=n[t];e.length&&r.push({personId:t,requests:e})}if(Object.keys(r).length){_c({element:t,extension:{value:r,name:uu}})}}return{...z}}function FM(t){const{tournamentRecords:e,requests:n,personId:r}=t,i=cc(t,[{[ms]:!0},{requests:!0,[nc]:Zs,[ec]:Jn}]);if(i.error)return i;const a=n.map((({requestId:t})=>t)).filter(Boolean),{personRequests:o}=VP({tournamentRecords:e}),s=t=>{o&&(o[t]=o[t].map((t=>{if(!a.includes(t.requestId))return t;const e=n.find((e=>e.requestId===t.requestId));return e.requestType?Object.assign(t,e):void 0})).filter(Boolean))};if(r&&o?.[r])s(r);else if(o)for(const t of Object.keys(o))s(t);const c=n.filter((t=>!t.requestId));return c.length&&CM({personRequests:o,personId:r,requests:c}),OM({tournamentRecords:e,personRequests:o})}function kM(t){const{tournamentRecords:e,requestType:n,requestId:r,personId:i,date:a}=t,o=cc(t,[{[ms]:!0}]);if(o.error)return o;const{personRequests:s}=VP({tournamentRecords:e}),c=t=>{s&&(s[t]=s[t].filter((t=>!(n&&t.requestType===n||r&&t.requestId===r||a&&t.date===a))),s?.[t]?.length||delete s[t])},u=!(n||r||i||a);if(!u)if(i&&s?.[i])c(i);else if(s)for(const t of Object.keys(s))c(t);return!u&&s&&Object.keys(s).length?OM({tournamentRecords:e,personRequests:s}):kc({name:uu,tournamentRecords:e,discover:!0})}function xM(t){const{tournamentRecords:e,personId:n,requests:r}=t,i=cc(t,[{[ms]:!0,[_s]:!0},{requests:!0,[nc]:Zs,[ec]:Jn}]);if(i.error)return i;const{personRequests:a}=VP({tournamentRecords:e}),{mergeCount:o}=CM({personRequests:a,personId:n,requests:r});return o&&a?OM({tournamentRecords:e,personRequests:a}):{error:Jn}}function _M({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r="modifyIndividualParticipantIds";if(!n)return ti({result:{error:nt},stack:r});if(!e||!t)return ti({result:{error:be},stack:r});const i=n.participants||[],a=i.find((t=>t.participantId===e));if(!a)return ti({result:{error:en},stack:r});if(![cp,op].includes(a.participantType))return ti({result:{error:Ke},context:{participantType:a.participantType},stack:r});const o=t.filter((t=>{const e=i.find((e=>e.participantId===t));return e?.participantType!==ap}));if(o.length)return ti({result:{error:ze,invalidParticipantIds:o},stack:r});const s=a.individualParticipantIds||[],c=t.filter((t=>!s.includes(t))),u=s.filter((e=>!t.includes(e))),d=pb({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:n});if(d.error)return ti({result:d,stack:r});const p=Dh({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:n});if(p.error)return ti({result:p,stack:r});const{topics:l}=Lr();if(l.includes(bd)){const t=i.find((({participantId:t})=>t===e));Or({topic:bd,payload:{tournamentId:n.tournamentId,participants:[t]}})}return{...d,...p}}function LM({tournamentRecord:t,participantIds:e,signInState:n}){if(!t)return{error:nt};if(!Array.isArray(e))return{error:be};if(![rp,np].includes(n))return{error:Jn,signInState:n};const r=t.participants||[];if(!r.length)return{error:Ze};const i=r.map(Mu),a=e.filter((t=>!i.includes(t)));if(a.length)return{error:Jn,context:{invalidParticipantIds:a}};const o=[],s=(new Date).toISOString();for(const i of r){const{participantId:r}=i;if(e.includes(r)){const e=oy({duplicateValues:!1,tournamentRecord:t,participantId:r,timeItem:{itemType:ep,itemValue:n,createdAt:s}});if(e.error)return e;o.push(i)}}const{topics:c}=Lr();return o.length&&c.includes(bd)&&Or({topic:bd,payload:{tournamentId:t.tournamentId,participants:o}}),{...z}}function BM({tournamentRecord:t,participantId:e,participantOtherName:n}){if(!t)return{error:nt};if(!e)return{error:Xe};const{participant:r}=hp({tournamentRecord:t,participantId:e});if(!r)return{error:en};r.participantOtherName=n;const{topics:i}=Lr();return i.includes(bd)&&Or({topic:bd,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...z}}function VM({personFormat:t,person:e}){const n=t=>t.replace(/\W/g,""),r=t=>t.toLowerCase().indexOf("l")<t.toLowerCase().indexOf("f"),i=t=>t.indexOf(",")>=0;if(!e)return;const a=t.indexOf(" ")>0?" ":"";let o=kh(e?.standardGivenName??""),s=kh(e?.standardFamilyName??"");if(!t)return`${o}${a}${s}`;!(t=>t.toLowerCase().indexOf("f.")>=0)(t)||i(t)||r(t)||(o=`${o[0]}.`),(t=>/^[a-z]*$/.test(n(t)))(t)?(o=o.toLowerCase(),s=s.toLowerCase()):(t=>/^[A-Z]*$/.test(n(t)))(t)?(o=o.toUpperCase(),s=s.toUpperCase()):(t=>/^[LAST]{4}/.test(n(t)))(t)&&(s=s.toUpperCase());let c=`${o}${a}${s}`;return(t=>t.toLowerCase().indexOf("f")<0)(t)?c=s:r(t)&&(c=i(t)?`${s},${a}${o}`:`${s}${a}${o}`),c}function jM({participantMap:t,participant:e,formats:n}){const{participantType:r,individualParticipantIds:i,person:a}=e,o=r&&n[r];if(r!==ip&&o){const{personFormat:n,doublesJoiner:s}=o;r===ap&&(e.participantName=VM({person:a,personFormat:n})),r===sp&&(e.participantName=i?.map((e=>{const r=t[e]?.person;return VM({person:r,personFormat:n})})).filter(Boolean).join(s??"/"))}}function GM({tournamentRecord:t,formats:e}){if(!t)return{error:nt};if(!G(e))return{error:be};const n=t.participants??[],r=$(n,"participantId");for(const t of n)jM({participant:t,participantMap:r,formats:e});return{...z}}function qM(t){const{tournamentRecord:e,policyDefinitions:n,contextProfile:r,participantId:i,personId:a}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if("string"!=typeof i&&"string"!=typeof a)return{error:be,stack:"publicFindParticipant"};let s,c;for(const t of Object.values(o)){c=t.tournamentId;if(s=Fc({tournamentParticipants:t.participants||[],internalUse:!0,policyDefinitions:n,contextProfile:r,participantId:i,personId:a}),s)break}return{participant:s,tournamentId:c,...z}}function $M({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:n=vh,tournamentRecord:r,participantId:i,groupName:a}){if(!r)return{error:nt};if(!a)return{error:be,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:Jn};const o=(ih({participantFilters:{participantTypes:[ap]},tournamentRecord:r}).participants??[]).map((t=>t.participantId));for(const e of t)if(!o.includes(e))return{error:Ke,participantId:e};const s=Xr({participantId:i||ha(),participantRoleResponsibilities:e,participantName:a,individualParticipantIds:t,participantType:op,participantRole:n}),c=WD({participant:s,tournamentRecord:r});if(c.error)return c;const{topics:u}=Lr();return u.includes(ld)&&Or({topic:ld,payload:{tournamentId:r.tournamentId,participants:[s]}}),{...z,participant:la(s)}}function WM({tournamentRecord:t,participantName:e,participantId:n}){if(!t)return{error:nt};if(!n)return{error:Xe};if(!e)return{error:be,info:"Missing participantName"};const{participant:r}=hp({tournamentRecord:t,participantId:n});if(!r)return{error:en};r.participantName=e;const{topics:i}=Lr();return i.includes(bd)&&Or({topic:bd,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...z}}function HM({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:n,initialTeamIndex:r=0,scaledParticipants:i=[],teamParticipantIds:a,tournamentRecord:o,scaleAttributes:s,teamNameBase:c,teamsCount:u,eventId:d,event:p}){if(!o)return{error:nt};if(!Array.isArray(a)&&!y(u)&&!d||!y(r)||i&&!Array.isArray(i)||s&&("object"!=typeof s||!Object.keys(s).length))return{error:Jn};if(!s&&!i.length||!i&&(!e||!s))return{error:be,info:"Missing scaling details"};if(d&&!a){if(p?.eventType!==lo)return{error:qt};a=p?.entries?.filter((({entryStatus:t})=>t===Wp)).map(Mu)}if(!a?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:be};let l=e??i.map((({participantId:t})=>t));n&&(a?.reverse(),r+=1),r>(a?.length||0)-1&&(r=0);const m=a?.slice(r).concat(...a.slice(0,r))??[],f=[];for(const t of o.participants??[]){const{participantId:e,participantType:n}=t;if(m.includes(e)){if(n!==ip)return{error:Ke,participant:t};f.push(t)}}if(u&&f.length<u){const t=c??"Team",e=E(0,u-(f?.length||0)).map((e=>({participantName:`${t} ${e+1}`,participantType:ip,participantRole:Ih}))),{participants:n=[]}=HD({participants:e,returnParticipants:!0,tournamentRecord:o}),r=n.map(Mu),i=o.participants?.filter((({participantId:t})=>r.includes(t)))??[];f.push(...i)}if(!f.length)return{error:Xn};if(t)for(const t of f)t.individualParticipantIds=[];else{const t=f.map((t=>t)).flat();e?.length?l=l.filter((e=>!t.includes(e))):i=i?.filter((({participantId:e})=>!t.includes(e)))}if(!e?.length&&!i?.length)return{error:Wn,info:"Nothing to be done"};if(!i.length){for(const t of o.participants??[]){const{participantId:e,participantType:n}=t;if(!l.includes(e))continue;if(n!==ap)return{error:Ke,participant:t};const r=$f({scaleAttributes:s,participant:t})?.scaleItem,a={participantId:e,scaleValue:s?.accessor?r?.scaleValue?.[s?.accessor]:r?.scaleValue};i.push(a)}if(!i.length)return{error:en}}i.sort(((t,e)=>s?.sortOrder?(e?.scaleValue||0)-(t?.scaleValue||0):(t?.scaleValue||1/0)-(e?.scaleValue||1/0)));for(const t of i)if(!t.participantId)return{error:Jn,scaledParticipant:t};let h=0;for(;h<i.length;){for(const t of f){if(h+1>i.length)break;const e=i[h];t.individualParticipantIds.push(e.participantId),h++}f.reverse()}const g=f.map(Mu);for(const t of o.events??[]){if(t.eventType!==lo)continue;const e=(t.entries??[]).filter((t=>g.includes(t.participantId)));for(const n of e){const e=n.participantId,r=f.find((t=>t.participantId===e)),i=r?.individualParticipantIds;t.entries=(t.entries??[]).filter((t=>!i.includes(t.participantId))),(t.drawDefinitions??[]).forEach((t=>{t.entries=(t.entries??[]).filter((t=>!i.includes(t.participantId)))}));const{flightProfile:a}=jm({event:t});(a?.flights||[]).forEach((t=>{t.drawEntries=(t.drawEntries||[]).filter((t=>!i.includes(t.participantId)))}))}}return{...z,scaledParticipants:i}}function zM(t){const e=cc(t,[{[hs]:!0,[Es]:!0},{ratingType:!1,[Xs]:t=>hU[t]}]);if(e.error)return e;const n=`${t.ratingType}.${dc}`,r=t.asDynamic?n:t.ratingType,i=[mc,lc,t.eventType,r].join("."),a=t.tournamentRecord.participants??[];for(const t of a)t.timeItems&&(t.timeItems=t.timeItems.filter((t=>t.itemType!==i)));return{...z}}function YM(t){const{tournamentRecords:e}=t;if("object"!=typeof e||!Object.keys(e).length)return{error:et};for(const n of Object.values(e)){const e=KM({...t,tournamentRecord:n});if(e.error&&e.error!==Pn)return e}return{...z}}function KM({tournamentRecord:t,penaltyId:e}){if(!t)return{error:nt};if(!e)return{error:wn};const n=[];let r,i=!1;return(t?.participants??[]).forEach((t=>{let a=!1;t.penalties=(t.penalties??[]).filter((o=>(o.penaltyId===e&&(a=!0,i||(r=o,i=!0)),a&&n.push(t),o.penaltyId!==e)))})),r&&Or({topic:bd,payload:{tournamentId:t.tournamentId,participants:n}}),r?{...z,penalty:r}:{error:Pn}}const QM=({penaltyId:t=ha()}={})=>({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});function JM(t){const{tournamentRecords:e}=t;if("object"!=typeof e||!Object.keys(e).length)return{error:et};for(const n of Object.values(e)){const e=ZM({...t,tournamentRecord:n});if(e.error&&e.error!==Pn)return e;if(e.success)return e}return{error:Pn}}function ZM({tournamentRecord:t,modifications:e,penaltyId:n}){if(!t)return{error:nt};if(!e)return{error:Jn,modifications:e};if(!n)return{error:wn};const r=t?.participants??[],i=Object.keys(QM()).filter((t=>"penaltyId"!==t)),a=Object.keys(e).filter((t=>i.includes(t)));if(!a.length)return{error:er};let o;const s=[];return r.forEach((t=>{let r=!1;t.penalties=(t.penalties??[]).map((t=>(t.penaltyId===n&&(r=!0,a.forEach((n=>Object.assign(t,{[n]:e[n]}))),o||(o=t)),t))),r&&s.push(t)})),o&&Or({topic:bd,payload:{tournamentId:t.tournamentId,participants:s}}),o?{...z,penalty:o}:{error:Pn}}function XM(t,e,n){if(!t&&e)return e;if(t&&!e)return t;if("object"!=typeof t||"object"!=typeof e)return t;return w(Object.keys(t).concat(Object.keys(e))).reduce(((r,i)=>{if(e[i])if(t[i])if(typeof t[i]!=typeof e[i])r[i]=e[i];else if(Array.isArray(t[i]))if(!0===n||Array.isArray(n)&&n.includes(i)){const n=w(t[i].map((t=>JSON.stringify(t))).concat(e[i].map((t=>JSON.stringify(t))))).map((t=>JSON.parse(t)));r[i]=n}else r[i]=e[i];else"object"==typeof t[i]?r[i]=XM(t[i],e[i],n):r[i]=e[i];else r[i]=e[i];else r[i]=t[i];return r}),{})}function tN({participants:t=[],tournamentRecord:e,arraysToMerge:n}){if(!e)return{error:nt};e.participants||(e.participants=[]);const r=t.filter(If(Ss)).map((t=>({[t.participantId]:t}))),i=Object.assign({},...r),a=[];e.participants=e.participants.map((t=>{if(i[t.participantId]){const e=XM(t,i[t.participantId],n);return a.push(e),e}return t}));const o=e.participants.map(If(Ss))||[],s=t.filter((({participantId:t})=>!o.includes(t))),{topics:c}=Lr();return s.length&&(e.participants=e.participants.concat(...s),c.includes(ld)&&Or({topic:ld,payload:{participants:s}})),a.length&&c.includes(bd)&&Or({topic:bd,payload:{tournamentId:e.tournamentId,participants:a}}),{modifiedParticipantsCount:a.length,newParticipantsCount:s.length,...z}}function eN(t){const{tournamentRecord:e,participantIds:n}=t,r=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{};let i;for(const e of Object.values(r)){const r=ih({tournamentRecord:e}).participants??[],a=r?.map(Mu).filter((t=>n.includes(t)));if(a.length){i=nN({...t,penaltyId:t.penaltyId??i,tournamentRecord:e,participantIds:a}).penaltyId}}return i?{...z,penaltyId:i}:{error:en}}function nN({refereeParticipantId:t,tournamentRecord:e,participantIds:n,penaltyCode:r,penaltyType:i,extensions:a,penaltyId:o,matchUpId:s,issuedAt:c,notes:u}){if(!e)return{error:nt};if(!n)return{error:Xe};if(!i)return{error:vn};const d=(e?.participants??[]).filter((t=>n.includes(t.participantId)));if(!d.length)return{error:en};const p=(new Date).toISOString(),l=Object.assign(QM({penaltyId:o}),{refereeParticipantId:t,penaltyCode:r,penaltyType:i,matchUpId:s,createdAt:p,issuedAt:c,notes:u});return Array.isArray(a)&&a.forEach((t=>_c({element:l,extension:t}))),d.forEach((t=>{t.penalties||(t.penalties=[]),t.penalties.push(l)})),Or({topic:bd,payload:{tournamentId:e.tournamentId,participants:d}}),{...z,penaltyId:l.penaltyId}}function rN({participantRole:t=Ih,tournamentRecord:e,persons:n}){if(!e)return{error:nt};if(!Array.isArray(n))return{error:Jn};if(!Object.keys(Ph).includes(t))return{error:Ye};const r=(e.participants||[]).map((({person:t})=>t?.personId)).filter(Boolean),i=[],a=n.filter((t=>t&&(!t.personId||!r.includes(t.personId)))).map((t=>(t.personId||(t.personId=ha()),i.push(t.personId),t)));let o=0,s=0,c=HD({participants:a.map((e=>{return Xr({extensions:e.participantExtensions,timeItems:e.participantTimeItems,participantType:ap,participantRole:t,person:(n=e,r=["participantExtensions","participantTimeItems","pairedPersons"],Object.assign({},...Object.keys(n).filter((t=>!r.includes(t))).map((t=>({[t]:n[t]})))))});var n,r})),tournamentRecord:e});if(c.error)return c;s=c.addedCount||0;const u=[],d=ih({participantFilters:{participantTypes:[ap]},tournamentRecord:e})?.participants??[];if(t===Ih&&n.filter((({pairedPersons:t})=>t)).forEach((({personId:t,pairedPersons:e})=>{Array.isArray(e)&&e.forEach((e=>{const n=[t,e.personId].map((t=>Fc({tournamentParticipants:d,personId:t}))).filter(Boolean);if(2===n.length){const t=n.map(Mu);u.push(Xr({extensions:e.participantExtensions,timeItems:e.timeItems,participantRole:Ih,individualParticipantIds:t,participantType:sp}))}}))})),u.length){if(c=HD({participants:u,tournamentRecord:e}),c.error)return c;o=c.addedCount||0}const p=s+o;return{...z,addedCount:p,newPersonIds:i}}var iN={__proto__:null,addDynamicRatings:AS,addIndividualParticipantIds:pb,addParticipant:WD,addParticipants:HD,addPenalty:eN,addPersonRequests:xM,addPersons:rN,createGroupParticipant:$M,createTeamsFromParticipantAttributes:BR,deleteParticipants:Rh,filterParticipants:nh,findParticipant:qM,getCompetitionParticipants:Gw,getPairedParticipant:Wm,getParticipantEventDetails:qw,getParticipantMembership:$w,getParticipantScaleItem:ES,getParticipantSchedules:Ww,getParticipantSignInStatus:Hw,getParticipantTimeItem:vp,getParticipants:ih,getScaleValues:gc,mergeParticipants:tN,modifyIndividualParticipantIds:_M,modifyParticipant:lb,modifyParticipantName:WM,modifyParticipantOtherName:BM,modifyParticipantsSignInStatus:LM,modifyPenalty:JM,modifyPersonRequests:FM,mutate:{__proto__:null,addDynamicRatings:AS,addIndividualParticipantIds:pb,addParticipant:WD,addParticipants:HD,addPenalty:eN,addPersonRequests:xM,addPersons:rN,createGroupParticipant:$M,createTeamsFromParticipantAttributes:BR,deleteParticipants:Rh,findParticipant:qM,mergeParticipants:tN,modifyIndividualParticipantIds:_M,modifyParticipant:lb,modifyParticipantName:WM,modifyParticipantOtherName:BM,modifyParticipantsSignInStatus:LM,modifyPenalty:JM,modifyPersonRequests:FM,regenerateParticipantNames:GM,removeIndividualParticipantIds:Dh,removeParticipantIdsFromAllTeams:bh,removePenalty:YM,removePersonRequests:kM,removeRatings:zM,scaledTeamAssignment:HM,setParticipantScaleItem:bS,setParticipantScaleItems:RS},participantScaleItem:$f,query:zw,regenerateParticipantNames:GM,removeIndividualParticipantIds:Dh,removeParticipantIdsFromAllTeams:bh,removePenalty:YM,removePersonRequests:kM,removeRatings:zM,scaledTeamAssignment:HM,setParticipantScaleItem:bS,setParticipantScaleItems:RS,validateLineUp:dg};function aN({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:n,tournamentRecord:r,status:i=am,drawIds:a=[],event:o}){if(!r)return{error:nt};if(!o)return{error:$t};const s=Yf({event:o,status:i}),c=(s?.seeding?.seedingScaleNames||n)&&{...s?.seeding?.seedingScaleNames,...n};return XD({statusObject:{seeding:Xr({stageSeedingScaleNames:(s?.seeding?.stageSeedingScaleNames||e)&&{...s?.seeding?.stageSeedingScaleNames,...e},seedingScaleNames:c,published:!0,drawIds:a})},removePriorValues:t,status:i,event:o}),Or({topic:Od,payload:{tournamentId:r.tournamentId,eventId:o.eventId,drawIds:a}}),{...z}}function oN({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:n,status:r=am,drawIds:i,stages:a,event:o}){if(!n)return{error:nt};if(!o)return{error:$t};const s=Yf({event:o});if(s){const n=s.seeding;if(Array.isArray(a)&&n.stageSeedingScaleNames)for(const t of a)n.stageSeedingScaleNames[t]&&delete n.stageSeedingScaleNames[t];Array.isArray(e)&&n?.seedingScaleNames&&(n.seedingScaleNames=n.seedingScaleNames.filter((t=>!e.includes(t)))),Array.isArray(i)&&n?.drawIds&&(n.drawIds=n.drawIds.filter((t=>!i.includes(t)))),(Object.values(n.stageSeedingScaleNames??{}).length||n.seedingScaleNames?.length||n.drawIds?.length)&&(a||e||i?.length)||(delete n.stageSeedingScaleNames,delete n.seedingScaleNames,delete n.drawIds,n.published=!1),XD({statusObject:{seeding:n},removePriorValues:t,status:r,event:o})}return Or({topic:_d,payload:{tournamentId:n.tournamentId,eventId:o.eventId}}),{...z}}function sN(t){const e=tp(t);if(!Object.keys(e).length)return{error:et};for(const n of Object.values(e)){const e=cN({tournamentRecord:n,...t});if(e.error)return e}return{...z}}function cN({removePriorValues:t=!0,tournamentRecord:e,status:n=am}){if(!e)return{error:nt};const r=`${im}.${om}`,{timeItem:i}=Ip({element:e,itemType:r}),a=i?.itemValue||{[n]:{}};a[n]&&delete a[n].participants;return ay({timeItem:{itemValue:a,itemType:r},element:e,removePriorValues:t}),Or({payload:{tournamentId:e.tournamentId},topic:"unPublishParticipants"}),{...z}}function uN(t){const e=tp(t);if(!Object.keys(e).length)return{error:et};for(const n of Object.values(e)){const e=dN({tournamentRecord:n,...t});if(e.error)return e}return{...z}}function dN({removePriorValues:t=!0,tournamentRecord:e,status:n=am}){if(!e)return{error:nt};const r=`${im}.${om}`,{timeItem:i}=Ip({element:e,itemType:r}),a=i?.itemValue||{[n]:{}};a[n]&&delete a[n].orderOfPlay;return ay({timeItem:{itemValue:a,itemType:r},element:e,removePriorValues:t}),Or({topic:Ld,payload:{tournamentId:e.tournamentId}}),{...z}}function pN(t){const e=tp(t);if(!Object.keys(e).length)return{error:et};for(const n of Object.values(e)){const e=lN({tournamentRecord:n,...t});if(e.error)return e}return{...z}}function lN({removePriorValues:t,tournamentRecord:e,status:n=am}){if(!e)return{error:nt};const r=`${im}.${om}`,{timeItem:i}=Ip({element:e,itemType:r}),a=i?.itemValue||{[n]:{}};a[n].participants={published:!0};return ay({timeItem:{itemValue:a,itemType:r},element:e,removePriorValues:t}),Or({payload:{tournamentId:e.tournamentId},topic:kd}),{...z}}function mN(t){const e=tp(t);if(!Object.keys(e).length)return{error:et};for(const n of Object.values(e)){const e=fN({tournamentRecord:n,...t});if(e.error)return e}return{...z}}function fN({scheduledDates:t=[],removePriorValues:e,tournamentRecord:n,status:r=am,eventIds:i=[]}){if(!n)return{error:nt};const a=`${im}.${om}`,{timeItem:o}=Ip({element:n,itemType:a}),s=o?.itemValue||{[r]:{}};s[r].orderOfPlay={published:!0,scheduledDates:t,eventIds:i};return ay({timeItem:{itemValue:s,itemType:a},element:n,removePriorValues:e}),Or({topic:Fd,payload:{tournamentId:n.tournamentId,scheduledDates:t,eventIds:i}}),{...z}}function hN({removePriorValues:t=!0,tournamentRecord:e,status:n=am,event:r}){if(!e)return{error:nt};if(!r)return{error:$t};const i=`${im}.${om}`,{timeItem:a}=yp({itemType:i,event:r}),o=a?.itemValue||{[n]:{}};delete o[n].structureIds,delete o[n].drawDetails,delete o[n].drawIds;return cy({event:r,timeItem:{itemValue:o,itemType:i},removePriorValues:t}),XD({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:n,event:r}),Or({topic:xd,payload:{tournamentId:e.tournamentId,eventId:r.eventId}}),{eventId:r.eventId,...z}}var gN={__proto__:null,bulkUpdatePublishedEventIds:UP,getAllEventData:PP,getCourtInfo:Bm,getDrawData:RP,getEventData:MP,getEventPublishStatus:Yf,getPublishState:Qf,getTournamentPublishStatus:zf,getVenueData:Vm,mutate:{__proto__:null,publishEvent:tT,publishEventSeeding:aN,publishOrderOfPlay:mN,publishParticipants:pN,setEventDisplay:RT,unPublishEvent:hN,unPublishEventSeeding:oN,unPublishOrderOfPlay:uN,unPublishParticipants:sN},publishEvent:tT,publishEventSeeding:aN,publishOrderOfPlay:mN,publishParticipants:pN,query:NP,setEventDisplay:RT,unPublishEvent:hN,unPublishEventSeeding:oN,unPublishOrderOfPlay:uN,unPublishParticipants:sN};function IN({participant:t,eventType:e}){const n=t?.person?.personId,r=t?.person?.personOtherIds?.[0],i=t?.person?.tennisId,a=t?.ratings?.[e]?.find((({scaleName:t})=>t===mU)),o=a?.scaleValue,{wtnRating:s,confidence:c}=o||{};return{timeStamp:a?.scaleDate,personOtherId:r,confidence:c,wtnRating:s,personId:n,tennisId:i}}function UN({eventType:t,matchUps:e,eventId:n,drawId:r}){const i={},a=e.filter((t=>n?t.eventId===n:t.drawId===r)).reduce(((t,e)=>((t=>{const e=t?.matchUpFormat;e&&(i[e]||(i[e]=0),i[e]+=1)})(e),(e.sides??[]).flatMap((t=>(t?.participant?.individualParticipants||[t?.participant]).filter(Boolean))).forEach((e=>t[e.participantId]=e)),t)),{}),o=Object.values(a),s=o.map((e=>IN({participant:e,eventType:t}))).filter((({wtnRating:t})=>t)),c=(o.length-s.length)/o.length*100,u=s.reduce(((t,e)=>{const{wtnRating:n,confidence:r}=e;return t.totalWTN+=n,t.totalConfidence+=r,t}),{totalWTN:0,totalConfidence:0}),d=s?.length?u.totalWTN/s.length:0,p=s?.length?u.totalConfidence/s.length:0,l=Object.values(i).reduce(((t,e)=>t+(e||0)),0);return{matchUpFormatCounts:i,matchUpsCount:l,avgConfidence:p,pctNoRating:c,avgWTN:d}}var yN={__proto__:null,getEntryStatusReports:function({tournamentRecord:t}){if(!t)return{error:nt};const n=t.tournamentId,{participantMap:i}=ih({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),a=(pf({matchUpFilters:{matchUpTypes:[e,r]},tournamentRecord:t}).matchUps??[]).flatMap((({sides:t,matchUpType:e})=>t?.flatMap((t=>e===r?t?.participant?.individualParticipantIds:t?.participant?.participantId||t.participantId)).filter(Boolean))).filter(Boolean),o=[],s={},c={},u={};let d=0;const p=({id:t,entry:e,eventId:r,eventType:a})=>{const{qualifyingSeeding:c,mainSeeding:u,entryStatus:d,entryStage:p,drawId:l}=e;s[t]||(s[t]=[]);const{participant:m,events:f}=i?.[t]??{},h=IN({participant:m,eventType:a}),g=f?.[r]?.ranking;d===PI&&o.push(t),s[t].push({participantType:m?.participantType,participantId:t,tournamentId:n,eventType:a,eventId:r,drawId:l,entryStatus:d,entryStage:p,...h,ranking:g,mainSeeding:u,qualifyingSeeding:c})};for(const e of t.events??[]){const t={},r=e=>{t[e]||(t[e]={count:0}),t[e].count+=1},{drawDefinitions:o=[],eventType:s,eventId:l}=e,m=o.flatMap((t=>{const{drawId:e,entries:n}=t;d+=1;const a=(t.structures??[]).filter((({stage:t,stageSequence:e})=>t===fo&&1===e||t===ho)).flatMap((({positionAssignments:t})=>t)).filter(Boolean).map((({participantId:t})=>t));return n?.filter((({participantId:t})=>a.includes(t))).map((t=>{const{participantId:n,entryStatus:a,entryStage:o}=t;r(a);const s=i?.[n]?.draws?.[e]?.seedAssignments?.[fo],c=i?.[n]?.draws?.[e]?.seedAssignments?.[ho];return{qualifyingSeeding:c,participantId:n,mainSeeding:s,entryStatus:a,entryStage:o,drawId:e}}))})),f=t=>{const e=t.participantId,n=i?.[e].participant.individualParticipantIds?.filter((t=>a.includes(t)));return e&&{[e]:{individualParticipantIds:n}}};s===uo?(()=>{const t=Object.assign({},...m.map(f).filter(Boolean));m.forEach((e=>{t[e.participantId].individualParticipantIds.forEach((t=>{p({id:t,eventType:s,eventId:l,entry:e})}))}))})():m.forEach((t=>{p({id:t?.participantId,eventType:s,eventId:l,entry:t})}));const h=Object.values(t).reduce(((t,e)=>t+e.count),0);Object.keys(t).forEach((e=>{t[e].pct=t[e].count/h*100})),u[l]={tournamentId:n,eventId:l,entries:m,entryStatuses:t};const g=Object.assign({},...al.flatMap((e=>[{[e+"_count"]:t[e]?.count},{[e+"_pct"]:t[e]?.pct}])));c[l]={tournamentId:n,eventId:l,...g}}const l=Object.values(i??{}).filter((({participant:{participantType:t,participantRole:e}})=>t===ap&&e===Ih)),m=l.filter((({participant:t})=>!a.includes(t.participantId))).map((({participant:t})=>t.participantId)),f={nonParticipatingEntriesCount:m.length,individualParticipantsCount:l.length,eventsCount:Object.values(u).length,nonParticipatingParticipantIds:m,drawDefinitionsCount:d,tournamentId:n};return{entryStatusReports:Object.values(c).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(u).flat(),withDrawnParticipantIds:o,tournamentEntryReport:f}},getParticipantStats:function({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:n,teamParticipantId:r,tournamentRecord:i,withScaleValues:o,tallyPolicy:s,matchUps:c}){if(!i)return{error:nt};if(c&&!Array.isArray(c))return{error:he};if(c=c??pf({tournamentRecord:i,participantsProfile:o?{withScaleValues:o}:void 0}).matchUps,!c?.length)return{error:me};const u=[];e&&u.push(e),r&&u.push(r);const d=ih({participantFilters:u.length?{participantIds:u}:{participantTypes:[ip]},tournamentRecord:i}).participants??[];if(!d.every((({participantType:t})=>t===ip)))return{error:ze};u.length||u.push(...d.map(Mu));const p=new Map,l=new Map,m=new Map,f=new Map,h=(t,e="")=>l.get(t)||l.set(t,{participantName:e,participantId:t,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(t);for(const t of d){const{participantId:e,individualParticipantIds:n}=t;f.set(e,n??[]),h(e,t.participantName)}if(r&&!f.get(r))return ti({result:{error:en},context:{teamParticipantId:r}});if(e&&!f.get(e))return ti({result:{error:en},context:{opponentParticipantId:e}});const g=[],I=t=>{const i=[[],[]];for(const e of t){const t=e.participant;if(t?.participantName){p.set(t.participantId,{participantName:t.participantName,ratings:t.ratings});const e=l.get(t.participantId);e&&(e.participantName=t.participantName)}}const a=({side:t,individualParticipantIds:e})=>t.participantId&&(!e?.length||e.includes(t.participantId))&&[t.participantId]||t.participant?.individualParticipantIds?.length&&(!e?.length||O(e,t.participant?.individualParticipantIds).length===t.participant?.individualParticipantIds?.length)&&t.participant.individualParticipantIds;if(f.size){const o=(e,r)=>{for(const o of t){if(!o.participant)continue;const t=a({individualParticipantIds:r,side:o});if(t?.length){const r=o.sideNumber;if(!r)continue;const a=[e];n&&a.push(...t),i[r-1]=a;const s=l.get(e);for(const e of t.filter(Boolean))s&&!s.competitorIds.includes(e)&&s.competitorIds.push(e)}}};if(r){(!e||t.every((t=>t.participant&&(a({individualParticipantIds:f.get(r),side:t})||a({individualParticipantIds:f.get(e),side:t})))))&&o(r,f.get(r))}else for(const[t,e]of f)o(t,e)}else if(n)for(const e of t){if(!e.participant)continue;const t=a({individualParticipantIds:[],side:e}),n=e.sideNumber;n&&(i[n-1]=t)}return i};for(const e of c){if(!G(e))return{error:he};const{matchUpStatus:n,matchUpFormat:r,matchUpType:i,winningSide:o,score:c,sides:u}=e;if(!u||!c||i===a||n===Fu)continue;const d=I(u);if(!d.filter(Boolean).length)continue;const l=t&&o&&El({matchUp:e})?.competitiveness;g.push(e);const m=UU({matchUpStatus:n,matchUpFormat:r,tallyPolicy:s,winningSide:o,score:c}),f=yU({matchUpStatus:n,matchUpFormat:r,tallyPolicy:s,winningSide:o,score:c}),{pointsTally:U,tiebreaksTally:y}=SU({matchUpFormat:r,score:c});d.forEach(((t,e)=>{for(const r of t){const t=p.get(r)?.participantName,i=h(r,t);if(i){const t=(t,e)=>e.forEach(((e,n)=>i[t][n]+=e)),r=e?[...y].reverse():y,a=e?[...U].reverse():U,s=e?[...f].reverse():f,c=e?[...m].reverse():m;if(t("tiebreaks",r),t("points",a),t("games",s),t("sets",c),o){const t=o-1===e?0:1;i.matchUps[t]+=1}if(l){const t=l.toLowerCase();i.competitiveness[t]||(i.competitiveness[t]=[0,0]),i.competitiveness[t][e]+=1}if(n){const t=n.toLowerCase();i.matchUpStatuses[t]||(i.matchUpStatuses[t]=0),i.matchUpStatuses[t]+=1}}}}))}const U=["tiebreaks","matchUps","points","games","sets"],y=["competitive","routine","decisive"],S=new Map,v=(t,e)=>(t??0)+(e??0);for(const[t,e]of l.entries()){for(const n of U){const r=e[n].reduce(v);if(r){const i=e[n][0]/r,a=`${n}Ratio`,o=parseFloat(i.toFixed(2));e[a]=o,m.set(t,!0),S.has(a)||S.set(a,[]),S.get(a)?.push(o)}}for(const t of y){const n=e.competitiveness?.[t]?.reduce(v);if(n){const r=e.competitiveness[t][0]/n,i=`${t}Ratio`,a=parseFloat(r.toFixed(2));e[i]=a}}}if(!r){const t=(t,e)=>e-t;for(const e of l.values())for(const n of U){const r=`${n}Ratio`;if("number"==typeof e[r]){const i=S.get(r)?.sort(t).indexOf(e[r]);if("number"==typeof i&&i>=0){e[`${n}Rank`]=i+1}}}}const w={relevantMatchUps:g,...z};return r?(w.teamStats=l.get(r),e&&(w.opponentStats=l.get(e))):w.participatingTeamsCount=m.size,w.allParticipantStats=[...l.values()],w},getStructureReports:function(t){const{tournamentRecord:e,extensionProfiles:n,firstFlightOnly:r}=t;if(!e)return{error:it};const i=[],a={},o={},s=[],c=Object.assign({},...(n??[]).map((({name:t,label:n,accessor:r})=>{const i=zc({element:e,name:t})?.extension?.value,a=r?hf({element:i,accessor:r})?.value:i;return{[n||t]:a}}))),u=e?.tournamentId,d=pf({participantsProfile:{withScaleValues:!0},tournamentRecord:e}).matchUps??[],p=t=>{const e=Ip({itemType:md,itemSubTypes:[fc],element:{timeItems:t}})?.timeItem;return e?.itemValue?.scaleBasis},l=e?.events?.flatMap((({timeItems:t,drawDefinitions:e=[],extensions:n,eventType:s,eventName:l,eventId:m,category:f})=>{const h=n?.find((t=>t.name===ru)),g=h?.value?.flights?.map((t=>({[t.drawId]:t.flightNumber}))),I=g&&Object.assign({},...g),U=n?.find((t=>t.name===eu)),y=t?.find((t=>t.itemType===eu)),S=U?.value?.length||y?.itemValue||0,v=Object.values(I??{}),w=I&&Math.min(...v),P=p(t);return o[m]={seedingBasis:P?JSON.stringify(P):void 0,totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:S,tournamentId:u,eventId:m},e.filter((t=>!r||!g||I[t.drawId]===w)).flatMap((t=>{const{matchUpFormat:e,tieFormat:n,timeItems:r,extensions:h,structures:g,drawName:U,drawType:y,drawId:S}=t,{matchUpFormatCounts:v,matchUpsCount:w,avgConfidence:D,pctNoRating:T,avgWTN:b}=UN({eventType:s,matchUps:d,drawId:S}),R=p(r)||P,M=function({extensions:t}){return t?.find((({name:t})=>t===du))?.value?.slice(1)}({extensions:h}),N=M?.length||0;return(({positionManipulations:t})=>{t?.forEach((t=>{const{structureId:e,name:n}=t,r=t.drawPositions||[t.drawPosition];a[e]||(a[e]=[]),a[e].push(`${n}: ${r.join("/")}`)}))})({positionManipulations:M}),o[m].totalPositionManipulations+=N,o[m].generatedDrawsCount+=1,N>o[m].maxPositionManipulations&&(o[m].maxPositionManipulations=N),g?.filter((t=>1===t.stageSequence&&[ho,fo,go,Uo].includes(t.stage))).map((t=>{const r=[fo,Uo].includes(t.stage)?d.find((e=>e.structureId===t.structureId&&1===e.finishingRound&&e.winningSide)):void 0;t.stage===fo&&i.push({eventName:l,drawName:U,structureId:t.structureId});const a=r?.sides?.find((t=>t.sideNumber===r.winningSide)),o=a?.participant,p=o?.participantType===ip&&o.participantId,h=o?.participantType===sp?o.individualParticipants:[],g=IN({participant:h?.[0]||o,eventType:s}),{personId:P,personOtherId:N,tennisId:A,confidence:E,wtnRating:C}=g||{},O=IN({participant:h?.[1],eventType:s}),{personId:F,personOtherId:k,tennisId:x,confidence:_,wtnRating:L}=O||{},{ageCategoryCode:B,categoryName:V,subType:j}=f??{},G=t.matchUpFormat||e,q=(v[G]||0)/w*100,{tieFormatName:$,tieFormatDesc:W}=pP(n),{tieFormatName:H,tieFormatDesc:z}=pP(t.tieFormat),Y=W===z,K=!Y&&H,Q=t.tieFormat&&!Y&&z,J=M?.filter((e=>e.structureId===t.structureId))?.length||0;return{...c,tournamentId:u,eventId:m,structureId:t.structureId,drawId:S,eventType:s,category:j,categoryName:V,ageCategoryCode:B,flightNumber:I?.[S],drawType:y,stage:t.stage,seedingBasis:R?JSON.stringify(R):void 0,winningPersonId:P,winningPersonOtherId:N,winningPersonTennisId:A,winningPersonWTNrating:C,winningPersonWTNconfidence:E,winningPerson2Id:F,winningPerson2OtherId:k,winningPerson2TennisId:x,winningPerson2WTNrating:L,winningPerson2WTNconfidence:_,winningTeamId:p,positionManipulations:J,pctNoRating:T,matchUpFormat:G,pctInitialMatchUpFormat:q,matchUpsCount:w,drawTieFormatName:$,drawTieFormatDesc:W,tieFormatName:K,tieFormatDesc:Q,avgConfidence:D,avgWTN:b}}))}))}));return i.forEach((({eventName:t,drawName:e,structureId:n})=>{a[n]?.length&&s.push({eventName:t,drawName:e,actions:a[n]})})),{eventStructureReports:Object.values(o),structureReports:l,flightReports:s}},getVenuesReport:function({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:n,venueIds:r=[],dates:i=[]}){if(!Array.isArray(i))return{error:Jn,dates:i};if(!Array.isArray(r))return{error:Jn,venueIds:r};if(!(e&&Object.keys(e).filter((t=>!n||t===n))||[]).length)return{error:et};if(!i.every(Ci))return{error:Oe};const a=vP({tournamentRecords:e,ignoreDisabled:t,dates:i});if(a.error)return a;const o=a?.venues?.filter((({venueId:t})=>!r?.length||r.includes(t))),s=a.courts?.reduce(((t,e)=>(e.dateAvailability?.forEach((e=>{const n=e.date;t.includes(n)||t.push(n)})),t)),[]).filter((t=>!i.length||i.includes(t))),c={venueIds:o?.map((({venueId:t})=>t))},{matchUps:u}=lf({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:c}),d=o?.map((t=>function(t,e,n){const{venueId:r,courts:i,venueName:a}=e,o={};return t.forEach((t=>{let e=0,a=0,s=0;for(const n of i){const r=n.dateAvailability.find((e=>e.date===t)),i=r&&zT({courtDate:r}).timeSlots,a=i?.reduce(((t,e)=>{const{startTime:n,endTime:r}=e;return t+(ji(r)-ji(n))}),0);a&&(s+=1),e+=a}const c=n.filter((({schedule:e})=>e.venueId===r&&ea(t,e.scheduledDate)));c.forEach((({schedule:t})=>{const e=qi(t.scheduledTime),n=ji(Zi(e,t.averageMinutes))-ji(e);a+=n}));const u=e?(a/e*100).toFixed(2):"100";o[t]={scheduledMatchUpsCount:c.length,availableCourts:s,availableMinutes:e,scheduledMinutes:a,percentUtilization:u}})),{venueId:r,venueName:a,venueReport:o}}(s,t,u)));return{venuesReport:d}}};function SN({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:n=90,remainingScheduleTimes:r,clearScheduleDates:i,tournamentRecords:a,periodLength:o,scheduleDate:s,startTime:c,venueIds:u,endTime:d}){if("object"!=typeof a||!Object.keys(a).length)return{error:et};o=o??QT({recoveryMinutes:e,averageMatchUpMinutes:n});const{courts:p,venues:l}=vP({dates:[s],ignoreDisabled:!0,tournamentRecords:a}),m=p?.filter((t=>!u||u.includes(t.venueId)));c||(c=m?.reduce(((t,e)=>{const n=e.dateAvailability?.find((t=>!t.date||ea(s,t.date))),r=n?.startTime??e.startTime;return r&&(!t||ji(r)<ji(t))?r:t}),void 0)),d||(d=m?.reduce(((t,e)=>{const n=e.dateAvailability?.find((t=>!t.date||ea(s,t.date))),r=n?.endTime??e.endTime;return r&&(!t||ji(r)>ji(t))?r:t}),void 0));const f=Object.values(a),h=Object.assign({},...f.map((t=>(t.events??[]).map((e=>{const{scheduleTiming:n}=Vp({tournamentRecord:t,event:e});return{[e.eventId]:{event:e,scheduleTiming:n}}})))).flat()),g=pD({sortDateMatchUps:!1,tournamentRecords:a,matchUpFilters:{scheduledDate:s,venueIds:u}}),I=g?.dateMatchUps??[],U=g?.completedMatchUps??[],y=[];y.push(...I),y.push(...U);const S={averageTimes:[{minutes:{default:n}}],recoveryTimes:[{minutes:{default:e}}]},v=y?.map((({eventId:t,schedule:e,matchUpFormat:n})=>{const{event:r,scheduleTiming:i}=h[t],a=r?.eventType,s={...i,defaultTiming:S,matchUpFormat:n},{averageMinutes:c,recoveryMinutes:u}=bm({eventType:a,timingDetails:s}),{courtId:d,venueId:p}=e,l=qi(e.scheduledTime),m=Zi(l,c);return{recoveryMinutes:u,averageMinutes:c,periodLength:o,startTime:l,endTime:m,courtId:d,venueId:p}})),w={calculateStartTimeFromCourts:t,remainingScheduleTimes:r,averageMatchUpMinutes:n,date:s,clearScheduleDates:i,periodLength:o,startTime:c,endTime:d,bookings:v,courts:m},{scheduleTimes:P}=XT(w);return{venueId:1===u?.length&&u[0]||1===l?.length&&l[0].venueId||void 0,scheduleTimes:P,dateScheduledMatchUpIds:y.map(Nu)}}function vN(t){const e=cc(t,[{[ms]:!0}]);if(e.error)return e;const{removePriorValues:n,tournamentRecords:r,tournamentId:i,courtDayDate:o,matchUpId:s,courtId:c,drawId:u}=t,d=r[i];if(!d)return{error:nt};const{drawDefinition:p,event:l}=Ey({tournamentRecord:d,drawId:u});if(!p)return{error:ot};const m=GU({drawDefinition:p,event:l,matchUpId:s});if(m.error)return m;if(m?.matchUp?.matchUpType===a){const{itemValue:t}=Mm({timeItems:m.matchUp.timeItems??[],itemType:xl}),e=c&&t.filter((t=>t.courtId!==c));return ib({duplicateValues:!1,removePriorValues:n,tournamentRecord:d,drawDefinition:p,matchUpId:s,timeItem:{itemType:xl,itemValue:e}})}return jb({tournamentRecord:d,drawDefinition:p,courtDayDate:o,courtId:"",matchUpId:s})}function wN({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:n,matchUps:r}){if(!yl(r))return{error:Jn};if(r.some((({hasContext:t})=>!t)))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Bn};let i=pD({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:n}});if(i.error)return i;const{rows:a}=i,o=[],s=t=>[(t.sides||[]).map((t=>[t.participantId,t.participant?.individualParticipantIds])),(t.potentialParticipants||[]).flat().map((t=>[t.participantId,t.individualParticipantIds]))].flat(1/0).filter(Boolean),c=a?.reduce(((t,e)=>{const n=[],r=[];Object.values(e).forEach((t=>{if(G(t)&&(t.matchUpId&&(n.push(t.matchUpId),o.push(t)),t.sides)){const e=s(t);r.push(...e)}}));const i=Object.values(e).filter((t=>G(t)&&!t.matchUpId));return t.concat({matchUpIds:n,availableCourts:i,rowId:e.rowId,participantIds:r})}),[]);r.filter((({matchUpStatus:e})=>e&&e!==Fu&&(t||!Xu.includes(e)))).sort(mf);const u=Sf({matchUps:r.concat(o),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,d=[],p=[];for(;r.length&&c.length;){const t=c.shift(),e=[];for(;r.length&&t.availableCourts.length;){const n=r.concat(e).map((t=>t.matchUpId)),i=r.shift(),a=i?.matchUpId,o=a&&u[a].matchUpIds.concat(u[a].dependentMatchUpIds),c=a&&n.some((t=>u[a].matchUpIds.includes(t))),l=a&&p.some((t=>u[a].dependentMatchUpIds.includes(t))),m=t.matchUpIds.some((t=>o.includes(t))),f=s(i),h=t.participantIds.some((t=>f.includes(t)));if(!i||m||c||h||l)i&&e.push(i);else{const e=t.availableCourts.shift();Object.assign(i.schedule,e.schedule),Object.assign(e,i),d.push(i),t.participantIds.push(...f),t.matchUpIds.push(a)}}r.push(...e),p.push(...t.matchUpIds)}const l=d.map((({matchUpId:t,tournamentId:e,schedule:r,drawId:i})=>({tournamentId:e,matchUpId:t,drawId:i,schedule:{...r,scheduledDate:n}})));i=OR({tournamentRecords:e,matchUpDetails:l});const m=r;return{...i,scheduled:d,notScheduled:m}}function PN(t){const{courtDayDate:e}=t,n=cc(t,[{courtAssignments:!0,[nc]:Zs,[ec]:be},{[ms]:!0}]);if(n.error)return n;const r=t.courtAssignments.reduce(((t,e)=>{const{tournamentId:n}=e;return t[n]||(t[n]=[]),t[n].push(e),t}),{});let i;return Object.keys(r).every((n=>{const a=t[ms][n];if(!a)return i={error:nt},!1;const o=r[n].reduce(((t,e)=>{const{drawId:n}=e;return t[n]||(t[n]=[]),t[n].push(e),t}),{});Object.keys(o).every((t=>{const{drawDefinition:n}=Gm({tournamentRecord:a,drawId:t});return n?(o[t].every((t=>{const{matchUpId:r,courtId:o}=t,s=jb({tournamentRecord:a,drawDefinition:n,courtDayDate:e,matchUpId:r,courtId:o});if(s.success)return s?.success;i={error:$n}})),!0):(i={error:ot},!1)}))})),i||z}function DN(t){const{tournamentRecords:e,allDateMatchUpIds:n=[],averageMatchUpMinutes:r=90,recoveryMinutes:i=0,recoveryMinutesMap:a,matchUpPotentialParticipantIds:o={},individualParticipantProfiles:s={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:d=!0,remainingScheduleTimes:p,clearScheduleDates:l,periodLength:m=30,scheduleDate:f,matchUpIds:h,venueIds:g,startTime:I,endTime:U,dryRun:y}=t,S=cc(t,[{[ms]:!0,[Rs]:!0},{[Xs]:Ci,[ec]:Oe,[Ps]:!0},{[Xs]:t=>!t||!isNaN(t),[Ys]:!1,[ec]:Jn,[Ks]:!1,[Qs]:!1}]);if(S.error)return S;const v=t.competitionMatchUps??lf({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],w=t.matchUpDependencies??Sf({includeParticipantDependencies:!0,matchUps:v,tournamentRecords:e}).matchUpDependencies;v.forEach((t=>{t.schedule?.scheduledDate&&ea(f,$i(t.schedule.scheduledDate))&&AP({matchUpPotentialParticipantIds:o,matchUpNotBeforeTimes:c,matchUp:t})}));const P=h.map((t=>v.find((e=>e.matchUpId===t)))).filter(Boolean),{venueId:D,scheduleTimes:T,dateScheduledMatchUpIds:b}=SN({tournamentRecords:e,remainingScheduleTimes:p,startTime:qi(I),endTime:qi(U),scheduleDate:$i(f),averageMatchUpMinutes:r,clearScheduleDates:l,periodLength:m,venueIds:g}),R={},M=[],N={},A={},E={},C=v.filter((({matchUpId:t})=>b?.includes(t)));C.forEach((t=>{PR({matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUp:t,value:1});const e=t.schedule?.scheduledTime;if(e){N[t.matchUpId]=e;const n=a?.[t.matchUpId];UR({recoveryMinutes:n||i,matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:r,matchUpDependencies:w,scheduleTime:e,matchUp:t})}}));let O=P.filter((t=>{const e=b?.includes(t.matchUpId),n=[Fu,Lu,xu,Cu,$u,zu].includes(t?.matchUpStatus);return!e&&!t.winningSide&&!n}));const{matchUpMap:F,overLimitMatchUpIds:k,participantIdsAtLimit:x}=O.reduce(((t,e)=>{const{drawId:n,tournamentId:r,matchUpType:i}=e,{participantIdsAtLimit:a,relevantParticipantIds:d}=ER({individualParticipantProfiles:s,matchUpPotentialParticipantIds:o,matchUpDailyLimits:u,matchUp:e});return a?.length?(t.overLimitMatchUpIds.push(e.matchUpId),t.participantIdsAtLimit.push(...a),t):(d.forEach((t=>{IR({individualParticipantProfiles:s,participantId:t});const e=s[t].counters;e[i]?e[i]+=1:e[i]=1,e[hm]?e[hm]+=1:e[hm]=1})),t.matchUpMap[r]||(t.matchUpMap[r]={}),t.matchUpMap[r][n]?t.matchUpMap[r][n].push(e):t.matchUpMap[r][n]=[e],AP({matchUpPotentialParticipantIds:o,matchUpNotBeforeTimes:c,matchUp:e}),t)}),{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});O=O.filter((({matchUpId:t})=>!k.includes(t)));let _=0;const L=T?.length??0,{personRequests:B}=VP({tournamentRecords:e,requestType:SR});for(;T?.length&&O.length&&_<=L;){_++;const{scheduleTime:t}=T.shift(),e=O.find((e=>{const{matchUpId:u}=e,{dependenciesScheduled:p,remainingDependencies:l}=gR({matchUpScheduleTimes:N,matchUpDependencies:w,allDateMatchUpIds:n,matchUp:e});if(!p)return E[u]||(E[u]=[]),E[u].push({scheduleTime:t,remainingDependencies:l}),!1;const{enoughTime:m}=NR({individualParticipantProfiles:s,matchUpNotBeforeTimes:c,matchUpDependencies:w,scheduleTime:t,matchUp:e});if(!m)return A[u]||(A[u]=[]),A[u].push({scheduleTime:t}),!1;const{conflicts:h}=wR({potentials:d,averageMatchUpMinutes:r,requestConflicts:R,personRequests:B,scheduleTime:t,scheduleDate:f,matchUp:e});if(h?.length)return!1;const g=a?.[e.matchUpId];return UR({recoveryMinutes:g||i,matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:r,matchUpDependencies:w,scheduleTime:t,matchUp:e}),N[e.matchUpId]=t,!0}));O=O.filter((({matchUpId:t})=>t!==e?.matchUpId)),e||M.push(t)}O.forEach((t=>{PR({individualParticipantProfiles:s,matchUpPotentialParticipantIds:o,value:-1,matchUp:t})}));const V=[];Object.keys(F).forEach((t=>{const n=e[t];n&&Object.keys(F[t]).forEach((r=>{const{drawDefinition:i}=Ey({tournamentRecord:n,drawId:r});if(i){F[t][r].forEach((({matchUpId:t})=>{const r=N[t];if(r){const a=r.split(":").map(ta).join(":"),o=`${$i(f)}T${a}`;if(y)V.push(t);else{xb({drawDefinition:i,matchUpId:t,scheduledTime:o}).success&&V.push(t),D&&Vb({tournamentRecords:e,tournamentRecord:n,drawDefinition:i,matchUpId:t,venueId:D})}}}))}}))}));const j=bu(O);return{...z,requestConflicts:Object.values(R),remainingScheduleTimes:T?.map((({scheduleTime:t})=>t)),individualParticipantProfiles:s,matchUpNotBeforeTimes:c,participantIdsAtLimit:x,skippedScheduleTimes:M,overLimitMatchUpIds:k,scheduledMatchUpIds:V,noTimeMatchUpIds:j,recoveryTimeDeferred:A,dependencyDeferred:E}}function TN({tournamentRecords:t,matchUps:e}){if(!yl(e))return{error:me};if(e.some((({matchUpId:t,hasContext:e})=>t&&!e)))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Bn};const n=E(1,Math.max(...e.map((({schedule:t})=>t?.courtOrder||1)).map((t=>d(t))))+1).map((t=>e.filter((e=>d(e.schedule?.courtOrder)===t)))),r={},i={},a={};n.flat().filter(Boolean).sort(mf).forEach((({schedule:t})=>delete t[Pm]));const o=Sf({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:w(e.map((({drawId:t})=>t)))}).matchUpDependencies,s=n.map(((t,e)=>t.reduce(((t,n)=>{if(!n.matchUpId)return t;const{matchUpId:s,winnerMatchUpId:c,loserMatchUpId:u,schedule:d,sides:p,potentialParticipants:l}=n,m=d?.courtId;r[s]=e,i[m]=[],t.matchUpIds.push(s),a[s]=n;const f=o[s].matchUpIds;f.length&&t.sourceMatchUpIds.push(...f);const h=p?.map((t=>[t.participant?.individualParticipantIds,t.participantId])).flat().filter(Boolean)??[],g=l?.flat().map((({individualParticipantIds:t,participantId:e})=>[t,e])).flat().filter(Boolean)||[];return t.participantIds.push(...g,...h),c&&t.targetMatchUpIds.push(c),u&&t.targetMatchUpIds.push(u),t}),{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]}))),c=s.map((()=>[])),u=(t,e,n,o)=>{if(!a[t].schedule[Pm]){a[t].schedule[Pm]=e,a[t].schedule[Um]=o,c[r[t]].push({matchUpId:t,issueType:n,issueIds:o,issue:e});const s=a[t].schedule.courtId;i[s]||(i[s]=[]),i[s].push({matchUpId:t,issue:e,issueType:n,issueIds:o})}};return s.forEach(((t,e)=>{const n=e?s[e-1]:void 0,r=s.slice(e+1),i={},c=T(t.participantIds),d=Object.keys(c).filter((t=>c[t]>1)),p=t.matchUpIds.filter((t=>o[t].participantIds.some((t=>d.includes(t)))));p.forEach((t=>{i[t]||(i[t]={}),i[t][ym]||(i[t][ym]=p.filter((e=>e!==t)))}));const l=n&&t.participantIds.filter((t=>n.participantIds.includes(t)));l&&l.forEach((e=>{const r=t.matchUpIds.concat(n.matchUpIds).filter((t=>o[t].participantIds.includes(e)));r.forEach((t=>{i[t]||(i[t]={}),i[t][Sm]||(i[t][Sm]=r.filter((e=>e!==t)))}))})),t.matchUpIds.forEach((e=>{const s=o[e].matchUpIds;for(const t of r){const n=t.matchUpIds.filter((t=>s.includes(t)));n?.length&&(n.forEach((t=>u(t,vm,Im,[e]))),u(e,vm,Im,n))}if(i[e]?.[ym]&&u(e,ym,gm,i[e][ym]),t.sourceMatchUpIds.includes(e)){const n=t.matchUpIds.filter((t=>o[t].matchUpIds.includes(e)));u(e,ym,Im,n),t.matchUpIds.filter((t=>o[t].matchUpIds.includes(e))).forEach((t=>u(t,ym,Im,[e])))}const c=n?.matchUpIds?.filter((t=>{return n=t,o[e].sources.reduce(((t,e,r)=>e.includes(n)&&r+1||t),0)>1;var n}));if(c?.length&&(u(e,wm,Im,c),c.forEach((t=>u(t,wm,Im,[e])))),i[e]?.[Sm]&&u(e,Sm,gm,i[e][Sm]),n?.targetMatchUpIds?.includes(e)){const t=a[e].schedule.courtId,r=s.filter((t=>n.matchUpIds.includes(t)));r.some((e=>a[e].schedule.courtId===t))||(r.forEach((t=>u(t,Sm,Im,[e]))),u(e,Sm,Im,r))}}))})),{courtIssues:i,rowIssues:c}}function bN(t){const e="reorderUpcomingMatchUps",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return ti({result:{error:et},stack:e});const{matchUpsContextIds:r,firstToLast:i}=t;if(!r)return ti({result:{error:be},stack:e});const a=r?.length;if(!a)return{...z};let o=0;return r.forEach(((t,e)=>{const{tournamentId:s,drawId:c,matchUpId:u}=t;let d=e+(i?-1:1);d<0&&(d=a-1),d===a&&(d=0);const p=function({tournamentId:t,scheduledTime:e,matchUpId:r,drawId:i}){const a=n[t],{drawDefinition:o}=Ey({tournamentRecord:a,drawId:i});return o?xb({drawDefinition:o,scheduledTime:e,matchUpId:r}):{error:ct}}({tournamentId:s,scheduledTime:r[d].schedule.scheduledTime,matchUpId:u,drawId:c});if(!p.success)return p;o++})),o===a?z:ti({result:{error:Gn},stack:e})}function RN(t){const{scheduleChange:e,matchUpIds:n,dryRun:r}=t;if(!n||!Array.isArray(n))return{error:pe};if("object"!=typeof e)return{error:Jn};const i=tp(t),a=[];let o=[];for(const t of Object.values(i)){const i=MN({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r});if(i.error)return i;Array.isArray(i.notRescheduled)&&o.push(...i.notRescheduled);const s=bu(i.notRescheduled),c=[];i.rescheduled?.forEach((t=>{const{matchUpId:e}=t;s.includes(e)&&c.push(e),a.push(t)})),c.length&&(o=i?.notRescheduled?.filter((({matchUpId:t})=>!c.includes(t)))||[])}const s=!(!a.length||o.length);return{...z,rescheduled:a,notRescheduled:o,allRescheduled:s}}function MN({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r}){if(!t)return{error:nt};if(!n||!Array.isArray(n))return{error:pe};if("object"!=typeof e)return{error:Jn};const i=[],a=[],{minutesChange:o,daysChange:s}=e;if(!o&&!s)return{...z};if(o&&isNaN(o))return{error:Jn};if(s&&isNaN(s))return{error:Jn};const{matchUps:c}=pf({matchUpFilters:{matchUpIds:n},tournamentRecord:t}),u=c?.filter((t=>aD({schedule:t.schedule}))).filter((t=>(({matchUpStatus:t})=>!Xu.includes(t))({matchUpStatus:t.matchUpStatus})));if(!u?.length)return{...z};const{tournamentInfo:d}=tP({tournamentRecord:t}),{startDate:p,endDate:l}=d,m=u?.reduce(((t,e)=>{const{matchUpId:n,drawId:r}=e;return t[r]?t[r].push(n):t[r]=[n],t}),{});for(const e of Object.keys(m)){const c=Ey({tournamentRecord:t,drawId:e});if(c.error)return c;const d=c.drawDefinition,f=m[e].filter((t=>n.includes(t)));for(const t of f)if(t&&d){const e=u.find((e=>e.matchUpId===t)),n=e?.schedule,{scheduledTime:c,scheduledDate:m}=n;let f,h,g;if(!f&&s&&m){g=Wi($i(m),s),f=new Date(g)<new Date(p)||new Date(g)>new Date(l)}if(o&&c){const t=$i(c),e=ji(qi(c))+o;if(f=e<0||e>1440,!f){const e=Zi(c,o),n=t&&g||m===t&&t;h=n?`${n}T${e}`:e}}if(f)a.push(t);else{if(!r){if(h){const e=xb({scheduledTime:h,drawDefinition:d,matchUpId:t});if(e.error)return e}if(g){const e=Lb({scheduledDate:g,drawDefinition:d,matchUpId:t});if(e.error)return e}}(h||g)&&i.push(t)}}}const f=pf({matchUpFilters:{matchUpIds:n},tournamentRecord:t}).matchUps??[],h=f.filter((({matchUpId:t})=>i.includes(t))),g=f.filter((({matchUpId:t})=>a.includes(t))),I=h.length&&!g.length;return{...z,rescheduled:h,notRescheduled:g,allRescheduled:I}}function NN(t){const e="matchUpScheduleChange",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return{error:et};const{sourceMatchUpContextIds:r,targetMatchUpContextIds:i,sourceCourtId:a,targetCourtId:s,courtDayDate:c}=t||{},{drawId:u,matchUpId:d,tournamentId:p}=r||{},{drawId:l,matchUpId:m,tournamentId:f}=i||{};if(!d&&!m)return ti({result:{error:be},stack:e});const{matchUps:h}=lf({matchUpFilters:{matchUpIds:[d,m].filter(Boolean),drawIds:[u,l].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=h?.find((({matchUpId:t})=>t===d)),I=h?.find((({matchUpId:t})=>t===m));let U=0;if(s&&d&&!m){const t=y({tournamentId:p,matchUpId:d,courtId:s,matchUp:g,drawId:u,tournamentRecords:n,sourceCourtId:a,courtDayDate:c});if(t?.success&&U++,t.error)return ti({result:t,stack:e})}else{if(!(a&&s&&d&&m))return{error:be};{const t=y({tournamentId:p,matchUpId:d,courtId:s,matchUp:g,drawId:u,tournamentRecords:n,sourceCourtId:a,courtDayDate:c});if(t.success&&U++,t.error)return ti({result:t,stack:e,info:"source"});const r=y({tournamentId:f,sourceCourtId:s,matchUpId:m,matchUp:I,courtId:a,drawId:l,tournamentRecords:n,courtDayDate:c});if(r.success&&U++,r.error)return ti({result:r,stack:e,info:"target"})}}return U?z:ti({result:{error:qn},stack:e});function y(t){const{tournamentRecords:e,tournamentId:n,matchUp:r,drawId:i}=t,a=e[n],{drawDefinition:s}=Ey({tournamentRecord:a,drawId:i});return r.matchUpType===o?function({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,sourceCourtId:i,courtDayDate:a,matchUpId:o,matchUp:s,courtId:c}){const u=[c].concat(s.schedule.allocatedCourts.map((({courtId:t})=>t)).filter((t=>t!==i)));return Bb({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,courtDayDate:a,matchUpId:o,courtIds:u})}({...t,tournamentRecord:a,drawDefinition:s}):jb({...t,tournamentRecord:a,drawDefinition:s})}}function AN({scheduleAttributes:t=[xl,_l,kl,Bl,Gl,ql,Hl,Wl,$l],tournamentRecord:e,drawDefinition:n,matchUpId:r}){const i=n?ff({matchUpFilters:{matchUpIds:[r]},inContext:!1,drawDefinition:n}).matchUps?.[0]:pf({matchUpFilters:{matchUpIds:[r]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:le};const a=(i.timeItems??[]).filter((e=>e?.itemType&&!t.includes(e?.itemType)));return i.timeItems=a,$d({tournamentId:e.tournamentId,context:"clearMatchUpSchedule",drawDefinition:n,matchUp:i}),{...z}}function EN(t){const{tournamentRecord:e,tournamentId:n,dailyLimits:r}=t,i=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if("object"!=typeof i||!Object.keys(i).length)return{error:et};if("object"!=typeof r)return{error:Yn};const a=Object.keys(i).filter((t=>!n||n===t));if(n&&!a.includes(n))return{error:Jn};for(const t of a){const e=i[t],n=_c({extension:{name:lu,value:{dailyLimits:r}},element:e});if(n.error)return n}return{...z}}var CN={__proto__:null,addMatchUpCourtOrder:$b,addMatchUpEndTime:zb,addMatchUpOfficial:Wb,addMatchUpResumeTime:Kb,addMatchUpScheduleItems:qb,addMatchUpScheduledDate:Lb,addMatchUpScheduledTime:xb,addMatchUpStartTime:Hb,addMatchUpStopTime:Yb,addSchedulingProfileRound:gM,allocateTeamMatchUpCourts:Bb,assignMatchUpCourt:jb,assignMatchUpVenue:Vb,bulkRescheduleMatchUps:RN,bulkScheduleMatchUps:OR,bulkScheduleTournamentMatchUps:CR,bulkUpdateCourtAssignments:PN,calculateScheduleTimes:SN,clearMatchUpSchedule:AN,clearScheduledMatchUps:kR,courtGridRows:WP,findMatchUpFormatTiming:CP,findVenue:km,generateBookings:TR,generateVirtualCourts:KT,getMatchUpsToSchedule:EP,getPersonRequests:VP,getProfileRounds:$P,getScheduledRoundsDetails:OP,getSchedulingProfile:xP,getSchedulingProfileIssues:BP,matchUpScheduleChange:NN,modifyMatchUpFormatTiming:sT,mutate:{__proto__:null,addMatchUpCourtOrder:$b,addMatchUpEndTime:zb,addMatchUpOfficial:Wb,addMatchUpResumeTime:Kb,addMatchUpScheduleItems:qb,addMatchUpScheduledDate:Lb,addMatchUpScheduledTime:xb,addMatchUpStartTime:Hb,addMatchUpStopTime:Yb,addSchedulingProfileRound:gM,allocateTeamMatchUpCourts:Bb,assignMatchUpCourt:jb,assignMatchUpVenue:Vb,bulkRescheduleMatchUps:RN,bulkScheduleMatchUps:OR,bulkScheduleTournamentMatchUps:CR,bulkUpdateCourtAssignments:PN,calculateScheduleTimes:SN,clearMatchUpSchedule:AN,clearScheduledMatchUps:kR,findMatchUpFormatTiming:CP,generateBookings:TR,generateVirtualCourts:KT,matchUpScheduleChange:NN,modifyMatchUpFormatTiming:sT,proAutoSchedule:wN,proConflicts:TN,removeEventMatchUpFormatTiming:pT,removeMatchUpCourtAssignment:vN,reorderUpcomingMatchUps:bN,scheduleMatchUps:DN,scheduleProfileRounds:_R,setMatchUpDailyLimits:EN,setMatchUpHomeParticipantId:Fb,setSchedulingProfile:_P,toggleParticipantCheckInState:sb,validateSchedulingProfile:kP},proAutoSchedule:wN,proConflicts:TN,publicFindCourt:Lm,query:HP,removeEventMatchUpFormatTiming:pT,removeMatchUpCourtAssignment:vN,reorderUpcomingMatchUps:bN,scheduleMatchUps:DN,scheduleProfileRounds:_R,setMatchUpDailyLimits:EN,setMatchUpHomeParticipantId:Fb,setSchedulingProfile:_P,toggleParticipantCheckInState:sb,validateSchedulingProfile:kP};function ON({drawDefinition:t,structureId:e,matchUpId:n,structure:r,matchUp:i,eventId:o,event:s}){const c="getTieFormat";let u;if(e=r?.structureId??e,((n=i?.matchUpId??n)||e)&&!t)return{error:ot};if(o&&s)u=ll(s);else if(n){if(t&&(!i||!r)){const e=GU({drawDefinition:t,matchUpId:n});if(e.error)return e;if(e.matchUp?.matchUpType!==a)return ti({result:{error:he},stack:c});r||(r=e.structure),i||(i=e.matchUp)}u=ml({item:i,drawDefinition:t,structure:r,event:s})||ml({item:r,drawDefinition:t,structure:r,event:s})||ll(t)||ll(s)}else if(t&&e){if(!r){const n=ad({drawDefinition:t,structureId:e});if(n.error)return n;r=n?.structure}u=ml({item:r,drawDefinition:t,structure:r,event:s})||ll(t)||ll(s)}else u=ll(t)||ll(s);return u?{...z,structure:r,tieFormat:u,matchUp:i}:ti({result:{error:ue},stack:c})}function FN({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![Xu].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==ju&&!vf(t))}function kN({from:t,to:e}){const n=Object.keys(t),r=O(n,Object.keys(e)).length===n.length,i=n.filter((n=>t[n]!==e[n])).map((n=>({countChange:e[n]-t[n],collectionId:n}))),a=n.every((n=>t[n]===e[n]));return{equivalent:r&&a,matchUpsCountChanges:i}}function xN({check:t,matchUp:e}){let n="";const r=[];return{changesArePossible:t.matchUpsCountChanges.every((({collectionId:t,countChange:i})=>{const a=e.tieMatchUps.filter((e=>e.collectionId===t&&e.matchUpStatus===Hu)).map(If("matchUpId")),o=a.length+i>=0||i>0;return!o&&i<0&&(n="Insufficient TO_BE_PLAYED matchUps"),r.push({toBePlayedTieMatchUpIds:a,collectionId:t,countChange:i}),o})),changes:r,cannotChangeReaon:n}}function _N({appliedPolicies:t,drawDefinition:e,auditData:n}){if(!t?.audit?.[Iu])return;const{extension:r}=zc({name:Iu,element:e});_c({element:e,extension:{value:Array.isArray(r?.value)?r?.value.concat(n):[n],name:Iu}})}function LN({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:n,collectionName:r,tieFormatName:i,drawDefinition:a,matchUpFormat:s,matchUpCount:c,collectionId:u,matchUpType:d,structureId:p,matchUpId:l,category:m,eventId:f,gender:h,event:g,collectionValueProfiles:I,collectionValue:U,matchUpValue:S,scoreValue:v,setValue:w}){const P="modifyCollectionDefinition";if(s&&!Di({matchUpFormat:s}))return ti({result:{error:Jn},context:{matchUpFormat:s},stack:P});if(r&&"string"!=typeof r)return ti({result:{error:Jn},context:{collectionName:r},stack:P});if(h&&!Object.values(oi).includes(h))return ti({result:{error:Jn},context:{gender:h},stack:P});if(m&&"object"!=typeof m)return ti({result:{error:Jn},context:{category:m},stack:P});const D={collectionValueProfiles:I,collectionValue:U,matchUpValue:S,scoreValue:v,setValue:w};if(!(Object.values(D).filter(Boolean).length||n||r||s||c||d))return ti({result:{error:be},stack:P});if(Object.values(D).filter(Boolean).length>1)return ti({info:"Only one value assignment allowed per collectionDefinition",result:{error:Jn},stack:P});let b=ON({drawDefinition:a,structureId:p,matchUpId:l,eventId:f,event:g});if(b.error)return ti({result:b,stack:P});const{matchUp:R,structure:M,tieFormat:N}=b,A=ZU(N),E=N?.collectionDefinitions.find((t=>t.collectionId===u)),C=A?.collectionDefinitions.find((t=>t.collectionId===u));if(!E)return ti({info:"source collectionDefinition",result:{error:rr},context:{collectionId:u},stack:P});const F=U??S??v??w;if(I?.length){const t=Q({matchUpCount:c??E?.matchUpCount??0,collectionValueProfiles:I});if(t.errors)return ti({result:{error:Jn},info:t.errors,stack:P})}else if(F&&!y(F))return ti({result:{error:Jn},info:"value is not an integer",context:{value:F},stack:P});const k=I&&(!E.collectionValueProfiles||(x=E.collectionValueProfiles,_=I,!(O(Object.keys(x),Object.keys(_)).length===Object.keys(x).length&&O(Object.values(x),Object.values(_)).length===Object.values(x).length)));var x,_;const L=[];if((y(U)&&E.collectionValue!==U||y(S)&&E.matchUpValue!==S||y(v)&&E.scoreValue!==v||y(w)&&E.setValue!==w||k)&&(C.collectionValueProfiles=void 0,C.collectionValue=void 0,C.matchUpValue=void 0,C.scoreValue=void 0,C.setValue=void 0,Object.assign(C,D),L.push({collectionId:u,...Xr(D)})),(y(v)||y(w))&&C.collectionGroupNumber){const t=C.collectionGroupNumber;A.collectionDefinitions=A.collectionDefinitions.map((e=>{const{collectionGroupNumber:n,...r}=e;return n===t?r:e})),A.collectionGroups=A.collectionGroups.filter((({groupNumber:e})=>e!==t)),L.push({collectionId:u,change:"collectionGroupNumber removed"})}const{aggregateValue:B,valueGoal:V}=gD(A),j=Xr({aggregateValue:B,valueGoal:V});if(j.aggregateValue===N?.winCriteria.aggregateValue&&j.valueGoal===N?.winCriteria.valueGoal||(A.winCriteria=j,L.push({collectionId:u,winCriteria:j})),y(n)&&E.collectionOrder!==n&&(C.collectionOrder=n,L.push({collectionId:u,collectionOrder:n})),r&&E.collectionName!==r&&(C.collectionName=r,L.push({collectionId:u,collectionName:r})),s&&E.matchUpFormat!==s&&(C.matchUpFormat=s,L.push({collectionId:u,matchUpFormat:s})),y(c)&&E.matchUpCount!==c&&(C.matchUpCount=c,L.push({collectionId:u,matchUpCount:c})),d&&E.matchUpType!==d)return ti({result:{error:ir},context:{matchUpType:d},stack:P});m&&E.category!==m&&(C.category=m,L.push({collectionId:u,category:m})),h&&E.gender!==h&&(C.gender=h,L.push({collectionId:u,gender:h}));const G=Xr(A);if(b=sa({tieFormat:G}),b.error)return ti({result:b,stack:P});if(!L.length)return ti({result:{...z,modifications:L}});if(N?.tieFormatName!==i?(G.tieFormatName=i,L.push({tieFormatName:i})):L.length&&(delete G.tieFormatName,L.push("tieFormatName removed: modifications without new tieFormatName")),b=function({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:n,structure:r,tieFormat:i,eventId:a,matchUp:s,event:c,uuids:u}){const d="updateTieFormat",p=e?.tournamentId;let l=0,m=0,f=0,h=0;const g=i?.collectionDefinitions.reduce(((t,e)=>(t[e.collectionId]=(t[e.collectionId]||0)+e.matchUpCount,t)),{}),I=({tieFormat:t})=>{const e=t?.collectionDefinitions.reduce(((t,e)=>(t[e.collectionId]=(t[e.collectionId]||0)+e.matchUpCount,t)),{});return kN({from:e,to:g}).equivalent},U=ON({drawDefinition:n})?.tieFormat,y=ON({event:c})?.tieFormat;if(c&&a){for(const t of c.drawDefinitions??[])S({drawDefinition:t});c.tieFormat=ZU(i),h+=1}else if(s){if(!s.tieMatchUps)return ti({result:{error:he},stack:d});const e=T(s.tieMatchUps?.map((({collectionId:t})=>t))),r=kN({to:g,from:e}),{changes:a,changesArePossible:o,cannotChangeReaon:l}=xN({matchUp:s,check:r});if(r.equivalent){if(!FN({matchUp:s,updateInProgressMatchUps:t}))return ti({result:{error:Ve},info:"matchUp is IN_PROGRESS or COMPLETE",stack:d});s.tieFormat=ZU(i),h+=1}else{if(!o)return ti({context:{collectionMap:g,matchUpMap:e},result:{error:ae},info:l||"specified changes not possible",stack:d});w({tieFormat:i,matchUp:s,changes:a,uuids:u})}m+=1,$d({eventId:c?.eventId,context:d,drawDefinition:n,tournamentId:p,matchUp:s})}else if(r){const t=U??y,e=v({inheritedTieFormat:t,structure:r})?.modifiedMatchUpsCount;e&&(m+=e,l+=1,h+=1);const a=!r.tieFormat||lP({ancestor:r.tieFormat,descendant:i}).different;a&&(r.tieFormat=ZU(i),l+=1,h+=1),(e||a)&&n&&Hd({structureIds:[r.structureId],eventId:c?.eventId,drawDefinition:n})}else{if(!n)return{error:ot};S({drawDefinition:n}),n.tieFormat=ZU(i),h+=1}return{modifiedStructuresCount:l,modifiedMatchUpsCount:m,addedMatchUpsCount:f,modifiedCount:h,...z,tieFormat:i};function S({drawDefinition:t}){const e=t.structures||[],n=[];for(const t of e){if(t.tieFormat)continue;const e=y,r=v({inheritedTieFormat:e,structure:t})?.modifiedMatchUpsCount;if(r){l+=1,m+=r;const e=t.structureId;n.push(e)}}return Hd({structureIds:n,eventId:c?.eventId,drawDefinition:t}),n.length}function v({inheritedTieFormat:r,structure:s}){let c=0;const p=Jm({matchUpFilters:{matchUpTypes:[o]},structure:s})?.matchUps||[];for(const o of p){const s=FN({matchUp:o,updateInProgressMatchUps:t});let p=!1;const l=kN({from:T(o.tieMatchUps?.map((({collectionId:t})=>t))),to:g});if(l.equivalent)o.tieFormat&&I(o)&&s&&(o.tieFormat=ZU(i),p=!0);else{const{changes:t,changesArePossible:e}=xN({matchUp:o,check:l});if(e&&!o.tieFormat)w({changes:t,matchUp:o,tieFormat:i,uuids:u});else{if(!r)return ti({result:{error:ue},stack:d});(!o.tieFormat||lP({ancestor:r,descendant:o.tieFormat}).different)&&(o.tieFormat=r,p=!0)}}p&&(c+=1,$d({tournamentId:e?.tournamentId,drawDefinition:n,context:d,eventId:a,matchUp:o}))}return{modifiedMatchUpsCount:c}}function w({uuids:t,matchUp:e,tieFormat:r,changes:i}){e.tieFormat=ZU(r);const o=[],s=[];return i.forEach((n=>{if(n.countChange>0){const i=Math.max(0,...e.tieMatchUps.filter((t=>t.collectionId===n.collectionId)).map(If("collectionPosition"))),a=r.collectionDefinitions.find((t=>t.collectionId===n.collectionId)),o=BI({matchUpsLimit:n.countChange,collectionPositionOffset:i,collectionDefinition:a,matchUp:e,uuids:t});s.push(...la(o,!1,!0)),f+=s.length,e.tieMatchUps.push(...o)}else{const t=n.toBePlayedTieMatchUpIds.slice(0,Math.abs(n.countChange));console.log("remove",t.length),o.push(...t),e.tieMatchUps=e.tieMatchUps.filter((({matchUpId:e})=>!t.includes(e)))}})),s.length&&Gd({matchUps:s,drawDefinition:n,tournamentId:p,eventId:a}),o.length&&qd({matchUpIds:o,action:"updateTieFormat",drawDefinition:n,tournamentId:p,eventId:a}),{matchUpIdsRemoved:o,matchUpsAdded:s}}}({tieFormat:G,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:a,structure:M,eventId:f,matchUp:R,event:g}),!b.error){const{appliedPolicies:t}=Np({tournamentRecord:e});_N({appliedPolicies:t,drawDefinition:a,auditData:Xr({collectionDefinition:C,drawId:a?.drawId,action:P,structureId:p,matchUpId:l,eventId:f})})}return ti({result:{...b,modifications:L},stack:P})}function BN({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:n,wasAggregateValue:r,tieFormatName:i,drawDefinition:a,structureId:s,structure:c,tieFormat:u,matchUpId:d,matchUp:p,eventId:l,event:m}){const{aggregateValue:f,valueGoal:h}=gD(u);u.winCriteria=Xr({aggregateValue:f,valueGoal:h}),(e&&e!==h||f&&!r)&&(i?u.tieFormatName=i:delete u.tieFormatName);const{targetMatchUps:g}=function({updateInProgressMatchUps:t,drawDefinition:e,structureId:n,structure:r,matchUpId:i,matchUp:a}){let s=[];i&&a?s=[a]:n&&r?s=Jm({matchUpFilters:{matchUpTypes:[o]},structure:r})?.matchUps??[]:e&&(s=ff({matchUpFilters:{matchUpTypes:[o]},drawDefinition:e})?.matchUps??[]);const c=s.filter((e=>!e.winningSide&&e.matchUpStatus!==xu&&(t||e.matchUpStatus!==ju&&!vf(e))));return{targetMatchUps:c}}({updateInProgressMatchUps:t,drawDefinition:a,structureId:s,structure:c,matchUpId:d,matchUp:p});!function({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:n,targetMatchUps:r,tieFormat:i,event:a}){for(const o of r){const r=!!o.tieFormat;let s;if(r&&(o.tieFormat=ZU(i)),t){const t=Np({tournamentRecord:e,drawDefinition:n,event:a}).appliedPolicies,r=ey({matchUpId:o.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:t,drawDefinition:n,event:a});if(r.error)return r;s=r.score}r&&!s&&$d({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:a?.eventId,matchUp:o,drawDefinition:n})}}({updateInProgressMatchUps:t,tournamentRecord:n,targetMatchUps:g,drawDefinition:a,tieFormat:u,event:m});const I=Xr(u),U=sa({tieFormat:I});if(U.error)return U;if(l&&m)m.tieFormat=I;else if(d&&p)p.tieFormat=u;else if(c)c.tieFormat=I;else if(a)a.tieFormat=I;else if(!p||!a)return{error:ot};return Hd({drawDefinition:a,eventId:m?.eventId}),{...z}}function VN({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:n,drawDefinition:r,tieFormatName:i,structureId:a,matchUpId:o,matchUp:s,eventId:c,event:u}){if(!e)return{error:be};if(isNaN(e))return{error:Jn};const d="removeCollectionGroup";let p=s?void 0:ON({drawDefinition:r,structureId:a,matchUpId:o,eventId:c,event:u});if(p?.error)return ti({result:p,stack:d});const l=p?.structure;s=s??p?.matchUp;const m=p?.tieFormat,f=m?.winCriteria.valueGoal,h=m?.winCriteria.aggregateValue,g=ZU(m);if(p=sa({tieFormat:g}),p.error)return ti({result:p,stack:d});const I=[];if(g.collectionDefinitions=g.collectionDefinitions.map((t=>{const{collectionGroupNumber:n,...r}=t;return n!==e?t:(I.push(t.collectionId),r)})),g.collectionGroups=g.collectionGroups.filter((({groupNumber:t})=>t!==e)),p=BN({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:h,tournamentRecord:n,drawDefinition:r,tieFormatName:i,structureId:a,structure:l,tieFormat:g,matchUpId:o,matchUp:s,eventId:c,event:u}),!p.error){const{appliedPolicies:t}=Np({tournamentRecord:n});_N({appliedPolicies:t,drawDefinition:r,auditData:Xr({drawId:r?.drawId,collectionGroupNumber:e,action:d,structureId:a,matchUpId:o,eventId:c})})}return ti({result:{...p,modifiedCollectionIds:I},stack:d})}function jN({tieFormat:t,orderMap:e}){const n=ZU(t);return n.collectionDefinitions?.forEach((t=>{const n=e[t.collectionId];n&&(t.collectionOrder=n)})),n.collectionDefinitions?.sort(((t,e)=>D(t.collectionOrder)-D(e.collectionOrder))),n}function GN({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,orderMap:i,eventId:a,matchUp:o,event:s}){if("object"!=typeof i||!Object.values(i).every((t=>y(t))))return ti({result:{error:Jn},context:{orderMap:i}});const c=n?ad({drawDefinition:e,structureId:n}):void 0;if(c?.error)return c;const u=c?.structure;if(a&&s?.tieFormat)qN({tournamentRecord:t,event:s,orderMap:i});else if(r){const n=e&&GU({drawDefinition:e,matchUpId:r});if(n?.error)return n;if(!(o=n.matchUp))return{error:fe};const a=gP({tournamentRecord:t,matchUpId:r,structure:u,drawDefinition:e,event:s})?.tieFormat;o.tieFormat=jN({tieFormat:a,orderMap:i}),$d({tournamentId:t?.tournamentId,eventId:s?.eventId,drawDefinition:e,matchUp:o})}else if(n)if(u?.tieFormat)u.tieFormat=jN({tieFormat:u.tieFormat,orderMap:i}),WN({eventId:s?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:i}),Hd({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)$N({structureIds:[n],tournamentRecord:t,drawDefinition:e,orderMap:i,event:s});else{if(!s?.tieFormat)return{error:rr};qN({structureIds:[n],tournamentRecord:t,orderMap:i,event:s})}else{if(!e?.tieFormat)return{error:rr};$N({tournamentRecord:t,drawDefinition:e,orderMap:i,event:s})}return{...z}}function qN({tournamentRecord:t,structureIds:e,orderMap:n,event:r}){const i=jN({tieFormat:r.tieFormat,orderMap:n});e?.length||(r.tieFormat=i);for(const i of r.drawDefinitions??[])$N({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:n,event:r})}function $N({tournamentRecord:t,drawDefinition:e,structureIds:n,orderMap:r,event:i}){const a=jN({tieFormat:e.tieFormat??i?.tieFormat,orderMap:r});n?.length||(e.tieFormat=a);const o=[];for(const a of e.structures??[])n?.length&&!n.includes(a.structureId)||((a.tieFormat||n?.includes(a.structureId))&&(a.tieFormat=jN({tieFormat:a.tieFormat??e.tieFormat??i?.tieFormat,orderMap:r})),WN({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,structure:a,orderMap:r}),o.push(a.structureId));Hd({drawDefinition:e,structureIds:o})}function WN({tournamentRecord:t,drawDefinition:e,structure:n,orderMap:r,eventId:i}){const a=Jm({matchUpFilters:{matchUpTypes:[o]},structure:n})?.matchUps;for(const n of a)n.tieFormat&&(n.tieFormat=jN({tieFormat:n.tieFormat,orderMap:r}),$d({tournamentId:t?.tournamentId,drawDefinition:e,eventId:i,matchUp:n}))}function HN({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:n,drawDefinition:r,tieFormatName:i,collectionId:a,structureId:s,matchUpId:c,eventId:u,matchUp:d,event:p}){const l="removeCollectionDefinition";let m=d?void 0:ON({drawDefinition:r,structureId:s,matchUpId:c,eventId:u,event:p});if(m?.error)return ti({result:m,stack:l});const f=m?.structure;d=d??m?.matchUp;const h=m?.tieFormat,g=ZU(h);if(m=sa({tieFormat:g}),m.error)return ti({result:m,stack:l});const I=g?.collectionDefinitions?.find((t=>t.collectionId===a));if(!I)return ti({result:{error:rr,collectionId:a}});g.collectionDefinitions=g.collectionDefinitions.filter((t=>t.collectionId!==a)),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map((t=>{const{collectionGroupNumber:e,...n}=t;return n})),g.collectionGroups=g.collectionGroups.filter((({groupNumber:t})=>t!==I.collectionGroupNumber)));const{aggregateValue:U,valueGoal:y}=gD(g);g.winCriteria=Xr({aggregateValue:U,valueGoal:y});const S=h?.winCriteria.valueGoal,v=h?.winCriteria.aggregateValue;(S&&S!==y||U&&!v)&&(i?g.tieFormatName=i:delete g.tieFormatName);let w=[];c&&d?w=[d]:s&&f?w=Jm({matchUpFilters:{matchUpTypes:[o]},structure:f})?.matchUps??[]:r?w=ff({matchUpFilters:{matchUpTypes:[o]},drawDefinition:r})?.matchUps??[]:p&&(w=df({matchUpFilters:{matchUpTypes:[o]}})?.matchUps??[]);const P=(w||[]).filter((n=>{const r=n.tieMatchUps?.filter((t=>t.collectionId===a)),i=r?.some(vf),o=!(!e||!n.tieFormat)&&lP({descendant:n.tieFormat,ancestor:g})?.different;return t&&!i||!n.winningSide&&n.matchUpStatus!==xu&&(t||n.matchUpStatus!==ju&&!vf(n)&&!o)}));if(!P.length)return{error:qn};const{appliedPolicies:D}=Np({tournamentRecord:n});if(c&&d&&t){const t=d.tieMatchUps?.filter((t=>t.collectionId===a));for(const e of t??[]){let t=Qb({matchUpId:e.matchUpId,tieMatchUpId:d?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:n,appliedPolicies:D,drawDefinition:r,event:p});if(t.error)return t;if(t=GU({drawDefinition:r,matchUpId:c}),t.error)return t;d=t?.matchUp}}const T=[];for(const e of P){for(const t of e?.sides??[])t.lineUp=(t.lineUp??[]).map((t=>({participantId:t.participantId,collectionAssignments:(t?.collectionAssignments??[]).filter((t=>t.collectionId!==a))})));if(e.tieMatchUps=(e.tieMatchUps??[]).filter((t=>{const e=t.collectionId===a;return e&&T.push(t.matchUpId),!e})),e.tieFormat&&(e.tieFormat=ZU(g)),t){const t=ey({matchUpId:e.matchUpId,exitWhenNoValues:!0,tournamentRecord:n,appliedPolicies:D,drawDefinition:r,event:p});if(t.error)return t}$d({tournamentId:n?.tournamentId,eventId:p?.eventId,drawDefinition:r,context:l,matchUp:e})}T.length&&qd({tournamentId:n?.tournamentId,matchUpIds:T,eventId:p?.eventId,drawDefinition:r});const b=Xr(g);if(m=sa({tieFormat:b}),m.error)return ti({result:m,stack:l});if(u&&p)p.tieFormat=b;else if(c&&d)d.tieFormat=b;else if(f)f.tieFormat=b;else if(r)r.tieFormat=b;else if(!d||!r)return{error:ot};Hd({drawDefinition:r,eventId:p?.eventId});return _N({appliedPolicies:D,drawDefinition:r,auditData:Xr({drawId:r?.drawId,action:l,collectionId:a,structureId:s,matchUpId:c,eventId:u})}),{tieFormat:b,deletedMatchUpIds:T,targetMatchUps:P,...z}}function zN({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:n,drawDefinition:r,collectionIds:i,tieFormatName:a,structureId:o,matchUpId:s,matchUp:c,eventId:u,event:d}){const p="addCollectionGroup";if(!Array.isArray(i))return ti({result:{error:be},stack:p});let l=c?void 0:ON({drawDefinition:r,structureId:o,matchUpId:s,eventId:u,event:d});if(l?.error)return ti({result:l,stack:p});const m=l?.structure;c=c||l?.matchUp;const f=l?.tieFormat,h=f?.winCriteria.valueGoal,g=ZU(f);if(l=sa({tieFormat:g}),l.error)return ti({result:l,stack:p});for(const t of g.collectionDefinitions){const{collectionId:e,collectionGroupNumber:n}=t;if(n&&i.includes(e))return ti({info:"collectionIds cannot be part of other collectionGroups",result:{error:Jn},stack:p})}const I=(g.collectionGroups||[]).reduce(((t,e)=>e.groupNumber>t?e.groupNumber:t),0)+1;return n.groupNumber=I,g.collectionDefinitions=g.collectionDefinitions.map((t=>i.includes(t.collectionId)?{...t,collectionGroupNumber:I}:t)),g.collectionGroups=[...g.collecitonGroups||[],n],BN({updateInProgressMatchUps:t,originalValueGoal:h,tournamentRecord:e,drawDefinition:r,tieFormatName:a,structureId:o,structure:m,tieFormat:g,matchUpId:s,matchUp:c,eventId:u,event:d})}function YN({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:n,tournamentRecord:r,policyDefinitions:i,enforceCategory:a,referenceGender:o,drawDefinition:s,tieFormatName:c,enforceGender:u,structureId:d,matchUpId:p,matchUp:l,eventId:m,uuids:f,event:h}){const g="addCollectionDefinition",I=Np({tournamentRecord:r,drawDefinition:s,event:h}).appliedPolicies??{},U=i?.[wc]??I?.[wc];a=a??U?.participants?.enforceCategory;const y=!1!==(u??U?.participants?.enforceGender),S=!(!(n??h?.category)||!1===a),v=!(!(o??h?.gender)||!y),w=oa({referenceCategory:n??h?.category,collectionDefinition:e,referenceGender:o,checkCategory:S,checkGender:v,event:h});if(w.error)return ti({result:w,stack:g});let P=l?.tieFormat?void 0:ON({drawDefinition:s,structureId:d,matchUpId:p,eventId:m,event:h});if(P?.error)return ti({result:{error:P.error},stack:g});const D=P?.structure;l=l??P?.matchUp;const T=l?.tieFormat??P?.tieFormat,b=ZU(T);if(P=sa({tieFormat:b}),P?.error)return ti({result:{error:P.error},stack:g});if(e.collectionId){if(b.collectionDefinitions.map((({collectionId:t})=>t)).includes(e.collectionId))return ti({context:{collectionId:e.collectionId},result:{error:Zn}})}else e.collectionId=ha();b.collectionDefinitions.push(e),b.collectionDefinitions.sort(((t,e)=>(t.collectionOrder||0)-(e.collectionOrder||0))).forEach(((t,e)=>t.collectionOrder=e+1));const{aggregateValue:R,valueGoal:M}=gD(b);b.winCriteria=Xr({aggregateValue:R,valueGoal:M});const N=T?.winCriteria.valueGoal,A=T?.winCriteria.aggregateValue;(N&&N!==M||R&&!A)&&(c?b.tieFormatName=c:delete b.tieFormatName);const E=[],C=[];let O=[];const F=Xr(b);if(P=sa({tieFormat:F}),P?.error)return ti({result:{error:P.error},stack:g});if(m&&h){h.tieFormat=F;for(const n of h.drawDefinitions??[])if(!n.tieFormat)for(const r of n.structures??[]){if(r.tieFormat)continue;const n=KN({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:f});C.push(...n.newMatchUps),O.push(...n.targetMatchUps),E.push(r.structureId)}QN({modifiedMatchUps:O,eventId:h?.eventId,modifiedStructureIds:E,tournamentRecord:r,drawDefinition:s,addedMatchUps:C,stack:g})}else if(d&&D){D.tieFormat=F;const n=KN({updateInProgressMatchUps:t,collectionDefinition:e,structure:D,uuids:f});C.push(...n.newMatchUps),O=n.targetMatchUps,QN({modifiedMatchUps:O,eventId:h?.eventId,modifiedStructureIds:E,tournamentRecord:r,drawDefinition:s,addedMatchUps:C,stack:g})}else if(p&&l){if(!FN({matchUp:l,updateInProgressMatchUps:t}))return ti({result:{error:Ve},stack:g});l.tieFormat=F;const n=BI({collectionDefinition:e,matchUp:l,uuids:f});Array.isArray(l.tieMatchUps)||(l.tieMatchUps=[]),l.tieMatchUps.push(...n),C.push(...n),QN({modifiedMatchUps:[l],eventId:h?.eventId,modifiedStructureIds:E,tournamentRecord:r,drawDefinition:s,addedMatchUps:C,stack:g})}else{if(!s)return{error:ot};s.tieFormat=F;for(const n of s.structures??[]){const r=KN({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:f});E.push(n.structureId),C.push(...r.newMatchUps),O.push(...r.targetMatchUps)}QN({modifiedMatchUps:O,eventId:h?.eventId,tournamentRecord:r,drawDefinition:s,addedMatchUps:C,stack:g})}return _N({appliedPolicies:I,drawDefinition:s,auditData:Xr({drawId:s?.drawId,collectionDefinition:e,action:g,structureId:d,matchUpId:p,eventId:m})}),{tieFormat:F,targetMatchUps:O,addedMatchUps:C,...z}}function KN({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:r}){const i=[],a=Jm({matchUpFilters:{matchUpTypes:[o]},structure:n})?.matchUps,s=a.filter((e=>FN({matchUp:e,updateInProgressMatchUps:t})&&!e.tieFormat));for(const t of s){const n=BI({collectionDefinition:e,matchUp:t,uuids:r});Array.isArray(t.tieMatchUps)||(t.tieMatchUps=[]),t.tieMatchUps.push(...n),i.push(...n)}return{newMatchUps:i,targetMatchUps:s}}function QN({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:n,drawDefinition:r,addedMatchUps:i,eventId:a,stack:o}){Gd({tournamentId:e?.tournamentId,matchUps:i,drawDefinition:r,eventId:a}),n?.forEach((t=>{$d({tournamentId:e?.tournamentId,drawDefinition:r,context:o,matchUp:t,eventId:a})})),Hd({structureIds:t,drawDefinition:r,eventId:a})}function JN({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:n,tournamentRecord:r,considerations:i,drawDefinition:a,structureId:o,matchUpId:s,eventId:c,uuids:u,event:d}){const p="modifyTieFormat";if(!sa({tieFormat:n}).valid)return ti({result:{error:ae},info:"falied validation",stack:p});const l=ON({drawDefinition:a,structureId:o,matchUpId:s,eventId:c,event:d});if(l.error)return ti({result:l,stack:p});const{matchUp:m,tieFormat:f}=l,h=ZU(f),g=lP({descendant:n,ancestor:h,considerations:i});if(g.invalid)return ti({context:{invalid:g.invalid},result:{error:ae},stack:p});if(!g?.different)return ti({result:{...z},info:"Nothing to do",stack:p});const I=h.collectionDefinitions.map((({collectionId:t})=>t)),U=n.collectionDefinitions.map((({collectionId:t})=>t)),y=I.filter((t=>!U.includes(t))),S=n.collectionDefinitions.filter((({collectionId:t})=>!I.includes(t))),v=S.map(If("collectionId")),w=[];let P;const T=n.tieFormatName;for(const e of n.collectionDefinitions){if(v.includes(e.collectionId))continue;const n=LN({updateInProgressMatchUps:t,...e,tournamentRecord:r,tieFormatName:T,drawDefinition:a,structureId:o,matchUpId:s,eventId:c,event:d});if(n.modifications&&w.push(...n.modifications),n.error)return ti({result:n,stack:p});n.tieFormat&&(P=n.tieFormat)}for(const e of S){const n=YN({updateInProgressMatchUps:t,collectionDefinition:e,tournamentRecord:r,drawDefinition:a,tieFormatName:T,structureId:o,matchUpId:s,matchUp:m,eventId:c,uuids:u,event:d});if(n.error)return ti({result:n,stack:p});n.tieFormat&&(P=n.tieFormat)}for(const n of y){const i=HN({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:r,drawDefinition:a,tieFormatName:T,collectionId:n,structureId:o,matchUpId:s,eventId:c,matchUp:m,event:d});if(i.error)return ti({result:i,stack:p});i.tieFormat&&(P=i.tieFormat)}return f?.tieFormatName!==T?(P.tieFormatName=T,w.push({tieFormatName:T})):(w.length||v.length||y.length)&&(delete P.tieFormatName,w.push("tieFormatName removed: modifications without new tieFormatName")),P.collectionDefinitions=P.collectionDefinitions.sort(((t,e)=>D(t.collectionOrder)-D(e.collectionOrder))).map(((t,e)=>({...t,collectionOrder:e+1}))),{processedTieFormat:ZU(P),modifications:w,...z}}function ZN({tournamentRecord:t}){if(!t)return{error:nt};let e=0;for(const n of t.events??[]){const r=n.tieFormats??[],i=t=>{if(!t.tieFormat)return;let n;for(const e of r){lP({descendant:t.tieFormat,ancestor:e}).different||(n=e.tieFormatId)}if(n)t.tieFormatId=n,delete t.tieFormat;else{const n=la(t.tieFormat,void 0,!0);n.tieFormatId||(n.tieFormatId=ha()),t.tieFormatId=n.tieFormatId,delete t.tieFormat,r.push(n),e+=1}};n.eventType,i({tieFormat:n.tieFormat});for(const t of n.drawDefinitions??[]){i({tieFormat:t.tieFormat});for(const e of t.structures??[])i({tieFormat:e.tieFormat})}const o=(e,r)=>{const i=c.matchUps?.find((t=>t.matchUpId===e));i&&(i.tieFormatId=r,delete i.tieFormat,$d({tournamentId:t?.tournamentId,eventId:n.eventId,matchUp:i}))},s=t=>{const n=la(t.tieFormat,void 0,!0);n.tieFormatId||(n.tieFormatId=ha()),r.push(n),e+=1,o(t.matchUpId,n.tieFormatId)},c=df({matchUpFilters:{matchUpTypes:[a]},event:n}),u=c.matchUps??[];for(const t of u){let e;for(const n of r){t.tieFormat&&lP({descendant:t.tieFormat,ancestor:n}).different||(e=n.tieFormatId)}e?o(t.matchUpId,e):s(t)}r.length&&(n.tieFormats=r)}return{...z,addedCount:e}}var XN={__proto__:null,addCollectionDefinition:YN,addCollectionGroup:zN,aggregateTieFormats:ZN,compareTieFormats:lP,getTieFormat:gP,modifyCollectionDefinition:LN,modifyTieFormat:JN,mutate:{__proto__:null,addCollectionDefinition:YN,addCollectionGroup:zN,aggregateTieFormats:ZN,modifyCollectionDefinition:LN,modifyTieFormat:JN,orderCollectionDefinitions:GN,removeCollectionDefinition:HN,removeCollectionGroup:VN},orderCollectionDefinitions:GN,query:IP,removeCollectionDefinition:HN,removeCollectionGroup:VN,tieFormatGenderValidityCheck:si,validateCollectionDefinition:oa};function tA(t){const e=cc(t,[{tournamentRecord:!0,startDate:!0,endDate:!1,tournamentName:!0}]);if(e.error)return e;const{startDate:n,endDate:r}=t.tournamentRecord,i=(n&&r?new Date($i(r)).getTime()-new Date($i(n)).getTime():0)/864e5,a=t.endDate||Ki(t.startDate,i),o=e=>e?.filter((({itemType:e})=>t.itemTypeList?.includes(e))),s=e=>e?.filter((({name:e})=>t.extensionList?.includes(e))),c={participants:t.copyParticipants?t.tournamentRecord.participants?.map((t=>{const{timeItems:e,extensions:n,...r}=t;return la({...r,timeItems:o(e),extensions:s(n)},!1,!0)}))??[]:[],parentOrganisation:la({...t.tournamentRecord.parentOrganisation},!1,!0),venues:la(t.tournamentRecord.venues??[],!1,!0),extensions:s(t.tournamentRecord.extensions),timeItems:o(t.tournamentRecord.timeItems),events:t.tournamentRecord.events?.map((e=>{const{drawDefinitions:n,timeItems:r,extensions:i,startDate:c,endDate:u,...d}=e;return la({extensions:s(i),timeItems:o(r),startDate:t.startDate,endDate:a,...d},!1,!0)}))??[],weekdays:[...t.tournamentRecord.weekdays??[]],tournamentName:t.tournamentName,startDate:t.startDate,tournamentId:ha(),endDate:a};return{...z,tournamentRecord:c}}const eA={ABANDONED:"ABANDONED",ACTIVE:"ACTIVE",CANCELLED:"CANCELLED",COMPLETED:"COMPLETED",IN_PROGRESS:"IN_PROGRESS"};function nA({tournamentRecord:t,status:e}){return t?e&&!Object.keys(eA).includes(e)?{error:Jn,info:"Unknown status"}:(t.tournamentStatus=e,{...z}):{error:nt}}function rA(t){const e=cc(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;const{tournamentRecord:n,onlineResource:r,organisationId:i,participantId:a,personId:o,courtId:s,venueId:c}=t;if(i){if(n.parentOrganisation?.parentOrganisationId!==i)return ti({result:{error:rr}});iA({element:n.parentOrganisation,onlineResource:r})}else if(a||o){const t=(n.participants??[]).find((t=>o&&t.person?.personId===o||t.participantId===a));if(!t)return ti(o?{result:{error:rr}}:{result:{error:en}});if(o){if(t.person?.personId!==o)return ti({result:{error:We}});iA({element:t.person,onlineResource:r})}else iA({element:t,onlineResource:r})}else if(s){const t=(n.venues??[]).filter((t=>!c||t.venueId===c)).flatMap((t=>(t.courts??[]).filter((t=>t.courtId===s))))?.[0];if(!t)return ti({result:{error:Tn}});iA({element:t,onlineResource:r})}else if(c){const t=(n.venues??[]).find((t=>t.venueId===c));if(!t)return ti({result:{error:Mn}});iA({element:t,onlineResource:r})}else iA({element:n,onlineResource:r}),Or({payload:{parentOrganisation:n.parentOrganisation,onlineResources:n.onlineResources,tournamentId:n.tournamentId},topic:Nd});return{...z}}function iA({element:t,onlineResource:e}){const n=(t.onlineResources??[]).filter((t=>!(t?.[ca]===e[ca]&&t?.[ua]===e[ua]&&t?.[da]===e[da])));t.onlineResources=n}function aA(t){const e=cc(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;const{tournamentRecord:n,onlineResource:r,organisationId:i,participantId:a,personId:o,courtId:s,venueId:c}=t;if(i){if(n.parentOrganisation?.parentOrganisationId!==i)return ti({result:{error:rr}});oA({element:n.parentOrganisation,onlineResource:r})}else if(a||o){const t=(n.participants??[]).find((t=>o&&t.person?.personId===o||t.participantId===a));if(!t)return ti(o?{result:{error:rr}}:{result:{error:en}});if(o){if(t.person?.personId!==o)return ti({result:{error:We}});oA({element:t.person,onlineResource:r})}else oA({element:t,onlineResource:r})}else if(s){const t=(n.venues??[]).filter((t=>!c||t.venueId===c)).flatMap((t=>(t.courts??[]).filter((t=>t.courtId===s))))?.[0];if(!t)return ti({result:{error:Tn}});oA({element:t,onlineResource:r})}else if(c){const t=(n.venues??[]).find((t=>t.venueId===c));if(!t)return ti({result:{error:Mn}});oA({element:t,onlineResource:r})}else oA({element:n,onlineResource:r}),Or({payload:{parentOrganisation:n.parentOrganisation,onlineResources:n.onlineResources,tournamentId:n.tournamentId},topic:Nd});return{...z}}function oA({element:t,onlineResource:e}){const n=(t.onlineResources??[]).filter((t=>t?.[ca]!==e[ca]&&t?.[ua]!==e[ua]&&t?.[da]!==e[da]));return n.push(e),t.onlineResources=n,{...z}}function sA({tournamentRecord:t,promotionalName:e,tournamentName:n,formalName:r}){if(!t)return{error:nt};const i=t.tournamentId,a={tournamentId:i};return n&&n!==t.tournamentName&&(t.tournamentName=n,a.tournamentName=n),e&&e!==t.promotionalName&&(t.promotionalName=e,a.promotionalName=e),r&&r!==t.formalName&&(t.formalName=r,a.formalName=r),t.promotionalName===t.tournamentName&&(delete t.promotionalName,a.promotionalName=""),t.formalName===t.tournamentName&&(delete t.formalName,a.formalName=""),Object.keys(a).length>1&&Or({topic:Nd,payload:{parentOrganisation:t.parentOrganisation,tournamentId:i,...a}}),{...z}}function cA({tournamentRecord:t,notes:e}){if(!t)return{error:nt};const n=e?qU({element:t,notes:e}):$U({element:t});return n.error?n:(Or({topic:Nd,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,notes:e??""}}),{...z})}function uA({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter((t=>t.categoryName&&t.type)),t.tournamentCategories=e,Or({topic:Nd,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,categories:e}}),{...z}):{error:nt}}function dA(t){const{tournamentRecord:e,startDate:n,endDate:r,weekdays:i}=t,a=t.activeDates?.filter(Boolean),o=cc(t,[{tournamentRecord:!0},{[Xs]:t=>Ri.test(t),[ec]:Oe,startDate:!1,endDate:!1},{[Xs]:t=>t.filter(Boolean).every((t=>Ri.test(t))),[ec]:Oe,activeDates:!1},{[Xs]:fT,weekdays:!1}]);if(o.error)return o;if(r&&n&&new Date(r)<new Date(n))return{error:Jn};if(r&&n&&new Date(n)>new Date(r))return{error:Jn};if(a?.length){const t=n||e.startDate,i=r||e.endDate,o=!t||a.every((e=>new Date(e)>=new Date(t))),s=!i||a.every((t=>new Date(t)<=new Date(i)));if(!o||!s)return{error:Oe}}let s;(n&&e.startDate&&new Date(n)>new Date(e.startDate)||r&&e.endDate&&new Date(r)<new Date(e.endDate))&&(s=!0);const c=_i(e.startDate,e.endDate);n&&(e.startDate=n),r&&(e.endDate=r);const u=_i(e.startDate,e.endDate),d=c.filter((t=>!u.includes(t))),p=u.filter((t=>!c.includes(t)));for(const t of e.events??[])n&&t.startDate&&new Date(t.startDate)<new Date(n)&&(t.startDate=n),r&&t.startDate&&new Date(t.startDate)>new Date(r)&&(t.startDate=n??r),r&&t.endDate&&new Date(t.endDate)>new Date(r)&&(t.endDate=r),n&&t.endDate&&new Date(t.endDate)<new Date(n)&&(t.endDate=r??n);n&&e.endDate&&new Date(n)>new Date(e.endDate)&&(e.endDate=n),r&&e.startDate&&new Date(r)<new Date(e.startDate)&&(e.startDate=r),a&&(e.activeDates=a),i&&(e.weekdays=i);const l=s&&function({tournamentRecord:t}){const e=pf({tournamentRecord:t}).matchUps??[],n=t.startDate&&new Date(t.startDate),r=t.endDate&&new Date(t.endDate),i=[],a=[];for(const t of e){const{schedule:e,matchUpId:o}=t;if(e&&e.scheduledDate){const t=new Date(e.scheduledDate);(n&&t<n||r&&t>r)&&(a.push(o),i.includes(e.scheduledDate)||i.push(e.scheduledDate))}}if(i.length){if(!kR({scheduledDates:i,tournamentRecord:t}).clearedScheduleCount)return{error:mt}}return{unscheduledMatchUpIds:a}}({tournamentRecord:e})?.unscheduledMatchUpIds;return function({tournamentRecord:t}){if(!t)return{error:nt};const{startDate:e,endDate:n}=t,r=_i(e,n),i=[];for(const e of t.venues||[])e?.courts?.length&&i.push(...e.courts);for(const t of i){const{startTime:e,endTime:n}=(t.dateAvailability??[]).reduce(((t,e)=>{const n=ji(t.startTime),r=ji(t.endTime);return e.startTime&&ji(e.startTime)<n&&(t.startTime=e.startTime),e.endTime&&ji(e.endTime)>r&&(t.endTime=e.endTime),t}),{startTime:"08:00",endTime:"18:00"}),i=r.map((r=>{const i=t.dateAvailability?.find((t=>t.date===r));return i??{date:r,startTime:e,endTime:n}})),a=t.dateAvailability?.find((t=>!t.date));a&&i.unshift(a),t.dateAvailability=i}}({tournamentRecord:e}),Or({payload:Xr({parentOrganisation:e.parentOrganisation,tournamentId:e.tournamentId,activeDates:a,startDate:n,weekdays:i,endDate:r}),topic:Nd}),{...z,unscheduledMatchUpIds:l,datesAdded:p,datesRemoved:d}}function pA({tournamentRecord:t,startDate:e}){return e?dA({tournamentRecord:t,startDate:e}):{error:Oe}}function lA({tournamentRecord:t,endDate:e}){return e?dA({tournamentRecord:t,endDate:e}):{error:Oe}}var mA={__proto__:null,addDrawDefinitionExtension:Bc,addEventExtension:Vc,addEventTimeItem:cy,addExtension:_c,addNotes:qU,addOnlineResource:aA,addParticipantExtension:jc,addParticipantTimeItem:oy,addTimeItem:ay,addTournamentExtension:Lc,addTournamentTimeItem:sy,analyzeDraws:Uy,analyzeTournament:aP,copyTournamentRecord:tA,createTournamentRecord:LR,generate:{__proto__:null,copyTournamentRecord:tA,createTournamentRecord:LR},getAggregateTeamResults:rP,getAllowedDrawTypes:Kw,getAllowedMatchUpFormats:Yw,getAppliedPolicies:Np,getCompetitionDateRange:eP,getCompetitionPenalties:Jw,getPolicyDefinitions:Ap,getTournamentInfo:tP,getTournamentPenalties:Qw,getTournamentPersons:nP,getTournamentPoints:uP,getTournamentStructures:Dg,getTournamentTimeItem:Sp,mutate:{__proto__:null,addDrawDefinitionExtension:Bc,addEventExtension:Vc,addEventTimeItem:cy,addExtension:_c,addNotes:qU,addOnlineResource:aA,addParticipantExtension:jc,addParticipantTimeItem:oy,addTimeItem:ay,addTournamentExtension:Lc,addTournamentTimeItem:sy,removeDrawDefinitionExtension:qc,removeEventExtension:$c,removeExtension:kc,removeNotes:$U,removeOnlineResource:rA,removeParticipantExtension:Wc,removeTournamentExtension:Gc,setTournamentCategories:uA,setTournamentDates:dA,setTournamentEndDate:lA,setTournamentName:sA,setTournamentNotes:cA,setTournamentStartDate:pA,setTournamentStatus:nA},query:dP,removeDrawDefinitionExtension:qc,removeEventExtension:$c,removeExtension:kc,removeNotes:$U,removeOnlineResource:rA,removeParticipantExtension:Wc,removeTournamentExtension:Gc,setTournamentCategories:uA,setTournamentDates:dA,setTournamentEndDate:lA,setTournamentName:sA,setTournamentNotes:cA,setTournamentStartDate:pA,setTournamentStatus:nA};function fA(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:nt};if(!t?.courtId)return{error:Te};const{scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r,venueMatchUps:i,courtId:a}=t,{schedulingProfile:o}=xP({tournamentRecord:n});if(Array.isArray(i))return{matchUps:c({matchUps:i,courtId:a})};const{matchUps:s}=pf({scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r});return{matchUps:c({matchUps:s,courtId:a})};function c({matchUps:t,courtId:e}){return sD({matchUps:t.filter((t=>{const n=t.schedule?.allocatedCourts?.map((({courtId:t})=>t));return t.schedule?.courtId===e||n?.includes(e)})),schedulingProfile:o})}}function hA({tournamentRecord:t,dateAvailability:e,disableNotice:n,venueMatchUps:r,courtId:i,force:a}){if(!t)return{error:nt};if(!i)return{error:Te};const o=vM({dateAvailability:e});if(o.error)return o;const{updatedDateAvailability:s,totalMergeCount:c}=function(t){let e=0;const n=t.reduce(((t,e)=>{const{date:n,startTime:r,endTime:i,bookings:a}=e;return t[n]||(t[n]=[]),t[n].push({startTime:r,endTime:i,bookings:a}),t}),{}),r=[];return Object.keys(n).forEach((t=>{n[t].sort(SM);const{mergedAvailability:i,mergeCount:a}=function(t){let e,n,r,i=t.length,a=0;const o=[];for(;t.length&&i;){const s=t.shift(),{startTime:c,endTime:u,bookings:d}=s;if(i-=1,e){if(Ji(Qi(n),Qi(c),!1)>0){const t={startTime:e,endTime:n};r?.length&&(t.bookings=r),o.push(t),e=c,r=d,n=u}else d&&(r?r.push(d):r=d),n=u,a+=1}else e=c,r=d,n=u}const s={startTime:e,endTime:n};r?.length&&(s.bookings=r);return o.push(s),{mergedAvailability:o,mergeCount:a}}(n[t]);r.push(...i.map((e=>({date:t,...e})))),e+=a})),{updatedDateAvailability:r,totalMergeCount:e}}(e);e=s;const u=_m({tournamentRecord:t,courtId:i});if(u.error)return u;const{court:d,venue:p}=u,{matchUps:l}=fA({tournamentRecord:t,venueMatchUps:r,courtId:i});if(l?.length){const e=Np({tournamentRecord:t})?.appliedPolicies,n=a??e?.[Rc]?.allowDeletionWithScoresPresent?.courts,r=[];r.length&&(n||console.log("throw error: scheduled court matchUps",r.length))}return d&&(d.dateAvailability=e,!n&&p&&Or({payload:{venue:p,tournamentId:t.tournamentId},topic:Ad,key:p.venueId})),{...z,totalMergeCount:c}}function gA({matchUpsCount:t=0}){return{error:lr,info:`Schedule would be deleted from ${t} ${1===t?"matchUp":"matchUps"}; use { force: true }`}}function IA({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:r}){if(!n)return{error:de};if(!e&&!r)return{error:Tt};let i;if(!e){if(!t)return{error:nt};({drawDefinition:e}=Gm({tournamentRecord:t,drawId:r}))}if(e)({matchUp:i}=GU({drawDefinition:e,matchUpId:n}));else{if(!t)return{error:nt};const e=pf({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=jU({matchUps:e,matchUpId:n}))}if(!i)return{error:le};if(i.timeItems){i.timeItems.find((t=>[_l,xl].includes(t.itemType)))&&(i.timeItems=i.timeItems.filter((({itemType:t})=>![_l,xl].includes(t))),$d({tournamentId:t?.tournamentId,context:"removeCourtAssignment",drawDefinition:e,matchUp:i}))}return{...z}}function UA(t){if("string"!=typeof t?.venueId)return{error:Nn};const{tournamentRecord:e,venueId:n,force:r}=t,i=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(i).length)return{error:nt};const a=lf({tournamentRecords:i,contextFilters:{venueIds:[n]}}).matchUps??[],o=Np({tournamentRecord:e})?.appliedPolicies,s=r??o?.[Rc]?.allowDeletionWithScoresPresent?.venues;if(a.length&&!s)return gA({matchUpsCount:a.length});for(const t of Object.values(i)){for(const e of a){const n=IA({matchUpId:e.matchUpId,drawId:e.drawId,tournamentRecord:t});if(n.error)return n}let e;t.venues=(t.venues??[]).filter((t=>t?.venueId!==n||(e=!0,!1))),e&&Or({payload:{venueId:n,tournamentId:t.tournamentId},topic:yd,key:n})}return LP({tournamentRecords:i}),{...z}}function yA({tournamentRecord:t,venueIds:e,force:n}){if(!t)return{error:nt};if(!Array.isArray(e))return{error:Jn};for(const r of t.venues||[]){const{venueId:i}=r;if(e.includes(i)){const{venueId:e}=r,i=UA({tournamentRecord:t,venueId:e,force:n});if(i.error)return i}}return{...z}}function SA(t){const{courtIds:e,dates:n}=t,r=tp(t),i=cc(t,[{[ms]:!0,[xs]:!0}]);if(i.error)return i;for(const t of Object.values(r))vA({tournamentRecord:t,courtIds:e,dates:n});return{...z}}function vA({tournamentRecord:t,courtIds:e,dates:n}){const r=!Array.isArray(n)||!n.length||{dates:n},i=t=>_c({extension:{value:r,name:Jc},creationTime:!1,element:t});for(const n of t.venues||[])for(const t of n.courts||[])if(e?.includes(t.courtId)){const e=i(t);if(e.error)return e}return{...z}}function wA(t){const{tournamentRecords:e,tournamentId:n,venueIds:r}=t,i=cc(t,[{[ms]:!0,[Ls]:!0}]);if(i.error)return i;const a=Object.keys(e).filter((t=>!n||t===n));for(const t of a){PA({tournamentRecord:e[t],venueIds:r})}return{...z}}function PA({tournamentRecord:t,venueIds:e}){for(const n of t.venues||[])if(e?.includes(n.venueId)){const t=_c({creationTime:!1,element:n,extension:{name:Jc,value:!0}});if(t.error)return t}return{...z}}function DA(t){const e=tp(t),n=[{[ms]:!0}];!t.enableAll&&n.push({[xs]:!0});const r=cc(t,n);if(r.error)return r;const{enableAll:i,courtIds:a,dates:o}=t;for(const t of Object.values(e))TA({tournamentRecord:t,courtIds:a,enableAll:i,dates:o});return{...z}}function TA({tournamentRecord:t,courtIds:e,enableAll:n,dates:r}){for(const i of t.venues||[])for(const t of i.courts||[])if(n||e?.includes(t.courtId))if(Array.isArray(r)){const{extension:e}=zc({element:t,name:Jc});if(e){const n=e.value;Array.isArray(n.dates)&&(n.dates=n.dates.filter((t=>!r.includes(t)))),_c({extension:{name:Jc,value:n},creationTime:!1,element:t})}}else kc({element:t,name:Jc});return{...z}}function bA(t){const e=tp(t),n=[{[ms]:!0}];!t.enableAll&&n.push({[Ls]:!0});const r=cc(t,n);if(r.error)return r;const{venueIds:i,enableAll:a}=t;for(const t of Object.values(e))for(const e of t.venues||[])(a||i?.includes(e.venueId))&&kc({element:e,name:Jc});return{...z}}function RA(t){const{courtId:e,disableNotice:n,force:r}=t,i=tp(t),a=cc(t,[{[ms]:!0,[Vs]:!0}]);if(a.error)return a;let o,s;for(const t of Object.values(i)){if(s=MA({tournamentRecord:t,disableNotice:n,courtId:e,force:r}),s.error&&s.error!==Tn)return s;s.success&&(o=!0)}return o?{...z}:s}function MA({tournamentRecord:t,disableNotice:e,courtId:n,force:r}){const i=_m({tournamentRecord:t,courtId:n});if(i.error)return i;const a=i.venue,{matchUps:o}=fA({tournamentRecord:t,courtId:n}),s=Np({tournamentRecord:t})?.appliedPolicies,c=r??s?.[Rc]?.allowDeletionWithScoresPresent?.courts;if(o?.length&&!c)return gA({matchUpsCount:o.length});for(const e of o??[]){const n=IA({matchUpId:e.matchUpId,drawId:e.drawId,tournamentRecord:t});if(n.error)return n}return a&&(a.courts=(a.courts??[]).filter((t=>t.courtId!==n)),e||Or({payload:{venue:a,tournamentId:t.tournamentId},topic:Ad,key:a.venueId})),{...z}}function NA(t){const{disableNotice:e,modifications:n,courtId:r,force:i,venueMatchUps:a}=t,o=tp(t);if(!Object.keys(o).length)return{error:et};let s;for(const t of Object.values(o)){const o=AA({tournamentRecord:t,disableNotice:e,venueMatchUps:a,modifications:n,courtId:r,force:i});if(o?.error)return o;s=!0}return s?{...z}:undefined}function AA({tournamentRecord:t,disableNotice:e,venueMatchUps:n,modifications:r,courtId:i,force:a}){if(!t)return{error:nt};if(!i)return{error:Te};if(!r||"object"!=typeof r)return{error:Yn};const o=_m({tournamentRecord:t,courtId:i});if(o.error)return o;const{venue:s,court:c}=o,u=Object.keys({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}).filter((t=>"courtId"!==t));if(!Object.keys(r).filter((t=>u.includes(t))).length)return{error:er};const d=u.filter((t=>!["dateAvailability"].includes(t))),p=Object.keys(r).filter((t=>d.includes(t)));if(c&&p.forEach((t=>Object.assign(c,{[t]:r[t]}))),r.dateAvailability){const o=hA({dateAvailability:r.dateAvailability,tournamentRecord:t,venueMatchUps:n,disableNotice:e,courtId:i,force:a});if(o.error)return o}return e||Or({payload:{venue:s,tournamentId:t.tournamentId},topic:Ad,key:s?.venueId}),{...z,court:la(c)}}function EA(t){const{modifications:e,venueId:n,force:r}=t,i=tp(t);if(!Object.keys(i).length)return{error:et};if("string"!=typeof n)return{error:Nn};let a,o;for(const t of Object.values(i)){const i=CA({tournamentRecord:t,modifications:e,venueId:n,force:r});if(i.success&&(o=!0),i.error&&(a=i.error),i.error&&i.error!==Mn)return i}return LP({tournamentRecords:i}),o?{...z}:{error:a}}function CA({tournamentRecord:t,modifications:e,venueId:n,force:r}){if(!t)return{error:nt};if(!e||"object"!=typeof e)return{error:Yn};if(!n)return{error:Nn};const i=Np({tournamentRecord:t})?.appliedPolicies,a=r??i?.[Rc]?.allowDeletionWithScoresPresent?.venues,{matchUps:o}=function({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n,venueId:r}){if(!e)return{error:nt};if(!r)return{error:Nn};const{schedulingProfile:i}=xP({tournamentRecord:e}),{matchUps:a}=pf({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n}),o=function({matchUps:t,venueId:e}){return sD({matchUps:t.filter((t=>{const n=t.schedule?.allocatedCourts?.map((({venueId:t})=>t));return t.schedule?.venueId===e||n?.includes(e)})),schedulingProfile:i})}({matchUps:a,venueId:r});return{matchUps:o}}({tournamentRecord:t,venueId:n}),s=km({tournamentRecord:t,venueId:n});if(s.error)return s;const c=s.venue,u=Object.keys({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]}).filter((t=>"venueId"!==t));if(!Object.keys(e).filter((t=>u.includes(t))).length)return{error:er};const d=u.filter((t=>!["courts","onlineResources"].includes(t))),p=Object.keys(e).filter((t=>d.includes(t)));c&&p.forEach((t=>Object.assign(c,{[t]:e[t]})));const l=c?.courts?.map((t=>t.courtId))??[],m=e.courts?.map((t=>t.courtId))||[],f=m.length?l.filter((t=>!m.includes(t))):e?.courts&&l,h=[];if(f?.length){const e=c?.courts?.filter((t=>f.includes(t.courtId))),n=e?.map((e=>{const n=fA({courtId:e.courtId,tournamentRecord:t,venueMatchUps:o});for(const t of n.matchUps??[])h.push({matchUpId:t.matchUpId,drawId:t.drawId});return n.matchUps?.length??0})).reduce(((t,e)=>t+e));if(!c||n&&!a)return gA({matchUpsCount:n});c.courts=c.courts?.filter((t=>m.includes(t.courtId))),CR({schedule:{courtId:"",scheduledDate:""},matchUpDetails:h,removePriorValues:!0,tournamentRecord:t})}if(e.courts)for(const i of e.courts){const{courtId:e}=i||{};let a=NA({modifications:i,disableNotice:!0,tournamentRecord:t,venueMatchUps:o,courtId:e,force:r});if(a.error===Tn&&(a=wM({disableNotice:!0,tournamentRecord:t,venueId:n,court:i})),a.error)return a}return LP({tournamentRecord:t}),c&&Or({payload:{venue:c,tournamentId:t.tournamentId},topic:Ad,key:c?.venueId}),{...z,venue:la(c)}}var OA={__proto__:null,addCourt:wM,addCourts:PM,addVenue:Om,deleteCourt:RA,deleteVenue:UA,deleteVenues:yA,disableCourts:SA,disableVenues:wA,enableCourts:DA,enableVenues:bA,generate:{__proto__:null,generateCourts:WT},generateCourts:WT,getCompetitionVenues:wP,getCourts:MD,getVenuesAndCourts:vP,modifyCourt:NA,modifyCourtAvailability:hA,modifyVenue:EA,mutate:{__proto__:null,addCourt:wM,addCourts:PM,addVenue:Om,deleteCourt:RA,deleteVenue:UA,deleteVenues:yA,disableCourts:SA,disableVenues:wA,enableCourts:DA,enableVenues:bA,modifyCourt:NA,modifyCourtAvailability:hA,modifyVenue:EA},publicFindVenue:xm,query:ND},FA={__proto__:null,competitionGovernor:Du,drawsGovernor:LD,entriesGovernor:KD,eventGovernor:CT,generationGovernor:eb,matchUpFormatGovernor:nb,matchUpGovernor:fR,mocksGovernor:AM,participantGovernor:iN,policyGovernor:Lw,publishingGovernor:gN,queryGovernor:OD,reportGovernor:yN,scheduleGovernor:CN,scoreGovernor:Dw,tieFormatGovernor:XN,tournamentGovernor:mA,venueGovernor:OA};const{extractTime:kA,timeStringMinutes:xA}=na;const _A=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function LA(t,e=".",n=[]){return"object"==typeof t&&Object.keys(t).reduce(((r,i)=>"object"!=typeof t[i]?(r[n.concat(i).join(e)]=t[i],r):Object.assign(r,LA(t[i],e,n.concat(i)))),{})}var BA={__proto__:null,JSON2CSV:function(t,e){if(e&&"object"!=typeof e)return{error:Jn};let{columnTransform:n={}}=e||{};const{includeTransformAccessors:r,includeHeaderRow:i=!0,returnTransformedJSON:a,removeEmptyColumns:o,onlyHeaderRow:s,columnAccessors:c=[],functionMap:u={},columnMap:d={},valuesMap:p={},context:l={},delimiter:m='"',columnJoiner:f=",",rowJoiner:g="\r\n",keyJoiner:I="."}=e||{};if(!Array.isArray(t)||!Array.isArray(c)||"object"!=typeof l||"object"!=typeof d||"object"!=typeof n||"object"!=typeof u||"object"!=typeof p||"string"!=typeof f||"string"!=typeof g||"string"!=typeof I||"string"!=typeof m)return{error:Jn};n=Object.assign({},...Object.keys(n).reverse().map((t=>({[t]:Array.isArray(n[t])?n[t]:["string"==typeof n[t]&&n[t]].filter(Boolean)}))));const U=t.filter(Boolean).map((t=>LA(t,I))),y=Object.values(n).flat();r&&c.push(...y);const S=U.reduce(((t,e)=>Object.keys(e).every((e=>!t.includes(e)&&t.push(e)||!0))&&t),[]).filter((t=>!c?.length||c.includes(t))),v=Object.assign({},...Object.keys(n).reverse().map((t=>n[t].map((e=>({[e]:t}))).flat())).flat()),w=S.reduce(((t,e)=>{const n=v[e];return n?t.includes(n)||t.push(n):t.push(e),t}),[]).sort(((t,n)=>e?.sortOrder?e.sortOrder.includes(t)&&e.sortOrder.includes(n)&&e.sortOrder.indexOf(t)-e.sortOrder.indexOf(n)||!e.sortOrder.includes(n)&&-1:0));Object.keys(d).forEach((t=>!w.includes(t)&&w.unshift(t))),Object.keys(n).forEach((t=>!w.includes(t)&&w.unshift(t))),"object"==typeof l&&Object.keys(l).forEach((t=>!w.includes(t)&&w.unshift(t)));let P=w.map((t=>d[t]||t));if(s)return[P];const D=t=>`${m}${t}${m}`,T=[];let b=U.map((t=>Object.values(w.reduce(((e,r,i)=>{const a=n[r],o=(a?.length?t[a.find((e=>t[e]))]:t[r])||l?.[r]||"",s=p[r]?.[o]||o,c=V(u[r])?u[r](s):s;return e[r]=D(c),c&&(T[i]=(T[i]||0)+1),e}),{}))));const R=o&&[...T].map(((t,e)=>!t&&e)).filter(h).reverse();if(R){const t=t=>t.filter(((t,e)=>!R.includes(e)));b=b.map(t),P=t(P)}const M=b.map((t=>t.join(f)));return a?M.map((t=>{const e=t.split(f);return Object.assign({},...e.map(((t,e)=>({[P[e]]:t}))))})):i?[P.map(D).join(f),...M].join(g):M.join(g)},UUID:ha,UUIDS:fa,allNumeric:_,attributeFilter:Ic,chunkArray:x,chunkByNth:B,chunkSizeProfile:function t(e,[n,...r]){return e.length?[e.slice(0,n),...t(e.slice(n),[...r,n])]:[]},constantToString:xh,countValues:function(t){return b(T(t))},createMap:$,dateTime:na,definedAttributes:Xr,dehydrateMatchUps:function({tournamentRecord:t}){if(!t)return{error:nt};if("object"!=typeof t||!t.tournamentId)return{error:Jn};const{matchUps:e}=pf({tournamentRecord:t,inContext:!1});if(e?.length){const n=function({tournamentRecord:t}){const e={};for(const n of t.events||[]){n.matchUpFormat&&(e[n.eventId]=n.matchUpFormat);for(const t of n.drawDefinitions||[]){t.matchUpFormat&&(e[t.drawId]=t.matchUpFormat);for(const n of t.structures||[]){n.matchUpFormat&&(e[n.structureId]=n.matchUpFormat);for(const t of n.structures||[])t.matchUpFormat&&(e[t.structureId]=t.matchUpFormat)}}}return e}({tournamentRecord:t});!function(t,e={}){for(const n of t){const{structureId:t,drawId:r,eventId:i}=n,a=e[t]||e[r]||e[i],o=n.matchUpFormat===a?void 0:n.matchUpFormat;for(const t of Object.keys(n))_A.includes(t)||delete n[t];n.sides&&n.drawPositions&&!n.tieMatchUps&&delete n.sides,o&&(n.matchUpFormat=o)}}(e,n)}return{...z}},extractAttributes:gf,flattenJSON:LA,generateDateRange:_i,generateHashCode:function(t){if(null===t||"object"!=typeof t)return;const e=JSON.stringify(t),n=W(t),r=e.split("").reduce(((t,e)=>t+e.charCodeAt(0)),0);return[e.length,n,r].map((t=>t.toString(36))).join("")},generateRange:E,generateTimeCode:EM,groupValues:b,hasAttributeValues:t=>e=>Object.keys(t).every((n=>e[n]===t[n])),instanceCount:T,intersection:O,isConvertableInteger:y,isNumeric:h,isOdd:g,isPowerOf2:p,makeDeepCopy:la,matchUpScheduleSort:function(t,e){const n=t.schedule??{},r=e.schedule??{};if(n.scheduledDate&&!r.scheduledDate)return 1;if(r.scheduledDate&&!n.scheduledDate)return-1;if(n.scheduledDate&&r.scheduledDate){if(n.scheduledDate===r.scheduledDate){if(n.scheduledTime&&!r.scheduledTime)return 1;if(r.scheduledTime&&!n.scheduledTime)return-1;if(n.scheduledTime&&r.scheduledTime){return xA(kA(n.scheduledTime))-xA(kA(r.scheduledTime))}}return new Date(n.scheduledDate).getTime()-new Date(r.scheduledDate).getTime()}return 0},matchUpSort:mf,nearestPowerOf2:f,nextPowerOf2:I,noNulls:function(t){return Array.isArray(t)?t?.map((t=>null===t?void 0:t)):t},noNumeric:L,numericSort:u,occurrences:function(t,e){return Array.isArray(e)&&e.reduce(((t,e)=>(t[e]=1+t[e]||1,t)),{})[t]||0},overlap:k,randomMember:A,randomPop:N,shuffleArray:P,structureSort:rd,subSort:function(t,e,n,r){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+n).sort(r),...t.slice(e+n,t.length)):[]},undefinedToNull:function t(e,n){if(void 0===e)return null;if(!G(e)||null===e)return e;const r=Object.keys(e);return Object.assign({},...r.map((r=>{return Array.isArray(e[r])?{[r]:n?e[r]:e[r].map((e=>t(e)))}:{[r]:n?(i=e[r],void 0===i?null:i):t(e[r])};var i})))},unique:w,visualizeScheduledMatchUps:function({scheduledMatchUps:t,showGlobalLog:e}){Mf.length=0;const n=t?.reduce(((t,{structureId:e})=>t.includes(e)?t:t.concat(e)),[]),r=Array.isArray(n)&&{...n.map((e=>{const{structureName:n,matchUpType:r}=t.find((t=>t.structureId===e));return{[e]:`${n} ${r}`}}))};n?.forEach((e=>{Nf({color:"blue",method:"draw",structure:r[e],keyColors:{structure:"magenta"}},!0);const n=t.filter((t=>t.structureId===e)),i=Sl({matchUps:n})?.roundMatchUps||[];Object.keys(i).forEach((t=>{Nf({roundNumber:t,keyColors:{roundNumber:"brightcyan"}},!0),i[t].forEach((({matchUpId:t,schedule:e})=>{Nf({matchUpId:t,time:qi(e.scheduledTime),date:e.scheduledDate,venue:e.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)}))}))})),e&&Af()}};const{FACTORY:VA}=Uu;function jA({timeStamp:t}){const e=qr(),n=Cr();return n&&Object.values(e).forEach((e=>{!function({tournamentRecord:t,value:e}){const{extension:n}=zc({element:t,name:VA});_c({element:t,extension:{name:VA,value:{...n?.value,...e}}})}({tournamentRecord:e,value:{version:"2.2.28",timeStamp:t}})})),n}function GA({engineType:t,methodName:e,elapsed:n,params:r,result:i}){const a=Pr();if("object"!=typeof a)return;const o={method:e},s=i?.error&&(!0===a.errors||Array.isArray(a.errors)&&a.errors.includes(e)),c=Array.isArray(a.params)&&a.params?.includes(e),u=a.params&&!Array.isArray(a.params)||c,d=Array.isArray(a.exclude)&&a.exclude.includes(e);!d&&![void 0,!1].includes(a.perf)&&!isNaN(a.perf)&&n>=a.perf&&(o.elapsed=n),d||!s&&!u||(o.params=r),!d&&(s||a.result&&!Array.isArray(a.result)&&(!Array.isArray(a.params)||c)||Array.isArray(a.result)&&a.result?.includes(e))&&(o.result=i),Object.keys(o).length>1&&Qr(o,t)}function qA({methodName:t,params:e,start:n}){const r={error:pr,methodName:t};return GA({result:r,methodName:t,elapsed:n?Date.now()-n:0,params:e,engineType:"sync"}),r}function $A(t,e,n,r,i){delete t.success,delete t.error;const a=Date.now(),o=jr();n&&(n.activeTournamentId=o);const s=n?.tournamentRecord||Gr(o),c="object"==typeof n?.tournamentRecord&&{[n?.tournamentRecord.tournamentId]:n.tournamentRecord}||qr(),u=n?la(n,void 0,!0):void 0,d=n?function(t,e){if(!1===e._middleware)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:nt};const n=e.drawId||e.matchUp?.drawId;if(n){const{event:r,drawDefinition:i,tournamentId:a}=Gm({tournamentRecords:t,drawId:n});i&&(e.drawDefinition=i),a&&(e.tournamentId=a),r&&(e.event=r)}if(e.eventId&&!e.event){const{event:n,tournamentId:r}=Gm({eventId:e.eventId,tournamentRecords:t});if(!n)return{error:Wt};e.tournamentId=r,e.event=n}const r=e.tournamentId??jr();if(!r&&e)return e;const i=t[r];return r&&!i?{error:nt}:i?(e.tournamentRecord=i,e):e}(c,n):void 0;if(d?.error)return d;const p=function({tournamentRecords:t,tournamentRecord:e,params:n,methodName:r,method:i}){if(Pr())return i({tournamentRecords:t,tournamentRecord:e,...n});try{return i({tournamentRecords:t,tournamentRecord:e,...n})}catch(t){return Kr({engineName:"engine",methodName:r,params:n,err:t})}}({params:d,tournamentRecords:c,tournamentRecord:s,methodName:r,method:e});return GA({result:p,methodName:r,elapsed:Date.now()-a,params:u,engineType:i}),p}function WA(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t||{},{topics:a}=Lr();for(const t of[...a].sort(YA)){const e=kr({topic:t});e?.length&&Vr({topic:t,notices:e})}e&&i&&a.includes(Ed)&&Vr({notices:[{tournamentId:n,directives:r,timeStamp:i}],topic:Ed})}async function HA(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t||{},{topics:a}=Lr();for(const t of[...a].sort(YA)){const e=kr({topic:t});e&&await Vr({topic:t,notices:e})}e&&i&&a.includes(Ed)&&Vr({notices:[{tournamentId:n,directives:r,timeStamp:i}],topic:Ed})}const zA={[_d]:5,[xd]:5,[Ld]:5,[Md]:5,[Rd]:5,[wd]:5,[Pd]:5,[Dd]:5,[Td]:1,[Bd]:1,[bd]:5,[Ad]:5,[vd]:4,[Ud]:4,[yd]:4,[Sd]:4,[pd]:3,[dd]:2};function YA(t,e){return(zA[e]||0)-(zA[t]||0)}function KA(t,e=!0){return"object"!=typeof t||Array.isArray(t)?{error:Yn}:t?.tournamentId?$r(e?la(t):t):{error:Jn}}function QA(t,e=!0){if("object"!=typeof t)return{error:Yn};if(Hr(),Array.isArray(t)){if(!(t.filter((t=>t?.tournamentId)).length===t.length))return{error:tt};t=Object.assign({},...t.map((t=>({[t.tournamentId]:t}))))}else if(t?.tournamentId)Hr((t={[t.tournamentId]:t}).tournamentId);else{if(!Object.keys(t).every((e=>t[e].tournamentId===e)))return{error:tt}}return Wr(e?la(t):t)}async function JA(t,e){if(!G(e))return{error:Jn,message:"args must be an object"};const n=Object.values(e).filter(V).length;if(n>1)return{message:"there must be only one arg with typeof function",error:Jn};const r=n?Object.keys(e).find((t=>V(e[t]))):j(e.method)&&e.method;if(!r)return{error:pr};const{[r]:i,...a}=e,o=e?.params?{...e.params}:{...a},s=o.rollbackOnError&&la(qr(),!1,!0),c=i||t[r]||Ur()[r];if(!c)return qA({methodName:r,params:o});const u=await $A(t,c,o,r,"async")??{};u?.error&&s&&QA(s);const d=Date.now(),p=jA({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&await HA({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&_r(),u}function ZA(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function XA(t,e){t.importMethods=(n,r,i,a)=>function(t,e,n,r,i,a){const o=Jr(n,r,i,a);if(o.error)return o;const s=o.methods??[];return Object.keys(s).filter((t=>V(s[t]))).forEach((n=>{t[n]=r=>{const i=()=>e(t,{[n]:s[n],...r});if(Pr())return i();try{return i()}catch(t){Kr({engineName:"engine",methodName:n,params:r,err:t})}}})),{...z,...t}}(t,e,n,r,i,a),t.getTournament=t=>function(t){const{convertExtensions:e=!1,removeExtensions:n=!1}=t??{},r=t?.tournamentId??jr();return"string"!=typeof r?{}:{tournamentRecord:la(Gr(r),e,!1,n)}}(t),t.getState=t=>function({convertExtensions:t,removeExtensions:e}){const n=qr();return{tournamentId:jr(),tournamentRecords:la(n,t,!1,e)}}({convertExtensions:t?.convertExtensions,removeExtensions:t?.removeExtensions}),t.version=()=>"2.2.28",t.reset=()=>(Wr({}),ZA(t)),t.devContext=e=>(Tr(e),ZA(t)),t.getDevContext=t=>Pr(t),t.newTournamentRecord=(t={})=>{const e=LR(t),n=e.tournamentId;return e.error?e:(KA(e),Hr(n),{...z,tournamentId:n})},t.setState=(e,n,r)=>{Mr(n,r);const i=QA(e,n);return ZA(t,i)},t.setTournamentId=t=>Hr(t),t.getTournamentId=()=>jr(),t.setTournamentRecord=(e,n,r)=>{Mr(n,r);const i=KA(e,n);return ZA(t,i)},t.removeTournamentRecord=e=>{const n=zr(e);return ZA(t,n)},t.removeUnlinkedTournamentRecords=()=>{const e=function(){const t=qr(),{extension:e}=zc({name:ou,tournamentRecords:t,discover:!0}),n=e?.value?.tournamentIds||[];return Object.keys(t).forEach((e=>{n.includes(e)||delete t[e]})),Wr(t)}();return ZA(t,e)}}function tE(t,e){if(!G(e))return{error:Jn,message:"args must be an object"};const n=Object.values(e).filter(V).length;if(n>1)return{message:"there must be only one arg with typeof function",error:Jn};const r=n?Object.keys(e).find((t=>V(e[t]))):j(e.method)&&e.method;if(!r)return{error:pr};const{[r]:i,...a}=e,o=e?.params?{...e.params}:{...a},s=o.rollbackOnError&&la(qr(),!1,!0),c=i||t[r]||Ur()[r];if(!c)return qA({methodName:r,params:o});const u=$A(t,c,o,r,"sync")??{};u?.error&&s&&QA(s);const d=Date.now(),p=jA({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&WA({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&_r(),u}const eE=(()=>{const t={executionQueue:(e,n)=>function(t,e,n){if(!Array.isArray(e))return{error:Jn,message:"directives must be an array"};const r=Fr(),i=Date.now(),a=n&&la(qr(),!1,!0),o=[];for(const n of e){if("object"!=typeof n)return{error:Jn,message:"directive must be an object"};if(n.params&&"object"!=typeof n.params)return{error:Jn,message:"params must be an object"};const{method:e,pipe:s}=n,c=n.params?{...n.params}:{};if(!r[e])return qA({methodName:e,start:i,params:c});if(s){const t=o[o.length-1],e=Object.keys(s);for(const n of e)t[n]&&(c[n]=t[n])}const u=$A(t,r[e],c,e,"sync");if(u?.error)return a&&QA(a),{...u,rolledBack:!!a};o.push({...u,methodName:e})}const s=Date.now();return WA({directives:e,mutationStatus:jA({timeStamp:s}),timeStamp:s}),_r(),{success:o.every((t=>t.success)),results:o}}(t,e,n),execute:e=>tE(t,e)};return XA(t,tE),t})();function nE(t,e){if(!G(e))return{error:Jn,message:"args must be an object"};const n=Object.values(e).filter(V).length;if(n>1)return{message:"there must be only one arg with typeof function",error:Jn};const r=n?Object.keys(e).find((t=>V(e[t]))):j(e.method)&&e.method;if(!r)return{error:pr};const{[r]:i,...a}=e,o=e?.params?{...e.params}:{...a},s=i||t[r]||Ur()[r];return s?$A(t,s,o,r,"ask"):qA({methodName:r,params:o})}const rE=(()=>{const t={execute:e=>nE(t,e)};return XA(t,nE),t})();let iE,aE={};function oE(t,e=!0){if(!t)return{error:be};if("object"!=typeof t)return{error:Yn};if(t.matchUpId)iE=t.matchUpId,aE[iE]=e?la(t):t;else if(Array.isArray(t))for(const n of t.reverse())n.matchUpId&&(aE[n.matchUpId]=e?la(n):n,iE||(iE=n.matchUpId));else for(const n of Object.values(t))n.matchUpId&&(aE[n.matchUpId]=e?la(n):n,iE||(iE=n.matchUpId));return e?la(t):t}const sE=(()=>{const t={getState:t=>function(t){return la(aE[iE],t?.convertExtensions,!1,t?.removeExtensions)}(t),version:()=>"2.2.28",reset:()=>(iE=void 0,aE={},{...z}),drawId:void 0,error:void 0,success:!1,devContext:e=>(Tr(e),t),setState:(e,n,r)=>{Mr(n,r);return function(e){e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0,t.drawId=e.drawId);return t}(oE(e))}};return function(t,e){e.forEach((e=>{Object.keys(e).forEach((n=>{t[n]=r=>{if(Pr())return cE(t,{params:r,governor:e,methodName:n});try{return cE(t,{params:r,governor:e,methodName:n})}catch(t){Kr({engineName:"matchUpEngine",methodName:n,params:r,err:t})}}}))}))}(t,[Dw]),t})();function cE(t,{params:e,governor:n,methodName:r}){t.error=void 0,t.success=!1;const i=e?.matchUp||aE[iE],a=e?.matchUps||Object.values(aE),o=e?.rollbackOnError&&la(i,!1,!0);e={...e,matchUpId:i?.matchUpId,matchUps:a,matchUp:i};const s=n[r](e);if(s?.error)return o&&oE(o),{...s,rolledBack:!!o};const c=s?.success&&!0!==e?.delayNotify&&!0!==e?.doNotNotify;return c&&WA(),(c||!s?.success||e?.doNotNotify)&&_r(),s}let uE=!1;const dE=(()=>{const t={version:()=>"2.2.28",setDeepCopy:(e,n)=>(Mr(e,n),t),devContext:e=>(Tr(e),uE=!0,t)};return function(n){n.forEach((n=>{Object.keys(n).forEach((r=>{t[r]=t=>{if(Pr()){const i=e(n[r],t);return!i?.error&&t?.setState&&i?.tournamentRecord&&QA(i.tournamentRecord),i}try{const i=e(n[r],t);return!i?.error&&t?.setState&&i?.tournamentRecord&&QA(i.tournamentRecord),i}catch(e){let n;"string"==typeof e?n=e.toUpperCase():e instanceof Error&&(n=e.message),console.log("ERROR",{params:JSON.stringify(t),method:r,error:n})}}}))}))}([AM]),t;function e(t,e){const n=t({...e});return n?.error||WA(),_r(),uE&&(Tr(!1),uE=!1),n}})();eE.importMethods(FA,!0,1);const pE=eE,lE=eE,mE={...{getTournamentPoints:uP},...{calculateNewRatings:OS,generateDynamicRatings:FS}};eE.importMethods(mE);const fE=eE,hE={[Mc]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}},gE={[vc]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[AI,RI]}},IE={[vc]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[AI,NI,EI],disabledActions:[]}]}},UE="Personal circumstance",yE={ratingsParameters:hU,matchUpFormats:Ma,countryToFlag:lp,tieFormats:QD,countries:mp,policies:{POLICY_AVOIDANCE_COUNTRY:hE,POLICY_POSITION_ACTIONS_DEFAULT:Fy,POLICY_POSITION_ACTIONS_DISABLED:{[vc]:{policyName:"positionActionsDisabled",enabledStructures:!1}},POLICY_POSITION_ACTIONS_NO_MOVEMENT:IE,POLICY_POSITION_ACTIONS_UNRESTRICTED:gE,POLICY_PRIVACY_DEFAULT:{[Tc]:{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}}}},POLICY_ROUND_NAMING_DEFAULT:Tl,POLICY_SCHEDULING_DEFAULT:eD,POLICY_SCORING_DEFAULT:{[Nc]:{processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},defaultMatchUpFormat:ba,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireParticipantsForScoring:!1,requireAllPositionsAssigned:void 0,allowChangePropagation:!1,stage:{[fo]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},matchUpFormats:[],matchUpStatusCodes:{[Cu]:[],[ku]:[],[Lu]:[],[Gu]:[],[$u]:[],[zu]:[]}}},POLICY_SCORING_USTA:{[Nc]:{requireAllPositionsAssigned:!1,stage:{[fo]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:ba,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:ba,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:{[Cu]:[{matchUpStatusCodeDisplay:"Abandoned",label:"Abandoned match",matchUpStatusCode:"OA"}],[ku]:[{matchUpStatusCodeDisplay:"Unplayed or Cancelled",label:"Cancelled match",matchUpStatusCode:"OC"}],[Gu]:[{matchUpStatusCodeDisplay:"Incomplete",label:"Incomplete match",matchUpStatusCode:"OI"}],[Lu]:[{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"}],[zu]:[{matchUpStatusCodeDisplay:"Wo [inj]",matchUpStatusCode:"W1",label:"Injury"},{matchUpStatusCodeDisplay:"Wo [ill]",matchUpStatusCode:"W2",label:"Illness"},{matchUpStatusCodeDisplay:"Wo [pc]",label:UE,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"}],[$u]:[{matchUpStatusCodeDisplay:"Ret [inj]",matchUpStatusCode:"RJ",label:"Injury"},{matchUpStatusCodeDisplay:"Ret [ill]",matchUpStatusCode:"RI",label:"Illness"},{matchUpStatusCodeDisplay:"Ret [pc]",label:UE,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"}],[el]:[{matchUpStatusCodeDisplay:"Wd [inj]",matchUpStatusCode:"WD.INJ",label:"Injury"},{matchUpStatusCodeDisplay:"Wd [ill]",matchUpStatusCode:"WD.ILL",label:"Illness"},{matchUpStatusCodeDisplay:"Wd [pc]",label:UE,matchUpStatusCode:"WD.PC"},{matchUpStatusCodeDisplay:"Wd/Wd",matchUpStatusCode:"WD.WD",label:"Double withdrawal"},{label:"Tournament Administrative Error",matchUpStatusCodeDisplay:"Wd [Tae]",matchUpStatusCode:"WD.TAE"}]}}},POLICY_SEEDING_ITF:{[Ac]:{seedingProfile:{positioning:To},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}]}},POLICY_SEEDING_DEFAULT:Bw},flagIOC:function(t){return lp(Object.assign({},...mp.filter((t=>t.ioc)).map((t=>({[t.ioc]:t.iso}))))[t])}},SE={COACHING:"Coaching",BALL_ABUSE:"Ball Abuse",RACKET_ABUSE:"Racket Abuse",VERBAL_ABUSE:"Verbal Abuse",PHYSICAL_ABUSE:"Physical Abuse",INELIGIBILITY:"INELIGIBILITY",UNSPORTSMANLIKE_CONDUCT:"Unsportmanlike Conduct",PROHIBITED_SUBSTANCE:"PROHIBITED_SUBSTANCE",DRESS_CODE_VIOLATION:"Dress Code Violation",EQUIMENT_VIOLATION:"Equipment Violation",LEAVING_THE_COURT:"Leaving the court",REFUSAL_TO_PLAY:"REFUSAL_TO_PLAY",FAILURE_TO_COMPLETE:"Failure to complete",NO_SHOW:"No Show",OTHER:"Other",PUNCTUALITY:"Puncuality",FAILUIRE_TO_SIGN_IN:"Failure to sign in"},vE={CLAY:"CLAY",HARD:"HARD",GRASS:"GRASS",CARPET:"CARPET",ARTIFICIAL:"ARTIFICIAL"},wE={INDOOR:"INDOOR",OUTDOOR:"OUTDOOR"};var PE={__proto__:null,activeMatchUpStatuses:td,auditConstants:iT,completedMatchUpStatuses:Xu,directingMatchUpStatuses:Ju,displayConstants:bP,drawDefinitionConstants:ls,entryStatusConstants:sl,errorConditionConstants:fr,eventConstants:mo,extensionConstants:Uu,flightConstants:kT,genderConstants:oi,keyValueConstants:xv,matchUpActionConstants:rS,matchUpStatusConstants:nd,matchUpTypes:s,nonDirectingMatchUpStatuses:Zu,particicipantsRequiredMatchUpStatuses:Ku,participantConstants:dp,participantRoles:Ph,participantTypes:up,penaltyConstants:SE,policyConstants:Oc,positionActionConstants:OI,ratingConstants:fU,recoveryTimeRequiredMatchUpStatuses:Yu,requestConstants:vR,resourceContants:pa,resultConstants:K,scaleConstants:hc,scheduleConstants:Dm,sortingConstants:qT,surfaceConstants:vE,tieFormatConstants:no,timeItemConstants:sm,topicConstants:Vd,tournamentConstants:eA,upcomingMatchUpStatuses:ed,validMatchUpStatuses:Qu,venueConstants:wE,weekdayConstants:mT};exports.activeMatchUpStatuses=td,exports.askEngine=rE,exports.asyncEngine=function(t){const e=wr();if(e.error&&!t)return e;const n={executionQueue:(t,e)=>async function(t,e,n){if(!Array.isArray(e))return{error:Jn,message:"directives must be an array"};const r=Fr(),i=Date.now(),a=n&&la(qr(),!1,!0),o=[];for(const n of e){if("object"!=typeof n)return{error:Jn,message:"directive must be an object"};const{method:e,pipe:s}=n,c=n.params?{...n.params}:{};if(!r[e])return qA({methodName:e,start:i,params:c});if(s){const t=o[o.length-1],e=Object.keys(s);for(const n of e)t[n]&&(c[n]=t[n])}const u=$A(t,r[e],c,e,"async");if(u?.error)return a&&QA(a),{...u,rolledBack:!!a};o.push({...u,methodName:e})}const s=Date.now(),c=jA({timeStamp:s});return await HA({directives:e,mutationStatus:c,timeStamp:s}),_r(),{success:o.every((t=>t.success)),results:o}}(n,t,e),execute:t=>JA(n,t)};return XA(n,JA),n},exports.auditConstants=iT,exports.competitionEngine=pE,exports.competitionGovernor=Du,exports.completedMatchUpStatuses=Xu,exports.directingMatchUpStatuses=Ju,exports.displayConstants=bP,exports.drawDefinitionConstants=ls,exports.drawsGovernor=LD,exports.entriesGovernor=KD,exports.entryStatusConstants=sl,exports.errorConditionConstants=fr,exports.eventConstants=mo,exports.eventGovernor=CT,exports.extensionConstants=Uu,exports.factoryConstants=PE,exports.fixtures=yE,exports.flightConstants=kT,exports.forge={},exports.genderConstants=oi,exports.generationGovernor=eb,exports.globalState=Zr,exports.governors=FA,exports.keyValueConstants=xv,exports.matchUpActionConstants=rS,exports.matchUpEngine=sE,exports.matchUpFormatCode=nb,exports.matchUpFormatGovernor=nb,exports.matchUpGovernor=fR,exports.matchUpStatusConstants=nd,exports.matchUpTypes=s,exports.mocksEngine=dE,exports.mocksGovernor=AM,exports.nonDirectingMatchUpStatuses=Zu,exports.particicipantsRequiredMatchUpStatuses=Ku,exports.participantConstants=dp,exports.participantGovernor=iN,exports.participantRoles=Ph,exports.participantTypes=up,exports.penaltyConstants=SE,exports.policyConstants=Oc,exports.policyGovernor=Lw,exports.positionActionConstants=OI,exports.publishingGovernor=gN,exports.queryGovernor=OD,exports.ratingConstants=fU,exports.recoveryTimeRequiredMatchUpStatuses=Yu,exports.reportGovernor=yN,exports.requestConstants=vR,exports.resourceContants=pa,exports.resultConstants=K,exports.scaleConstants=hc,exports.scaleEngine=fE,exports.scheduleConstants=Dm,exports.scheduleGovernor=CN,exports.scoreGovernor=Dw,exports.sortingConstants=qT,exports.surfaceConstants=vE,exports.syncEngine=eE,exports.tieFormatConstants=no,exports.tieFormatGovernor=XN,exports.timeItemConstants=sm,exports.tools=BA,exports.topicConstants=Vd,exports.tournamentConstants=eA,exports.tournamentEngine=lE,exports.tournamentGovernor=mA,exports.upcomingMatchUpStatuses=ed,exports.utilities=BA,exports.validMatchUpStatuses=Qu,exports.venueConstants=wE,exports.venueGovernor=OA,exports.version=t,exports.weekdayConstants=mT;
//# sourceMappingURL=tods-competition-factory.production.cjs.min.js.map